Repository: alexcohn/tess-two Branch: 4.1 Commit: 377ddf88f65d Files: 594 Total size: 7.4 MB Directory structure: gitextract_37xgee5l/ ├── .gitignore ├── .gitmodules ├── BUILDING.md ├── CHANGELOG.md ├── COPYING ├── ISSUE_TEMPLATE.md ├── README.md ├── build.gradle ├── eyes-two/ │ ├── .classpath │ ├── .project │ ├── AndroidManifest.xml │ ├── COPYING │ ├── build.gradle │ ├── build.xml │ ├── project.properties │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── OpticalFlowTest.java │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── googlecode/ │ │ └── eyesfree/ │ │ ├── opticflow/ │ │ │ ├── ImageBlur.java │ │ │ └── OpticalFlow.java │ │ └── textdetect/ │ │ ├── HydrogenTextDetector.java │ │ └── Thresholder.java │ └── jni/ │ ├── Android.mk │ ├── Application.mk │ ├── common/ │ │ ├── Android.mk │ │ ├── time_log.cpp │ │ ├── time_log.h │ │ ├── types.h │ │ └── utils.h │ ├── hydrogen/ │ │ ├── Android.mk │ │ ├── jni/ │ │ │ ├── common.h │ │ │ ├── hydrogentextdetector.cpp │ │ │ ├── jni.cpp │ │ │ └── thresholder.cpp │ │ └── src/ │ │ ├── clusterer.cpp │ │ ├── clusterer.h │ │ ├── hydrogentextdetector.cpp │ │ ├── hydrogentextdetector.h │ │ ├── leptonica.h │ │ ├── thresholder.cpp │ │ ├── thresholder.h │ │ ├── utilities.cpp │ │ ├── utilities.h │ │ ├── validator.cpp │ │ └── validator.h │ ├── imageutils/ │ │ ├── Android.mk │ │ ├── blur-jni.cpp │ │ ├── blur.cpp │ │ ├── blur.h │ │ ├── similar-jni.cpp │ │ ├── similar.cpp │ │ └── similar.h │ └── opticalflow/ │ ├── Android.mk │ ├── feature_detector.cpp │ ├── feature_detector.h │ ├── image.h │ ├── optical_flow-jni.cpp │ ├── optical_flow.cpp │ ├── optical_flow.h │ └── optical_flow_utils.h ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── preparetests.cmd ├── preparetests.sh ├── settings.gradle ├── tess-two/ │ ├── .classpath │ ├── .gitignore │ ├── .project │ ├── AndroidManifest.xml │ ├── COPYING │ ├── build.gradle │ ├── build.xml │ ├── jni/ │ │ ├── Android.mk │ │ ├── Application.mk │ │ ├── com_googlecode_leptonica_android/ │ │ │ ├── Android.mk │ │ │ ├── box.cpp │ │ │ ├── boxa.cpp │ │ │ ├── common.h │ │ │ ├── endianness.h │ │ │ ├── jni.cpp │ │ │ ├── pix.cpp │ │ │ ├── pixa.cpp │ │ │ ├── readfile.cpp │ │ │ ├── utilities.cpp │ │ │ └── writefile.cpp │ │ ├── com_googlecode_tesseract_android/ │ │ │ ├── Android.mk │ │ │ ├── common.h │ │ │ ├── debugpixa.h │ │ │ ├── pageiterator.cpp │ │ │ ├── resultiterator.cpp │ │ │ ├── tess_version.h │ │ │ └── tessbaseapi.cpp │ │ ├── libjpeg/ │ │ │ ├── Android.mk │ │ │ ├── Makefile.am │ │ │ ├── README │ │ │ ├── ar-lib │ │ │ ├── cderror.h │ │ │ ├── cdjpeg.c │ │ │ ├── cdjpeg.h │ │ │ ├── change.log │ │ │ ├── cjpeg.1 │ │ │ ├── cjpeg.c │ │ │ ├── ckconfig.c │ │ │ ├── coderules.txt │ │ │ ├── compile │ │ │ ├── config.guess │ │ │ ├── config.sub │ │ │ ├── configure.ac │ │ │ ├── depcomp │ │ │ ├── djpeg.1 │ │ │ ├── djpeg.c │ │ │ ├── example.c │ │ │ ├── filelist.txt │ │ │ ├── install-sh │ │ │ ├── install.txt │ │ │ ├── jaricom.c │ │ │ ├── jcapimin.c │ │ │ ├── jcapistd.c │ │ │ ├── jcarith.c │ │ │ ├── jccoefct.c │ │ │ ├── jccolor.c │ │ │ ├── jcdctmgr.c │ │ │ ├── jchuff.c │ │ │ ├── jcinit.c │ │ │ ├── jcmainct.c │ │ │ ├── jcmarker.c │ │ │ ├── jcmaster.c │ │ │ ├── jcomapi.c │ │ │ ├── jconfig.bcc │ │ │ ├── jconfig.cfg │ │ │ ├── jconfig.dj │ │ │ ├── jconfig.h │ │ │ ├── jconfig.mac │ │ │ ├── jconfig.manx │ │ │ ├── jconfig.mc6 │ │ │ ├── jconfig.sas │ │ │ ├── jconfig.st │ │ │ ├── jconfig.txt │ │ │ ├── jconfig.vc │ │ │ ├── jconfig.vms │ │ │ ├── jconfig.wat │ │ │ ├── jcparam.c │ │ │ ├── jcprepct.c │ │ │ ├── jcsample.c │ │ │ ├── jctrans.c │ │ │ ├── jdapimin.c │ │ │ ├── jdapistd.c │ │ │ ├── jdarith.c │ │ │ ├── jdatadst.c │ │ │ ├── jdatasrc.c │ │ │ ├── jdcoefct.c │ │ │ ├── jdcolor.c │ │ │ ├── jdct.h │ │ │ ├── jddctmgr.c │ │ │ ├── jdhuff.c │ │ │ ├── jdinput.c │ │ │ ├── jdmainct.c │ │ │ ├── jdmarker.c │ │ │ ├── jdmaster.c │ │ │ ├── jdmerge.c │ │ │ ├── jdpostct.c │ │ │ ├── jdsample.c │ │ │ ├── jdtrans.c │ │ │ ├── jerror.c │ │ │ ├── jerror.h │ │ │ ├── jfdctflt.c │ │ │ ├── jfdctfst.c │ │ │ ├── jfdctint.c │ │ │ ├── jidctflt.c │ │ │ ├── jidctfst.c │ │ │ ├── jidctint.c │ │ │ ├── jinclude.h │ │ │ ├── jmemansi.c │ │ │ ├── jmemdos.c │ │ │ ├── jmemdosa.asm │ │ │ ├── jmemmac.c │ │ │ ├── jmemmgr.c │ │ │ ├── jmemname.c │ │ │ ├── jmemnobs.c │ │ │ ├── jmemsys.h │ │ │ ├── jmorecfg.h │ │ │ ├── jpegint.h │ │ │ ├── jpeglib.h │ │ │ ├── jpegtran.1 │ │ │ ├── jpegtran.c │ │ │ ├── jquant1.c │ │ │ ├── jquant2.c │ │ │ ├── jutils.c │ │ │ ├── jversion.h │ │ │ ├── libjpeg.txt │ │ │ ├── ltmain.sh │ │ │ ├── makcjpeg.st │ │ │ ├── makdjpeg.st │ │ │ ├── makeadsw.vc6 │ │ │ ├── makeasln.v10 │ │ │ ├── makecdep.vc6 │ │ │ ├── makecdsp.vc6 │ │ │ ├── makecfil.v10 │ │ │ ├── makecmak.vc6 │ │ │ ├── makecvcx.v10 │ │ │ ├── makeddep.vc6 │ │ │ ├── makeddsp.vc6 │ │ │ ├── makedfil.v10 │ │ │ ├── makedmak.vc6 │ │ │ ├── makedvcx.v10 │ │ │ ├── makefile.ansi │ │ │ ├── makefile.b32 │ │ │ ├── makefile.bcc │ │ │ ├── makefile.dj │ │ │ ├── makefile.manx │ │ │ ├── makefile.mc6 │ │ │ ├── makefile.mms │ │ │ ├── makefile.sas │ │ │ ├── makefile.unix │ │ │ ├── makefile.vc │ │ │ ├── makefile.vms │ │ │ ├── makefile.wat │ │ │ ├── makejdep.vc6 │ │ │ ├── makejdsp.vc6 │ │ │ ├── makejdsw.vc6 │ │ │ ├── makejfil.v10 │ │ │ ├── makejmak.vc6 │ │ │ ├── makejsln.v10 │ │ │ ├── makejvcx.v10 │ │ │ ├── makeproj.mac │ │ │ ├── makerdep.vc6 │ │ │ ├── makerdsp.vc6 │ │ │ ├── makerfil.v10 │ │ │ ├── makermak.vc6 │ │ │ ├── makervcx.v10 │ │ │ ├── maketdep.vc6 │ │ │ ├── maketdsp.vc6 │ │ │ ├── maketfil.v10 │ │ │ ├── maketmak.vc6 │ │ │ ├── maketvcx.v10 │ │ │ ├── makewdep.vc6 │ │ │ ├── makewdsp.vc6 │ │ │ ├── makewfil.v10 │ │ │ ├── makewmak.vc6 │ │ │ ├── makewvcx.v10 │ │ │ ├── makljpeg.st │ │ │ ├── maktjpeg.st │ │ │ ├── makvms.opt │ │ │ ├── missing │ │ │ ├── rdbmp.c │ │ │ ├── rdcolmap.c │ │ │ ├── rdgif.c │ │ │ ├── rdjpgcom.1 │ │ │ ├── rdjpgcom.c │ │ │ ├── rdppm.c │ │ │ ├── rdrle.c │ │ │ ├── rdswitch.c │ │ │ ├── rdtarga.c │ │ │ ├── structure.txt │ │ │ ├── testimg.ppm │ │ │ ├── transupp.c │ │ │ ├── transupp.h │ │ │ ├── usage.txt │ │ │ ├── wizard.txt │ │ │ ├── wrbmp.c │ │ │ ├── wrgif.c │ │ │ ├── wrjpgcom.1 │ │ │ ├── wrjpgcom.c │ │ │ ├── wrppm.c │ │ │ ├── wrrle.c │ │ │ └── wrtarga.c │ │ └── libpng/ │ │ ├── ANNOUNCE │ │ ├── Android.bp │ │ ├── Android.mk │ │ ├── CHANGES │ │ ├── CMakeLists.txt │ │ ├── CleanSpec.mk │ │ ├── INSTALL │ │ ├── LICENSE │ │ ├── MODULE_LICENSE_BSD_LIKE │ │ ├── Makefile.am │ │ ├── README │ │ ├── README.android │ │ ├── README.version │ │ ├── TODO │ │ ├── arm/ │ │ │ ├── arm_init.c │ │ │ ├── filter_neon.S │ │ │ └── filter_neon_intrinsics.c │ │ ├── autogen.sh │ │ ├── configure.ac │ │ ├── contrib/ │ │ │ ├── README.txt │ │ │ ├── arm-neon/ │ │ │ │ ├── README │ │ │ │ ├── android-ndk.c │ │ │ │ ├── linux-auxv.c │ │ │ │ └── linux.c │ │ │ ├── conftest/ │ │ │ │ ├── README │ │ │ │ ├── pngcp.dfa │ │ │ │ ├── read.dfa │ │ │ │ ├── s_read.dfa │ │ │ │ ├── s_write.dfa │ │ │ │ ├── simple.dfa │ │ │ │ └── write.dfa │ │ │ ├── examples/ │ │ │ │ ├── README.txt │ │ │ │ ├── iccfrompng.c │ │ │ │ ├── pngpixel.c │ │ │ │ ├── pngtopng.c │ │ │ │ └── simpleover.c │ │ │ ├── gregbook/ │ │ │ │ ├── COPYING │ │ │ │ ├── LICENSE │ │ │ │ ├── Makefile.mingw32 │ │ │ │ ├── Makefile.sgi │ │ │ │ ├── Makefile.unx │ │ │ │ ├── Makefile.w32 │ │ │ │ ├── README │ │ │ │ ├── makevms.com │ │ │ │ ├── readpng.c │ │ │ │ ├── readpng.h │ │ │ │ ├── readpng2.c │ │ │ │ ├── readpng2.h │ │ │ │ ├── readppm.c │ │ │ │ ├── rpng-win.c │ │ │ │ ├── rpng-x.c │ │ │ │ ├── rpng2-win.c │ │ │ │ ├── rpng2-x.c │ │ │ │ ├── wpng.c │ │ │ │ ├── writepng.c │ │ │ │ └── writepng.h │ │ │ ├── intel/ │ │ │ │ ├── INSTALL │ │ │ │ ├── Makefile.am.patch │ │ │ │ ├── configure.ac.patch │ │ │ │ ├── filter_sse2_intrinsics.c │ │ │ │ ├── intel_init.c │ │ │ │ └── intel_sse.patch │ │ │ ├── libtests/ │ │ │ │ ├── fakepng.c │ │ │ │ ├── gentests.sh │ │ │ │ ├── makepng.c │ │ │ │ ├── pngimage.c │ │ │ │ ├── pngstest-errors.h │ │ │ │ ├── pngstest.c │ │ │ │ ├── pngunknown.c │ │ │ │ ├── pngvalid.c │ │ │ │ ├── readpng.c │ │ │ │ ├── tarith.c │ │ │ │ └── timepng.c │ │ │ ├── mips-msa/ │ │ │ │ ├── README │ │ │ │ └── linux.c │ │ │ ├── pngminim/ │ │ │ │ ├── README │ │ │ │ ├── decoder/ │ │ │ │ │ ├── README │ │ │ │ │ ├── pngusr.dfa │ │ │ │ │ └── pngusr.h │ │ │ │ ├── encoder/ │ │ │ │ │ ├── README │ │ │ │ │ ├── pngusr.dfa │ │ │ │ │ └── pngusr.h │ │ │ │ └── preader/ │ │ │ │ ├── README │ │ │ │ ├── pngusr.dfa │ │ │ │ └── pngusr.h │ │ │ ├── pngminus/ │ │ │ │ ├── README │ │ │ │ ├── makefile.std │ │ │ │ ├── makefile.tc3 │ │ │ │ ├── makevms.com │ │ │ │ ├── png2pnm.bat │ │ │ │ ├── png2pnm.c │ │ │ │ ├── png2pnm.sh │ │ │ │ ├── pngminus.bat │ │ │ │ ├── pngminus.sh │ │ │ │ ├── pnm2png.bat │ │ │ │ ├── pnm2png.c │ │ │ │ └── pnm2png.sh │ │ │ ├── pngsuite/ │ │ │ │ └── README │ │ │ ├── tools/ │ │ │ │ ├── README.txt │ │ │ │ ├── checksum-icc.c │ │ │ │ ├── chkfmt │ │ │ │ ├── cvtcolor.c │ │ │ │ ├── genpng.c │ │ │ │ ├── intgamma.sh │ │ │ │ ├── makesRGB.c │ │ │ │ ├── png-fix-itxt.c │ │ │ │ ├── pngcp.c │ │ │ │ ├── pngfix.c │ │ │ │ ├── reindent │ │ │ │ └── sRGB.h │ │ │ └── visupng/ │ │ │ ├── PngFile.c │ │ │ ├── PngFile.h │ │ │ ├── README.txt │ │ │ ├── VisualPng.c │ │ │ ├── VisualPng.dsp │ │ │ ├── VisualPng.dsw │ │ │ ├── VisualPng.rc │ │ │ ├── cexcept.h │ │ │ └── resource.h │ │ ├── example.c │ │ ├── libpng-config.in │ │ ├── libpng-manual.txt │ │ ├── libpng.3 │ │ ├── libpng.pc.in │ │ ├── libpngpf.3 │ │ ├── mips/ │ │ │ ├── filter_msa_intrinsics.c │ │ │ └── mips_init.c │ │ ├── png.5 │ │ ├── png.c │ │ ├── png.h │ │ ├── pngconf.h │ │ ├── pngdebug.h │ │ ├── pngerror.c │ │ ├── pngget.c │ │ ├── pnginfo.h │ │ ├── pnglibconf.h │ │ ├── pngmem.c │ │ ├── pngpread.c │ │ ├── pngpriv.h │ │ ├── pngread.c │ │ ├── pngrio.c │ │ ├── pngrtran.c │ │ ├── pngrutil.c │ │ ├── pngset.c │ │ ├── pngstruct.h │ │ ├── pngtest.c │ │ ├── pngtrans.c │ │ ├── pngusr.dfa │ │ ├── pngusr.h │ │ ├── pngwio.c │ │ ├── pngwrite.c │ │ ├── pngwtran.c │ │ ├── pngwutil.c │ │ ├── projects/ │ │ │ ├── owatcom/ │ │ │ │ ├── libpng.tgt │ │ │ │ ├── libpng.wpj │ │ │ │ ├── pngconfig.mak │ │ │ │ ├── pngstest.tgt │ │ │ │ ├── pngtest.tgt │ │ │ │ └── pngvalid.tgt │ │ │ ├── visualc71/ │ │ │ │ ├── PRJ0041.mak │ │ │ │ ├── README.txt │ │ │ │ ├── README_zlib.txt │ │ │ │ ├── libpng.sln │ │ │ │ ├── libpng.vcproj │ │ │ │ ├── pngtest.vcproj │ │ │ │ └── zlib.vcproj │ │ │ └── vstudio/ │ │ │ ├── libpng/ │ │ │ │ └── libpng.vcxproj │ │ │ ├── pnglibconf/ │ │ │ │ └── pnglibconf.vcxproj │ │ │ ├── pngstest/ │ │ │ │ └── pngstest.vcxproj │ │ │ ├── pngtest/ │ │ │ │ └── pngtest.vcxproj │ │ │ ├── pngunknown/ │ │ │ │ └── pngunknown.vcxproj │ │ │ ├── pngvalid/ │ │ │ │ └── pngvalid.vcxproj │ │ │ ├── readme.txt │ │ │ ├── vstudio.sln │ │ │ ├── zlib/ │ │ │ │ └── zlib.vcxproj │ │ │ └── zlib.props │ │ ├── scripts/ │ │ │ ├── README.txt │ │ │ ├── SCOPTIONS.ppc │ │ │ ├── checksym.awk │ │ │ ├── def.c │ │ │ ├── descrip.mms │ │ │ ├── dfn.awk │ │ │ ├── genchk.cmake.in │ │ │ ├── genout.cmake.in │ │ │ ├── gensrc.cmake.in │ │ │ ├── intprefix.c │ │ │ ├── libpng-config-body.in │ │ │ ├── libpng-config-head.in │ │ │ ├── libpng.pc.in │ │ │ ├── macro.lst │ │ │ ├── makefile.32sunu │ │ │ ├── makefile.64sunu │ │ │ ├── makefile.acorn │ │ │ ├── makefile.aix │ │ │ ├── makefile.amiga │ │ │ ├── makefile.atari │ │ │ ├── makefile.bc32 │ │ │ ├── makefile.beos │ │ │ ├── makefile.bor │ │ │ ├── makefile.cegcc │ │ │ ├── makefile.darwin │ │ │ ├── makefile.dec │ │ │ ├── makefile.dj2 │ │ │ ├── makefile.freebsd │ │ │ ├── makefile.gcc │ │ │ ├── makefile.hp64 │ │ │ ├── makefile.hpgcc │ │ │ ├── makefile.hpux │ │ │ ├── makefile.ibmc │ │ │ ├── makefile.intel │ │ │ ├── makefile.knr │ │ │ ├── makefile.linux │ │ │ ├── makefile.mips │ │ │ ├── makefile.msc │ │ │ ├── makefile.msys │ │ │ ├── makefile.ne12bsd │ │ │ ├── makefile.netbsd │ │ │ ├── makefile.openbsd │ │ │ ├── makefile.sco │ │ │ ├── makefile.sggcc │ │ │ ├── makefile.sgi │ │ │ ├── makefile.so9 │ │ │ ├── makefile.solaris │ │ │ ├── makefile.solaris-x86 │ │ │ ├── makefile.std │ │ │ ├── makefile.sunos │ │ │ ├── makefile.tc3 │ │ │ ├── makefile.vcwin32 │ │ │ ├── makevms.com │ │ │ ├── options.awk │ │ │ ├── pnglibconf.dfa │ │ │ ├── pnglibconf.h.prebuilt │ │ │ ├── pnglibconf.mak │ │ │ ├── pngwin.rc │ │ │ ├── prefix.c │ │ │ ├── smakefile.ppc │ │ │ ├── sym.c │ │ │ ├── symbols.c │ │ │ ├── symbols.def │ │ │ ├── test.cmake.in │ │ │ └── vers.c │ │ └── tests/ │ │ ├── pngimage-full │ │ ├── pngimage-quick │ │ ├── pngstest │ │ ├── pngstest-1.8 │ │ ├── pngstest-1.8-alpha │ │ ├── pngstest-linear │ │ ├── pngstest-linear-alpha │ │ ├── pngstest-none │ │ ├── pngstest-none-alpha │ │ ├── pngstest-sRGB │ │ ├── pngstest-sRGB-alpha │ │ ├── pngtest │ │ ├── pngunknown-IDAT │ │ ├── pngunknown-discard │ │ ├── pngunknown-if-safe │ │ ├── pngunknown-sAPI │ │ ├── pngunknown-sTER │ │ ├── pngunknown-save │ │ ├── pngunknown-vpAg │ │ ├── pngvalid-gamma-16-to-8 │ │ ├── pngvalid-gamma-alpha-mode │ │ ├── pngvalid-gamma-background │ │ ├── pngvalid-gamma-expand16-alpha-mode │ │ ├── pngvalid-gamma-expand16-background │ │ ├── pngvalid-gamma-expand16-transform │ │ ├── pngvalid-gamma-sbit │ │ ├── pngvalid-gamma-threshold │ │ ├── pngvalid-gamma-transform │ │ ├── pngvalid-progressive-interlace-standard │ │ ├── pngvalid-progressive-size │ │ ├── pngvalid-progressive-standard │ │ ├── pngvalid-standard │ │ └── pngvalid-transform │ ├── proguard-rules.pro │ ├── project.properties │ ├── res/ │ │ └── .gitkeep │ └── src/ │ └── com/ │ └── googlecode/ │ ├── leptonica/ │ │ └── android/ │ │ ├── AdaptiveMap.java │ │ ├── Binarize.java │ │ ├── Box.java │ │ ├── Boxa.java │ │ ├── Clip.java │ │ ├── Constants.java │ │ ├── Convert.java │ │ ├── Edge.java │ │ ├── Enhance.java │ │ ├── GrayQuant.java │ │ ├── JpegIO.java │ │ ├── MorphApp.java │ │ ├── Pix.java │ │ ├── Pixa.java │ │ ├── ReadFile.java │ │ ├── Rotate.java │ │ ├── Scale.java │ │ ├── Skew.java │ │ └── WriteFile.java │ └── tesseract/ │ └── android/ │ ├── PageIterator.java │ ├── ResultIterator.java │ ├── TessBaseAPI.java │ └── TessPdfRenderer.java └── tess-two-test/ ├── .classpath ├── .project ├── AndroidManifest.xml ├── build.gradle ├── project.properties ├── res/ │ └── values/ │ └── strings.xml └── src/ └── com/ └── googlecode/ ├── leptonica/ │ └── android/ │ └── test/ │ ├── AdaptiveMapTest.java │ ├── BinarizeTest.java │ ├── BoxTest.java │ ├── BoxaTest.java │ ├── ClipTest.java │ ├── ConvertTest.java │ ├── EdgeTest.java │ ├── EnhanceTest.java │ ├── GrayQuantTest.java │ ├── JpegIOTest.java │ ├── PixTest.java │ ├── PixaTest.java │ ├── ReadFileTest.java │ ├── RotateTest.java │ ├── ScaleTest.java │ ├── SkewTest.java │ ├── TestUtils.java │ └── WriteFileTest.java └── tesseract/ └── android/ └── test/ ├── TessBaseAPITest.java └── TessPdfRendererTest.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .settings .svn local.properties proguard.cfg proguard-project.txt bin/ gen/ libs/ obj/ patches/ target/ src/test/resources/META-INF/config.properties *.Plo *.dylib *.la *.a *.lo .libs/ .deps/ autom4te.cache/ Makefile.in Makefile config.status *.m4 config_auto.h configure libtool tesseract.pc stamp-h1 build/ .gradle/ .idea/ *.iml javadoc/ tessdata/ .externalNativeBuild eyes-two/.cxx tess-two/.cxx ================================================ FILE: .gitmodules ================================================ [submodule "leptonica"] path = leptonica url = https://github.com/alexcohn/leptonica [submodule "tesseract"] path = tesseract url = https://github.com/alexcohn/tesseract ================================================ FILE: BUILDING.md ================================================ # Building This project may be built manually as an alternative to including the pre-built AAR as an external dependency in your app project. To start the build, import the root directory of this project into Android Studio as an existing Android Studio project, or follow the instructions below to build on the command line. ## _Building with Android Studio_ The Gradle build uses the gradle-stable plugin and the Android NDK to build the Tesseract and Leptonica native C/C++ code through a call to `ndk-build` in `build.gradle`. In Android Studio, use Build -> Rebuild Project to build or rebuild the project. Note: When building from Android Studio, you may need to set the path to your NDK installation in the Project Structure dialog (File->Project Structure). ## _Building on the Command Line_ _On Mac/Linux:_ Edit your local.properties file to include the path to your NDK directory: ndk.dir=/path/to/your/android-ndk Run the following commands: export ANDROID_HOME=/path/to/your/android-sdk git clone git://github.com/rmtheis/tess-two tess cd tess ./gradlew assemble _On Windows:_ Edit your local.properties file to include the path to your NDK directory: ndk.dir=C\:\\path\\to\\your\\android-ndk Run the following commands: set ANDROID_HOME=C:\\path\\to\\your\\android-sdk git clone git://github.com/rmtheis/tess-two tess cd tess gradlew assemble On all above platforms you can build a command-line static banary, e.g. ndk-build -C tess-two-git/tess-two tesseract APP_ABI=arm64-v8a It can be deployed to `/data/local/tmp` of a compatible Android device and run from adb shell: adb shell time tesseract --tessdata-dir tessdata imagename outputbase With v.4.1 you can use new or old data files. # Importing After building, the code that is generated may be imported into your app project in Android Studio as a module using File -> New -> Import Module -> `tess-two` folder and then adding the dependency to your app module build.gradle: dependencies { implementation project(':tess-two') } # Testing _On Mac/Linux:_ ./preparetests.sh ./gradlew connectedAndroidTest _On Windows:_ preparetests.cmd gradlew connectedAndroidTest # Removing If you want to remove your app's dependency on the tess-two module, reverse the import process by removing the module using the Project Structure dialog (File->Project Structure), manually deleting the tess-two subfolder from your app project folder, and removing the tess-two reference from your app module build.gradle. ================================================ FILE: CHANGELOG.md ================================================ # Change Log ## [9.1.0](https://github.com/rmtheis/tess-two/tree/9.1.0) (2019-10-19) [Full Changelog](https://github.com/rmtheis/tess-two/compare/9.0.0...9.1.0) **Fixed bugs:** - WriteFile.writeBytes altering the source image endiannes and producing artefacts [\#228](https://github.com/rmtheis/tess-two/issues/228) - Crashing reported on 64-bit devices [\#197](https://github.com/rmtheis/tess-two/issues/197) - testPixaReplacePix crashes in native code [\#159](https://github.com/rmtheis/tess-two/issues/159) - ReadFile.readBitmap alters image colors [\#87](https://github.com/rmtheis/tess-two/issues/87) **Closed issues:** - read Jpeg and PNG produce wrong alpha in 32bpp pix [\#264](https://github.com/rmtheis/tess-two/issues/264) - Native crush when 'vert'.tessdata is used [\#263](https://github.com/rmtheis/tess-two/issues/263) - In versions higher than 5.4.1 TessBaseAPI.ProgressNotifier never called [\#262](https://github.com/rmtheis/tess-two/issues/262) - Decoding is slow when multiple languages are used [\#261](https://github.com/rmtheis/tess-two/issues/261) - Getting different results when using tesseract on mobile vs on PC using Python. [\#260](https://github.com/rmtheis/tess-two/issues/260) - Illegible words recognition in Persian lang [\#259](https://github.com/rmtheis/tess-two/issues/259) - Could not initialize Tesseract API with language=ces! [\#258](https://github.com/rmtheis/tess-two/issues/258) - Can't lanch [\#257](https://github.com/rmtheis/tess-two/issues/257) - Tess4 initialize crash [\#255](https://github.com/rmtheis/tess-two/issues/255) - tess4 on android studio [\#254](https://github.com/rmtheis/tess-two/issues/254) - How I can init the tesseract to work only with digits? [\#253](https://github.com/rmtheis/tess-two/issues/253) - java.lang.NoSuchFieldError: no "I" field "mNativeData" in class "Lcom/googlecode/tesseract/android/TessBaseAPI;" or its superclasses [\#252](https://github.com/rmtheis/tess-two/issues/252) - java.lang.NoSuchFieldError: no "I" field "mNativeData" in class "Lcom/googlecode/tesseract/android/TessBaseAPI;" or its superclasses [\#251](https://github.com/rmtheis/tess-two/issues/251) - Arabic trained-data produce 20% accuracy [\#250](https://github.com/rmtheis/tess-two/issues/250) - import tess two error [\#249](https://github.com/rmtheis/tess-two/issues/249) - error in Android 7.0 [\#248](https://github.com/rmtheis/tess-two/issues/248) - How to build tess-two without JNI? [\#247](https://github.com/rmtheis/tess-two/issues/247) - Initializing TessBaseAPI crashes app [\#246](https://github.com/rmtheis/tess-two/issues/246) - OCR number [\#245](https://github.com/rmtheis/tess-two/issues/245) - compile binary only [\#244](https://github.com/rmtheis/tess-two/issues/244) - Skip tesseract's default image preprocessing \(Otsu\) [\#243](https://github.com/rmtheis/tess-two/issues/243) - How to add OPTITypewriter-Special font [\#242](https://github.com/rmtheis/tess-two/issues/242) - Special requirements for Hindi and Arabic OCR [\#239](https://github.com/rmtheis/tess-two/issues/239) **Merged pull requests:** - fix Java tests for leptronica [\#265](https://github.com/rmtheis/tess-two/pull/265) ([alexcohn](https://github.com/alexcohn)) - Update to support latest Android Studio [\#256](https://github.com/rmtheis/tess-two/pull/256) ([Robyer](https://github.com/Robyer)) ## [9.0.0](https://github.com/rmtheis/tess-two/tree/9.0.0) (2018-04-20) [Full Changelog](https://github.com/rmtheis/tess-two/compare/8.0.0...9.0.0) **Change:** - This version fixes and adds back in the 64-bit ABIs, and removes the deprecated armv5 and mips/mips64 ABIs. **Implemented enhancements:** - Improve developer support for Hindi/Arabic [\#240](https://github.com/rmtheis/tess-two/issues/240) **Fixed bugs:** - Crashing reported on 64-bit devices [\#197](https://github.com/rmtheis/tess-two/issues/197) **Merged pull requests:** - Updated repositories. Changed compile to implementation. [\#233](https://github.com/rmtheis/tess-two/pull/233) ([mauriciotogneri](https://github.com/mauriciotogneri)) - Updated version of SDK, build tools and support libraries [\#231](https://github.com/rmtheis/tess-two/pull/231) ([mauriciotogneri](https://github.com/mauriciotogneri)) ## [8.0.0](https://github.com/rmtheis/tess-two/tree/8.0.0) (2017-08-13) [Full Changelog](https://github.com/rmtheis/tess-two/compare/7.0.0...8.0.0) **Change:** - This version removes the 64-bit ABIs from the default build in order to avoid crashes due to [\#197](https://github.com/rmtheis/tess-two/issues/197) **Closed issues:** - Build failure with Android Studio 3 and NDK ver. 15.x [\#215](https://github.com/rmtheis/tess-two/issues/215) **Merged pull requests:** - clone tag 3.04.00 from tessdata [\#217](https://github.com/rmtheis/tess-two/pull/217) ([ivankolev](https://github.com/ivankolev)) - See issue \#215 [\#216](https://github.com/rmtheis/tess-two/pull/216) ([ivankolev](https://github.com/ivankolev)) ## [7.0.0](https://github.com/rmtheis/tess-two/tree/7.0.0) (2017-06-12) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.3.0...7.0.0) **API-breaking change:** - ResultIterator getChoicesAndConfidence\(\) is now getSymbolChoicesAndConfidence\(\) **Fixed bugs:** - ResultIterator crashes with certain character combinations [\#126](https://github.com/rmtheis/tess-two/issues/126) - ResultIterator returns single Character as Alternatives for Words [\#119](https://github.com/rmtheis/tess-two/issues/119) - beginDocument\(\) returns false even when successful [\#103](https://github.com/rmtheis/tess-two/issues/103) **Closed issues:** - Hardcoded path in TessBaseAPITest.java [\#208](https://github.com/rmtheis/tess-two/issues/208) **Merged pull requests:** - Add missing PageSegMode constant [\#209](https://github.com/rmtheis/tess-two/pull/209) ([Robyer](https://github.com/Robyer)) - Fix return value of BeginDocument \(fixes \#103\) [\#207](https://github.com/rmtheis/tess-two/pull/207) ([Robyer](https://github.com/Robyer)) - Improve ResultIterator [\#206](https://github.com/rmtheis/tess-two/pull/206) ([Robyer](https://github.com/Robyer)) - Update gradle plugin [\#205](https://github.com/rmtheis/tess-two/pull/205) ([Robyer](https://github.com/Robyer)) - Fix javadocs errors and warnings [\#202](https://github.com/rmtheis/tess-two/pull/202) ([Robyer](https://github.com/Robyer)) ## [6.3.0](https://github.com/rmtheis/tess-two/tree/6.2.0) (2017-04-06) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.2.0...6.3.0) **Updates:** - Tesseract code updated to version 3.05.00 [Tesseract change log](https://github.com/tesseract-ocr/tesseract/blob/cf0b378577e7ed0c75bfaf97cae7e35d7634cf4d/ChangeLog#L22) ## [6.2.0](https://github.com/rmtheis/tess-two/tree/6.2.0) (2017-02-04) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.1.1...6.2.0) **Updates:** - Leptonica 1.74.1 - Libpng 1.6.25 **Fixed bugs:** - Stop\(\) does not work with GetUTF8Text\(\) [\#185](https://github.com/rmtheis/tess-two/issues/185) - TessBaseAPI stop\(\) sometimes causes SIGSEGV [\#97](https://github.com/rmtheis/tess-two/issues/97) **Merged pull requests:** - Issue 185 [\#186](https://github.com/rmtheis/tess-two/pull/186) ([Xyresic](https://github.com/Xyresic)) ## [6.1.1](https://github.com/rmtheis/tess-two/tree/6.1.1) (2016-11-27) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.1.0...6.1.1) **Updates:** - Changed ProGuard settings ## [6.1.0](https://github.com/rmtheis/tess-two/tree/6.1.0) (2016-11-22) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.0.4...6.1.0) **Updates:** - Tesseract code updated, version 3.05.00dev **Closed issues:** - Tests doesn't work on devices without sdcard [\#171](https://github.com/rmtheis/tess-two/issues/171) - no field with name='mNativeData' signature='J' in class Lcom/googlecode/tesseract/android/TessBaseAPI; [\#166](https://github.com/rmtheis/tess-two/issues/166) **Merged pull requests:** - Pass native pointer as parameter [\#172](https://github.com/rmtheis/tess-two/pull/172) ([jereksel](https://github.com/jereksel)) ## [6.0.4](https://github.com/rmtheis/tess-two/tree/6.0.4) (2016-08-21) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.0.3...6.0.4) **Updates:** - Changed ProGuard settings **Closed issues:** - android studio2.1.2 not build [\#168](https://github.com/rmtheis/tess-two/issues/168) - no field with name='mNativeData' signature='J' in class Lcom/googlecode/tesseract/android/TessBaseAPI; [\#166](https://github.com/rmtheis/tess-two/issues/166) ## [6.0.3](https://github.com/rmtheis/tess-two/tree/6.0.3) (2016-07-16) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.0.2...6.0.3) **Closed issues:** - UnsatisfiedLinkError; thrown while initializing Lcom/googlecode/tesseract/android/TessBaseAPI 'libjpgt.so' and 'liblept.so' w/ compile 'com.rmtheis:tess-two:6.0.0' [\#150](https://github.com/rmtheis/tess-two/issues/150) ## [6.0.2](https://github.com/rmtheis/tess-two/tree/6.0.2) (2016-06-20) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.0.1...6.0.2) **Closed issues:** - Building project error on Windows - javadoc failed [\#148](https://github.com/rmtheis/tess-two/issues/148) **Merged pull requests:** - Refactor nativeMergeAndReplacePix. Addresses \#132. [\#157](https://github.com/rmtheis/tess-two/pull/157) ([megabytefisher](https://github.com/megabytefisher)) - Fix memory leak in setImage\(Bitmap bmp\) [\#154](https://github.com/rmtheis/tess-two/pull/154) ([megabytefisher](https://github.com/megabytefisher)) ## [6.0.1](https://github.com/rmtheis/tess-two/tree/6.0.1) (2016-06-09) [Full Changelog](https://github.com/rmtheis/tess-two/compare/6.0.0...6.0.1) **Bug fix:** - Fixed nativeGetPix for 64-bit devices ## [6.0.0](https://github.com/rmtheis/tess-two/tree/6.0.0) (2016-05-16) [Full Changelog](https://github.com/rmtheis/tess-two/compare/5.4.1...6.0.0) **API-breaking changes:** - Progress values no longer available when using getUTF8Text. Use getHOCRText instead. - Android 2.2 (API level 8) no longer supported - Eyes-two project refactored. Code similar to what was removed is available from the [Google Mobile Vision API](https://developers.google.com/vision/). - Tess-two deprecated methods removed **Updates:** - Tesseract 3.05.00dev (tesseract-ocr/tesseract@add1ed1) - Leptonica 1.73 - Libpng 1.6.20 (android/platform_external_libpng@2789184) **Implemented enhancements:** - GetUTF8Text\(\) monitor and multi-platform projects [\#116](https://github.com/rmtheis/tess-two/issues/116) - Update eyes-two structure [\#95](https://github.com/rmtheis/tess-two/issues/95) - Expand image I/O format support [\#94](https://github.com/rmtheis/tess-two/issues/94) **Fixed bugs:** - NDK r11 clang build error: undefined reference to isnanf/\_\_isinff [\#138](https://github.com/rmtheis/tess-two/issues/138) - init\(\) crashes when using OEM\_TESSERACT\_CUBE\_COMBINED for Arabic [\#12](https://github.com/rmtheis/tess-two/issues/12) ## [5.4.1](https://github.com/rmtheis/tess-two/tree/5.4.1) (2016-01-17) [Full Changelog](https://github.com/rmtheis/tess-two/compare/5.4.0...5.4.1) **Updates:** - Added libjpeg 9b **Closed issues:** - Pdf renderer isn't working with jpg input images [\#122](https://github.com/rmtheis/tess-two/issues/122) ## [5.4.0](https://github.com/rmtheis/tess-two/tree/5.4.0) (2016-01-10) [Full Changelog](https://github.com/rmtheis/tess-two/compare/5.3.0...5.4.0) **Updates:** - Added Gradle build - Released on Bintray **Closed issues:** - Add Maven support [\#53](https://github.com/rmtheis/tess-two/issues/53) **Merged pull requests:** - Gradle build [\#99](https://github.com/rmtheis/tess-two/pull/99) ([Aaargh20318](https://github.com/Aaargh20318)) ## [5.3.0](https://github.com/rmtheis/tess-two/tree/5.3.0) (2015-10-30) [Full Changelog](https://github.com/rmtheis/tess-two/compare/5.2.0...5.3.0) **Implemented enhancements:** - Added TessPdfRenderer for PDF output [\#46](https://github.com/rmtheis/tess-two/issues/46) - Added libpng 1.6.10 (android/platform_external_libpng@37f83eb) **Closed issues:** - java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "png\_set\_longjmp\_fn" referenced by "liblept.so"... [\#106](https://github.com/rmtheis/tess-two/issues/106) - "'libpng.so' not found" message on some 4.x versions of Android [\#105](https://github.com/rmtheis/tess-two/issues/105) - libpng fails to build on ARMv8 [\#102](https://github.com/rmtheis/tess-two/issues/102) **Merged pull requests:** - fix 64-bit ARMv8 build [\#124](https://github.com/rmtheis/tess-two/pull/124) ([panzerfahrer](https://github.com/panzerfahrer)) - Bugfix for progress notifier [\#115](https://github.com/rmtheis/tess-two/pull/115) ([FDIM](https://github.com/FDIM)) ## [5.2.0](https://github.com/rmtheis/tess-two/tree/5.2.0) (2015-07-21) [Full Changelog](https://github.com/rmtheis/tess-two/compare/5.1.0...5.2.0) **Updates:** - Added support for using multiple training data files/languages - Tesseract 3.04 (tesseract-ocr/tesseract@e8b6d6f) - Leptonica 1.72 **Fixed bugs:** - Fix finalizers [\#88](https://github.com/rmtheis/tess-two/issues/88) - WriteFile.writeImpliedFormat fails for jpegs [\#86](https://github.com/rmtheis/tess-two/issues/86) - WriteFile don't work as expected [\#25](https://github.com/rmtheis/tess-two/issues/25) **Closed issues:** - clang "atomicity.h:49: error: undefined reference to '\_\_atomic\_fetch\_add\_4''" for armeabi [\#81](https://github.com/rmtheis/tess-two/issues/81) - Android \(ART\) crash with error JNI DETECTED ERROR IN APPLICATION: jarray is an invalid stack indirect reference table or invalid reference [\#78](https://github.com/rmtheis/tess-two/issues/78) ## [5.1.0](https://github.com/rmtheis/tess-two/tree/5.1.0) (2015-03-16) [Full Changelog](https://github.com/rmtheis/tess-two/compare/5.0.0...5.1.0) **Updates:** - Added 64-bit ABI support - Tesseract 3.04 (tesseract-ocr/tesseract@239f350) **Added to Tesseract API:** - ProgressNotifier for getting OCR percent complete values - ChoiceIterator support for getting per-symbol alternatives - GetConnectedComponents **Added to Leptonica API:** - Edge.pixSobelEdgeFilter - GrayQuant.pixThresholdToBinary - Pix.clipRectangle - Pix.pixFastTophat - Pix.pixTophat - Pix.rotateOrth - Pix.scaleWithoutSharpening ## [5.0.0](https://github.com/rmtheis/tess-two/tree/5.0.0) (2014-08-13) [Full Changelog](https://github.com/rmtheis/tess-two/compare/4.0.0...5.0.0) **Updates:** - Tesseract 3.03 - Leptonica 1.71 ## [4.0.0](https://github.com/rmtheis/tess-two/tree/4.0.0) (2014-02-17) [Full Changelog](https://github.com/rmtheis/tess-two/compare/3.0.0...4.0.0) **Updates:** - Tesseract 3.03 - Leptonica 1.70 **Merged pull requests:** - Add some useful functions [\#40](https://github.com/rmtheis/tess-two/pull/40) ([ductranit](https://github.com/ductranit)) ## [3.0.0](https://github.com/rmtheis/tess-two/tree/3.0.0) (2013-01-22) [Full Changelog](https://github.com/rmtheis/tess-two/compare/2.0.0...3.0.0) **Updates:** - Tesseract 3.03 - Leptonica 1.69 ## [2.0.0](https://github.com/rmtheis/tess-two/tree/2.0.0) (2012-05-31) [Full Changelog](https://github.com/rmtheis/tess-two/compare/1.0.0...2.0.0) **Updates:** - Eyes-free project added - Tesseract 3.02 ## [1.0.0](https://github.com/rmtheis/tess-two/tree/1.0.0) (2011-11-06) - Initial release, branched from tesseract-android-tools project - Tesseract 3.01 - Leptonica 1.68 \* *This change log was generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* ================================================ FILE: COPYING ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: ISSUE_TEMPLATE.md ================================================ Summary: Steps to reproduce the issue: 1. 2. 3. Expected result: Actual result: Tess-two version: Android version: Phone/device model: Phone/device architecture (armeabi, armeabi-v7a, x86, mips, arm64-v8a, x86_64, mips64): Link to training data used: Link to image used as input: ================================================ FILE: README.md ================================================ ## NO LONGER MAINTAINED This project won't be receiving further updates or maintenance. Please consider trying one of the forks of this project such as [https://github.com/alexcohn/tess-two](https://github.com/alexcohn/tess-two). # tess-two A fork of Tesseract Tools for Android ([tesseract-android-tools][tesseract-android-tools]) that adds some additional functions. Tesseract Tools for Android is a set of Android APIs and build files for the [Tesseract OCR][tesseract-ocr] and [Leptonica][leptonica] image processing libraries. This project works with: - Tesseract 4.1 (submodule) - Leptonica 1.9 (submodule) - libjpeg 9b - libpng 1.6.25 The source code for these dependencies is included within the `tess-two/jni` folder. The `tess-two` module contains tools for compiling the Tesseract and Leptonica libraries for use on the Android platform. It provides a Java API for accessing natively-compiled Tesseract and Leptonica APIs. The `eyes-two` module contains additional image processing code copied from the [eyes-free project][eyes-free]. It includes native functions for text detection, blur detection, optical flow detection, and thresholding. Eyes-two is not needed for using the Tesseract or Leptonica APIs. The `tess-two-test` module contains instrumented unit tests for tess-two. ## Pre-requisites * Android 2.3 or higher * A v4.1 or 3.02 [trained data file][tessdata] for a language. Data files must be copied to the Android device in a subdirectory named `tessdata`. ## Usage To use tess-two from your app, edit your app module's `build.gradle` file to add tess-two as an external dependency: dependencies { implementation 'com.rmtheis:tess-two:9.1.0' } [Javadoc][javadoc] is available. ## Building If you want to modify the tess-two code, or you want to use the eyes-two module, you may build the project yourself locally. See [BUILDING.md](BUILDING.md). ## Versions Release points are tagged with [version numbers][semantic-versioning]. A change to the major version number indicates an API change making that version incompatible with previous versions. The [change log](CHANGELOG.md) shows what's new in each version. ## Support * Stack Overflow: https://stackoverflow.com/questions/tagged/tess-two * tesseract-ocr: https://groups.google.com/forum/#!forum/tesseract-ocr ## License Copyright 2011 Robert Theis Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ## See Also The Google Mobile Vision API team has made available an OCR capability that is provided to developers through the Google Play Services library: The [Mobile Vision API][mobile-vision-api] offers a simple API for OCR that currently works for Latin-based characters. [tesseract-android-tools]: https://github.com/alanv/tesseract-android-tools [Tesseract4Android]: https://github.com/adaptech-cz/Tesseract4Android [tesseract-ocr]: https://github.com/tesseract-ocr/tesseract [leptonica]: https://github.com/DanBloomberg/leptonica [eyes-free]: https://github.com/rmtheis/eyes-free [tessdata]: https://github.com/tesseract-ocr/tessdata/tree/3.04.00 [javadoc]: https://rmtheis.github.io/tess-two/javadoc/index.html [semantic-versioning]: http://semver.org [stackoverflow]: https://stackoverflow.com/ [mobile-vision-api]: https://developers.google.com/vision/ ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:4.1.1' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2' classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' } } allprojects { group = 'com.rmtheis' version = '9.1.0' repositories { google() jcenter() } } ================================================ FILE: eyes-two/.classpath ================================================ ================================================ FILE: eyes-two/.project ================================================ eyes-two com.android.ide.eclipse.adt.ResourceManagerBuilder com.android.ide.eclipse.adt.PreCompilerBuilder org.eclipse.jdt.core.javabuilder com.android.ide.eclipse.adt.ApkBuilder com.android.ide.eclipse.adt.AndroidNature org.eclipse.jdt.core.javanature ================================================ FILE: eyes-two/AndroidManifest.xml ================================================ ================================================ FILE: eyes-two/COPYING ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: eyes-two/build.gradle ================================================ apply plugin: 'com.android.library' android { compileSdkVersion 30 defaultConfig { minSdkVersion 16 targetSdkVersion 30 versionCode 1 versionName '1.0' testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" externalNativeBuild { ndkBuild { arguments "TESSERACT_BUILD_PATH=${project(':tess-two').getBuildDir().path}" } } } externalNativeBuild { ndkBuild { path "src/main/jni/Android.mk" } } lintOptions { abortOnError false } } dependencies { implementation project(':tess-two') androidTestImplementation 'androidx.test:runner:1.3.0' } ================================================ FILE: eyes-two/build.xml ================================================ ================================================ FILE: eyes-two/project.properties ================================================ # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system use, # "ant.properties", and override values to adapt the script to your # project structure. # Indicates whether an apk should be generated for each density. split.density=false # Project target. target=android-16 android.library=true android.library.reference.1=../tess-two ================================================ FILE: eyes-two/src/androidTest/java/OpticalFlowTest.java ================================================ import android.util.Log; import junit.framework.TestCase; import androidx.test.filters.SmallTest; import com.googlecode.eyesfree.opticflow.OpticalFlow; public class OpticalFlowTest extends TestCase { private static final String TAG = OpticalFlowTest.class.getSimpleName(); @SmallTest public void testInit() { OpticalFlow of = new OpticalFlow(); of.initialize(360, 240, 2); assertTrue(of != null); } } ================================================ FILE: eyes-two/src/main/AndroidManifest.xml ================================================ ================================================ FILE: eyes-two/src/main/java/com/googlecode/eyesfree/opticflow/ImageBlur.java ================================================ /* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.eyesfree.opticflow; /** * Wrapper for native image blur detection code. Modified by Alan Viverette from * Xiaotao Duan's original source. * * @author Xiaotao Duan * @author alanv@google.com (Alan Viverette) */ public class ImageBlur { static { System.loadLibrary("imageutils"); } /** * Tests if a given image is blurred or not. * * @param input An array of input pixels in YUV420SP format. * @param width The width of the input image. * @param height The height of the input image. * @return true when input image is blurred. */ public static native boolean isBlurred(byte[] input, int width, int height); /** * Computes signature of a given image. * * @param input An array of input pixels in YUV420SP format. * @param width The width of the input image. * @param height The height of the input image. * @param signatureBuffer A buffer for output signature. If it's null or not * in the right size, this buffer will be ignored and not used. * This is used to avoid GC. * @return Signature of input image. If signatureBuffer is valid, * signatureBuffer will be returned. Otherwise a new array will be * returned and can be used as signature buffer in next function * call. */ public static native int[] computeSignature( byte[] input, int width, int height, int[] signatureBuffer); /** * Computes how similar of two given images represented by their signatures. * * @return An integer from 0 to 100 is returned indicating how much * percentage of signature2 is different from signature1. */ public static native int diffSignature(int[] signature1, int[] signature2); } ================================================ FILE: eyes-two/src/main/java/com/googlecode/eyesfree/opticflow/OpticalFlow.java ================================================ /* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.eyesfree.opticflow; import android.graphics.PointF; /** * Interface to native optical flow library. * * Modified by Alan Viverette from Andrew Harp's original source. * * @author Andrew Harp * @author alanv@google.com (Alan Viverette) */ public class OpticalFlow { static { System.loadLibrary("opticalflow"); } @Override protected void finalize() { resetNative(); } public void initialize(int width, int height, int downsampleFactor) { initNative(width, height, downsampleFactor); } public void setImage(byte[] data, long timestamp) { addFrameNative(data, timestamp); } public void computeOpticalFlow() { computeFeaturesNative(true); computeFlowNative(); printInfoNative(); } public float[] getFeatures(boolean onlyReturnCorrespondingFeatures) { return getFeaturesNative(onlyReturnCorrespondingFeatures); } public PointF getAccumulatedDelta( long timestamp, float positionX, float positionY, float radius) { float[] delta = new float[2]; getAccumulatedDeltaNative(timestamp, positionX, positionY, radius, delta); return new PointF(delta[0], delta[1]); } public void addInterestRegion(int numX, int numY, int left, int top, int right, int bottom) { addInterestRegionNative(numX, numY, left, top, right, bottom); } /*********************** NATIVE METHODS *************************************/ private native void initNative(int width, int height, int downsampleFactor); private native void addFrameNative(byte[] data, long timeStamp); private native void computeFeaturesNative(boolean cachedOk); private native void computeFlowNative(); private native void printInfoNative(); private native void getAccumulatedDeltaNative( long timestamp, float positionX, float positionY, float radius, float[] delta); private native void addInterestRegionNative( int numX, int numY, float left, float top, float right, float bottom); private native float[] getFeaturesNative(boolean onlyReturnCorrespondingFeatures); private native void resetNative(); } ================================================ FILE: eyes-two/src/main/java/com/googlecode/eyesfree/textdetect/HydrogenTextDetector.java ================================================ /* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.eyesfree.textdetect; import android.os.Environment; import com.googlecode.leptonica.android.Pix; import com.googlecode.leptonica.android.Pixa; /** * @author alanv@google.com (Alan Viverette) */ @SuppressWarnings("unused") public class HydrogenTextDetector { private final long mNative; static { System.loadLibrary("lept"); System.loadLibrary("hydrogen"); } private Parameters mParams; public HydrogenTextDetector() { mNative = nativeConstructor(); mParams = new Parameters(); setParameters(mParams); } public void setSize(int width, int height) { // TODO(alanv): Set up native buffers } @Override protected void finalize() throws Throwable { try { nativeDestructor(mNative); } finally { super.finalize(); } } public void setParameters(Parameters params) { mParams = params; nativeSetParameters(mNative, mParams); } public Parameters getParameters() { return mParams; } public Pixa getTextAreas() { long nativePixa = nativeGetTextAreas(mNative); if (nativePixa == 0) { return null; } int width = nativeGetSourceWidth(mNative); int height = nativeGetSourceHeight(mNative); return new Pixa(nativePixa, width, height); } public float getSkewAngle() { return nativeGetSkewAngle(mNative); } public float[] getTextConfs() { return nativeGetTextConfs(mNative); } public Pix getSourceImage() { long nativePix = nativeGetSourceImage(mNative); if (nativePix == 0) { return null; } return new Pix(nativePix); } /** * Sets the text detection source image to be a clone of the supplied source * image. The supplied image may be recycled after calling this method. * * @param pixs The source image on which to perform text detection. */ public void setSourceImage(Pix pixs) { nativeSetSourceImage(mNative, pixs.getNativePix()); } public void detectText() { nativeDetectText(mNative); } public void clear() { nativeClear(mNative); } // ****************** // * PUBLIC CLASSES * // ****************** public class Parameters { public boolean debug; public String out_dir; // Edge-based thresholding public int edge_tile_x; public int edge_tile_y; public int edge_thresh; public int edge_avg_thresh; // Skew angle correction public boolean skew_enabled; public float skew_min_angle; public float skew_sweep_range; public float skew_sweep_delta; public int skew_sweep_reduction; public int skew_search_reduction; public float skew_search_min_delta; // Singleton filter public float single_min_aspect; public float single_max_aspect; public int single_min_area; public float single_min_density; // Quick pair filter public float pair_h_ratio; public float pair_d_ratio; public float pair_h_dist_ratio; public float pair_v_dist_ratio; public float pair_h_shared; // Cluster pair filter public int cluster_width_spacing; public float cluster_shared_edge; public float cluster_h_ratio; // Finalized cluster filter public int cluster_min_blobs; public float cluster_min_aspect; public float cluster_min_fdr; public int cluster_min_edge; public int cluster_min_edge_avg; public Parameters() { debug = false; out_dir = Environment.getExternalStorageDirectory().toString(); // Edge-based thresholding edge_tile_x = 32; edge_tile_y = 64; edge_thresh = 64; edge_avg_thresh = 4; // Skew angle correction skew_enabled = true; skew_min_angle = 1.0f; skew_sweep_range = 30.0f; skew_sweep_delta = 5.0f; skew_sweep_reduction = 8; skew_search_reduction = 4; skew_search_min_delta = 0.01f; // Singleton filter single_min_aspect = 0.1f; single_max_aspect = 4.0f; single_min_area = 4; single_min_density = 0.2f; // Quick pair filter pair_h_ratio = 1.0f; pair_d_ratio = 1.5f; pair_h_dist_ratio = 2.0f; pair_v_dist_ratio = 0.25f; pair_h_shared = 0.25f; // Cluster pair filter cluster_width_spacing = 2; cluster_shared_edge = 0.5f; cluster_h_ratio = 1.0f; // Finalized cluster filter cluster_min_blobs = 5; cluster_min_aspect = 2; cluster_min_fdr = 2.5f; cluster_min_edge = 32; cluster_min_edge_avg = 1; } } // ****************** // * NATIVE METHODS * // ****************** private static native long nativeConstructor(); private static native void nativeDestructor(long nativePtr); private static native void nativeSetParameters(long nativePtr, Parameters params); private static native long nativeGetTextAreas(long nativePtr); private static native float nativeGetSkewAngle(long nativePtr); private static native int nativeGetSourceWidth(long nativePtr); private static native int nativeGetSourceHeight(long nativePtr); private static native float[] nativeGetTextConfs(long nativePtr); private static native long nativeGetSourceImage(long nativePtr); private static native void nativeSetSourceImage(long nativePtr, long nativePix); private static native void nativeDetectText(long nativePtr); private static native void nativeClear(long nativePtr); } ================================================ FILE: eyes-two/src/main/java/com/googlecode/eyesfree/textdetect/Thresholder.java ================================================ /* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.eyesfree.textdetect; import com.googlecode.leptonica.android.Pix; /** * @author alanv@google.com (Alan Viverette) */ public class Thresholder { static { System.loadLibrary("lept"); System.loadLibrary("hydrogen"); } /* Threshold under which pixels will be pulled low */ public final static int SOBEL_THRESH = 64; public static Pix sobelEdgeThreshold(Pix pixs) { return sobelEdgeThreshold(pixs, SOBEL_THRESH); } public static Pix sobelEdgeThreshold(Pix pixs, int thresh) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); if (thresh >= 255 || thresh < 0) throw new IllegalArgumentException("Threshold must be in the range 0 <= thresh < 255"); long nativePix = nativeSobelEdgeThreshold(pixs.getNativePix(), thresh); if (nativePix == 0) throw new RuntimeException("Failed to run Sobel edge threshold on Pix"); return new Pix(nativePix); } /* Desired tile X dimension; actual size may vary */ public static final int EDGE_TILE_X = 32; /* Desired tile Y dimension; actual size may vary */ public static final int EDGE_TILE_Y = 64; /* Threshold for maximum edge, typically 32 */ public static final int EDGE_THRESH = 32; /* Threshold for average edge, typically 1 */ public static final int EDGE_AVERAGE = 1; /** * Returns a version of the image thresholded using Fisher's discriminant. * * @return a thresholded image or null on error */ public static Pix edgeAdaptiveThreshold(Pix pixs) { return edgeAdaptiveThreshold(pixs, EDGE_TILE_X, EDGE_TILE_Y, EDGE_THRESH, EDGE_AVERAGE); } public static Pix edgeAdaptiveThreshold( Pix pixs, int tileX, int tileY, int threshold, int average) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); if (tileX < 8) throw new IllegalArgumentException("Tile width must be at least 8 pixels"); if (tileY < 8) throw new IllegalArgumentException("Tile height must be at least 8 pixels"); long nativePix = nativeEdgeAdaptiveThreshold( pixs.getNativePix(), tileX, tileY, threshold, average); if (nativePix == 0) throw new RuntimeException("Failed to run Fisher adaptive threshold on Pix"); return new Pix(nativePix); } /* Desired tile X dimension; actual size may vary */ public static final int FDR_TILE_X = 48; /* Desired tile Y dimension; actual size may vary */ public static final int FDR_TILE_Y = 48; /* Fraction of the max Otsu score, typically 0.01 */ public static final float FDR_SCORE_FRACT = 0.0f; /* Threshold for Fisher's Discriminant Rate, typically 3.5 */ public static final float FDR_THRESH = 2.5f; /** * Returns a version of the image thresholded using Fisher's discriminant. * * @return a thresholded image or null on error */ public static Pix fisherAdaptiveThreshold(Pix pixs) { return fisherAdaptiveThreshold(pixs, 30, 20); } public static Pix fisherAdaptiveThreshold(Pix pixs, int numTilesX, int numTilesY) { int tileX = pixs.getWidth() / numTilesX; int tileY = pixs.getHeight() / numTilesY; return fisherAdaptiveThreshold(pixs, tileX, tileY, FDR_SCORE_FRACT, FDR_THRESH); } public static Pix fisherAdaptiveThreshold( Pix pixs, int tileX, int tileY, float scoreFract, float thresh) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); if (tileX < 8) throw new IllegalArgumentException("Tile width must be at least 8 pixels"); if (tileY < 8) throw new IllegalArgumentException("Tile height must be at least 8 pixels"); long nativePix = nativeFisherAdaptiveThreshold( pixs.getNativePix(), tileX, tileY, scoreFract, thresh); if (nativePix == 0) throw new RuntimeException("Failed to run Fisher adaptive threshold on Pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native long nativeFisherAdaptiveThreshold( long nativePix, int tileX, int tileY, float scoreFract, float thresh); private static native long nativeEdgeAdaptiveThreshold( long nativePix, int tileX, int tileY, int threshold, int average); private static native long nativeSobelEdgeThreshold(long nativePix, int threshold); } ================================================ FILE: eyes-two/src/main/jni/Android.mk ================================================ out_path := $(realpath $(NDK_OUT)) out_path := $(out_path:$(realpath $(out_path)/../../../..)%=%) TESSERACT_TOOLS_PATH := $(TESSERACT_BUILD_PATH)/$(out_path)/local PREBUILT_PATH := $(TESSERACT_TOOLS_PATH)/$(TARGET_ARCH_ABI) ROOT_PATH := $(TESSERACT_BUILD_PATH)/../.. include $(call all-subdir-makefiles) ================================================ FILE: eyes-two/src/main/jni/Application.mk ================================================ APP_ABI := armeabi-v7a x86 arm64-v8a x86_64 APP_OPTIM := release NDK_TOOLCHAIN_VERSION := clang ================================================ FILE: eyes-two/src/main/jni/common/Android.mk ================================================ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES := time_log.cpp LOCAL_CFLAGS := -Wall \ -DHAVE_MALLOC_H \ -DHAVE_PTHREAD \ -finline-functions \ -frename-registers \ -ffast-math \ -s \ -fomit-frame-pointer ifeq ($(LOG_TIME),true) LOCAL_CFLAGS += -DLOG_TIME endif LOCAL_MODULE := common include $(BUILD_STATIC_LIBRARY) ================================================ FILE: eyes-two/src/main/jni/common/time_log.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Andrew Harp #include "types.h" #include "time_log.h" #ifdef LOG_TIME // Storage for logging functionality. int32 num_time_logs = 0; LogEntry time_logs[NUM_LOGS]; int32 num_avg_entries = 0; AverageEntry avg_entries[NUM_LOGS]; float32 running_total = 0.0f; #endif ================================================ FILE: eyes-two/src/main/jni/common/time_log.h ================================================ // Copyright 2010 Google Inc. All Rights Reserved. // Author: andrewharp@google.com (Andrew Harp) // // Utility functions for performance profiling. #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_TIME_LOG_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_TIME_LOG_H_ #include #include "utils.h" #include "types.h" #ifdef LOG_TIME inline static long currentThreadTimeNanos() { struct timespec tm; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tm); return tm.tv_sec * 1000000000LL + tm.tv_nsec; } // Blend constant for running average. #define ALPHA 0.98f #define NUM_LOGS 100 struct LogEntry { const char* id; clock_t time_stamp; }; struct AverageEntry { const char* id; float32 average_duration; }; // Storage for keeping track of this frame's values. extern int32 num_time_logs; extern LogEntry time_logs[NUM_LOGS]; // Storage for keeping track of average values (each entry may not be printed // out each frame). extern AverageEntry avg_entries[NUM_LOGS]; extern int32 num_avg_entries; extern float32 running_total; // Call this at the start of a logging phase. inline static void resetTimeLog() { num_time_logs = 0; } // Log a message to be printed out when printTimeLog is called, along with the // amount of time in ms that has passed since the last call to this function. inline static void timeLog(const char* str) { if (num_time_logs >= NUM_LOGS) { LOGE("Out of log entries!"); return; } time_logs[num_time_logs].id = str; time_logs[num_time_logs].time_stamp = currentThreadTimeNanos(); ++num_time_logs; } inline static float32 blend(float32 old_val, float32 new_val) { return ALPHA * old_val + (1.0f - ALPHA) * new_val; } inline static float32 updateAverage(const char* str, const float32 new_val) { for (int32 entry_num = 0; entry_num < num_avg_entries; ++entry_num) { AverageEntry* const entry = avg_entries + entry_num; if (str == entry->id) { entry->average_duration = blend(entry->average_duration, new_val); return entry->average_duration; } } if (num_avg_entries >= NUM_LOGS) { LOGE("Too many log entries!"); } // If it wasn't there already, add it. avg_entries[num_avg_entries].id = str; avg_entries[num_avg_entries].average_duration = new_val; ++num_avg_entries; return new_val; } // Prints out all the timeLog statements in chronological order with the // interval that passed between subsequent statements. The total time between // the first and last statements is printed last. inline static void printTimeLog() { LogEntry* last_time = time_logs; for (int i = 0; i < num_time_logs; ++i) { LogEntry* this_time = time_logs + i; const float32 curr_time = (this_time->time_stamp - last_time->time_stamp) / 1000000.0f; const float32 avg_time = updateAverage(this_time->id, curr_time); LOGD("%32s: %6.2fms %6.2fms", this_time->id, curr_time, avg_time); last_time = this_time; } float32 total_time = (last_time->time_stamp - time_logs->time_stamp) / 1000000.0f; running_total = blend(running_total, total_time); LOGD("TOTAL TIME: %6.2fms %6.2fms\n", total_time, running_total); } #else inline static void resetTimeLog() {} inline static void timeLog(const char* str) {} inline static void printTimeLog() {} #endif #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_TIME_LOG_H_ ================================================ FILE: eyes-two/src/main/jni/common/types.h ================================================ // Copyright 2010 Google Inc. All Rights Reserved. // Author: andrewharp@google.com (Andrew Harp) // // This file exists to make the optical flow library more portable to different // platforms. #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_NATIVE_TYPES_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_NATIVE_TYPES_H_ //typedef unsigned char bool; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef signed char int8; typedef short int16; typedef signed int int32; typedef float float32; #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_NATIVE_TYPES_H_ ================================================ FILE: eyes-two/src/main/jni/common/utils.h ================================================ // Copyright 2009 Google Inc. All Rights Reserved. // Author: andrewharp@google.com (Andrew Harp) #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_UTILS_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_UTILS_H_ #include #include #ifdef HAVE_ARMEABI_V7A #include #include #endif #include #include "types.h" #define SAFE_DELETE(pointer) {\ if ((pointer) != NULL) {\ LOGV("Safe deleting pointer: %s", #pointer);\ delete (pointer);\ (pointer) = NULL;\ } else {\ LOGV("Pointer already null: %s", #pointer);\ }\ } #ifdef VERBOSE_LOGGING #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #else #define LOGV(...) {} #endif #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOG_TAG "goggles" #ifdef SANITY_CHECKS #define CHECK(condition, ...) {\ if (!(condition)) {\ LOGE("CHECK FAILED: (%s) @ %s:%u\n", #condition, __FILE__, __LINE__);\ LOGE(__VA_ARGS__);\ }\ } #else #define CHECK(...) {} #endif #ifdef HAVE_ARMEABI_V7A // Runtime check for NEON support. Only call on devices that support at least // armeabi-v7a. inline bool supportsNeon() { return (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0; } #endif #ifndef max #define max(a, b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(a, b) (((a) > (b)) ? (b) : (a)) #endif template inline static T square(const T a) { return a * a; } template inline static T clip(const T a, const T floor, const T ceil) { return min(ceil, max(a, floor)); } template inline static int32 floor(const T a) { return static_cast(a); } template inline static int32 ceil(const T a) { return floor(a) + 1; } template inline static bool inRange(const T a, const T min, const T max) { return (a >= min) && (a <= max); } template inline static int32 round(const float a) { return (a - (float) floor(a) > 0.5f) ? ceil(a) : floor(a); } template inline static void swap(T* const a, T* const b) { // Cache out the VALUE of what's at a. T tmp = *a; *a = *b; *b = tmp; } #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_COMMON_UTILS_H_ ================================================ FILE: eyes-two/src/main/jni/hydrogen/Android.mk ================================================ ifneq ($(TARGET_SIMULATOR),true) LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := libhydrogen LOCAL_SRC_FILES += \ src/clusterer.cpp \ src/hydrogentextdetector.cpp \ src/thresholder.cpp \ src/utilities.cpp \ src/validator.cpp LOCAL_SRC_FILES += \ jni/hydrogentextdetector.cpp \ jni/thresholder.cpp \ jni/jni.cpp LOCAL_C_INCLUDES += \ $(LOCAL_PATH)/src \ $(ROOT_PATH)/tess-two/jni/com_googlecode_leptonica_android \ $(ROOT_PATH)/leptonica/src LOCAL_LDLIBS += \ -llog LOCAL_MODULE_TAGS := optional LOCAL_PRELINK_MODULE := false LOCAL_DISABLE_FORMAT_STRING_CHECKS := true TARGET_PREBUILT_SHARED_LIBRARIES += \ $(PREBUILT_PATH)/liblept.so include $(BUILD_SHARED_LIBRARY) endif #TARGET_SIMULATOR ================================================ FILE: eyes-two/src/main/jni/hydrogen/jni/common.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TEXTDETECT_JNI_COMMON_H #define TEXTDETECT_JNI_COMMON_H #include #include #include #include #define LOG_TAG "TextDetect(native)" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__) #endif /* TEXTDETECT_JNI_COMMON_H */ ================================================ FILE: eyes-two/src/main/jni/hydrogen/jni/hydrogentextdetector.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include "hydrogentextdetector.h" #define DEBUG_MODE false #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jlong Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeConstructor( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = new HydrogenTextDetector(); return (jlong) ptr; } void Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeDestructor( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; delete ptr; } bool getBoolField(JNIEnv *env, jclass &clazz, jobject &obj, const char *field) { jfieldID fieldID = env->GetFieldID(clazz, field, "Z"); return (env->GetBooleanField(obj, fieldID) == JNI_TRUE); } int getIntField(JNIEnv *env, jclass &clazz, jobject &obj, const char *field) { jfieldID fieldID = env->GetFieldID(clazz, field, "I"); return (int) env->GetIntField(obj, fieldID); } float getFloatField(JNIEnv *env, jclass &clazz, jobject &obj, const char *field) { jfieldID fieldID = env->GetFieldID(clazz, field, "F"); return (float) env->GetFloatField(obj, fieldID); } void getStringField(JNIEnv *env, jclass &clazz, jobject &obj, const char *field, char *dst) { jfieldID fieldID = env->GetFieldID(clazz, field, "Ljava/lang/String;"); jstring str = (jstring) env->GetObjectField(obj, fieldID); if (str != NULL) { jsize len = L_MIN(env->GetStringLength(str), 254); env->GetStringUTFRegion(str, 0, len, dst); dst[len + 1] = 0; } else { dst[0] = 0; } } void Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeSetParameters( JNIEnv *env, jclass clazz, jlong nativePtr, jobject params) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; HydrogenTextDetector::TextDetectorParameters *myParams = ptr->GetMutableParameters(); jclass paramClass = env->GetObjectClass(params); getStringField(env, paramClass, params, "out_dir", myParams->out_dir); myParams->debug = getBoolField(env, paramClass, params, "debug"); myParams->edge_tile_x = getIntField(env, paramClass, params, "edge_tile_x"); myParams->edge_tile_y = getIntField(env, paramClass, params, "edge_tile_y"); myParams->edge_thresh = getIntField(env, paramClass, params, "edge_thresh"); myParams->edge_avg_thresh = getIntField(env, paramClass, params, "edge_avg_thresh"); myParams->skew_enabled = getBoolField(env, paramClass, params, "skew_enabled"); myParams->skew_min_angle = getFloatField(env, paramClass, params, "skew_min_angle"); myParams->skew_sweep_range = getFloatField(env, paramClass, params, "skew_sweep_range"); myParams->skew_sweep_delta = getFloatField(env, paramClass, params, "skew_sweep_delta"); myParams->skew_sweep_reduction = getIntField(env, paramClass, params, "skew_sweep_reduction"); myParams->skew_search_reduction = getIntField(env, paramClass, params, "skew_search_reduction"); myParams->skew_search_min_delta = getFloatField(env, paramClass, params, "skew_search_min_delta"); myParams->single_min_aspect = getFloatField(env, paramClass, params, "single_min_aspect"); myParams->single_max_aspect = getFloatField(env, paramClass, params, "single_max_aspect"); myParams->single_min_area = getIntField(env, paramClass, params, "single_min_area"); myParams->single_min_density = getFloatField(env, paramClass, params, "single_min_density"); myParams->pair_h_ratio = getFloatField(env, paramClass, params, "pair_h_ratio"); myParams->pair_d_ratio = getFloatField(env, paramClass, params, "pair_d_ratio"); myParams->pair_h_dist_ratio = getFloatField(env, paramClass, params, "pair_h_dist_ratio"); myParams->pair_v_dist_ratio = getFloatField(env, paramClass, params, "pair_v_dist_ratio"); myParams->pair_h_shared = getFloatField(env, paramClass, params, "pair_h_shared"); myParams->cluster_width_spacing = getIntField(env, paramClass, params, "cluster_width_spacing"); myParams->cluster_shared_edge = getFloatField(env, paramClass, params, "cluster_shared_edge"); myParams->cluster_h_ratio = getFloatField(env, paramClass, params, "cluster_h_ratio"); myParams->cluster_min_blobs = getIntField(env, paramClass, params, "cluster_min_blobs"); myParams->cluster_min_aspect = getFloatField(env, paramClass, params, "cluster_min_aspect"); myParams->cluster_min_fdr = getFloatField(env, paramClass, params, "cluster_min_fdr"); myParams->cluster_min_edge = getIntField(env, paramClass, params, "cluster_min_edge"); myParams->cluster_min_edge_avg = getIntField(env, paramClass, params, "cluster_min_edge_avg"); } jlong Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeGetTextAreas( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; PIXA *textAreas = ptr->GetTextAreas(); return (jlong) textAreas; } jfloat Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeGetSkewAngle( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; l_float32 skew_angle = ptr->GetSkewAngle(); return (jfloat) skew_angle; } jint Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeGetSourceWidth( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; PIX *pix = ptr->GetSourceImage(); jint h = pixGetWidth(pix); pixDestroy(&pix); return (jint) h; } jint Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeGetSourceHeight( JNIEnv *env, jclass clazz, jlong nativePtr) { //LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; PIX *pix = ptr->GetSourceImage(); jint w = pixGetHeight(pix); pixDestroy(&pix); return (jint) w; } jfloatArray Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeGetTextConfs( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; NUMA *confs = ptr->GetTextConfs(); l_int32 count = numaGetCount(confs); jfloatArray ret = env->NewFloatArray(count); l_float32 nval; jfloat jval; if (ret != NULL) { for (int i = 0; i < count; i++) { numaGetFValue(confs, i, &nval); jval = (jfloat) nval; env->SetFloatArrayRegion(ret, i, 1, &jval); } } numaDestroy(&confs); return ret; } jlong Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeGetSourceImage( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; return (jlong) ptr->GetSourceImage(); } void Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeSetSourceImage( JNIEnv *env, jclass clazz, jlong nativePtr, jlong nativePix) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; PIX *pix = (PIX *) nativePix; ptr->SetSourceImage(pix); } void Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeDetectText( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; ptr->DetectText(); } void Java_com_googlecode_eyesfree_textdetect_HydrogenTextDetector_nativeClear( JNIEnv *env, jclass clazz, jlong nativePtr) { if (DEBUG_MODE) LOGV(__FUNCTION__); HydrogenTextDetector *ptr = (HydrogenTextDetector *) nativePtr; ptr->Clear(); } #ifdef __cplusplus } #endif /* __cplusplus */ #undef DEBUG_MODE ================================================ FILE: eyes-two/src/main/jni/hydrogen/jni/jni.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("ERROR: GetEnv failed\n"); return -1; } assert(env != NULL); return JNI_VERSION_1_6; } ================================================ FILE: eyes-two/src/main/jni/hydrogen/jni/thresholder.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include "thresholder.h" #include "utilities.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jlong Java_com_googlecode_eyesfree_textdetect_Thresholder_nativeSobelEdgeThreshold(JNIEnv *env, jclass clazz, jlong nativePix, jlong threshold) { LOGV(__FUNCTION__); PIX *pixs = (PIX *) nativePix; PIX *pixd = pixThreshedSobelEdgeFilter(pixs, (l_int32) threshold); return (jlong) pixd; } jlong Java_com_googlecode_eyesfree_textdetect_Thresholder_nativeEdgeAdaptiveThreshold(JNIEnv *env, jclass clazz, jlong nativePix, jint tileX, jint tileY, jint threshold, jint average) { LOGV(__FUNCTION__); PIX *pixs = (PIX *) nativePix; PIX *pixd; if (pixEdgeAdaptiveThreshold(pixs, &pixd, (l_int32) tileX, (l_int32) tileY, (l_int32) threshold, (l_int32) average)) { return (jlong) 0; } return (jlong) pixd; } jlong Java_com_googlecode_eyesfree_textdetect_Thresholder_nativeFisherAdaptiveThreshold(JNIEnv *env, jclass clazz, jlong nativePix, jint tileX, jint tileY, jfloat scoreFract, jfloat thresh) { LOGV(__FUNCTION__); PIX *pixs = (PIX *) nativePix; PIX *pixd; if (pixFisherAdaptiveThreshold(pixs, &pixd, (l_int32) tileX, (l_int32) tileY, (l_float32) scoreFract, (l_float32) thresh)) { return (jlong) 0; } return (jlong) pixd; } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/clusterer.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "leptonica.h" #include "clusterer.h" #include "validator.h" /* Type of connected components: 4 is up/down/left/right. 8 includes diagonals */ #define CONN_COMP 8 l_int32 ConnCompValidPixa(PIX *pix8, PIX *pix, PIXA **ppixa, NUMA **pconfs, HydrogenTextDetector::TextDetectorParameters ¶ms) { l_int32 h, iszero; l_int32 x, y, xstart, ystart; l_float32 singleton_conf; PIX *pixt1, *pixt2, *pixt3, *pixt4, *pixt5; PIXA *pixa, *pixasort; NUMA *confs, *confsort; BOX *box; BOXA *boxa; L_STACK *lstack, *auxstack; PROCNAME("pixConnCompValidPixa"); if (!ppixa) return ERROR_INT("&pixa not defined", procName, 1); if (!pconfs) return ERROR_INT("&confs not defined", procName, 1); *ppixa = NULL; *pconfs = NULL; if (!pix || pixGetDepth(pix) != 1) return ERROR_INT("pixs undefined or not 1 bpp", procName, 1); pixa = pixaCreate(0); confs = numaCreate(0); pixZero(pix, &iszero); if (iszero) { *ppixa = pixa; return 0; } if ((pixt1 = pixCopy(NULL, pix)) == NULL) return ERROR_INT("pixt1 not made", procName, 1); if ((pixt2 = pixCopy(NULL, pix)) == NULL) return ERROR_INT("pixt2 not made", procName, 1); h = pixGetHeight(pix); if ((lstack = lstackCreate(h)) == NULL) return ERROR_INT("lstack not made", procName, 1); if ((auxstack = lstackCreate(0)) == NULL) return ERROR_INT("auxstack not made", procName, 1); lstack->auxstack = auxstack; if ((boxa = boxaCreate(0)) == NULL) return ERROR_INT("boxa not made", procName, 1); xstart = 0; ystart = 0; while (1) { if (!nextOnPixelInRaster(pixt1, xstart, ystart, &x, &y)) break; if ((box = pixSeedfillBB(pixt1, lstack, x, y, CONN_COMP)) == NULL) return ERROR_INT("box not made", procName, 1); /* Save the c.c. and remove from pixt2 as well */ pixt3 = pixClipRectangle(pixt1, box, NULL); pixt4 = pixClipRectangle(pixt2, box, NULL); pixt5 = pixClipRectangle(pix8, box, NULL); pixXor(pixt3, pixt3, pixt4); pixRasterop(pixt2, box->x, box->y, box->w, box->h, PIX_SRC ^ PIX_DST, pixt3, 0, 0); pixDestroy(&pixt4); if (ValidateSingleton(pixt3, box, pixt5, &singleton_conf, params)) { boxaAddBox(boxa, box, L_INSERT); pixaAddPix(pixa, pixt3, L_INSERT); numaAddNumber(confs, singleton_conf); } else { boxDestroy(&box); pixDestroy(&pixt3); } pixDestroy(&pixt5); xstart = x; ystart = y; } /* Remove old boxa of pixa and replace with a clone copy */ boxaDestroy(&pixa->boxa); pixa->boxa = boxaCopy(boxa, L_CLONE); /* Sort pixa, then destroy old pixa */ NUMA *naindex; if ((pixasort = pixaSort(pixa, L_SORT_BY_X, L_SORT_INCREASING, &naindex, L_CLONE)) == NULL) return ERROR_INT("pixasort not made", procName, 1); confsort = numaSortByIndex(confs, naindex); /* Cleanup, freeing the fillsegs on each stack */ lstackDestroy(&lstack, TRUE); pixDestroy(&pixt1); pixDestroy(&pixt2); boxaDestroy(&boxa); pixaDestroy(&pixa); *ppixa = pixasort; *pconfs = confsort; return 0; } l_int32 MergePix(PIXA *pixad, l_int32 d_idx, PIXA *pixas, l_int32 s_idx) { l_int32 op; l_int32 x, y, w, h; l_int32 dx, dy, dw, dh; PIX *pixd, *pixs, *pixmerge; BOX *boxd, *boxs, *boxmerge; PROCNAME("pixMergePix"); if (!pixad) return ERROR_INT("pixad not defined", procName, 1); if (!pixas) return ERROR_INT("pixas not defined", procName, 1); boxd = pixaGetBox(pixad, d_idx, L_CLONE); boxs = pixaGetBox(pixas, s_idx, L_CLONE); boxmerge = boxBoundingRegion(boxd, boxs); boxGetGeometry(boxmerge, &x, &y, &w, &h); pixmerge = pixCreate(w, h, 1); op = PIX_SRC | PIX_DST; pixs = pixaGetPix(pixas, s_idx, L_CLONE); if (!pixs) return ERROR_INT("s_idx not valid", procName, 1); boxGetGeometry(boxs, &dx, &dy, &dw, &dh); pixRasterop(pixmerge, dx - x, dy - y, dw, dh, op, pixs, 0, 0); pixDestroy(&pixs); boxDestroy(&boxs); pixd = pixaGetPix(pixad, d_idx, L_CLONE); if (!pixd) return ERROR_INT("d_idx not valid", procName, 1); boxGetGeometry(boxd, &dx, &dy, &dw, &dh); pixRasterop(pixmerge, dx - x, dy - y, dw, dh, op, pixd, 0, 0); pixDestroy(&pixd); boxDestroy(&boxd); pixaReplacePix(pixad, d_idx, pixmerge, boxmerge); return 0; } l_int32 MergePairFragments(PIX *pix8, PIXA *clusters, PIXA *pixa, l_uint8 *remove) { l_uint8 setj; l_int32 i, j, real_j, contains, n, count, num_clusters, initj; l_int32 xi, yi, wi, hi; l_int32 xj, yj, wj, hj; BOX *boxi, *boxj; PIXA *pixasort; NUMA *numa; PROCNAME("pixMergePairFragments"); if (!pixa) return ERROR_INT("pixa not defined", procName, -1); if (!remove) return ERROR_INT("remove not defined", procName, -1); n = pixaGetCount(pixa); num_clusters = pixaGetCount(clusters); if (!n) { L_INFO("pixa contained 0 pix", procName); return 0; } if (!num_clusters) { L_INFO("clusters contained 0 pix", procName); return 0; } if ((pixasort = pixaSort(pixa, L_SORT_BY_Y, L_SORT_INCREASING, &numa, L_CLONE)) == NULL) return ERROR_INT("failed to sort pixa", procName, -1); count = 0; initj = 0; setj = 0; for (i = 0; i < num_clusters; i++) { pixaGetBoxGeometry(clusters, i, &xi, &yi, &wi, &hi); boxi = pixaGetBox(clusters, i, L_CLONE); setj = 0; for (j = initj; j < n; j++) { numaGetIValue(numa, j, &real_j); // Only consider removed pix if (!remove[real_j]) continue; pixaGetBoxGeometry(pixasort, j, &xj, &yj, &wj, &hj); // If the top of this pix is above the top of the cluster, skip if (yj < yi) continue; if (!setj) { initj = j; setj = 1; } // If the bottom of this pix is below the bottom of the cluster, stop if (yj > yi + hi) break; boxj = pixaGetBox(pixasort, j, L_CLONE); boxIntersects(boxi, boxj, &contains); if (contains) { MergePix(clusters, i, pixasort, j); //remove[real_j] = 0; // TODO eliminates duplicates count++; } boxDestroy(&boxj); } boxDestroy(&boxi); } pixaDestroy(&pixasort); numaDestroy(&numa); return count; } l_int32 RemoveInvalidPairs(PIX *pix8, PIXA *pixa, NUMA *confs, l_uint8 *remove, HydrogenTextDetector::TextDetectorParameters ¶ms) { l_int32 i, j, n, count; l_float32 pair_conf; l_uint8 *has_partner; BOX *b1, *b2; PROCNAME("pixRemoveInvalidPairs"); if (!pixa) return ERROR_INT("pixa not defined", procName, -1); if (!remove) return ERROR_INT("remove not defined", procName, -1); n = pixaGetCount(pixa); if (!n) { L_INFO("pixa contained 0 pix", procName); return 0; } has_partner = (l_uint8 *) calloc(n, sizeof(l_uint8)); count = 0; for (i = 0; i < n; i++) { if (remove[i]) continue; b1 = pixaGetBox(pixa, i, L_CLONE); /* Search right for a partner for i */ for (j = i + 1; j < n; j++) { if (remove[j]) continue; b2 = pixaGetBox(pixa, j, L_CLONE); /* Check whether this is a valid pair */ if (!ValidatePair(b1, b2, &pair_conf, params)) { boxDestroy(&b2); continue; } // We don't need to adjust confidence values here, since we'll // generate cluster pairs and use those later. boxDestroy(&b2); has_partner[i] = 1; has_partner[j] = 1; break; } boxDestroy(&b1); } for (i = 0; i < n; i++) { if (!has_partner[i]) { remove[i] = 1; count++; } } free(has_partner); return count; } // Clustering pass l_int32 GenerateClusterPartners(PIX *pix8, PIXA *pixa, NUMA *confs, l_uint8 *remove, l_int32 **pleft, l_int32 **pright, HydrogenTextDetector::TextDetectorParameters ¶ms) { l_int32 n, i, j; l_int32 xi, yi, wi, hi, maxd; l_int32 xj, yj, wj, hj; l_int32 dx, dy, d, mind, minj; l_int32 *left, *right; l_float32 clusterpair_conf, minconf; BOX *b1, *b2; bool too_far; PROCNAME("GenerateClusterPartners"); if (!pixa) return ERROR_INT("pixa not defined", procName, -1); if (!pright) return ERROR_INT("&right not defined", procName, -1); if (!pleft) return ERROR_INT("&left not defined", procName, -1); n = pixaGetCount(pixa); if (!n) { L_INFO("pixa contained 0 pix", procName); return 0; } /* If n == 0, remove may be NULL. Since we have already checked for that, * any NULL arrays signal an error condition. */ if (!remove) return ERROR_INT("remove not defined", procName, -1); left = (l_int32 *) malloc(n * sizeof(l_int32)); right = (l_int32 *) malloc(n * sizeof(l_int32)); /* Initialize left and right arrays */ for (i = 0; i < n; i++) { left[i] = -2; right[i] = -2; } /* For each component, check all possible neighbors to find the most likely * right neighbor. If that right neighbor already has a left neighbor, insert * the component to the right of the existing neighbor and the left of the * right neighbor. */ for (i = 0; i < n; i++) { if (remove[i]) continue; pixaGetBoxGeometry(pixa, i, &xi, &yi, &wi, &hi); b1 = pixaGetBox(pixa, i, L_CLONE); mind = -1; minj = -1; maxd = L_MAX(wi, hi); minconf = 0.0; /* Search for closest right neighbor */ for (j = i + 1; j < n; j++) { if (remove[j]) continue; pixaGetBoxGeometry(pixa, j, &xj, &yj, &wj, &hj); b2 = pixaGetBox(pixa, j, L_CLONE); if (!ValidateClusterPair(b1, b2, &too_far, &clusterpair_conf, params)) { if (too_far) break; else continue; } /* calculate spacing between i and j */ dx = xj - (xi + wi); dy = (yj + hj) - (yi + hi); d = dx * dx + dy * dy; /* If we haven't found a neighbor OR we're the closest neighbor, update * i's record for most likely neighbor. */ if (mind < 0 || d < mind) { mind = d; minj = j; minconf = clusterpair_conf; } } /* If we found a valid neighbor, go ahead and use it. */ if (mind >= 0) { j = left[minj]; /* If minj already had a left neighbor, replace it with i */ // TODO(alanv): Insertion fudges the partner confidence value if (j >= 0) { left[i] = j; right[j] = i; } left[minj] = i; right[i] = minj; // Adjust confidence to reflect partner confidence l_float32 conf; numaGetFValue(confs, i, &conf); conf *= minconf; numaReplaceNumber(confs, i, conf); } } *pleft = left; *pright = right; return 0; } l_int32 MergeClusterPartners(PIX *pix8, PIXA *pixa, NUMA *confs, l_uint8 *remove, l_int32 *left, l_int32 *right, PIXA **ppixad, NUMA **pclusterconfs, HydrogenTextDetector::TextDetectorParameters ¶ms) { l_int32 n, count, i, j, temp; l_uint32 x, y, w, h; l_int32 xi, yi, wi, hi; l_int32 xj, yj, wj, hj; PIXA *pixad, *pixa_cluster; NUMA *confd, *numa_cluster; PIX *pix, *pixd, *pix_cluster; BOX *box, *boxd; PROCNAME("ClusterValidComponents"); if (!ppixad) return ERROR_INT("&pixad not defined", procName, -1); if (!pclusterconfs) return ERROR_INT("&clusterconfs not defined", procName, -1); n = pixaGetCount(pixa); pixad = pixaCreate(0); confd = numaCreate(0); *ppixad = pixad; *pclusterconfs = confd; if (!n) { L_INFO("pixa contained 0 pix", procName); return 0; } /* If n == 0, then left, right, and remove may be NULL. Since we have * already checked for that, any NULL arrays signal an error condition. */ if (!left) return ERROR_INT("left not defined", procName, -1); if (!right) return ERROR_INT("right not defined", procName, -1); if (!remove) return ERROR_INT("remove not defined", procName, -1); count = 0; /* Starting from the first component, generate a cluster by traveling * left and right as far as possible. Ignore components that have no * neighbors. */ for (i = 0; i < n; i++) { if (remove[i]) continue; if (left[i] < -1 && right[i] < -1) remove[i] = 1; if (left[i] < 0 && right[i] < 0) continue; pixa_cluster = pixaCreate(1); numa_cluster = numaCreate(1); /* We don't need to destroy this pix and box since pixa_cluster * takes ownership with L_INSERT. */ pix = pixaGetPix(pixa, i, L_CLONE); box = pixaGetBox(pixa, i, L_CLONE); pixaAddPix(pixa_cluster, pix, L_INSERT); pixaAddBox(pixa_cluster, box, L_INSERT); numaAddNumber(numa_cluster, i); boxGetGeometry(box, &xi, &yi, &wi, &hi); x = xi; y = yi; w = xi + wi; h = yi + hi; /* Move along left neighbors */ j = left[i]; left[i] = -1; while (j >= 0) { pix = pixaGetPix(pixa, j, L_CLONE); box = pixaGetBox(pixa, j, L_CLONE); pixaAddPix(pixa_cluster, pix, L_INSERT); pixaAddBox(pixa_cluster, box, L_INSERT); numaAddNumber(numa_cluster, j); boxGetGeometry(box, &xj, &yj, &wj, &hj); x = L_MIN(x, (l_uint32) xj); y = L_MIN(y, (l_uint32) yj); w = L_MAX(w, (l_uint32) (xj + wj)); h = L_MAX(h, (l_uint32) (yj + hj)); right[j] = -1; temp = left[j]; left[j] = -1; j = temp; } /* Move along right neighbors */ j = right[i]; right[i] = -1; while (j >= 0) { pix = pixaGetPix(pixa, j, L_CLONE); box = pixaGetBox(pixa, j, L_CLONE); pixaAddPix(pixa_cluster, pix, L_INSERT); pixaAddBox(pixa_cluster, box, L_INSERT); numaAddNumber(numa_cluster, j); boxGetGeometry(box, &xj, &yj, &wj, &hj); x = L_MIN(x, (l_uint32) xj); y = L_MIN(y, (l_uint32) yj); w = L_MAX(w, (l_uint32) xj + wj); h = L_MAX(h, (l_uint32) (yj + hj)); left[j] = -1; temp = right[j]; right[j] = -1; j = temp; } w = w - x; h = h - y; boxd = boxCreate(x, y, w, h); pix_cluster = pixClipRectangle(pix8, boxd, NULL); l_float32 temp_conf; l_float32 cluster_conf; /* If pixa seems valid, collapse its components to a single pix */ if (ValidateCluster(pix_cluster, pixa_cluster, boxd, &cluster_conf, params)) { l_int32 num_comps = pixaGetCount(pixa_cluster); l_float32 avg_conf = 0.0; pixd = pixCreate(w, h, 1); for (int i = 0; i < num_comps; i++) { pix = pixaGetPix(pixa_cluster, i, L_CLONE); pixaGetBoxGeometry(pixa_cluster, i, &xj, &yj, &wj, &hj); pixRasterop(pixd, xj - x, yj - y, wj, hj, PIX_PAINT, pix, 0, 0); pixDestroy(&pix); numaGetFValue(confs, i, &temp_conf); avg_conf += temp_conf; } // Adjust average confidence to reflect overall cluster confidence avg_conf /= num_comps; avg_conf *= cluster_conf; pixaAddPix(pixad, pixd, L_INSERT); pixaAddBox(pixad, boxd, L_INSERT); numaAddNumber(confd, avg_conf); count++; } else { l_int32 num_nums = numaGetCount(numa_cluster); // Otherwise, mark its components as removed for (int i = 0; i < num_nums; i++) { if (!numaGetIValue(numa_cluster, i, &temp)) { remove[temp] = 1; } } boxDestroy(&boxd); } pixDestroy(&pix_cluster); pixaDestroy(&pixa_cluster); numaDestroy(&numa_cluster); } free(left); free(right); PIXA *pixasort; NUMA *confsort; /* Sort pixa, then destroy old pixa */ NUMA *naindex; if ((pixasort = pixaSort(pixad, L_SORT_BY_Y, L_SORT_INCREASING, &naindex, L_CLONE)) == NULL) return ERROR_INT("pixasort not made", procName, 1); confsort = numaSortByIndex(confd, naindex); *ppixad = pixasort; *pclusterconfs = confsort; pixaDestroy(&pixad); numaDestroy(&confd); return count; } l_int32 ClusterValidComponents(PIX *pix8, PIXA *pixa, NUMA *confs, l_uint8 *remove, PIXA **ppixad, NUMA **pclusterconfs, HydrogenTextDetector::TextDetectorParameters ¶ms) { l_int32 *left, *right; PIXA *pixad; NUMA *clusterconfs; if (GenerateClusterPartners(pix8, pixa, confs, remove, &left, &right, params)) return -1; int count = MergeClusterPartners(pix8, pixa, confs, remove, left, right, &pixad, &clusterconfs, params); *ppixad = pixad; *pclusterconfs = clusterconfs; return count; } ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/clusterer.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HYDROGEN_CLUSTERER_H_ #define HYDROGEN_CLUSTERER_H_ #include "leptonica.h" #include "hydrogentextdetector.h" l_int32 ConnCompValidPixa(PIX *pix8, PIX *pix, PIXA **ppixa, NUMA **pconfs, HydrogenTextDetector::TextDetectorParameters ¶ms); l_int32 MergePix(PIXA *pixad, l_int32 i, PIXA *pixas, l_int32 j); l_int32 RemoveInvalidPairs(PIX *pix8, PIXA *pixa, NUMA *confs, l_uint8 *remove, HydrogenTextDetector::TextDetectorParameters ¶ms); l_int32 ClusterValidComponents(PIX *pix8, PIXA *pixa, NUMA *confs, l_uint8 *remove, PIXA **ppixad, NUMA **pconfs, HydrogenTextDetector::TextDetectorParameters ¶ms); l_int32 MergePairFragments(PIX *pix8, PIXA *clusters, PIXA *pixa, l_uint8 *remove); #endif /* HYDROGEN_CLUSTERER_H_ */ ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/hydrogentextdetector.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include "leptonica.h" #include "hydrogentextdetector.h" #include "clusterer.h" #include "thresholder.h" #include "utilities.h" HydrogenTextDetector::HydrogenTextDetector() { pixs_ = NULL; text_areas_ = NULL; text_confs_ = NULL; } HydrogenTextDetector::~HydrogenTextDetector() { Clear(); } PIXA *HydrogenTextDetector::ExtractTextRegions(PIX *pix8, PIX *edges, NUMA **pconfs) { l_int32 result; if (parameters_.debug) fprintf(stderr, "ExtractTextRegions()\n"); // TODO(alanv): More error checking for invalid arguments if (!pconfs) { return NULL; } clock_t timer = clock(); NUMA *connconfs; PIXA *conncomp; if (parameters_.debug) fprintf(stderr, "ConnCompValidPixa()\n"); result = ConnCompValidPixa(pix8, edges, &conncomp, &connconfs, parameters_); if (parameters_.debug) fprintf(stderr, "Found %d connected components\n", result); if (parameters_.debug && parameters_.out_dir[0] != '\0' && result > 0) { PIX *temp = pixaDisplayHeatmap(conncomp, pix8->w, pix8->h, connconfs); char filename[255]; sprintf(filename, "%s/%d_validsingles.jpg", parameters_.out_dir, (int) timer); pixWriteImpliedFormat(filename, temp, 85, 0); } l_int32 count = pixaGetCount(conncomp); l_uint8 *remove = (l_uint8 *) calloc(count, sizeof(l_uint8)); if (parameters_.debug) fprintf(stderr, "RemoveInvalidPairs()\n"); result = RemoveInvalidPairs(pix8, conncomp, connconfs, remove, parameters_); if (parameters_.debug) fprintf(stderr, "Removed %d invalid pairs\n", result); if (parameters_.debug && parameters_.out_dir[0] != '\0' && result > 0) { PIX *temp = pixaDisplayRandomCmapFiltered(conncomp, pix8->w, pix8->h, remove); char filename[255]; sprintf(filename, "%s/%d_validpairs.jpg", parameters_.out_dir, (int) timer); pixWriteImpliedFormat(filename, temp, 85, 0); } NUMA *clusterconfs; PIXA *clusters; if (parameters_.debug) fprintf(stderr, "ClusterValidComponents()\n"); result = ClusterValidComponents(pix8, conncomp, connconfs, remove, &clusters, &clusterconfs, parameters_); if (parameters_.debug) fprintf(stderr, "Created %d clusters\n", result); if (parameters_.debug && parameters_.out_dir[0] != '\0' && result > 0) { PIX *temp = pixaDisplayHeatmap(clusters, pix8->w, pix8->h, clusterconfs); char filename[255]; sprintf(filename, "%s/%d_validclusters.jpg", parameters_.out_dir, (int) timer); pixWriteImpliedFormat(filename, temp, 85, 0); } // Merge unused components that are contained inside the detected text areas. // This typically catches punctuation and dots over i's and j's. if (parameters_.debug) fprintf(stderr, "MergePairFragments()\n"); result = MergePairFragments(pix8, clusters, conncomp, remove); *pconfs = clusterconfs; pixaDestroy(&conncomp); free(remove); return clusters; } PIX *HydrogenTextDetector::DetectAndFixSkew(PIX *pixs) { l_float32 angle, conf; skew_angle_ = 0.0; if (!parameters_.skew_enabled) { if (parameters_.debug) fprintf(stderr, "Bypassed skew (skew detection is disabled)\n"); return pixClone(pixs); } if (pixFindSkewSweepAndSearch(pixs, &angle, &conf, parameters_.skew_sweep_reduction, parameters_.skew_search_reduction, parameters_.skew_sweep_range, parameters_.skew_sweep_delta, parameters_.skew_search_min_delta)) { if (parameters_.debug) fprintf(stderr, "Bypassed skew (failed sweep and search)\n"); return pixClone(pixs); } if (conf <= 0 || L_ABS(angle) < parameters_.skew_min_angle) { if (parameters_.debug) fprintf(stderr, "Bypassed skew (low confidence or small angle)\n"); return pixClone(pixs); } if (parameters_.debug) fprintf(stderr, "Found %f degree skew with confidence %f\n", angle, conf); // The detected angle is the one required to align the text, // which is the opposite of the angle of the text itself. skew_angle_ = -angle; l_float32 deg2rad = 3.1415926535 / 180.0; l_float32 radians = angle * deg2rad; PIX *pixd = pixRotate(pixs, radians, L_ROTATE_SAMPLING, L_BRING_IN_WHITE, 0, 0); return pixd; } void HydrogenTextDetector::SetSourceImage(PIX *pixs) { pixs_ = pixClone(pixs); } void HydrogenTextDetector::DetectText() { if (parameters_.debug) fprintf(stderr, "DetectText()\n"); clock_t timer = clock(); PIX *pix8 = pixConvertTo8(pixs_, false); if (parameters_.debug && parameters_.out_dir[0] != '\0') { char filename[255]; sprintf(filename, "%s/%d_input.jpg", parameters_.out_dir, (int) timer); pixWriteImpliedFormat(filename, pix8, 85, 0); } PIX *edges; pixEdgeAdaptiveThreshold(pix8, &edges, parameters_.edge_tile_x, parameters_.edge_tile_y, parameters_.edge_thresh, parameters_.edge_avg_thresh); if (parameters_.debug && parameters_.out_dir[0] != '\0') { char filename[255]; sprintf(filename, "%s/%d_edges.jpg", parameters_.out_dir, (int) timer); PIX *edges8 = pixConvertTo8(edges, false); pixWriteImpliedFormat(filename, edges8, 85, 0); pixDestroy(&edges8); } PIX *deskew = DetectAndFixSkew(edges); pixDestroy(&edges); if (parameters_.debug && parameters_.out_dir[0] != '\0') { char filename[255]; sprintf(filename, "%s/%d_deskew.jpg", parameters_.out_dir, (int) timer); PIX *deskew8 = pixConvertTo8(deskew, false); pixWriteImpliedFormat(filename, deskew8, 85, 0); pixDestroy(&deskew8); } NUMA *confs; PIXA *clusters = ExtractTextRegions(pix8, deskew, &confs); if (parameters_.debug) fprintf(stderr, "Inverting image...\n"); pixInvert(deskew, deskew); NUMA *invconfs; PIXA *invclusters = ExtractTextRegions(pix8, deskew, &invconfs); pixDestroy(&deskew); pixDestroy(&pix8); pixaJoin(clusters, invclusters, 0, 0); pixaDestroy(&invclusters); numaJoin(confs, invconfs); numaDestroy(&invconfs); text_areas_ = pixaCopy(clusters, L_CLONE); pixaDestroy(&clusters); text_confs_ = numaClone(confs); numaDestroy(&confs); if (parameters_.debug && parameters_.out_dir[0] != '\0') { PIX *temp = pixaDisplayHeatmap(text_areas_, pixs_->w, pixs_->h, text_confs_); char filename[255]; sprintf(filename, "%s/heatmap.jpg", parameters_.out_dir); pixWriteImpliedFormat(filename, temp, 85, 0); } } void HydrogenTextDetector::Clear() { if (text_confs_) { numaDestroy(&text_confs_); } if (text_areas_) { pixaDestroy(&text_areas_); } if (pixs_) { pixDestroy(&pixs_); } } PIXA *HydrogenTextDetector::GetTextAreas() { return pixaCopy(text_areas_, L_CLONE); } l_float32 HydrogenTextDetector::GetSkewAngle() { return skew_angle_; } NUMA *HydrogenTextDetector::GetTextConfs() { return numaClone(text_confs_); } PIX *HydrogenTextDetector::GetSourceImage() { return pixClone(pixs_); } HydrogenTextDetector::TextDetectorParameters *HydrogenTextDetector::GetMutableParameters() { return ¶meters_; } ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/hydrogentextdetector.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HYDROGEN_HYDROGENTEXTDETECTOR_H_ #define HYDROGEN_HYDROGENTEXTDETECTOR_H_ #include "leptonica.h" class HydrogenTextDetector { public: HydrogenTextDetector(); ~HydrogenTextDetector(); struct TextDetectorParameters { bool debug; char out_dir[255]; // Edge-based thresholding l_int32 edge_tile_x; l_int32 edge_tile_y; l_int32 edge_thresh; l_int32 edge_avg_thresh; // Skew angle correction bool skew_enabled; l_float32 skew_min_angle; l_float32 skew_sweep_range; l_float32 skew_sweep_delta; l_int32 skew_sweep_reduction; l_int32 skew_search_reduction; l_float32 skew_search_min_delta; // Singleton filter l_float32 single_min_aspect; l_float32 single_max_aspect; l_int32 single_min_area; l_float32 single_min_density; // Quick pair filter l_float32 pair_h_ratio; l_float32 pair_d_ratio; l_float32 pair_h_dist_ratio; l_float32 pair_v_dist_ratio; l_float32 pair_h_shared; // Cluster pair filter l_int32 cluster_width_spacing; l_float32 cluster_shared_edge; l_float32 cluster_h_ratio; // Finalized cluster filter l_int32 cluster_min_blobs; l_float32 cluster_min_aspect; l_float32 cluster_min_fdr; l_int32 cluster_min_edge; l_int32 cluster_min_edge_avg; TextDetectorParameters() : debug(false), edge_tile_x(32), edge_tile_y(64), edge_thresh(64), edge_avg_thresh(4), skew_enabled(true), skew_min_angle(1.0), skew_sweep_range(30.0), skew_sweep_delta(5.0), skew_sweep_reduction(8), skew_search_reduction(4), skew_search_min_delta(0.01), single_min_aspect(0.1), single_max_aspect(4.0), single_min_area(4), single_min_density(0.2), pair_h_ratio(1.0), pair_d_ratio(1.5), pair_h_dist_ratio(2.0), pair_v_dist_ratio(0.25), pair_h_shared(0.25), cluster_width_spacing(2), cluster_shared_edge(0.5), cluster_h_ratio(1.0), cluster_min_blobs(5), cluster_min_aspect(2), cluster_min_fdr(2.5), cluster_min_edge(32), cluster_min_edge_avg(1) { } }; // Function to set the original source image void SetSourceImage(PIX *); // Main text detection function void DetectText(); // Clear recognition results between calls void Clear(); // Function to return text area clippings of the original image PIXA *GetImageAreas(); // Function to return binarized text areas PIXA *GetTextAreas(); // Function to return text area confidences NUMA *GetTextConfs(); // Function to return detected skew angle l_float32 GetSkewAngle(); // Function to return the original source image PIX *GetSourceImage(); TextDetectorParameters *GetMutableParameters(); private: TextDetectorParameters parameters_; // Source image PIX *pixs_; // Detected text areas PIXA *text_areas_; // Confidences of detected text areas NUMA *text_confs_; // Detected skew angle l_float32 skew_angle_; // Function to extract text areas from a PIX PIXA *ExtractTextRegions(PIX *pix8, PIX *edges, NUMA **pconfs); // Function to detect and fix text skew PIX *DetectAndFixSkew(PIX *pixs); }; #endif /* HYDROGEN_HYDROGENTEXTDETECTOR_H_ */ ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/leptonica.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HYDROGEN_LEPTONICA_H_ #define HYDROGEN_LEPTONICA_H_ #include "allheaders.h" #endif /* HYDROGEN_LEPTONICA_H_ */ ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/thresholder.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "leptonica.h" #include "thresholder.h" /*! * pixFisherAdaptiveThreshold() * * Input: pixs (8 bpp) * &pixd ( thresholded input for pixs) * sx, sy (desired tile dimensions; actual size may vary) * scorefract (fraction of the max Otsu score; typ. 0.1) * fdrthresh (threshold for Fisher's Discriminant Rate; typ. 5.0) * Return: 0 if OK, 1 on error */ l_int32 pixFisherAdaptiveThreshold(PIX *pixs, PIX **ppixd, l_int32 tile_x, l_int32 tile_y, l_float32 score_fract, l_float32 thresh) { l_float32 fdr; l_int32 w, h, d, nx, ny, x, y, t; PIX *pixb, *pixd, *pixt; PIXTILING *pt; PROCNAME("pixFisherAdaptiveThreshold"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!ppixd) return ERROR_INT("&ppixd not defined", procName, 1); pixGetDimensions(pixs, &w, &h, &d); if (d != 8) return ERROR_INT("pixs not 8 bpp", procName, 1); if (tile_x < 8 || tile_y < 8) return ERROR_INT("sx and sy must be >= 8", procName, 1); /* Compute FDR & threshold for individual tiles */ nx = L_MAX(1, w / tile_x); ny = L_MAX(1, h / tile_y); pt = pixTilingCreate(pixs, nx, ny, 0, 0, 0, 0); pixd = pixCreate(w, h, 1); for (y = 0; y < ny; y++) { for (x = 0; x < nx; x++) { pixt = pixTilingGetTile(pt, y, x); pixGetFisherThresh(pixt, score_fract, &fdr, &t); if (fdr > thresh) { pixb = pixThresholdToBinary(pixt, t); pixTilingPaintTile(pixd, y, x, pixb, pt); pixDestroy(&pixb); } pixDestroy(&pixt); } } pixTilingDestroy(&pt); *ppixd = pixd; return 0; } /*! * pixGetFisherThresh() * * Input: pixs (any depth; cmapped ok) * scorefract (fraction of the max score, used to determine * the range over which the histogram min is searched) * &xfdr ( Fisher's Discriminate Rate value) * &xthresh ( Otsu threshold value) * Return: 0 if OK, 1 on error */ l_int32 pixGetFisherThresh(PIX *pixs, l_float32 scorefract, l_float32 *pfdr, l_int32 *pthresh) { l_float32 mean1, mean2, sum, sum1, sum2, fract; l_float32 var, between, within, fdr; l_int32 thresh; NUMA *na; PROCNAME("pixGetFisherThresh"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pfdr && !pthresh) return ERROR_INT("neither &pfdr nor &pthresh defined", procName, 1); na = pixGetGrayHistogram(pixs, 1); /* Compute Otsu threshold for histogram */ numaSplitDistribution(na, scorefract, &thresh, &mean1, &mean2, &sum1, &sum2, NULL); /* Compute Fisher's Discriminant Rate if needed */ if (pfdr) { numaGetHistogramStats(na, 0.0, 1.0, NULL, NULL, NULL, &var); numaGetSum(na, &sum); /* Between-class variance = sum of weighted squared distances between-class and overall means */ fract = sum1 / sum; between = (fract * (1 - fract)) * (mean1 - mean2) * (mean1 - mean2); /* Within-class variance = difference between total variance and between-class variance */ within = var - between; /* FDR = between-class variance over within-class variance */ if (within <= 1) { fdr = between; } else { fdr = between / within; } *pfdr = fdr; } if (pthresh) *pthresh = thresh; numaDestroy(&na); return 0; } PIX *pixThreshedSobelEdgeFilter(PIX *pixs, l_int32 threshold) { l_uint8 bval, bidx; l_int32 w, h, d, i, j, wplt, wpld, gx, gy, vald; l_int32 val1, val2, val3, val4, val5, val6, val7, val8, val9; l_uint32 *datat, *linet, *datad, *lined; PIX *pixd; PROCNAME("pixThreshedSobelEdgeFilter"); if (!pixs) return (PIX *) ERROR_PTR("pixs not defined", procName, NULL); pixGetDimensions(pixs, &w, &h, &d); if (d != 8) return (PIX *) ERROR_PTR("pixs not 8 bpp", procName, NULL); /* Compute filter output at each location. */ pixd = pixCreateNoInit(w, h, 1); datat = pixGetData(pixs); wplt = pixGetWpl(pixs); datad = pixGetData(pixd); wpld = pixGetWpl(pixd); val1 = val2 = val3 = val4 = val5 = 0; val6 = val7 = val8 = val9 = 0; bval = bidx = 0; for (i = 0; i < h - 1; i++) { linet = datat + i * wplt; lined = datad + i * wpld; for (j = 0; j < w - 1; j++) { if (j == 0) { /* start a new row */ val1 = GET_DATA_BYTE(linet, j); val2 = GET_DATA_BYTE(linet + wplt, j); val3 = GET_DATA_BYTE(linet + (wplt << 1), j); val4 = GET_DATA_BYTE(linet, j + 1); val5 = GET_DATA_BYTE(linet + wplt, j + 1); val6 = GET_DATA_BYTE(linet + (wplt << 1), j + 1); val7 = GET_DATA_BYTE(linet, j + 2); val8 = GET_DATA_BYTE(linet + wplt, j + 2); val9 = GET_DATA_BYTE(linet + (wplt << 1), j + 2); bval = 0; bidx = 0x80; } else { /* shift right by 1 pixel; update incrementally */ val1 = val4; val2 = val5; val3 = val6; val4 = val7; val5 = val8; val6 = val9; val7 = GET_DATA_BYTE(linet, j + 2); val8 = GET_DATA_BYTE(linet + wplt, j + 2); val9 = GET_DATA_BYTE(linet + (wplt << 1), j + 2); } bval <<= 1; bidx >>= 1; gx = val1 + (val2 << 1) + val3 - val7 - (val8 << 1) - val9; gy = val1 + (val4 << 1) + val7 - val3 - (val6 << 1) - val9; vald = L_MIN(255, L_ABS(gx) + L_ABS(gy)); /* Flip high bit if value exceeds threshold */ if (vald >= threshold) { bval |= 1; } if (bidx == 0) { SET_DATA_BYTE(lined, j / 8, bval); bval = 0; bidx = 0x80; } } } return pixd; } l_uint8 pixGradientEnergy(PIX *pixs, PIX *mask, l_float32 *penergy) { l_int32 w, h, d; l_uint8 val1, val2; l_uint32 mask1, mask2; l_int32 wpls, wplm; l_uint32 *datas, *lines; l_uint32 *datam, *linem; l_int32 total, count; PROCNAME("pixGradientEnergy"); if (!pixs) return ERROR_INT("pixs not defined", procName, -1); pixGetDimensions(pixs, &w, &h, &d); if (d != 8) return ERROR_INT("pixs not 8 bpp", procName, -1); /* Compute filter output at each location. */ datas = pixGetData(pixs); wpls = pixGetWpl(pixs); datam = pixGetData(mask); wplm = pixGetWpl(mask); total = 0; count = 1; mask1 = mask2 = 0; val1 = val2 = 0; for (int y = 0; y < h; y++) { lines = datas + y * wpls; linem = datam + y * wplm; for (int x = 0; x < w - 1; x++) { if (x == 0) { /* start a new row */ mask1 = GET_DATA_BIT(linem, x); mask2 = GET_DATA_BIT(linem, x + 1); val1 = GET_DATA_BYTE(lines, x); val2 = GET_DATA_BYTE(lines, x + 1); } else { /* shift right by 1 pixel; update incrementally */ val1 = val2; val2 = GET_DATA_BYTE(lines, x + 1); mask1 = mask2; mask2 = GET_DATA_BIT(linem, x + 1); } /* If we're on an edge, add the gradient value and increment */ if (mask1 != mask2) { total += L_ABS(val1 - val2); count += 1; } } } *penergy = total / (l_float32) count; return 0; } l_uint8 pixEdgeMax(PIX *pixs, l_int32 *pmax, l_int32 *pavg) { l_int32 w, h, d, wplt, vald; l_uint8 val1, val2, val3, val4, val5; l_uint32 *datat, *linet; l_int32 max, total; PROCNAME("pixEdgeMax"); if (!pixs) return ERROR_INT("pixs not defined", procName, -1); pixGetDimensions(pixs, &w, &h, &d); if (d != 8) return ERROR_INT("pixs not 8 bpp", procName, -1); /* Compute filter output at each location. */ datat = pixGetData(pixs); wplt = pixGetWpl(pixs); max = 0; total = 0; val1 = val2 = val3 = val4 = val5 = 0; for (int y = 0; y < h; y++) { linet = datat + y * wplt; for (int x = 0; x < w - 5; x++) { if (x == 0) { /* start a new row */ val1 = GET_DATA_BYTE(linet, x); val2 = GET_DATA_BYTE(linet, x + 1); val3 = GET_DATA_BYTE(linet, x + 2); val4 = GET_DATA_BYTE(linet, x + 3); val5 = GET_DATA_BYTE(linet, x + 4); } else { /* shift right by 1 pixel; update incrementally */ val1 = val2; val2 = val3; val3 = val4; val4 = val5; val5 = GET_DATA_BYTE(linet, x + 4); } //maxd = L_MAX(val5, L_MAX(val4, L_MAX(val3, L_MAX(val2, val1)))); //mind = L_MIN(val5, L_MIN(val4, L_MIN(val3, L_MIN(val2, val1)))); vald = L_ABS(val1 - val5); //maxd - mind; if (vald > max) { max = vald; } total += vald; } } *pmax = max; *pavg = total / (w * h); return 0; } /*! * pixEdgeAdaptiveThreshold() * * Input: pixs (8 bpp) * &pixd ( thresholded input for pixs) * tile_x, tile_y (desired tile dimensions; actual size may vary) * thresh * avg_thresh * Return: 0 if OK, 1 on error */ l_uint8 pixEdgeAdaptiveThreshold(PIX *pixs, PIX **ppixd, l_int32 tile_x, l_int32 tile_y, l_int32 thresh, l_int32 avg_thresh) { l_int32 w, h, d, nx, ny, x, y, t, max, avg; PIX *pixb, *pixd, *pixt; PIXTILING *pt; PROCNAME("pixEdgeAdaptiveThreshold"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!ppixd) return ERROR_INT("&ppixd not defined", procName, 1); pixGetDimensions(pixs, &w, &h, &d); if (d != 8) return ERROR_INT("pixs not 8 bpp", procName, 1); if (tile_x < 8 || tile_y < 8) return ERROR_INT("sx and sy must be >= 8", procName, 1); /* Compute FDR & threshold for individual tiles */ nx = L_MAX(1, w / tile_x); ny = L_MAX(1, h / tile_y); pt = pixTilingCreate(pixs, nx, ny, 0, 0, 0, 0); pixd = pixCreate(w, h, 1); for (y = 0; y < ny; y++) { for (x = 0; x < nx; x++) { pixt = pixTilingGetTile(pt, y, x); pixEdgeMax(pixt, &max, &avg); if (max > thresh && avg > avg_thresh) { pixSplitDistributionFgBg(pixt, 0.0, 1, &t, NULL, NULL, 0); pixb = pixThresholdToBinary(pixt, t); pixTilingPaintTile(pixd, y, x, pixb, pt); pixDestroy(&pixb); } pixDestroy(&pixt); } } pixTilingDestroy(&pt); *ppixd = pixd; return 0; } ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/thresholder.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HYDROGEN_THRESHOLDER_H_ #define HYDROGEN_THRESHOLDER_H_ #include "leptonica.h" l_int32 pixGetFisherThresh(PIX *pixs, l_float32 scorefract, l_float32 *pfdr, l_int32 *pthresh); l_int32 pixFisherAdaptiveThreshold(PIX *pixs, PIX **ppixd, l_int32 tile_x, l_int32 tile_y, l_float32 score_fract, l_float32 thresh); PIX *pixThreshedSobelEdgeFilter(PIX *pixs, l_int32 threshold); l_uint8 pixGradientEnergy(PIX *pixs, PIX *mask, l_float32 *pdensity); l_uint8 pixEdgeMax(PIX *pixs, l_int32 *pmax, l_int32 *pavg); l_uint8 pixEdgeAdaptiveThreshold(PIX *pixs, PIX **ppixd, l_int32 tile_x, l_int32 tile_y, l_int32 thresh, l_int32 avg_thresh); #endif /* HYDROGEN_THRESHOLDER_H_ */ ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/utilities.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* smart sharpen * PIX *edgemask = pixThreshedSobelEdgeFilter(pix8, 16, 2, L_ALL_EDGES); * PIX *enhanced = pixUnsharpMasking(pix8, UNSHARP_HALFWIDTH, UNSHARP_FRACTION); * PIX *blended = pixBlendWithGrayMask(normalized, enhanced, edgemask, 0, 0); */ #include "leptonica.h" #include "utilities.h" void numaJoin(NUMA *dst, NUMA *src) { l_int32 count = numaGetCount(src); l_float32 temp; for (int i = 0; i < count; i++) { numaGetFValue(src, i, &temp); numaAddNumber(dst, temp); } } PIX *pixaDisplayRandomCmapFiltered(PIXA *pixa, l_int32 w, l_int32 h, l_uint8 *filter) { l_int32 i, n, d, index, xb, yb, wb, hb; BOXA *boxa; PIX *pixs, *pixt, *pixd; PIXCMAP *cmap; PROCNAME("pixaDisplayRandomCmapFiltered"); if (!pixa) return (PIX *) ERROR_PTR("pixa not defined", procName, NULL); n = pixaGetCount(pixa); if (n == 0) return (PIX *) ERROR_PTR("no components", procName, NULL); /* Use the first pix in pixa to verify depth is 1 bpp */ pixs = pixaGetPix(pixa, 0, L_CLONE); d = pixGetDepth(pixs); pixDestroy(&pixs); if (d != 1) return (PIX *) ERROR_PTR("components not 1 bpp", procName, NULL); /* If w and h not input, determine the minimum size required * to contain the origin and all c.c. */ if (w == 0 || h == 0) { boxa = pixaGetBoxa(pixa, L_CLONE); boxaGetExtent(boxa, &w, &h, NULL); boxaDestroy(&boxa); } /* Set up an 8 bpp dest pix, with a colormap with 254 random colors */ if ((pixd = pixCreate(w, h, 8)) == NULL) return (PIX *) ERROR_PTR("pixd not made", procName, NULL); cmap = pixcmapCreateRandom(8, 1, 1); pixSetColormap(pixd, cmap); /* Color each component and blit it in */ for (i = 0; i < n; i++) { if (filter[i]) continue; index = 1 + (i % 254); pixaGetBoxGeometry(pixa, i, &xb, &yb, &wb, &hb); pixs = pixaGetPix(pixa, i, L_CLONE); pixt = pixConvert1To8(NULL, pixs, 0, index); pixRasterop(pixd, xb, yb, wb, hb, PIX_PAINT, pixt, 0, 0); pixDestroy(&pixs); pixDestroy(&pixt); } return pixd; } /*! * pixcmapCreateHeatmap() * * Input: d (depth of pix for this colormap; 1, 2, 4 or 8) * Return: cmap, or null on error * * Notes: * (1) Colormap shows 0 as black, 1-MAX as a range from violet to red. */ PIXCMAP * pixcmapCreateHeatmap(l_int32 d) { l_int32 nlevels, i, h, s, v; PIXCMAP *cmap; PROCNAME("pixcmapCreateHeatmap"); if (d != 1 && d != 2 && d !=4 && d != 8) return (PIXCMAP *)ERROR_PTR("d not in {1, 2, 4, 8}", procName, NULL); nlevels = 1 << d; cmap = pixcmapCreate(d); nlevels--; pixcmapAddColor(cmap, 0, 0, 0); for (i = nlevels; i > 0; i--) { h = 170 * i / nlevels; s = 255; v = 255; pixcmapAddColor(cmap, h, s, v); } pixcmapConvertHSVToRGB(cmap); return cmap; } PIX *pixaDisplayHeatmap(PIXA *pixa, l_int32 w, l_int32 h, NUMA *confs) { l_int32 i, n, d, val, xb, yb, wb, hb; l_float32 maxconf, minconf, confrange, conf; BOXA *boxa; PIX *pixs, *pixt, *pixd; PIXCMAP *cmap; PROCNAME("pixaDisplayHeatmap"); if (!pixa) return (PIX *) ERROR_PTR("pixa not defined", procName, NULL); n = pixaGetCount(pixa); if (n == 0) return (PIX *) ERROR_PTR("no components", procName, NULL); /* Use the first pix in pixa to verify depth is 1 bpp */ pixs = pixaGetPix(pixa, 0, L_CLONE); d = pixGetDepth(pixs); pixDestroy(&pixs); if (d != 1) return (PIX *) ERROR_PTR("components not 1 bpp", procName, NULL); /* If w and h not input, determine the minimum size required * to contain the origin and all c.c. */ if (w == 0 || h == 0) { boxa = pixaGetBoxa(pixa, L_CLONE); boxaGetExtent(boxa, &w, &h, NULL); boxaDestroy(&boxa); } /* Determine the confidence range */ numaGetMin(confs, &minconf, NULL); numaGetMax(confs, &maxconf, NULL); confrange = maxconf - minconf; /* Set up an 8 bpp dest pix, with a colormap with 254 random colors */ if ((pixd = pixCreate(w, h, 8)) == NULL) return (PIX *) ERROR_PTR("pixd not made", procName, NULL); cmap = pixcmapCreateHeatmap(8); pixSetColormap(pixd, cmap); /* Color each component and blit it in */ for (i = 0; i < n; i++) { numaGetFValue(confs, i, &conf); val = (l_int32) ((conf - minconf) / confrange * 254) + 1; pixaGetBoxGeometry(pixa, i, &xb, &yb, &wb, &hb); pixs = pixaGetPix(pixa, i, L_CLONE); pixt = pixConvert1To8(NULL, pixs, 0, val); pixRasterop(pixd, xb, yb, wb, hb, PIX_PAINT, pixt, 0, 0); pixDestroy(&pixs); pixDestroy(&pixt); } return pixd; } ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/utilities.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HYDROGEN_UTILITIES_H_ #define HYDROGEN_UTILITIES_H_ #include "leptonica.h" void numaJoin(NUMA *dst, NUMA *src); PIX *pixaDisplayRandomCmapFiltered(PIXA *pixa, l_int32 w, l_int32 h, l_uint8 *filter); PIX *pixaDisplayHeatmap(PIXA *pixa, l_int32 w, l_int32 h, NUMA *confs); #endif /* HYDROGEN_UTILITIES_H_ */ ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/validator.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "leptonica.h" #include "validator.h" #include "thresholder.h" #include "utilities.h" #include "hydrogentextdetector.h" l_int32 BBoxHDist(BOX *b1, BOX *b2) { return L_MAX(b1->x, b2->x) - L_MIN(b1->x + b1->w, b2->x + b2->w); } l_int32 BBoxVDist(BOX *b1, BOX *b2) { return L_MAX(b1->y, b2->y) - L_MIN(b1->y + b1->h, b2->y + b2->h); } l_float32 RelativeDiff(l_int32 v1, l_int32 v2) { return L_ABS(v1 - v2) / (L_MIN(v1, v2) + 1.0); } #define OLDPAIR_MIN_HPAIR_RATIO 0.5 #define OLDPAIR_MIN_WPAIR_RATIO 0.1 #define OLDPAIR_MAX_HDIST_RATIO 3.0 #define OLDPAIR_MAX_VDIST_RATIO 0.5 /** * Test whether b1 and b2 are close enough to be a character pair. */ bool ValidatePairOld(BOX *b1, BOX *b2) { l_int32 max_w = L_MAX(b1->w, b2->w); l_int32 centerx1 = b1->x + b1->w / 2; l_int32 centerx2 = b2->x + b2->w / 2; l_int32 h_dist = L_ABS(centerx1 - centerx2); /* Horizontal distance between centers is * less than twice the wider character */ if (h_dist > max_w * OLDPAIR_MAX_HDIST_RATIO) return false; l_int32 max_h = L_MAX(b1->h, b2->h); l_int32 centery1 = b1->y + b1->h / 2; l_int32 centery2 = b2->y + b2->h / 2; l_int32 v_dist = L_ABS(centery1 - centery2); /* Vertical distance between centers is less than 50% of the taller character */ if (v_dist > max_h * OLDPAIR_MAX_VDIST_RATIO) return false; l_int32 min_h = L_MIN(b1->h, b2->h); l_float32 h_ratio = min_h / (max_h + 1.0); /* Height ratio is between 0.5 and 2 */ if (h_ratio < OLDPAIR_MIN_HPAIR_RATIO) return false; l_int32 min_w = L_MIN(b1->w, b2->w); l_float32 w_ratio = min_w / (max_w + 1.0); /* Width ratio is between 0.1 and 10 */ if (w_ratio < OLDPAIR_MIN_WPAIR_RATIO) return false; return true; } l_float32 ComputeFDR(PIX *cc8) { l_float32 fdr; pixGetFisherThresh(cc8, 0.0, &fdr, NULL); return fdr; } l_float32 ComputeGradientEnergy(PIX *cc8, PIX *cc) { l_float32 energy; pixGradientEnergy(cc8, cc, &energy); return energy; } l_float32 ComputeCCDensity(PIX *pix) { l_int32 area = pix->w * pix->h; l_int32 pixel_count; pixCountPixels(pix, &pixel_count, NULL); return pixel_count / (l_float32) area; } l_float32 ComputeCCEdgeMax(PIX *pix8) { l_int32 max; l_int32 avg; pixEdgeMax(pix8, &max, &avg); return (l_float32) max; } l_float32 ComputeSingletonConfidence(PIX *pix, BOX *box, PIX *pix8) { l_float32 aspect_ratio = box->w / (l_float32) box->h; l_float32 density = ComputeCCDensity(pix); l_float32 gradient = ComputeGradientEnergy(pix8, pix); l_float32 edgemax = ComputeCCEdgeMax(pix8); /* Compute features for confidence */ l_float32 features[6]; features[0] = 1.0; features[1] = aspect_ratio; features[2] = aspect_ratio * aspect_ratio; features[3] = gradient; features[4] = aspect_ratio / density; features[5] = edgemax; l_float32 beta[6]; beta[0] = -3.099; beta[1] = 1.244; beta[2] = -0.1142; beta[3] = 39.86; beta[4] = -0.4005; beta[5] = 0; l_float32 confidence = 0.0; for (int i = 0; i < 6; i++) { confidence += features[i] * beta[i]; } return confidence; } bool ValidateSingleton(PIX *pix, BOX *box, PIX *pix8, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms) { l_float32 aspect_ratio = box->w / (l_float32) box->h; l_float32 density = ComputeCCDensity(pix); *pconf = 0.0; /* Aspect ratio */ if (aspect_ratio > params.single_max_aspect) return false; if (aspect_ratio < params.single_min_aspect) return false; /* Pixel density */ if (density < params.single_min_density) return false; l_int32 area = box->w * box->h; /* Area */ if (area < params.single_min_area) return false; *pconf = 1.0; //ComputeSingletonConfidence(pix, box, pix8); return true; } /** * Test whether b1 and b2 are close enough to be a character pair. */ bool ValidatePair(BOX *b1, BOX *b2, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms) { *pconf = 0.0; l_int32 max_h = L_MAX(b1->h, b2->h); l_int32 h_dist = BBoxHDist(b1, b2); l_int32 v_dist = BBoxVDist(b1, b2); l_float32 h_ratio = RelativeDiff(b1->h, b2->h); l_int32 d1 = L_MAX(b1->h, b1->w); l_int32 d2 = L_MAX(b2->h, b2->w); l_float32 d_ratio = RelativeDiff(d1, d2); /* Horizontal spacing less than 2x taller edge */ if (h_dist > params.pair_h_dist_ratio * max_h) return false; /* Must share at least 0.25x the larger vertical edge */ if (v_dist > 0 || L_ABS(v_dist) < max_h * params.pair_h_shared) return false; /* Heights must be at least 2x tolerance */ if (h_ratio > params.pair_h_ratio) return false; /* Maximum dimensions must be within 3x tolerance */ if (d_ratio > params.pair_d_ratio) return false; // TODO(alanv): Does this need to return a confidence value? *pconf = 1.0; return true; } l_float32 ComputePairNormalizedOverlapArea(BOX *b1, BOX *b2) { BOX *overlap = boxOverlapRegion(b1, b2); if (!overlap || overlap->w == 0.0 || overlap->h == 0.0) return 0.0; l_float32 area0 = overlap->w * overlap->h; l_float32 area1 = b1->w * b1->h; l_float32 area2 = b2->w * b2->h; l_float32 oarea = 2.0 * area0 / (area1 + area2); return oarea; } l_float32 ComputePairNormalizedBaselineDistance(BOX *b1, BOX *b2) { l_float32 dy = (b1->y + b1->h) - (b2->y + b2->h); l_float32 vdist = 2.0 * L_ABS(dy) / (b1->h + b2->h); return vdist; } l_float32 ComputePairNormalizedToplineDistance(BOX *b1, BOX *b2) { l_float32 dy = b1->y - b2->y; l_float32 vdist = 2.0 * L_ABS(dy) / (b1->h + b2->h); return vdist; } l_float32 ComputePairNormalizedHorizontalDistance(BOX *b1, BOX *b2) { l_float32 dx = (b1->x - b2->x) + (b1->w - b2->w) / 2.0; l_float32 hdist = 2.0 * L_ABS(dx) / (b1->w + b2->w); return hdist; } l_float32 ComputePairAreaRatio(BOX *b1, BOX *b2) { l_float32 area1 = b1->w * b1->h; l_float32 area2 = b2->w * b2->h; l_float32 ratio = L_MIN(area1, area2) / L_MAX(area1, area2); return ratio; } l_float32 ComputePairWidthRatio(BOX *b1, BOX *b2) { l_float32 ratio = L_MIN(b1->w, b2->w) / L_MAX(b1->w, b2->w); return ratio; } l_float32 ComputePairHeightRatio(BOX *b1, BOX *b2) { l_float32 ratio = L_MIN(b1->h, b2->h) / L_MAX(b1->h, b2->h); return ratio; } l_float32 ComputePairContainmentCheck(BOX *b1, BOX *b2) { l_int32 contains1, contains2; boxContains(b1, b2, &contains1); boxContains(b2, b1, &contains2); l_float32 contains = (l_float32) (contains1 || contains2); return contains; } l_float32 ComputePairConfidence(BOX *b1, BOX *b2) { l_float32 features[9]; features[0] = 1.0; features[1] = ComputePairNormalizedOverlapArea(b1, b2); features[2] = ComputePairNormalizedBaselineDistance(b1, b2); features[3] = ComputePairNormalizedToplineDistance(b1, b2); features[4] = ComputePairNormalizedHorizontalDistance(b1, b2); features[5] = ComputePairAreaRatio(b1, b2); features[6] = ComputePairWidthRatio(b1, b2); features[7] = ComputePairHeightRatio(b1, b2); features[8] = ComputePairContainmentCheck(b1, b2); l_float32 beta[9]; beta[0] = 3.987; beta[1] = -9.681; beta[2] = -5.804; beta[3] = -4.857; beta[4] = -2.906; beta[5] = -1.813; beta[6] = 3.481; beta[7] = 3.983; beta[8] = -39.24; l_float32 confidence = 0.0; for (int i = 0; i < 5; i++) { confidence += features[i] * beta[i]; } return confidence; } /** * Test whether b1 and b2 are close enough to be clustered. More relaxed constraints than ValidatePair(). */ bool ValidateClusterPair(BOX *b1, BOX *b2, bool *too_far, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms) { *pconf = 0.0; l_int32 max_d = L_MAX(b1->w, b1->h); l_float32 h_ratio = RelativeDiff(b1->h, b2->h); // If we're already too far out, quit if (b2->x > b1->x + b1->w + params.cluster_width_spacing * max_d) { *too_far = true; return false; } *too_far = false; // Must share at least 0.25x the larger vertical edge //l_int32 v_dist = BBoxVDist(b1, b2); //if (v_dist > 0 || L_ABS(v_dist) < L_MIN(min_h, max_h) * PAIR_H_SHARED) // return false; // i and j must share at least half an edge if (b2->y + b2->h * params.cluster_shared_edge < b1->y) return false; if (b1->y + b1->h * params.cluster_shared_edge < b2->y) return false; // Heights must be at least 2x tolerance if (h_ratio > params.pair_h_ratio) return false; *pconf = 1.0; //ComputePairConfidence(b1, b2); return true; } /** * Test whether a finalized cluster is valid. */ bool ValidateCluster(PIX *pix8, PIXA *pixa, BOX *box, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms) { *pconf = 0.0; l_float32 aspect = box->w / (l_float32) box->h; l_int32 count = pixaGetCount(pixa); l_float32 fdr = ComputeFDR(pix8); if (box->h < 15) return false; if (aspect < params.cluster_min_aspect) return false; if (count < params.cluster_min_blobs) return false; if (fdr < params.cluster_min_fdr) return false; /* l_int32 edge_max, edge_avg; pixEdgeMax(pix8, &edge_max, &edge_avg); if (edge_max < params.cluster_min_edge || edge_avg < params.cluster_min_edge_avg) return false; */ // TODO(alanv): Combine all of these into a confidence score, higher = better *pconf = log(fdr); //log(fdr * edge_max * edge_avg); return true; } ================================================ FILE: eyes-two/src/main/jni/hydrogen/src/validator.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HYDROGEN_VALIDATOR_H_ #define HYDROGEN_VALIDATOR_H_ #include "leptonica.h" #include "hydrogentextdetector.h" bool ValidatePairOld(BOX *b1, BOX *b2); bool ValidateSingleton(PIX *pix, BOX *box, PIX *pix8, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms); bool ValidatePair(BOX *b1, BOX *b2, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms); bool ValidateClusterPair(BOX *b1, BOX *b2, bool *too_far, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms); bool ValidateCluster(PIX *pix8, PIXA *pixa, BOX *box, l_float32 *pconf, HydrogenTextDetector::TextDetectorParameters ¶ms); #endif /* HYDROGEN_VALIDATOR_H_ */ ================================================ FILE: eyes-two/src/main/jni/imageutils/Android.mk ================================================ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := imageutils$(LIB_SUFFIX) LOCAL_SRC_FILES := blur-jni.cpp \ similar-jni.cpp \ blur.cpp \ similar.cpp ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) LOCAL_CFLAGS += -DHAVE_ARMEABI_V7A=1 -mfloat-abi=softfp -mfpu=neon LOCAL_C_INCLUDES += $(NDK_ROOT)/sources/android/cpufeatures LOCAL_STATIC_LIBRARIES += cpufeatures endif LOCAL_C_INCLUDES += $(LOCAL_PATH)/../common LOCAL_STATIC_LIBRARIES += common include $(BUILD_SHARED_LIBRARY) ================================================ FILE: eyes-two/src/main/jni/imageutils/blur-jni.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Xiaotao Duan #include #include #include #include "types.h" #include "time_log.h" #include "blur.h" #ifdef __cplusplus extern "C" { #endif JNIEXPORT jboolean JNICALL Java_com_googlecode_eyesfree_opticflow_ImageBlur_isBlurred( JNIEnv* env, jclass clazz, jbyteArray input, jint width, jint height); #ifdef __cplusplus } #endif JNIEXPORT jboolean JNICALL Java_com_googlecode_eyesfree_opticflow_ImageBlur_isBlurred( JNIEnv* env, jclass clazz, jbyteArray input, jint width, jint height) { jboolean inputCopy = JNI_FALSE; jbyte* const i = env->GetByteArrayElements(input, &inputCopy); float blur = 0; float extent = 0; resetTimeLog(); int blurred = IsBlurred(reinterpret_cast(i), width, height, &blur, &extent); timeLog("Finished image blur detection"); printTimeLog(); env->ReleaseByteArrayElements(input, i, JNI_ABORT); return blurred ? JNI_TRUE : JNI_FALSE; } ================================================ FILE: eyes-two/src/main/jni/imageutils/blur.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Xiaotao Duan // // This library contains image processing method to detect // image blurriness. // // This library is *not* thread safe because static memory is // used for performance. // // A method to detect whether a given image is blurred or not. // The algorithm is based on H. Tong, M. Li, H. Zhang, J. He, // and C. Zhang. "Blur detection for digital images using wavelet // transform". // // To achieve better performance on client side, the method // is running on four 128x128 portions which compose the 256x256 // central area of the given image. On Nexus One, average time // to process a single image is ~5 milliseconds. #include #include #include #include #include "blur.h" #include "utils.h" static const int kDecomposition = 3; static const int kThreshold = 35; static const float kMinZero = 0.05; static const int kMaximumWidth = 256; static const int kMaximumHeight = 256; static int32 _smatrix[kMaximumWidth * kMaximumHeight]; static int32 _arow[kMaximumWidth > kMaximumHeight ? kMaximumWidth : kMaximumHeight]; // Does Haar Wavelet Transformation in place on a given row of a matrix. // The matrix is in size of matrix_height * matrix_width and represented // in a linear array. Parameter offset_row indicates transformation is // performed on which row. offset_column and num_columns indicate column // range of the given row. inline void Haar1DX(int* matrix, int matrix_height, int matrix_width, int offset_row, int offset_column, int num_columns) { int32* ptr_a = _arow; int32* ptr_matrix = matrix + offset_row * matrix_width + offset_column; int half_num_columns = num_columns / 2; int32* a_tmp = ptr_a; int32* matrix_tmp = ptr_matrix; for (int j = 0; j < half_num_columns; ++j) { *a_tmp++ = (matrix_tmp[0] + matrix_tmp[1]) / 2; matrix_tmp += 2; } int32* average = ptr_a; a_tmp = ptr_a + half_num_columns; matrix_tmp = ptr_matrix; for (int j = 0; j < half_num_columns; ++j) { *a_tmp++ = *matrix_tmp - *average++; matrix_tmp += 2; } memcpy(ptr_matrix, ptr_a, sizeof(int32) * num_columns); } // Does Haar Wavelet Transformation in place on a given column of a matrix. inline void Haar1DY(int* matrix, int matrix_height, int matrix_width, int offset_column, int offset_row, int num_rows) { int32* ptr_a = _arow; int32* ptr_matrix = matrix + offset_row * matrix_width + offset_column; int half_num_rows = num_rows / 2; int two_line_width = matrix_width * 2; int32* a_tmp = ptr_a; int32* matrix_tmp = ptr_matrix; for (int j = 0; j < half_num_rows; ++j) { *a_tmp++ = (matrix_tmp[matrix_width] + matrix_tmp[0]) / 2; matrix_tmp += two_line_width; } int32* average = ptr_a; a_tmp = ptr_a + half_num_rows; matrix_tmp = ptr_matrix; for (int j = 0; j < num_rows; j += 2) { *a_tmp++ = *matrix_tmp - *average++; matrix_tmp += two_line_width; } for (int j = 0; j < num_rows; ++j) { *ptr_matrix = *ptr_a++; ptr_matrix += matrix_width; } } // Does Haar Wavelet Transformation in place for a specified area of // a matrix. The matrix size is specified by matrix_width and matrix_height. // The area on which the transformation is performed is specified by // offset_column, num_columns, offset_row and num_rows. void Haar2D(int* matrix, int matrix_height, int matrix_width, int offset_column, int num_columns, int offset_row, int num_rows) { for (int i = offset_row; i < offset_row + num_rows; ++i) { Haar1DX(matrix, matrix_height, matrix_width, i, offset_column, num_columns); } for (int i = offset_column; i < offset_column + num_columns; ++i){ Haar1DY(matrix, matrix_height, matrix_width, i, offset_row, num_rows); } } // Reads in a given matrix, does first round HWT and outputs result // matrix into target array. This function is used for optimization by // avoiding a memory copy. The input matrix has height rows and width // columns. The transformation is performed on the given area specified // by offset_column, num_columns, offset_row, num_rows. After // transformation, the output matrix has num_columns columns and // num_rows rows. void HwtFirstRound(const uint8* const data, int height, int width, int offset_column, int num_columns, int offset_row, int num_rows, int32* matrix) { int32* ptr_a = _arow; const uint8* ptr_data = data + offset_row * width + offset_column; int half_num_columns = num_columns / 2; for (int i = 0; i < num_rows; ++i) { int32* a_tmp = ptr_a; const uint8* data_tmp = ptr_data; for (int j = 0; j < half_num_columns; ++j) { *a_tmp++ = (int32) ((data_tmp[0] + data_tmp[1]) / 2); data_tmp += 2; } int32* average = ptr_a; a_tmp = ptr_a + half_num_columns; data_tmp = ptr_data; for (int j = 0; j < half_num_columns; ++j) { *a_tmp++ = *data_tmp - *average++; data_tmp += 2; } int32* ptr_matrix = matrix + i * num_columns; a_tmp = ptr_a; for (int j = 0; j < num_columns; ++j) { *ptr_matrix++ = *a_tmp++; } ptr_data += width; } // Column transformation does not involve input data. for (int i = 0; i < num_columns; ++i) { Haar1DY(matrix, num_rows, num_columns, i, 0, num_rows); } } // Returns the weight of a given point in a certain scale of a matrix // after wavelet transformation. // The point is specified by k and l which are y and x coordinate // respectively. Parameter scale tells in which scale the weight is // computed, must be 1, 2 or 3 which stands respectively for 1/2, 1/4 // and 1/8 of original size. int ComputeEdgePointWeight(int* matrix, int width, int height, int k, int l, int scale) { int r = k >> scale; int c = l >> scale; int window_row = height >> scale; int window_column = width >> scale; int v_top_right = square(matrix[r * width + c + window_column]); int v_bot_left = square(matrix[(r + window_row) * width + c]); int v_bot_right = square(matrix[(r + window_row) * width + c + window_column]); int v = sqrt(v_top_right + v_bot_left + v_bot_right); return v; } // Computes point with maximum weight for a given local window for a // given scale. // Parameter scaled_width and scaled_height define scaled image size // of a certain decomposition level. The window size is defined by // window_size. Output value k and l store row (y coordinate) and // column (x coordinate) respectively of the point with maximum weight. // The maximum weight is returned. int ComputeLocalMaximum(int* matrix, int width, int height, int scaled_width, int scaled_height, int top, int left, int window_size, int* k, int* l) { int max = -1; *k = top; *l = left; for (int i = 0; i < window_size; ++i) { for (int j = 0; j < window_size; ++j) { int r = top + i; int c = left + j; int v_top_right = abs(matrix[r * width + c + scaled_width]); int v_bot_left = abs(matrix[(r + scaled_height) * width + c]); int v_bot_right = abs(matrix[(r + scaled_height) * width + c + scaled_width]); int v = v_top_right + v_bot_left + v_bot_right; if (v > max) { max = v; *k = r; *l = c; } } } int r = *k; int c = *l; int v_top_right = square(matrix[r * width + c + scaled_width]); int v_bot_left = square(matrix[(r + scaled_height) * width + c]); int v_bot_right = square(matrix[(r + scaled_height) * width + c + scaled_width]); int v = sqrt(v_top_right + v_bot_left + v_bot_right); return v; } // Detects blurriness of a transformed matrix. // Blur confidence and extent will be returned through blur_conf // and blur_extent. 1 is returned while input matrix is blurred. int DetectBlur(int* matrix, int width, int height, float* blur_conf, float* blur_extent) { int nedge = 0; int nda = 0; int nrg = 0; int nbrg = 0; // For each scale for (int current_scale = kDecomposition; current_scale > 0; --current_scale) { int scaled_width = width >> current_scale; int scaled_height = height >> current_scale; int window_size = 16 >> current_scale; // 2, 4, 8 // For each window for (int r = 0; r + window_size < scaled_height; r += window_size) { for (int c = 0; c + window_size < scaled_width; c += window_size) { int k, l; int emax = ComputeLocalMaximum(matrix, width, height, scaled_width, scaled_height, r, c, window_size, &k, &l); if (emax > kThreshold) { int emax1, emax2, emax3; switch (current_scale) { case 1: emax1 = emax; emax2 = ComputeEdgePointWeight(matrix, width, height, k << current_scale, l << current_scale, 2); emax3 = ComputeEdgePointWeight(matrix, width, height, k << current_scale, l << current_scale, 3); break; case 2: emax1 = ComputeEdgePointWeight(matrix, width, height, k << current_scale, l << current_scale, 1); emax2 = emax; emax3 = ComputeEdgePointWeight(matrix, width, height, k << current_scale, l << current_scale, 3); break; case 3: emax1 = ComputeEdgePointWeight(matrix, width, height, k << current_scale, l << current_scale, 1); emax2 = ComputeEdgePointWeight(matrix, width, height, k << current_scale, l << current_scale, 2); emax3 = emax; break; } nedge++; if (emax1 > emax2 && emax2 > emax3) { nda++; } if (emax1 < emax2 && emax2 < emax3) { nrg++; if (emax1 < kThreshold) { nbrg++; } } if (emax2 > emax1 && emax2 > emax3) { nrg++; if (emax1 < kThreshold) { nbrg++; } } } } } } // TODO(xiaotao): No edge point at all, blurred or not? float per = nedge == 0 ? 0 : (float)nda / nedge; *blur_conf = per; *blur_extent = (float)nbrg / nrg; return per < kMinZero; } // Detects blurriness of a given portion of a luminance matrix. int IsBlurredInner(const uint8* const luminance, const int width, const int height, const int left, const int top, const int width_wanted, const int height_wanted, float* const blur, float* const extent) { int32* matrix = _smatrix; HwtFirstRound(luminance, height, width, left, width_wanted, top, height_wanted, matrix); Haar2D(matrix, height_wanted, width_wanted, 0, width_wanted >> 1, 0, height_wanted >> 1); Haar2D(matrix, height_wanted, width_wanted, 0, width_wanted >> 2, 0, height_wanted >> 2); int blurred = DetectBlur(matrix, width_wanted, height_wanted, blur, extent); return blurred; } int IsBlurred(const uint8* const luminance, const int width, const int height, float* const blur, float* const extent) { int desired_width = min(kMaximumWidth, width); int desired_height = min(kMaximumHeight, height); int left = (width - desired_width) >> 1; int top = (height - desired_height) >> 1; float conf1, extent1; int blur1 = IsBlurredInner(luminance, width, height, left, top, desired_width >> 1, desired_height >> 1, &conf1, &extent1); float conf2, extent2; int blur2 = IsBlurredInner(luminance, width, height, left + (desired_width >> 1), top, desired_width >> 1, desired_height >> 1, &conf2, &extent2); float conf3, extent3; int blur3 = IsBlurredInner(luminance, width, height, left, top + (desired_height >> 1), desired_width >> 1, desired_height >> 1, &conf3, &extent3); float conf4, extent4; int blur4 = IsBlurredInner(luminance, width, height, left + (desired_width >> 1), top + (desired_height >> 1), desired_width >> 1, desired_height >> 1, &conf4, &extent4); *blur = (conf1 + conf2 + conf3 + conf4) / 4; *extent = (extent1 + extent2 + extent3 + extent4) / 4; return *blur < kMinZero; } ================================================ FILE: eyes-two/src/main/jni/imageutils/blur.h ================================================ // Copyright 2010 Google Inc. All Rights Reserved. // Author: xiaotao@google.com (Xiaotao Duan) #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_IMAGEUTILS_BLUR_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_IMAGEUTILS_BLUR_H_ #include "types.h" #ifdef __cplusplus extern "C" { #endif // Detects whether a given luminance matrix is blurred or not. // The input matrix size if width * height. 1 is returned when // input image is blurred along with blur confidence and extent // returned through output value blur and extent. int IsBlurred(const uint8* const luminance, const int width, const int height, float* const blur, float* const extent); #ifdef __cplusplus } #endif #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_IMAGEUTILS_BLUR_H_ ================================================ FILE: eyes-two/src/main/jni/imageutils/similar-jni.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Xiaotao Duan #include #include #include #include "types.h" #include "time_log.h" #include "similar.h" #ifdef __cplusplus extern "C" { #endif JNIEXPORT jintArray JNICALL Java_com_googlecode_eyesfree_opticflow_ImageBlur_computeSignature( JNIEnv* env, jclass clazz, jbyteArray input, jint width, jint height, jintArray signatureBuffer); JNIEXPORT jint JNICALL Java_com_googlecode_eyesfree_opticflow_ImageBlur_diffSignature( JNIEnv* env, jclass clazz, jintArray signature1, jintArray signature2); #ifdef __cplusplus } #endif JNIEXPORT jintArray JNICALL Java_com_googlecode_eyesfree_opticflow_ImageBlur_computeSignature( JNIEnv* env, jclass clazz, jbyteArray input, jint width, jint height, jintArray signatureBuffer) { jboolean inputCopy = JNI_FALSE; jbyte* const i = env->GetByteArrayElements(input, &inputCopy); int sig_len = 0; resetTimeLog(); uint32_t* sig = ComputeSignature(reinterpret_cast(i), width, height, &sig_len); timeLog("Finished image signature computation"); printTimeLog(); env->ReleaseByteArrayElements(input, i, JNI_ABORT); jintArray ret = signatureBuffer; if (ret == NULL || env->GetArrayLength(ret) != sig_len) { ret = env->NewIntArray(sig_len); } jint* body = env->GetIntArrayElements(ret, 0); for (int i = 0; i < sig_len; ++i) { body[i] = sig[i]; } env->ReleaseIntArrayElements(ret, body, 0); return ret; } JNIEXPORT jint JNICALL Java_com_googlecode_eyesfree_opticflow_ImageBlur_diffSignature( JNIEnv* env, jclass clazz, jintArray signature1, jintArray signature2) { jint* sig1 = env->GetIntArrayElements(signature1, 0); jint* sig2 = env->GetIntArrayElements(signature2, 0); int size = env->GetArrayLength(signature1); int diff = Diff(sig1, sig2, size); env->ReleaseIntArrayElements(signature1, sig1, 0); env->ReleaseIntArrayElements(signature2, sig2, 0); return diff; } ================================================ FILE: eyes-two/src/main/jni/imageutils/similar.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Xiaotao Duan // // This library contains image processing method to estimate // similarity of two given images. // // This library is *not* thread safe because static memory is // used for performance. // // Two methods are provided to estimate the similarity of two // given images. ComputeSignature() is used to compute the // signature of a given image. Diff() takes two signatures // as input to compute how similar two given images are. // The algorithm is based on R. O. Stehling, M. A. Nascimento, // and A. X. Falc ̃ao. "A Compact and Efficient Image Retrieval // Approach Based on Border/Interior Pixel Classification". // // For performance consideration, 480x480 of central area of // a given image is used for signature computation. #include #include "similar.h" #include "utils.h" // How many quantized colors using to compute signature. // For performance consideration, it's specified in format of // number of left shift bits rather than color numbers directly. // e.g. kShiftColors 4 means (1 << 4 == 16) colors are used. static const int kShiftColors = 4; static const int kDesiredWidthForSignature = 480; static const int kDesiredHeightForSignature = 480; static uint8 _colors[kDesiredHeightForSignature * kDesiredWidthForSignature]; // The final signature contains both color information of // inner and outer pixels, and total pixel count at last. static uint32_t _signature[1 + (1 << kShiftColors) * 2]; uint32_t* ComputeSignatureInner(const uint8* const luminance, int width, int height, int left, int top, int desired_width, int desired_height, int* size) { int num_colors = 1 << kShiftColors; memset(_signature, 0, sizeof(int32) * num_colors * 2); // Build quantized color map for input image. For each possible lumiance // value from 0 to 255, quantize it into more coarse value. #ifdef HAVE_ARMEABI_V7A if (supportsNeon()) { for (int i = 0; i < desired_height; ++i) { uint8* ptr_colors = _colors + i * desired_width; const uint8* ptr_lumi = luminance + (i + top) * width + left; int itrs = desired_width / 8; for (int j = 0; j < itrs; ++j) { // Load 8 bytes from ptr_lumi into neon vector uint8x8_t lumix8 = vld1_u8(ptr_lumi); // Batch right shift every elements (8 - kShiftColors) bits // in the vector uint8x8_t colorx8 = vshr_n_u8(lumix8, 8 - kShiftColors); // Store above result into our own memory starting from ptr_colors vst1_u8(ptr_colors, colorx8); ptr_lumi += 8; ptr_colors += 8; } } } else { #endif int shift_bits = 8 - kShiftColors; // equals to 256/num_colors for (int i = 0; i < desired_height; ++i) { uint8* ptr_colors = &_colors[i * desired_width]; const uint8* ptr_lumi = luminance + (i + top) * width + left; for (int j = 0; j < desired_width; ++j) { *ptr_colors++ = *ptr_lumi++ >> shift_bits; } } #ifdef HAVE_ARMEABI_V7A } #endif // Go through each pixel, decide it is a inner pixel (having same // quantized color as its 4 neighbours) or an outer one (at least one of // his 4 neighbours has different color), update signature respectively. int h = desired_height - 1; int w = desired_width - 1; for (int i = 1; i < h; ++i) { uint8* ptr_colors = _colors + i * desired_width; for (int j = 1; j < w; ++j) { int inner = 0; uint8 y = ptr_colors[j]; uint8 yleft = ptr_colors[j - 1]; if (y == yleft) { uint8 yright = ptr_colors[j + 1]; if (y == yright) { uint8 yup = ptr_colors[j - desired_width]; if (y == yup) { uint8 ydown = ptr_colors[j + desired_width]; if (y == ydown) { inner = 1; } } } } _signature[inner * num_colors + y] += 1; } } *size = sizeof(_signature) / sizeof(uint32); _signature[*size - 1] = (desired_height - 2) * (desired_width - 2); return _signature; } uint32_t* ComputeSignature(const uint8* const luminance, const int width, const int height, int* size) { int desired_width = min(kDesiredWidthForSignature, width); int desired_height = min(kDesiredHeightForSignature, height); int left = (width - desired_width) >> 1; int top = (height - desired_height) >> 1; return ComputeSignatureInner(luminance, width, height, left, top, desired_width, desired_height, size); } int Diff(const int32* const signature1, const int32* const signature2, const int size) { int total = signature1[size - 1]; int diff = 0; for (int i = 0; i < size; ++i) { diff += abs(signature1[i] - signature2[i]); } return diff * 50 / total; } ================================================ FILE: eyes-two/src/main/jni/imageutils/similar.h ================================================ // Copyright 2010 Google Inc. All Rights Reserved. // Author: xiaotao@google.com (Xiaotao Duan) #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_IMAGEUTILS_SIMILAR_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_IMAGEUTILS_SIMILAR_H_ #include "types.h" #ifdef __cplusplus extern "C" { #endif // Computes signature of a given image. This signature can be used to // compute similarity of two different images. Signature is returned // and size is returned via output parameter size. uint32* ComputeSignature(const uint8* const luminance, const int width, const int height, int* size); // Returns how different two given images (represented by their signatures) // are. The input signatures must be in the same size. An integer from 0 to // 100 is returned to indicate difference percentage of signature2 // comparing against signature1. int Diff(const int32* const signature1, const int32* const signature2, const int size); #ifdef __cplusplus } #endif #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_IMAGEUTILS_SIMILAR_H_ ================================================ FILE: eyes-two/src/main/jni/opticalflow/Android.mk ================================================ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := libopticalflow LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := -Wall \ -DHAVE_MALLOC_H \ -DHAVE_PTHREAD \ -finline-functions \ -frename-registers \ -ffast-math \ -s \ -fomit-frame-pointer LOCAL_SRC_FILES := optical_flow-jni.cpp \ optical_flow.cpp \ feature_detector.cpp LOCAL_C_INCLUDES += $(LOCAL_PATH)/../common ifeq ($(LOG_TIME),true) LOCAL_CFLAGS += -DLOG_TIME endif ifeq ($(SANITY_CHECKS),true) LOCAL_CFLAGS += -DSANITY_CHECKS endif ifeq ($(VERBOSE_LOGGING),true) LOCAL_CFLAGS += -DVERBOSE_LOGGING endif ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) LOCAL_CFLAGS += -DHAVE_ARMEABI_V7A=1 -mfloat-abi=softfp -mfpu=neon LOCAL_C_INCLUDES += $(NDK_ROOT)/sources/android/cpufeatures LOCAL_STATIC_LIBRARIES += cpufeatures endif LOCAL_LDLIBS := -llog LOCAL_STATIC_LIBRARIES += common include $(BUILD_SHARED_LIBRARY) include $(NDK_ROOT)/sources/android/cpufeatures/Android.mk ================================================ FILE: eyes-two/src/main/jni/opticalflow/feature_detector.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Andrew Harp // // Various feature detecting functions. #include #include #include "utils.h" #include "time_log.h" #include "image.h" #include "feature_detector.h" // Threshold for pixels to be considered different. #define FAST_DIFF_AMOUNT 10 // How far from edge of frame to stop looking for FAST features. #define FAST_BORDER_BUFFER 20 // Minimum enforced distance between detected features. // Default #define MIN_FEATURE_DIST_NORMAL 24 // Regions selected as "interesting" (aka have annotations) can have denser // feature coverage. #define MIN_FEATURE_DIST_INTEREST 12 // How many FAST qualifying pixels must be connected to a pixel for it to be // considered a candidate feature for Harris filtering. #define MIN_NUM_CONNECTED 8 // Size of the window to integrate over for Harris filtering. // Compare to WINDOW_SIZE in optical_flow.h. #define HARRIS_WINDOW_SIZE 2 // Arbitrary parameter for how picky Harris filter is, the higher the more // discriminating. #define SENSITIVITY 0.2f namespace flow { void scoreFeatures(const Image& I_x, const Image& I_y, const int32 num_candidates, Point2D* const candidate_features) { // Score all the features for (int32 i = 0; i < num_candidates; ++i) { Point2D* const feature = candidate_features + i; feature->score = harrisFilter(I_x, I_y, feature->x, feature->y); } } // Quicksorts detected features by score and then selects them such that // they are separated by a minimum distance. int32 sortAndSelect(const int32 num_candidates, const int32 max_features, const Image& interest_map, Point2D* const candidate_features, Point2D* const final_features, Image* const best_feature_map) { qsort(candidate_features, num_candidates); #ifdef SANITY_CHECKS // Verify that the array got sorted. float32 last_score = -FLT_MAX; for (int32 i = 0; i < num_candidates; ++i) { const float32 curr_score = (candidate_features + i)->score; // Scores should be monotonically increasing. CHECK(last_score <= curr_score, "Quicksort failure! %d: %.5f > %d: %.5f", i - 1, last_score, i, curr_score); last_score = curr_score; } #endif best_feature_map->clear(false); int32 num_features = 0; for (int32 i = num_candidates - 1; i >= 0; --i) { const Point2D& candidate = candidate_features[i]; // Since features are sorted, the first 0 or less value means we can stop // looking. if (candidate.score <= 0.0f) { break; } // Lookup whether this feature is in an interest region. If so, other // features may appear closer to it than normal. const int32 distance = interest_map.getPixel(candidate.x, candidate.y) ? MIN_FEATURE_DIST_INTEREST : MIN_FEATURE_DIST_NORMAL; if (markImage(candidate.x, candidate.y, distance, best_feature_map)) { final_features[num_features] = candidate; num_features++; if (num_features >= max_features) { break; } } } return num_features; } // Walks along the given circle checking for pixels above or below the center. // Returns a score, or 0 if the feature did not pass the criteria. // // Parameters: // circle_perimeter: the circumference in pixels of the circle. // threshold: the minimum number of contiguous pixels that must be above or // below the center value. // center_ptr: the location of the center pixel in memory // offsets: the relative offsets from the center pixel of the edge pixels. inline int32 testCircle(const int32 circle_perimeter, const int32 threshold, const uint8* const center_ptr, const int32* offsets) { // Get the actual value of the center pixel for easier reference later on. const int32 center_value = static_cast(*center_ptr); // Number of total pixels to check. Have to wrap around some in case // the contiguous section is split by the array edges. const int32 num_total = circle_perimeter + threshold - 1; int32 num_above = 0; int32 above_diff = 0; int32 num_below = 0; int32 below_diff = 0; // Used to tell when this is definitely not going to meet the threshold so we // can early abort. int32 minimum_by_now = threshold - num_total + 1; // Go through every pixel along the perimeter of the circle, and then around // again a little bit. for (int32 i = 0; i < num_total; ++i) { // This should be faster than mod. const int32 perim_index = i < circle_perimeter ? i : i - circle_perimeter; // This gets the value of the current pixel along the perimeter by using // a precomputed offset. const int32 curr_value = static_cast(center_ptr[offsets[perim_index]]); const int32 difference = curr_value - center_value; if (difference > FAST_DIFF_AMOUNT) { above_diff += difference; ++num_above; num_below = 0; below_diff = 0; if (num_above >= threshold) { return above_diff; } } else if (difference < -FAST_DIFF_AMOUNT) { below_diff += difference; ++num_below; num_above = 0; above_diff = 0; if (num_below >= threshold) { return below_diff; } } else { num_above = 0; num_below = 0; above_diff = 0; below_diff = 0; } // See if there's any chance of making the threshold. if (max(num_above, num_below) < minimum_by_now) { // Didn't pass. return 0; } ++minimum_by_now; } // Didn't pass. return 0; } // Creates features in a regular grid, regardless of image contents. int32 seedFeatures(const Image& frame, const int32 num_x, const int32 num_y, const float32 left, const float32 top, const float32 right, const float32 bottom, const int32 type, Point2D* const features) { int32 num_features = 0; const float32 step_x = ((right - left) / (num_x - 1)); const float32 step_y = ((bottom - top) / (num_y - 1)); for (int32 x = 0; x < num_x; ++x) { for (int32 y = 0; y < num_y; ++y) { const int32 x_pos = x * step_x + left; const int32 y_pos = y * step_y + top; if (inRange(x_pos, 0, frame.width_less_one_) && inRange(y_pos, 0, frame.height_less_one_)) { Point2D* const feature = features + num_features; feature->x = x_pos; feature->y = y_pos; feature->type = type; ++num_features; } } } return num_features; } // Returns how likely a point in the image is to be a corner. float32 harrisFilter(const Image& I_x, const Image& I_y, const int32 x, const int32 y) { // Image gradient matrix. float32 G[] = { 0, 0, 0, 0 }; calculateG(HARRIS_WINDOW_SIZE, x, y, I_x, I_y, G); const float32 g_sum = G[0] + G[1] + G[2] + G[3]; const float32 a = G[0] / g_sum; const float32 b = G[1] / g_sum; const float32 c = G[2] / g_sum; const float32 d = G[3] / g_sum; const float32 det = a * d - b * c; const float32 trace = a + d; const float32 inner = square(trace) - 4 * det; if (inner >= 0.0f) { const float32 square_root_inner = sqrtf(inner); const float32 eig1 = (trace + square_root_inner) / 2.0f; const float32 eig2 = (trace - square_root_inner) / 2.0f; return eig1 * eig2 - SENSITIVITY * square(eig1 + eig2); } // Way negative. return -100.0f; } // FAST feature detector. int32 findFastFeatures(const Image& frame, const int32 max_num_features, Point2D* const features, Image* const best_feature_map) { /* // Reference for a circle of diameter 7. const int32 circle[] = {0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0}; const int32 circle_offset[] = {2, 3, 4, 8, 12, 14, 20, 21, 27, 28, 34, 36, 40, 44, 45, 46}; */ // Quick test of compass directions. Any length 16 circle with a break of up // to 4 pixels will have at least 3 of these 4 pixels active. static const int32 short_circle_perimeter = 4; static const int32 short_threshold = 3; static const int32 short_circle_x[] = { -3, 0, +3, 0 }; static const int32 short_circle_y[] = { 0, -3, 0, +3 }; // Precompute image offsets. int32 short_offsets[short_circle_perimeter]; for (int i = 0; i < short_circle_perimeter; ++i) { short_offsets[i] = short_circle_x[i] + short_circle_y[i] * frame.getWidth(); } // Large circle values. static const int32 full_circle_perimeter = 16; static const int32 full_threshold = 12; static const int32 full_circle_x[] = { -1, 0, +1, +2, +3, +3, +3, +2, +1, +0, -1, -2, -3, -3, -3, -2 }; static const int32 full_circle_y[] = { -3, -3, -3, -2, -1, 0, +1, +2, +3, +3, +3, +2, +1, +0, -1, -2 }; // Precompute image offsets. int32 full_offsets[full_circle_perimeter]; for (int i = 0; i < full_circle_perimeter; ++i) { full_offsets[i] = full_circle_x[i] + full_circle_y[i] * frame.getWidth(); } const int frame_width = frame.getWidth(); const int end_y = frame.getHeight() - FAST_BORDER_BUFFER; const int end_x = frame.getWidth() - FAST_BORDER_BUFFER; best_feature_map->clear(0); // Loop through once to find FAST feature clumps. for (int32 img_y = FAST_BORDER_BUFFER; img_y < end_y; ++img_y) { const uint8* curr_pixel_ptr = frame.getPixelPtrConst(FAST_BORDER_BUFFER, img_y); for (int32 img_x = FAST_BORDER_BUFFER; img_x < end_x; ++img_x) { // Only insert it if it meets the quick minimum requirements test. if (testCircle(short_circle_perimeter, short_threshold, curr_pixel_ptr, short_offsets) != 0) { // Longer test for actual feature score.. const int32 fast_score = testCircle(full_circle_perimeter, full_threshold, curr_pixel_ptr, full_offsets); // Non-zero score means the feature was found. if (fast_score != 0) { uint8* const center_ptr = best_feature_map->getPixelPtr(img_x, img_y); // Increase the feature count on this pixel and the pixels in all // 4 cardinal directions. *center_ptr += 5; *(center_ptr - 1) += 1; *(center_ptr + 1) += 1; *(center_ptr - frame_width) += 1; *(center_ptr + frame_width) += 1; } } ++curr_pixel_ptr; } // x } // y timeLog("Found FAST features"); int32 num_features = 0; // Loop through again and Harris filter pixels in the center of clumps. // We can shrink the window by 1 pixel on every side. for (int32 img_y = FAST_BORDER_BUFFER + 1; img_y < end_y - 1; ++img_y) { const int32 start_x = FAST_BORDER_BUFFER + 1; const uint8* curr_pixel_ptr = best_feature_map->getPixelPtrConst(start_x, img_y); for (int32 img_x = start_x; img_x < end_x - 1; ++img_x) { if (*curr_pixel_ptr >= MIN_NUM_CONNECTED) { Point2D* const feature = features + num_features; feature->x = img_x; feature->y = img_y; feature->score = 0; feature->type = FEATURE_FAST; ++num_features; if (num_features >= max_num_features) { return num_features; } } ++curr_pixel_ptr; } // x } // y timeLog("Filtered FAST features"); return num_features; } } // namespace flow ================================================ FILE: eyes-two/src/main/jni/opticalflow/feature_detector.h ================================================ // Copyright 2010 Google Inc. All Rights Reserved. // Author: andrewharp@google.com (Andrew Harp) #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_FEATURE_DETECTOR_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_FEATURE_DETECTOR_H_ namespace flow { // Add features along a regular grid. int32 seedFeatures(const Image& frame, const int32 num_x, const int32 num_y, const float32 left, const float32 top, const float32 right, const float32 bottom, const int32 type, Point2D* const features); // Compute the corneriness of a point in the image. float32 harrisFilter(const Image& I_x, const Image& I_y, const int32 x, const int32 y); // Scan the frame for potential features using the FAST feature detector. int32 findFastFeatures(const Image& frame, const int32 max_num_features, Point2D* const features, Image* const best_feature_map); // Score a bunch of candidate features. Assigns the scores to the input // candidate_features array entries. void scoreFeatures(const Image& I_x, const Image& I_y, const int32 num_candidates, Point2D* const candidate_features); // Copy the best features (with local non-max suppression) from // candidate_features to final_features. // Returns the number of features copied. int32 sortAndSelect(const int32 num_candidates, const int32 max_features, const Image& interest_map, Point2D* const candidate_features, Point2D* const final_features, Image* const best_feature_map); } // namespace flow #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_FEATURE_DETECTOR_H_ ================================================ FILE: eyes-two/src/main/jni/opticalflow/image.h ================================================ // Copyright 2009 Google Inc. All Rights Reserved. // Author: andrewharp@google.com (Andrew Harp) #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_IMAGE_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_IMAGE_H_ #include "optical_flow_utils.h" // TODO(andrewharp): Make this a cast to uint32 if/when we go unsigned for // operations. #define ZERO 0 #ifdef SANITY_CHECKS #define CHECK_PIXEL(IMAGE, X, Y) {\ CHECK((IMAGE)->validPixel((X), (Y)), \ "CHECK_PIXEL(%d,%d) in %dx%d image.", \ static_cast(X), static_cast(Y), \ (IMAGE)->getWidth(), (IMAGE)->getHeight());\ } #define CHECK_PIXEL_INTERP(IMAGE, X, Y) {\ CHECK((IMAGE)->validInterpPixel((X), (Y)), \ "CHECK_PIXEL_INTERP(%.2f, %.2f) in %dx%d image.", \ static_cast(X), static_cast(Y), \ (IMAGE)->getWidth(), (IMAGE)->getHeight());\ } #else #define CHECK_PIXEL(image, x, y) {} #define CHECK_PIXEL_INTERP(IMAGE, X, Y) {} #endif namespace flow { // TODO(andrewharp): Make explicit which operations support negative numbers or // struct/class types in image data (possibly create fast multi-dim array class // for data where pixel arithmetic does not make sense). // Image class optimized for working on numeric arrays as grayscale image data. // Supports other data types as a 2D array class, so long as no pixel math // operations are called (convolution, downsampling, etc). template class Image { public: Image(const int32 width, const int32 height) : width_(width), height_(height), width_less_one_(width_ - 1), height_less_one_(height_ - 1), num_pixels_(width_ * height_) { allocate(); } explicit Image(const Size& size) : width_(size.width), height_(size.height), width_less_one_(width_ - 1), height_less_one_(height_ - 1), num_pixels_(width_ * height_) { allocate(); } // Constructor that creates an image from preallocated data. // Note: The image takes ownership of the data. Image(const int32 width, const int32 height, T* const image) : width_(width), height_(height), width_less_one_(width_ - 1), height_less_one_(height_ - 1), num_pixels_(width_ * height_) { image_data_ = image; if (image_data_ == NULL) { LOGE("Can't create image with NULL data!"); } } ~Image() { free(image_data_); } inline int32 getWidth() const { return width_; } inline int32 getHeight() const { return height_; } // Bilinearly sample a value between pixels. // Values outside of the image are sampled from the nearest edge of the image. inline float32 getPixelInterp(const float32 x, const float32 y) const { // Do int32 conversion one time. const int32 floored_x = (int32) x; const int32 floored_y = (int32) y; // Note: it might be the case that the *_[min|max] values are clipped, and // these (the a b c d vals) aren't (for speed purposes), but that doesn't // matter. We'll just be blending the pixel with itself in that case anyway. const float32 b = x - floored_x; const float32 a = 1.0f - b; const float32 d = y - floored_y; const float32 c = 1.0f - d; CHECK(validInterpPixel(x, y), "x or y out of bounds! %.2f [0 - %d), %.2f [0 - %d)", x, width_less_one_, y, height_less_one_); const T* const pix_ptr = getPixelPtrConst(floored_x, floored_y); // Experimental NEON acceleration... not to be turned on until it's faster. #if FALSE #ifdef HAVE_ARMEABI_V7A if (supportsNeon()) { // Output value: // a * c * p1 + // b * c * p2 + // a * d * p3 + // b * d * p4 const float32x2_t ab = {a, b}; const float32x4_t ab_c_ab_d = vcombine_f32(vmul_n_f32(ab, c), vmul_n_f32(ab, d)); const float32x4_t p1p2p3p4 = {pix_ptr[0], pix_ptr[1], pix_ptr[width_], pix_ptr[width_ + 1]}; float32x4_t almost = vmulq_f32(ab_c_ab_d, p1p2p3p4); // Butterfly-ish sum. almost = vaddq_f32(vrev64q_f32(almost), almost); return vgetq_lane_f32(almost, 0) + vgetq_lane_f32(almost, 1); } #endif #endif // Get the pixel values surrounding this point. const T& p1 = pix_ptr[0]; const T& p2 = pix_ptr[1]; const T& p3 = pix_ptr[width_]; const T& p4 = pix_ptr[width_ + 1]; // Simple bilinear interpolation between four reference pixels. // If x is the value requested: // a b // ------- // c |p1 p2| // | x | // d |p3 p4| // ------- return c * ((a * p1) + (b * p2)) + d * ((a * p3) + (b * p4)); } // Returns true iff the pixel is in the image's boundaries. inline bool validPixel(const int32 x, const int32 y) const { return inRange(x, ZERO, width_less_one_) && inRange(y, ZERO, height_less_one_); } // Returns true iff the pixel is in the image's boundaries for interpolation // purposes. // TODO(andrewharp): check in interpolation follow-up change. inline bool validInterpPixel(const float32 x, const float32 y) const { // Exclusive of max because we can be more efficient if we don't handle // interpolating on or past the last pixel. return (x >= ZERO) && (x < width_less_one_) && (y >= ZERO) && (y < height_less_one_); } // Safe lookup with boundary enforcement. inline T getPixelClipped(const int32 x, const int32 y) const { return getPixel(clip(x, ZERO, width_less_one_), clip(y, ZERO, height_less_one_)); } // Returns a const pointer to the pixel in question. inline const T* getPixelPtrConst(const int32 x, const int32 y) const { CHECK_PIXEL(this, x, y); return image_data_ + y * width_ + x; } // Returns a pointer to the pixel in question. inline T* getPixelPtr(const int32 x, const int32 y) const { CHECK_PIXEL(this, x, y); return image_data_ + y * width_ + x; } // Fast lookup without boundary enforcement. inline const T getPixel(const int32 x, const int32 y) const { CHECK_PIXEL(this, x, y); return image_data_[y * width_ + x]; } // Fast setting without boundary enforcement. inline void setPixel(const int32 x, const int32 y, const T& val) { CHECK_PIXEL(this, x, y); image_data_[y * width_ + x] = val; } // Clears image to a single value. inline void clear(const T& val) { memset(image_data_, val, sizeof(*image_data_) * num_pixels_); } #ifdef HAVE_ARMEABI_V7A // This function does the bulk of the work. inline void downsample32ColumnsNeon(const uint8* const original, const int32 stride, const int32 orig_x) { // Divide input x offset by 4 to find output offset. const int32 new_x = orig_x >> 2; // Initial offset into top row. const uint8* offset = original + orig_x; // Sum along vertical columns. // Process 32x4 input pixels and 8x1 output pixels per iteration. for (int32 new_y = 0; new_y < height_; ++new_y) { uint16x8_t accum1 = vdupq_n_u16(0); uint16x8_t accum2 = vdupq_n_u16(0); // Go top to bottom across the four rows of input pixels that make up // this output row. for (int32 row_num = 0; row_num < 4; ++row_num) { // First 16 bytes. { // Load 32 bytes of data from current offset. const uint8x16_t curr_data1 = vld1q_u8(offset); // Pairwise add and accumulate into accum vectors (16 bit to account // for values above 255). accum1 = vpadalq_u8(accum1, curr_data1); } // Second 16 bytes. { // Load 32 bytes of data from current offset. const uint8x16_t curr_data2 = vld1q_u8(offset + 16); // Pairwise add and accumulate into accum vectors (16 bit to account // for values above 255). accum2 = vpadalq_u8(accum2, curr_data2); } // Move offset down one row. offset += stride; } // Add and widen, then divide by 16 (number of input pixels per output // pixel) and narrow data from 32 bits per pixel to 16 bpp. const uint16x4_t tmp_pix1 = vqshrn_n_u32(vpaddlq_u16(accum1), 4); const uint16x4_t tmp_pix2 = vqshrn_n_u32(vpaddlq_u16(accum2), 4); // Combine 4x1 pixel strips into 8x1 pixel strip and narrow from // 16 bits to 8 bits per pixel. const uint8x8_t allpixels = vmovn_u16(vcombine_u16(tmp_pix1, tmp_pix2)); // This points to the leftmost pixel of our 8 horizontally arranged // pixels in the destination data. uint8* const ptr_dst = getPixelPtr(new_x, new_y); // Copy all pixels from composite 8x1 vector into output strip. vst1_u8(ptr_dst, allpixels); } } // Hardware accelerated downsampling method for supported devices. // Requires that image size be a multiple of 16 pixels in each dimension, // and that downsampling be by a factor of 4. void downsampleAveragedNeon(const uint8* const original, const int32 stride) { // Hardcoded to only work on 4x downsampling. const int32 orig_width = width_ * 4; // We process 32 input pixels lengthwise at a time. // The output per pass of this loop is an 8 wide by 1 tall pixel strip. for (int32 orig_x = 0; orig_x < orig_width; orig_x += 32) { // Push it to the left enough so that it never goes out of bounds. // This will result in some extra computation on the last pass on // devices whose frame widths are not multiples of 32. downsample32ColumnsNeon(original, stride, min(orig_x, orig_width - 32)); } } #endif // Naive downsampler that reduces image size by factor by averaging pixels in // blocks of size factor x factor. void downsampleAveraged(const T* const original, const int32 stride, const int32 factor) { #ifdef HAVE_ARMEABI_V7A if (supportsNeon() && factor == 4 && (height_ % 4) == 0) { downsampleAveragedNeon(original, stride); return; } #endif const int32 pixels_per_block = factor * factor; // For every pixel in resulting image. for (int32 y = 0; y < height_; ++y) { const int32 orig_y = y * factor; const int32 y_bound = orig_y + factor; // Sum up the original pixels. for (int32 x = 0; x < width_; ++x) { const int32 orig_x = x * factor; const int32 x_bound = orig_x + factor; // Making this int32 because type U or T might overflow. int32 pixel_sum = 0; // Grab all the pixels that make up this pixel. for (int32 curr_y = orig_y; curr_y < y_bound; ++curr_y) { const T* p = original + curr_y * stride + orig_x; for (int32 curr_x = orig_x; curr_x < x_bound; ++curr_x) { pixel_sum += *p++; } } setPixel(x, y, pixel_sum / pixels_per_block); } } } // Naive downsampler that reduces image size by factor by averaging pixels in // blocks of size factor x factor. void downsampleAveraged(const Image& original, const int32 factor) { downsampleAveraged(original.getPixelPtr(0, 0), original.getWidth(), factor); } // Relatively efficient downsampling of an image by a factor of two with a // low-pass 3x3 smoothing operation thrown in. void downsampleSmoothed3x3(const Image& original) { for (int32 y = 0; y < height_; ++y) { const int32 orig_y = clip(2 * y, ZERO, original.height_less_one_); const int32 min_y = clip(orig_y - 1, ZERO, original.height_less_one_); const int32 max_y = clip(orig_y + 1, ZERO, original.height_less_one_); for (int32 x = 0; x < width_; ++x) { const int32 orig_x = clip(2 * x, ZERO, original.width_less_one_); const int32 min_x = clip(orig_x - 1, ZERO, original.width_less_one_); const int32 max_x = clip(orig_x + 1, ZERO, original.width_less_one_); // Center. int32 pixel_sum = original.getPixel(orig_x, orig_y) * 4; // Sides. pixel_sum += (original.getPixel(max_x, orig_y) + original.getPixel(min_x, orig_y) + original.getPixel(orig_x, max_y) + original.getPixel(orig_x, min_y)) * 2; // Diagonals. pixel_sum += (original.getPixel(max_x, max_y) + original.getPixel(min_x, max_y) + original.getPixel(max_x, min_y) + original.getPixel(min_x, min_y)); const int32 pixel_val = pixel_sum>>4; // 16 //LOGV("Setting %d,%d to %d", col, row, pixel_val); setPixel(x, y, pixel_val); } } } // Relatively efficient downsampling of an image by a factor of two with a // low-pass 5x5 smoothing operation thrown in. void downsampleSmoothed5x5(const Image& original) { const int32 max_x = original.width_less_one_; const int32 max_y = original.height_less_one_; // The JY Bouget paper on Lucas-Kanade recommends a // [1/16 1/4 3/8 1/4 1/16]^2 filter. // This works out to a [1 4 6 4 1]^2 / 256 array, precomputed below. static const int32 window_radius = 2; static const int32 window_size = window_radius*2 + 1; static const int32 window_weights[] = {1, 4, 6, 4,1, // 16 + 4,16,24,16,4, // 64 + 6,24,36,24,6, // 96 + 4,16,24,16,4, // 64 + 1, 4, 6, 4,1}; // 16 = 256 // We'll multiply and sum with the the whole numbers first, then divide by // the total weight to normalize at the last moment. for (int32 y = 0; y < height_; ++y) { for (int32 x = 0; x < width_; ++x) { int32 pixel_sum = 0; const int32* w = window_weights; const int32 start_x = clip((x<<1) - window_radius, ZERO, max_x); // Clip the boundaries to the size of the image. for (int32 window_y = 0; window_y < window_size; ++window_y) { const int32 start_y = clip((y<<1) - window_radius + window_y, ZERO, max_y); const T* p = original.getPixelPtrConst(start_x, start_y); for (int32 window_x = 0; window_x < window_size; ++window_x) { pixel_sum += *p++ * *w++; } } // Conversion to type T will happen here after shifting right 8 bits to // divide by 256. setPixel(x, y, pixel_sum >> 8); } } } // Optimized Scharr filter on a single pixel in the X direction. // Scharr filters are like central-difference operators, but have more // rotational symmetry in their response because they also consider the // diagonal neighbors. template inline T scharrPixelX(const Image& original, const int32 center_x, const int32 center_y) const { const int32 min_x = clip(center_x - 1, ZERO, original.width_less_one_); const int32 max_x = clip(center_x + 1, ZERO, original.width_less_one_); const int32 min_y = clip(center_y - 1, ZERO, original.height_less_one_); const int32 max_y = clip(center_y + 1, ZERO, original.height_less_one_); // Convolution loop unrolled for performance... return (3 * (original.getPixel(max_x, min_y) + original.getPixel(max_x, max_y) - original.getPixel(min_x, min_y) - original.getPixel(min_x, min_y)) + 10 * (original.getPixel(max_x, center_y) - original.getPixel(min_x, center_y))) / 32; } // Optimized Scharr filter on a single pixel in the X direction. // Scharr filters are like central-difference operators, but have more // rotational symmetry in their response because they also consider the // diagonal neighbors. template inline T scharrPixelY(const Image& original, const int32 center_x, const int32 center_y) const { const int32 min_x = clip(center_x - 1, 0, original.width_less_one_); const int32 max_x = clip(center_x + 1, 0, original.width_less_one_); const int32 min_y = clip(center_y - 1, 0, original.height_less_one_); const int32 max_y = clip(center_y + 1, 0, original.height_less_one_); // Convolution loop unrolled for performance... return (3 * (original.getPixel(min_x, max_y) + original.getPixel(max_x, max_y) - original.getPixel(min_x, min_y) - original.getPixel(max_x, min_y)) + 10 * (original.getPixel(center_x, max_y) - original.getPixel(center_x, min_y))) / 32; } // Convolve the image with a Scharr filter in the X direction. // Much faster than an equivalent generic convolution. template inline void scharrX(const Image& original) { for (int32 y = 0; y < height_; ++y) { for (int32 x = 0; x < width_; ++x) { setPixel(x, y, scharrPixelX(original, x, y)); } } } // Convolve the image with a Scharr filter in the Y direction. // Much faster than an equivalent generic convolution. template inline void scharrY(const Image& original) { for (int32 y = 0; y < height_; ++y) { for (int32 x = 0; x < width_; ++x) { setPixel(x, y, scharrPixelY(original, x, y)); } } } static inline T halfDiff(int32 first, int32 second) { return (second - first) / 2; } template void derivativeX(const Image& original) { for (int32 y = 0; y < height_; ++y) { T* const dest_row = getPixelPtr(0, y); const U* const source_row = original.getPixelPtrConst(0, y); // Compute first pixel. dest_row[0] = halfDiff(source_row[0], source_row[1]); // Last pixel. dest_row[width_less_one_] = halfDiff(source_row[width_less_one_ - 1], source_row[width_less_one_]); // All the pixels in between. const U* const source_prev_pixel = source_row - 1; const U* const source_next_pixel = source_row + 1; for (int32 x = 1; x < width_less_one_; ++x) { dest_row[x] = halfDiff(source_prev_pixel[x], source_next_pixel[x]); } } } template void derivativeY(const Image& original) { for (int32 y = 0; y < height_; ++y) { T* const dest_row = getPixelPtr(0, y); const U* const source_prev_pixel = original.getPixelPtrConst(0, max(0, y - 1)); const U* const source_next_pixel = original.getPixelPtrConst(0, min(height_less_one_, y + 1)); for (int32 x = 0; x < width_; ++x) { dest_row[x] = halfDiff(source_prev_pixel[x], source_next_pixel[x]); } } } // Generic function for convolving pixel with 3x3 filter. // Filter pixels should be in row major order. template inline T convolvePixel3x3(const Image& original, const int32* const filter, const int32 center_x, const int32 center_y, const int32 total) const { int32 sum = 0; for (int32 filter_y = 0; filter_y < 3; ++filter_y) { const int32 y = clip(center_y - 1 + filter_y, 0, original.getHeight()); for (int32 filter_x = 0; filter_x < 3; ++filter_x) { const int32 x = clip(center_x - 1 + filter_x, 0, original.getWidth()); sum += original.getPixel(x, y) * filter[filter_y * 3 + filter_x]; } } return sum / total; } // Generic function for convolving an image with a 3x3 filter. // TODO(andrewharp): Generalize this for any size filter. template inline void convolve3x3(const Image& original, const int32* const filter) { int32 sum = 0; for (int32 i = 0; i < 9; ++i) { sum += abs(filter[i]); } for (int32 y = 0; y < height_; ++y) { for (int32 x = 0; x < width_; ++x) { setPixel(x, y, convolvePixel3x3(original, filter, x, y, sum)); } } } // Load this image's data from a data array. The data at pixels is assumed to // have dimensions equivalent to this image's dimensions * factor. inline void fromArray(const T* const pixels, const int32 stride, const int32 factor) { if (factor == 1) { // If not subsampling, memcpy per line should be faster. memcpy(this->image_data_, pixels, num_pixels_ * sizeof(T)); return; } downsampleAveraged(pixels, stride, factor); } // Copy the image back out to an appropriately sized data array. inline void toArray(T* const pixels) const { // If not subsampling, memcpy should be faster. memcpy(pixels, this->image_data_, num_pixels_ * sizeof(T)); } private: inline void allocate() { image_data_ = (T*)malloc(num_pixels_ * sizeof(T)); if (image_data_ == NULL) { LOGE("Couldn't allocate image data!"); } } T* image_data_; int32 width_; int32 height_; public: // Precompute these for efficiency's sake as they're used by a lot of // clipping code and loop code. // TODO(andrewharp): make these only accessible by other Images. int32 width_less_one_; int32 height_less_one_; int32 num_pixels_; }; // Create a pyramid of downsampled images. The first level of the pyramid is the // original image. inline void computeSmoothedPyramid(const Image& frame, const int32 num_levels, Image** const pyramid) { // TODO(andrewharp): Find a const correct solution to this... // Maybe make an pyramid class with the first level of this pyramid as a // separate pointer? // Cast away const, but we're not going to hurt it, honest! pyramid[0] = const_cast*>(&frame); for (int32 l = 1; l < num_levels; ++l) { pyramid[l]->downsampleSmoothed3x3(*pyramid[l - 1]); } } // Create a spatial derivative pyramid based on a downsampled pyramid. inline void computeSpatialPyramid(const Image** const pyramid, const int32 num_levels, Image** pyramid_x, Image** pyramid_y) { for (int32 l = 0; l < num_levels; ++l) { const Image& frame = *pyramid[l]; // Fast convolutions to find spatial derivatives. pyramid_x[l]->derivativeX(frame); pyramid_y[l]->derivativeY(frame); } } // Marks a circle of a given radius on the boolean image. // If the center spot is already marked, don't do anything and return false. // Otherwise, mark everything in range true and return true. template inline static bool markImage(const int32 x, const int32 y, const int32 radius, Image* const img) { if (img->getPixel(x, y)) { // Already claimed, sorry. return false; } const int32 squared_radius = square(radius); for (int32 d_y = 0; d_y < radius; ++d_y) { const int32 squared_y_dist = square(d_y); const int32 min_y = y > d_y ? y - d_y : ZERO; const int32 max_y = min(y + d_y, img->height_less_one_); for (int32 d_x = 0; d_x < radius; ++d_x) { if (squared_y_dist + square(d_x) <= squared_radius) { const int32 min_x = x > d_x ? x - d_x : ZERO; const int32 max_x = min(x + d_x, img->width_less_one_); // Mark all four quadrants. img->setPixel(max_x, max_y, true); img->setPixel(max_x, min_y, true); img->setPixel(min_x, max_y, true); img->setPixel(min_x, min_y, true); } else { // Once we're too far out, we're not coming back in. break; } } } return true; } // Puts the image gradient matrix about a pixel into the 2x2 float array G. // vals_x should be an array of the window x gradient values, whose indices // can be in any order but are parallel to the vals_y entries. // See http://robots.stanford.edu/cs223b04/algo_tracking.pdf for more details. inline void calculateG(const float32* const vals_x, const float32* const vals_y, const int32 num_vals, float* const G) { // Defined here because we want to keep track of how many values were // processed by NEON, so that we can finish off the remainder the normal // way. int32 i = 0; #ifdef HAVE_ARMEABI_V7A if (supportsNeon()) { const float32_t* const arm_vals_x = (const float32_t*) vals_x; const float32_t* const arm_vals_y = (const float32_t*) vals_y; // Running sums. float32x4_t xx = vdupq_n_f32(0.0f); float32x4_t xy = vdupq_n_f32(0.0f); float32x4_t yy = vdupq_n_f32(0.0f); // Maximum index we can load 4 consecutive values from. // e.g. if there are 81 values, our last full pass can be from index 77: // 81-4=>77 (77, 78, 79, 80) const int32 max_i = num_vals - 4; // Process values 4 at a time, accumulating the sums of // the pixel-wise x*x, x*y, and y*y values. for (; i <= max_i; i += 4) { // Load xs float32x4_t x = vld1q_f32(arm_vals_x + i); // Multiply x*x and accumulate. xx = vmlaq_f32(xx, x, x); // Load ys float32x4_t y = vld1q_f32(arm_vals_y + i); // Multiply x*y and accumulate. xy = vmlaq_f32(xy, x, y); // Multiply y*y and accumulate. yy = vmlaq_f32(yy, y, y); } static float32_t xx_vals[4]; static float32_t xy_vals[4]; static float32_t yy_vals[4]; vst1q_f32(xx_vals, xx); vst1q_f32(xy_vals, xy); vst1q_f32(yy_vals, yy); // Accumulated values are store in sets of 4, we have to manually add // the last bits together. for (int32 j = 0; j < 4; ++j) { G[0] += xx_vals[j]; G[1] += xy_vals[j]; G[3] += yy_vals[j]; } } #endif // Non-accelerated version, also finishes off last few values (< 4) from // above. for (; i < num_vals; ++i) { G[0] += square(vals_x[i]); G[1] += vals_x[i] * vals_y[i]; G[3] += square(vals_y[i]); } // The matrix is symmetric, so this is a given. G[2] = G[1]; } // Puts the image gradient matrix about a pixel into the 2x2 float array G. // Looks up interpolated pixels, then calls above method for implementation. inline void calculateG(const int window_size, const float32 center_x, const float center_y, const Image& I_x, const Image& I_y, float* const G) { CHECK(I_x.validPixel(center_x, center_y), "Problem in calculateG!"); // Hardcoded to allow for a max window radius of 5 (9 pixels x 9 pixels). static const int kMaxWindowRadius = 5; CHECK(window_size <= kMaxWindowRadius, "Window %d > %d!", window_size, kMaxWindowRadius); // Diameter of window is 2 * radius + 1 for center pixel. static const int kWindowBufferSize = (kMaxWindowRadius * 2 + 1) * (kMaxWindowRadius * 2 + 1); // Preallocate buffers statically for efficiency. static float32 vals_x[kWindowBufferSize]; static float32 vals_y[kWindowBufferSize]; int32 num_vals = 0; for (int32 win_x = -window_size; win_x <= window_size; ++win_x) { for (int32 win_y = -window_size; win_y <= window_size; ++win_y) { vals_x[num_vals] = I_x.getPixelInterp(center_x + win_x, center_y + win_y); vals_y[num_vals] = I_y.getPixelInterp(center_x + win_x, center_y + win_y); ++num_vals; } } calculateG(vals_x, vals_y, num_vals, G); } } // namespace flow #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_IMAGE_H_ ================================================ FILE: eyes-two/src/main/jni/opticalflow/optical_flow-jni.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Andrew Harp #include #include #include #include #include "types.h" #include "optical_flow_utils.h" #include "time_log.h" #include "image.h" #include "optical_flow.h" namespace flow { #ifdef __cplusplus extern "C" { #endif JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_initNative( JNIEnv* env, jobject thiz, jint width, jint height, jint downsample_factor); JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_addFrameNative( JNIEnv* env, jobject thiz, jbyteArray photo_data, jlong timestamp); JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_computeFeaturesNative( JNIEnv* env, jobject thiz, jboolean cached_ok); JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_computeFlowNative( JNIEnv* env, jobject thiz); JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_printInfoNative( JNIEnv* env, jobject thiz); JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_addInterestRegionNative( JNIEnv* env, jobject thiz, jint num_x, jint num_y, jfloat left, jfloat top, jfloat right, jfloat bottom); JNIEXPORT jfloatArray JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_getFeaturesNative( JNIEnv* env, jobject thiz, jboolean only_found_); JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_getAccumulatedDeltaNative( JNIEnv* env, jobject thiz, jlong timestamp, jfloat position_x, jfloat position_y, jfloat radius, jfloatArray delta); JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_resetNative( JNIEnv* env, jobject thiz); #ifdef __cplusplus } #endif OpticalFlow* optical_flow = NULL; JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_initNative( JNIEnv* env, jobject thiz, jint width, jint height, jint downsample_factor) { SAFE_DELETE(optical_flow); LOGI("Initializing optical flow. %dx%d, %d", width, height, downsample_factor); optical_flow = new OpticalFlow(width, height, downsample_factor); } JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_addFrameNative( JNIEnv* env, jobject thiz, jbyteArray photo_data, jlong timestamp) { CHECK(optical_flow != NULL, "Optical flow not initialized!"); resetTimeLog(); timeLog("Starting optical flow"); // Copy image into currFrame. jboolean iCopied = JNI_FALSE; jbyte* pixels = env->GetByteArrayElements(photo_data, &iCopied); timeLog("Got elements"); // Add the frame to the optical flow object. optical_flow->nextFrame(reinterpret_cast(pixels), timestamp); env->ReleaseByteArrayElements(photo_data, pixels, JNI_ABORT); timeLog("Released elements"); } JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_computeFeaturesNative( JNIEnv* env, jobject thiz, jboolean cached_ok) { CHECK(optical_flow != NULL, "Optical flow not initialized!"); optical_flow->computeFeatures(cached_ok); } JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_computeFlowNative( JNIEnv* env, jobject thiz) { CHECK(optical_flow != NULL, "Optical flow not initialized!"); optical_flow->computeFlow(); } JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_printInfoNative( JNIEnv* env, jobject thiz) { CHECK(optical_flow != NULL, "Optical flow not initialized!"); printTimeLog(); optical_flow->printInfo(); } JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_addInterestRegionNative( JNIEnv* env, jobject thiz, jint num_x, jint num_y, jfloat left, jfloat top, jfloat right, jfloat bottom) { CHECK(optical_flow != NULL, "Optical flow not initialized!"); optical_flow->addInterestRegion(num_x, num_y, left, top, right, bottom); timeLog("Added interest region."); } JNIEXPORT jfloatArray JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_getFeaturesNative( JNIEnv* env, jobject thiz, jboolean only_found) { CHECK(optical_flow != NULL, "Optical flow not initialized!"); jfloat feature_arr[MAX_FEATURES * FEATURE_STEP]; const int32 number_of_features = optical_flow->getFeatures(only_found, feature_arr); // Create and return the array that will be passed back to Java. jfloatArray features = env->NewFloatArray(number_of_features * FEATURE_STEP); if (features == NULL) { LOGE("null array!"); return NULL; } env->SetFloatArrayRegion( features, 0, number_of_features * FEATURE_STEP, feature_arr); return features; } JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_getAccumulatedDeltaNative( JNIEnv* env, jobject thiz, jlong timestamp, jfloat position_x, jfloat position_y, jfloat radius, jfloatArray delta) { CHECK(optical_flow != NULL, "Optical flow not initialized!"); const Point2D query_position(position_x, position_y); const Point2D query_delta = optical_flow->getAccumulatedDelta(query_position, radius, timestamp); const jfloat point_arr[] = { query_delta.x, query_delta.y }; env->SetFloatArrayRegion(delta, 0, 2, point_arr); } JNIEXPORT void JNICALL Java_com_googlecode_eyesfree_opticflow_OpticalFlow_resetNative( JNIEnv* env, jobject thiz) { LOGI("Cleaning up optical flow."); SAFE_DELETE(optical_flow); } } // namespace flow ================================================ FILE: eyes-two/src/main/jni/opticalflow/optical_flow.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: Andrew Harp #include #include "utils.h" #include "time_log.h" #include "image.h" #include "math.h" #include "optical_flow.h" #include "feature_detector.h" namespace flow { OpticalFlow::OpticalFlow(const int32 frame_width, const int32 frame_height, const int32 downsample_factor) : downsample_factor_(downsample_factor), original_size_(frame_width, frame_height), working_size_(frame_width / downsample_factor_, frame_height / downsample_factor_), first_frame_index_(0), num_frames_(0), last_time_fresh_features_(0), frame_added_(false), features_computed_(false), flow_computed_(false) { for (int i = 0; i < NUM_FRAMES; ++i) { frame_pairs_[i].init(0); } interest_map_ = new Image(working_size_); feature_scratch_ = new Image(working_size_); frame1_ = new ImageData(working_size_); frame2_ = new ImageData(working_size_); } OpticalFlow::~OpticalFlow() { // Delete all image storage. SAFE_DELETE(feature_scratch_); SAFE_DELETE(interest_map_); SAFE_DELETE(frame1_); SAFE_DELETE(frame2_); } void OpticalFlow::nextFrame(const uint8* const new_frame, const clock_t timestamp) { frame_added_ = false; features_computed_ = false; flow_computed_ = false; // Move the current framechange index up. ++num_frames_; // If we've got too many, push up the start of the queue. if (num_frames_ > NUM_FRAMES) { first_frame_index_ = geNthIndexFromStart(1); --num_frames_; } FramePair* const curr_change = frame_pairs_ + geNthIndexFromEnd(0); curr_change->init(timestamp); interest_map_->clear(false); // Cache out data from last frame. // Don't run on frame 0 (no point) or frame 1 (because the old frame will // already be in frame1_). if (num_frames_ > 2) { swap(&frame1_, &frame2_); timeLog("Copied data from last run"); } frame2_->init(new_frame, original_size_.width, timestamp, downsample_factor_); // Special case for the first frame: make sure the image ends up in // frame1_ so that feature detection can be done on it if desired. // TODO(andrewharp): Make it so that feature detection is always done // on the last frame added. if (num_frames_ == 1) { swap(&frame1_, &frame2_); } frame_added_ = true; } void OpticalFlow::computeFlow() { CHECK(frame_added_ && features_computed_ && !flow_computed_, "Optical Flow function called out of order!"); if (num_frames_ < 2) { LOGV("Frame index was %d, skipping computation.", num_frames_); return; } FramePair* const curr_change = &frame_pairs_[geNthIndexFromEnd(0)]; findCorrespondences(curr_change); flow_computed_ = true; } void OpticalFlow::findFeatures(const FramePair& prev_change, FramePair* const curr_change) { int32 number_of_tmp_features = 0; // Copy features from second frame of last pass to temp features of this // pass. number_of_tmp_features = copyFeatures(prev_change, tmp_features_); const float32 buffer = 30.0f; number_of_tmp_features += seedFeatures(*frame1_->image_, FEATURE_GRID_WIDTH, FEATURE_GRID_HEIGHT, buffer, buffer, (float32) working_size_.width - buffer, (float32) working_size_.height - buffer, FEATURE_DEFAULT, tmp_features_ + number_of_tmp_features); timeLog("Seeded features."); const int32 max_num_fast = MAX_TEMP_FEATURES - number_of_tmp_features; number_of_tmp_features += findFastFeatures(*frame1_->image_, max_num_fast, tmp_features_ + number_of_tmp_features, feature_scratch_); if (number_of_tmp_features >= MAX_TEMP_FEATURES) { LOGW("Hit cap of %d for temporary features!", number_of_tmp_features); } // Score them... scoreFeatures(*frame1_->spatial_x_[0], *frame1_->spatial_y_[0], number_of_tmp_features, tmp_features_); timeLog("Scored features"); // Now pare it down a bit. curr_change->number_of_features_ = sortAndSelect( number_of_tmp_features, MAX_FEATURES, *interest_map_, tmp_features_, curr_change->frame1_features_, feature_scratch_); timeLog("Sorted and selected features"); LOGV("Picked %d (%d max) final features out of %d potential.", curr_change->number_of_features_, MAX_FEATURES, number_of_tmp_features); last_time_fresh_features_ = curr_change->end_time; } int32 OpticalFlow::copyFeatures(const FramePair& prev_change, Point2D* const new_features) { int32 number_of_features = 0; // Caching values from last pass, just copy and compact. for (int32 i = 0; i < prev_change.number_of_features_; ++i) { if (prev_change.optical_flow_found_feature_[i]) { new_features[number_of_features] = prev_change.frame2_features_[i]; new_features[number_of_features].score = prev_change.frame1_features_[i].score; ++number_of_features; } } timeLog("Copied features"); return number_of_features; } void OpticalFlow::computeFeatures(const bool cached_ok) { CHECK(frame_added_ && !features_computed_ && !flow_computed_, "Optical Flow function called out of order!"); const FramePair& prev_change = frame_pairs_[geNthIndexFromEnd(1)]; FramePair* const curr_change = &frame_pairs_[geNthIndexFromEnd(0)]; const int32 num_found_features = prev_change.countFoundFeatures(); const clock_t ms_since_last_refresh = (curr_change->end_time - last_time_fresh_features_); if (cached_ok && num_found_features >= MIN_FEATURES && ms_since_last_refresh <= REGEN_FEATURES_MS) { // Reuse the found features from the last frame if we can. curr_change->number_of_features_ = copyFeatures(prev_change, curr_change->frame1_features_); } else { // Only find new features to track if we've lost too many since the last // time, or it's time to regenerate anyway. LOGV("Not enough features (%d/%d), or it's been too long (%ld), " "finding more.", num_found_features, MIN_FEATURES, ms_since_last_refresh); findFeatures(prev_change, curr_change); } features_computed_ = true; } int32 OpticalFlow::getFeatures(const bool only_found, float32* const out_data) const { CHECK(frame_added_ && features_computed_, "Optical Flow function called out of order!"); int32 curr_feature = 0; const FramePair& change = frame_pairs_[geNthIndexFromEnd(0)]; for (int32 i = 0; i < change.number_of_features_; ++i) { if (!only_found || change.optical_flow_found_feature_[i]) { const int base = curr_feature * FEATURE_STEP; out_data[base + 0] = change.frame1_features_[i].x * downsample_factor_; out_data[base + 1] = change.frame1_features_[i].y * downsample_factor_; out_data[base + 2] = change.optical_flow_found_feature_[i]; out_data[base + 3] = change.frame2_features_[i].x * downsample_factor_; out_data[base + 4] = change.frame2_features_[i].y * downsample_factor_; out_data[base + 5] = change.frame1_features_[i].score; out_data[base + 6] = change.frame1_features_[i].type; ++curr_feature; } } LOGV("Got %d features.", curr_feature); return curr_feature; } // Finds the correspondences for all the points in the current pair of frames. // Stores the results in the given FramePair. void OpticalFlow::findCorrespondences(FramePair* const frame_pair) const { // Features aren't found until they're found. memset(frame_pair->optical_flow_found_feature_, false, sizeof(*frame_pair->optical_flow_found_feature_) * MAX_FEATURES); timeLog("Cleared old found features"); int32 num_features_found = 0; // For every feature... for (int32 i_feat = 0; i_feat < frame_pair->number_of_features_; ++i_feat) { Point2D* feature1 = frame_pair->frame1_features_ + i_feat; Point2D* feature2 = frame_pair->frame2_features_ + i_feat; if (findFlowAtPoint(feature1->x, feature1->y, &feature2->x, &feature2->y)) { frame_pair->optical_flow_found_feature_[i_feat] = true; ++num_features_found; } } timeLog("Found correspondences"); LOGV("Found %d of %d feature correspondences", num_features_found, frame_pair->number_of_features_); } // An implementation of the Pyramidal Lucas-Kanade Optical Flow algorithm. // See http://robots.stanford.edu/cs223b04/algo_tracking.pdf for details. bool OpticalFlow::findFlowAtPoint(const float32 u_x, const float32 u_y, float32* final_x, float32* final_y) const { const float32 threshold_squared = square(THRESHOLD); // Initial guess. float32 g_x = 0.0f; float32 g_y = 0.0f; // For every level in the pyramid, update the coordinates of the best match. for (int32 l = NUM_LEVELS - 1; l >= 0; --l) { // Shrink factor from original. const int32 shrink_factor = (1 << l); // Images I (prev) and J (next). const Image& img_I = *frame1_->pyramid_[l]; const Image& img_J = *frame2_->pyramid_[l]; // Computed gradients. const Image& I_x = *frame1_->spatial_x_[l]; const Image& I_y = *frame1_->spatial_y_[l]; // Image position vector (p := u^l), scaled for this level. const float32 p_x = u_x / static_cast(shrink_factor); const float32 p_y = u_y / static_cast(shrink_factor); // LOGV("Level %d: (%d, %d) / %d -> (%d, %d)", // l, u_x, u_y, shrink_factor, p_x, p_y); // Get values for frame 1. They remain constant through the inner // iteration loop. float32 vals_I[ARRAY_SIZE]; float32 vals_I_x[ARRAY_SIZE]; float32 vals_I_y[ARRAY_SIZE]; int32 val_idx = 0; for (int32 win_x = -WINDOW_SIZE; win_x <= WINDOW_SIZE; ++win_x) { for (int32 win_y = -WINDOW_SIZE; win_y <= WINDOW_SIZE; ++win_y) { const float32 x_pos = p_x + win_x; const float32 y_pos = p_y + win_y; if (!img_I.validInterpPixel(x_pos, y_pos)) { return false; } vals_I[val_idx] = img_I.getPixelInterp(x_pos, y_pos); vals_I_x[val_idx] = I_x.getPixelInterp(x_pos, y_pos); vals_I_y[val_idx] = I_y.getPixelInterp(x_pos, y_pos); ++val_idx; } } // Compute the spatial gradient matrix about point p. float32 G[] = { 0, 0, 0, 0 }; calculateG(vals_I_x, vals_I_y, ARRAY_SIZE, G); // Find the inverse of G. float32 G_inv[4]; if (!invert2x2(G, G_inv)) { // If we can't invert, hope that the next level will have better luck. continue; } #ifdef NORMALIZE const float32 mean_I = computeMean(vals_I, ARRAY_SIZE); const float32 std_dev_I = computeStdDev(vals_I, ARRAY_SIZE, mean_I); #endif // Iterate NUM_ITERATIONS times or until we converge. for (int32 iteration = 0; iteration < NUM_ITERATIONS; ++iteration) { // Get values for frame 2. float32 vals_J[ARRAY_SIZE]; int32 val_idx = 0; for (int32 win_x = -WINDOW_SIZE; win_x <= WINDOW_SIZE; ++win_x) { for (int32 win_y = -WINDOW_SIZE; win_y <= WINDOW_SIZE; ++win_y) { const float32 x_pos = p_x + win_x + g_x; const float32 y_pos = p_y + win_y + g_y; if (!img_I.validInterpPixel(x_pos, y_pos)) { return false; } vals_J[val_idx] = img_J.getPixelInterp(x_pos, y_pos); ++val_idx; } } #ifdef NORMALIZE const float32 mean_J = computeMean(vals_J, ARRAY_SIZE); const float32 std_dev_J = computeStdDev(vals_J, ARRAY_SIZE, mean_J); const float32 std_dev_ratio = std_dev_I / std_dev_J; #endif // Compute image mismatch vector. float32 b_x = 0.0f; float32 b_y = 0.0f; val_idx = 0; for (int32 win_x = -WINDOW_SIZE; win_x <= WINDOW_SIZE; ++win_x) { for (int32 win_y = -WINDOW_SIZE; win_y <= WINDOW_SIZE; ++win_y) { // Normalized Image difference. #ifdef NORMALIZE const float32 dI = (vals_I[val_idx] - mean_I) - (vals_J[val_idx] - mean_J) * std_dev_ratio; #else const float32 dI = vals_I[val_idx] - vals_J[val_idx]; #endif b_x += dI * vals_I_x[val_idx]; b_y += dI * vals_I_y[val_idx]; ++val_idx; } } // Optical flow... solve n = G^-1 * b const float32 n_x = (G_inv[0] * b_x) + (G_inv[1] * b_y); const float32 n_y = (G_inv[2] * b_x) + (G_inv[3] * b_y); // Update best guess with residual displacement from this level and // iteration. g_x += n_x; g_y += n_y; // LOGV("Iteration %d: delta (%.3f, %.3f)", iteration, n_x, n_y); // Abort early if we're already below the threshold. if (square(n_x) + square(n_y) < threshold_squared) { break; } } // Iteration. if (l > 0) { // Every lower level of the pyramid is 2x as large dimensionally. g_x = 2.0f * g_x; g_y = 2.0f * g_y; } } // Level. // LOGV("Final displacement for feature %d was (%.2f, %.2f)", // iFeat, g_x, g_y); *final_x = u_x + g_x; *final_y = u_y + g_y; // Assign the best guess, if we're still in the image. if (frame1_->pyramid_[0]->validInterpPixel(*final_x, *final_y)) { return true; } else { return false; } } void OpticalFlow::addInterestRegion(const int32 num_x, const int32 num_y, float32 left, float32 top, float32 right, float32 bottom) { left = max(left / downsample_factor_, 0); top = max(top / downsample_factor_, 0); right = min(right / downsample_factor_, working_size_.width - 1); bottom = min(bottom / downsample_factor_, working_size_.height - 1); if (left > right || top > bottom) { return; } // This is inclusive of the border pixels, hence the +1. const int32 width = right - left + 1; // Also inclusive, so it uses a LTE. for (int32 y = top; y <= bottom; ++y) { bool* row_start = interest_map_->getPixelPtr(left, y); memset(row_start, true, width * sizeof(*row_start)); } } Point2D OpticalFlow::getAccumulatedDelta(const Point2D& position, const float32 radius, const clock_t timestamp) const { Point2D curr_pos(position); // Scale down to downsampled size. curr_pos.x /= downsample_factor_; curr_pos.y /= downsample_factor_; LOGV("Tracking accumulated delta from %.2f, %.2f", curr_pos.x, curr_pos.y); const float32 cutoff_dist = radius / downsample_factor_; // Anything that ended before the requested timestamp is of no concern to us. bool found_it = false; int32 num_frames_back = -1; for (int32 i = 0; i < num_frames_; ++i) { const FramePair& frame_pair = frame_pairs_[geNthIndexFromEnd(i)]; if (frame_pair.end_time <= timestamp) { num_frames_back = i - 1; if (num_frames_back > 0) { LOGV("Went %d out of %d frames before finding frame. (index: %d)", num_frames_back, num_frames_, geNthIndexFromEnd(i)); } found_it = true; break; } } if (!found_it) { const FramePair& frame_pair = frame_pairs_[geNthIndexFromStart(0)]; const FramePair& latest_frame_pair = frame_pairs_[geNthIndexFromEnd(0)]; clock_t latest_time = latest_frame_pair.end_time; LOGW("History did not go back far enough! %ld vs %ld", latest_time - frame_pair.end_time, latest_time - timestamp); } // Loop over all the frames in the queue, tracking the accumulated delta // of the point from frame to frame. It's possible the point could // go out of frame, but keep tracking as best we can, using points near // the edge of the screen where it went out of bounds. for (int32 i = num_frames_back; i >= 0; --i) { const FramePair& frame_pair = frame_pairs_[geNthIndexFromEnd(i)]; CHECK(frame_pair.end_time >= timestamp, "Frame timestamp was too early!"); const Point2D delta = frame_pair.queryFlow(curr_pos, cutoff_dist); curr_pos.x += delta.x; curr_pos.y += delta.y; } // Scale back to original size. curr_pos.x *= downsample_factor_; curr_pos.y *= downsample_factor_; // Return the delta only. return curr_pos - position; } void FramePair::init(const clock_t end_time) { this->end_time = end_time; memset(optical_flow_found_feature_, false, sizeof(*optical_flow_found_feature_) * MAX_FEATURES); number_of_features_ = 0; } Point2D FramePair::queryFlow( const Point2D& initial, const float32 cutoff_dist) const { float32 weights[MAX_FEATURES]; memset(weights, 0, sizeof(float32) * MAX_FEATURES); // Compute the max score. float32 max_score = 0.0f; for (int32 i = 0; i < MAX_FEATURES; ++i) { if (optical_flow_found_feature_[i]) { max_score = max(max_score, frame1_features_[i].score); } } const float32 cutoff_dist_squared = cutoff_dist * cutoff_dist; for (int32 i = 0; i < MAX_FEATURES; ++i) { if (optical_flow_found_feature_[i]) { const float32 sq_x_dist = square(initial.x - frame1_features_[i].x); const float32 sq_y_dist = square(initial.y - frame1_features_[i].y); const float32 dist_squared = sq_x_dist + sq_y_dist; // The weighting based off distance. Anything within the cuttoff // distance has a weight of 1, and everything outside of that is within // the range [0, 1). const float32 distance_score = min(cutoff_dist_squared / dist_squared, 1.0f); // The weighting based on score strength. 0.5f - 1.0f. float32 intrinsic_score = 1.0f; if (max_score > 0) { intrinsic_score = (frame1_features_[i].score / max_score) / 2.0f; } // The final score will be in the range [0, 1]. weights[i] = distance_score * intrinsic_score; } } return getWeightedDelta(weights); } Point2D FramePair::getWeightedDelta(const float32* const weights) const { float32 total_weight = 0.0f; float32 weighted_sum_x = 0.0f; float32 weighted_sum_y = 0.0f; Point2D deltas[MAX_FEATURES]; // Compute weighted mean and deltas. for (int32 i = 0; i < MAX_FEATURES; ++i) { const float32 weight = weights[i]; if (weight > 0.0f) { deltas[i] = frame2_features_[i] - frame1_features_[i]; weighted_sum_x += deltas[i].x * weight; weighted_sum_y += deltas[i].y * weight; total_weight += weight; } } const float32 weighted_mean_x = weighted_sum_x / total_weight; const float32 weighted_mean_y = weighted_sum_y / total_weight; // Compute weighted squared standard deviation from weighted mean. float32 weighted_dev_squared_sum = 0.0f; for (int32 i = 0; i < MAX_FEATURES; ++i) { const float32 weight = weights[i]; if (weight > 0.0f) { const float32 devX = deltas[i].x - weighted_mean_x; const float32 devY = deltas[i].y - weighted_mean_y; const float32 squared_deviation = (devX * devX) + (devY * devY); weighted_dev_squared_sum += squared_deviation * weight; } } const float32 weighted_std_dev_squared = weighted_dev_squared_sum / total_weight; // Recompute weighted mean change without outliers. float32 good_weight = 0.0f; float32 good_sum_x = 0.0f; float32 good_sum_y = 0.0f; for (int32 i = 0; i < MAX_FEATURES; ++i) { const float32 weight = weights[i]; if (weight > 0.0f) { const float32 dev_x = deltas[i].x - weighted_mean_x; const float32 dev_y = deltas[i].y - weighted_mean_y; const float32 sqrd_deviation = (dev_x * dev_x) + (dev_y * dev_y); // Throw out anything beyond NUM_DEVIATIONS. if (sqrd_deviation <= NUM_DEVIATIONS * weighted_std_dev_squared) { good_sum_x += deltas[i].x * weight; good_sum_y += deltas[i].y * weight; good_weight += weight; } } } if (good_weight > 0.0f) { return Point2D(good_sum_x / good_weight, good_sum_y / good_weight); } else { return Point2D(0.0f, 0.0f); } } } // namespace flow ================================================ FILE: eyes-two/src/main/jni/opticalflow/optical_flow.h ================================================ // Copyright 2009 Google Inc. All Rights Reserved. // Author: andrewharp@google.com (Andrew Harp) #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_OPTICAL_FLOW_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_OPTICAL_FLOW_H_ #include "types.h" #include "utils.h" // Feature detection. #define MAX_TEMP_FEATURES 4096 #define MAX_FEATURES 128 // Number of floats each feature takes up when exporting to an array. #define FEATURE_STEP 7 // Number of frame deltas to keep around in the circular queue. #define NUM_FRAMES 128 // Redetect if we ever have less than this number of features. #define MIN_FEATURES 6 // How long to wait between forcing complete feature regeneration. #define REGEN_FEATURES_MS 400 // Number of iterations to do tracking on each feature at each pyramid level. #define NUM_ITERATIONS 3 // Number of pyramid levels used for tracking. #define NUM_LEVELS 4 // Window size to integrate over to find local image derivative. #define WINDOW_SIZE 3 // Total area of integration windows. #define ARRAY_SIZE (2 * WINDOW_SIZE + 1) * (2 * WINDOW_SIZE + 1) // Error that's considered good enough to early abort tracking. #define THRESHOLD 0.03f // Maximum number of deviations a feature delta can be from the weighted // average before being thrown out for region-based queries. #define NUM_DEVIATIONS 2.0f // Resolution of feature grid to seed features with. #define FEATURE_GRID_WIDTH 4 #define FEATURE_GRID_HEIGHT 3 // Whether to normalize feature windows for intensity. #define NORMALIZE namespace flow { template class Image; // Class that encapsulates all bulky processed data for a frame. class ImageData { public: explicit ImageData(Size size) { timestamp_ = 0; image_ = new Image(size); for (int32 i = 0; i < NUM_LEVELS; ++i) { pyramid_[i] = (i == 0) ? image_ : new Image(size); spatial_x_[i] = new Image(size); spatial_y_[i] = new Image(size); size.width /= 2; size.height /= 2; } } ~ImageData() { // image_ will be deleted along with the rest of the pyramids. for (int32 i = 0; i < NUM_LEVELS; ++i) { SAFE_DELETE(pyramid_[i]); SAFE_DELETE(spatial_x_[i]); SAFE_DELETE(spatial_y_[i]); } } void init(const uint8* const new_frame, const int32 stride, const clock_t timestamp, const int32 downsample_factor_) { timestamp_ = timestamp; image_->fromArray(new_frame, stride, downsample_factor_); timeLog("Downsampled image"); // Create the smoothed pyramids. computeSmoothedPyramid(*image_, NUM_LEVELS, pyramid_); timeLog("Created smoothed pyramids"); // Create the spatial derivatives for frame 1. computeSpatialPyramid((const Image**)pyramid_, NUM_LEVELS, spatial_x_, spatial_y_); timeLog("Created spatial derivatives"); } clock_t timestamp_; Image* image_; Image* pyramid_[NUM_LEVELS]; Image* spatial_x_[NUM_LEVELS]; Image* spatial_y_[NUM_LEVELS]; }; // A class that records a timestamped frame features // translation delta for optical flow. class FramePair { public: // Cleans up the FramePair so that they can be reused. void init(const clock_t end_time); // Throws out outliers based on the input weighting. Point2D getWeightedDelta(const float32* const weights) const; // Weights points based on the query_point and cutoff_dist, then // returns getWeightedDelta. Essentially tells you where a point at the // beginning of a frame ends up. Point2D queryFlow(const Point2D& query_point, const float32 cutoff_dist) const; // Just count up and return the number of features from the first frame that // were found in the second frame. inline int32 countFoundFeatures() const { int32 num_found_features = 0; for (int32 i = 0; i < number_of_features_; ++i) { if (optical_flow_found_feature_[i]) { ++num_found_features; } } return num_found_features; } // The time at frame2. clock_t end_time; // This array will contain the features found in frame 1. Point2D frame1_features_[MAX_FEATURES]; // Contain the locations of the points from frame 1 in frame 2. Point2D frame2_features_[MAX_FEATURES]; // The number of features in frame 1. int32 number_of_features_; // Keeps track of which features were actually found from one frame // another. // The i-th element of this array will be non-zero if and only if the i-th // feature of frame 1 was found in frame 2. bool optical_flow_found_feature_[MAX_FEATURES]; }; // Class encapsulating all the data and logic necessary for performing optical // flow. The general order of operations on a per frame basis is: // // // Notify optical flow that a new frame is available. // nextFrame(...); // // // Tell it any regions we want it to pay special attention to. // addInterestRegion(...); // // // Have it compute the flow. // computeFlow(); // // // Look up the delta from a given point at a given time to the current time. // getAccumulatedDelta(...); class OpticalFlow { public: OpticalFlow(const int32 frame_width, const int32 frame_height, const int32 downsample_factor); ~OpticalFlow(); // Add a new frame to the optical flow. Will update all the non-feature // related member variables. // // new_frame should be a buffer of grayscale values, one byte per pixel, // at the original frame_width and frame_height used to initialize the // OpticalFlow object. Downsampling will be handled internally. // // time_stamp should be a time in milliseconds that later calls to this and // other methods will be relative to. void nextFrame(const uint8* const new_frame, const clock_t timestamp); // Find the features in the frame before the current frame. // If only one frame exists, features will be found in that frame. void computeFeatures(const bool cached_ok = false); // Process the most recent two frames, and fill in the feature arrays. void computeFlow(); // Copy the feature arrays after computeFlow is called. // out_data should be at least MAX_FEATURES * FEATURE_STEP long. // Currently, its format is [x1 y1 found x2 y2 score] repeated N times, // where N is the number of features tracked. N is returned as the result. int32 getFeatures(const bool only_found, float32* const out_data) const; // Tells you the overall flow for region of a given radius at a given time to // the present. Point2D getAccumulatedDelta(const Point2D& position, const float radius, const clock_t timestamp) const; // Pay special attention to the area inside this box on the next // optical flow pass. void addInterestRegion(const int32 num_x, const int32 num_y, float32 left, float32 top, float32 right, float32 bottom); // Finds the correspondences for all the points in the current pair of frames. // Stores the results in the given FramePair. void findCorrespondences(FramePair* const curr_change) const; // An implementation of the Pyramidal Lucas-Kanade Optical Flow algorithm. bool findFlowAtPoint(const float32 u_x, const float32 u_y, float32* final_x, float32* final_y) const; void printInfo() const { #ifdef VERBOSE_LOGGING const int32 first_frame_index = geNthIndexFromStart(0); const FramePair& first_frame_pair = frame_pairs_[first_frame_index]; const int32 last_frame_index = geNthIndexFromEnd(0); const FramePair& last_frame_pair = frame_pairs_[last_frame_index]; LOGV ("Queue size: %d, last/first: %4d %4d: %8ld - %8ld = %8ld", num_frames_, last_frame_index, first_frame_index, last_frame_pair.end_time, first_frame_pair.end_time, last_frame_pair.end_time - first_frame_pair.end_time); #endif } private: inline int32 geNthIndexFromStart(const int32 offset) const { CHECK(offset >= 0 && offset < num_frames_, "Offset out of range! %d out of %d.", offset, num_frames_); return (first_frame_index_ + offset) % NUM_FRAMES; } inline int32 geNthIndexFromEnd(const int32 offset) const { return geNthIndexFromStart(num_frames_ - 1 - offset); } // Finds features in the previous frame and adds them to curr_change. void findFeatures(const FramePair& prev_change, FramePair* const curr_change); // Copies and compacts the found features in the second frame of prev_change // into the array at new_features. static int32 copyFeatures(const FramePair& prev_change, Point2D* const new_features); const int32 downsample_factor_; // Size of the original images. const Size original_size_; // Size of the internally allocated images (after original is downsampled). const Size working_size_; int32 first_frame_index_; int32 num_frames_; clock_t last_time_fresh_features_; Point2D tmp_features_[MAX_TEMP_FEATURES]; FramePair frame_pairs_[NUM_FRAMES]; // Scratch memory for feature candidacy detection and non-max suppression. Image* feature_scratch_; // Regions of the image to pay special attention to. Image* interest_map_; ImageData* frame1_; ImageData* frame2_; bool frame_added_; bool features_computed_; bool flow_computed_; }; } // namespace flow #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_OPTICAL_FLOW_H_ ================================================ FILE: eyes-two/src/main/jni/opticalflow/optical_flow_utils.h ================================================ // Copyright 2010 Google Inc. All Rights Reserved. // Author: andrewharp@google.com (Andrew Harp) #ifndef JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_OPTICAL_FLOW_UTILS_H_ #define JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_OPTICAL_FLOW_UTILS_H_ #include "utils.h" #include namespace flow { // Arbitrary feature type ids for labeling the origin of tracked features. #define FEATURE_DEFAULT 0 #define FEATURE_FAST 1 #define FEATURE_INTEREST 2 #define EPSILON 0.0000001f class Size { public: int32 width; int32 height; Size(const int32 width, const int32 height) : width(width), height(height) {} }; // For keeping track of features. class Point2D { public: float32 x; float32 y; float32 score; uint8 type; Point2D() : x(0.0f), y(0.0f), score(0.0f), type(0) {} Point2D(const float32 x, const float32 y) : x(x), y(y), score(0.0f), type(0) {} // The following operators all compare the computed score of the feature for // sorting purposes. // TODO(andrewharp): Use the qsort function in stdlib. inline bool operator< (const Point2D& that) const { return this->score < that.score; } inline bool operator<= (const Point2D& that) const { return this->score <= that.score; } inline bool operator> (const Point2D& that) const { return this->score > that.score; } inline Point2D operator- (const Point2D& that) const { return Point2D(this->x - that.x, this->y - that.y); } }; // Returns the determinant of a 2x2 matrix. inline float findDeterminant2x2(const float32* const a) { // Determinant: (ad - bc) return a[0] * a[3] - a[1] * a[2]; } // Finds the inverse of a 2x2 matrix. // Returns true upon success, false if the matrix is not invertible. inline bool invert2x2(const float32* const a, float32* const a_inv) { const float det = findDeterminant2x2(a); if (std::fabs(det) < EPSILON) { return false; } const float32 inv_det = 1.0f / static_cast(det); a_inv[0] = inv_det * a[3]; // d a_inv[1] = inv_det * -a[1]; // -b a_inv[2] = inv_det * -a[2]; // -c a_inv[3] = inv_det * a[0]; // a return true; } // TODO(andrewharp): Accelerate with NEON. inline float32 computeMean(const float32* const values, const int32 num_vals) { // Get mean. float32 sum = 0.0f; for (int32 i = 0; i < num_vals; ++i) { sum += values[i]; } return sum / static_cast(num_vals); } // TODO(andrewharp): Accelerate with NEON. inline float32 computeStdDev(const float32* const values, const int32 num_vals, const float32 mean) { // Get Std dev. float32 squared_sum = 0.0f; for (int32 i = 0; i < num_vals; ++i) { squared_sum += square(values[i] - mean); } return sqrt(squared_sum / static_cast(num_vals)); } // TODO(andrewharp): Accelerate with NEON. inline float32 computeWeightedMean(const float32* const values, const float32* const weights, const int32 num_vals) { float32 sum = 0.0f; float32 total_weight = 0.0f; for (int32 i = 0; i < num_vals; ++i) { sum += values[i] * weights[i]; total_weight += weights[i]; } return sum / num_vals; } // Partitioning phase of quicksort. template inline int32 partition(T* const arr_start, const int32 num_elems, const T pivot) { int32 i = 0; int32 j = num_elems - 1; // Put everything <= pivot on the left, and everything > pivot to the right. while (true) { while (arr_start[i] <= pivot && (i < j)) { ++i; } while (arr_start[j] > pivot && (i < j)) { --j; } // Termination condition. if (i >= j) { break; } swap(arr_start + i, arr_start + j); ++i; --j; } int32 part_size; for (part_size = 0; part_size < num_elems; ++part_size) { if (arr_start[part_size] > pivot) { break; } } return part_size; } // Just your basic quicksort implementation. // Sorts an array of size num_elems inplace by the score field of the elements. template void qsort(T* const arr_start, const int32 num_elems) { // No point in sorting a list of size 1 or 0! if (num_elems <= 1) { return; } // Check to see if we're already sorted... bool sorted = true; T last_score = arr_start[0]; for (int32 i = 1; i < num_elems; ++i) { const T curr_score = arr_start[i]; if (last_score > curr_score) { sorted = false; break; } last_score = curr_score; } if (sorted) { return; } // Select partition element randomly. const int32 sort_ind = rand() % num_elems; const T pivot = arr_start[sort_ind]; const int32 first_part_size = partition(arr_start, num_elems, pivot); const int32 second_part_size = num_elems - first_part_size; qsort(arr_start, first_part_size); qsort(arr_start + first_part_size, second_part_size); } } // namespace flow #endif // JAVA_COM_GOOGLE_ANDROID_APPS_UNVEIL_JNI_OPTICALFLOW_OPTICAL_FLOW_UTILS_H_ ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Mon Dec 28 12:31:23 IST 2020 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip ================================================ FILE: gradle.properties ================================================ ## For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx1024m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true #Mon Dec 28 14:15:43 IST 2020 android.enableJetifier=true android.useAndroidX=true org.gradle.jvmargs=-Xmx2048M ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: preparetests.cmd ================================================ for /f %%i in ('adb shell echo $EXTERNAL_STORAGE') do set DIR=%%i git clone -b 3.04.00 https://github.com/tesseract-ocr/tessdata.git adb shell rm %DIR%/testAddPageToDocument.pdf adb shell rm %DIR%/testCreate.pdf adb uninstall com.googlecode.tesseract.android.test adb shell mkdir %DIR%/tessdata adb push -p tessdata/eng.cube.bigrams %DIR%/tessdata adb push -p tessdata/eng.cube.fold %DIR%/tessdata adb push -p tessdata/eng.cube.lm %DIR%/tessdata adb push -p tessdata/eng.cube.nn %DIR%/tessdata adb push -p tessdata/eng.cube.params %DIR%/tessdata adb push -p tessdata/eng.cube.size %DIR%/tessdata adb push -p tessdata/eng.cube.word-freq %DIR%/tessdata adb push -p tessdata/eng.tesseract_cube.nn %DIR%/tessdata adb push -p tessdata/eng.traineddata %DIR%/tessdata adb push -p tess-two/jni/com_googlecode_tesseract_android/src/tessdata/pdf.ttf %DIR%/tessdata ================================================ FILE: preparetests.sh ================================================ #!/bin/sh DIR="`adb shell echo \\$EXTERNAL_STORAGE`" git clone -b 3.04.00 https://github.com/tesseract-ocr/tessdata.git adb shell rm $DIR/testAddPageToDocument.pdf adb shell rm $DIR/testCreate.pdf adb uninstall com.googlecode.tesseract.android.test adb shell mkdir $DIR/tessdata for f in tessdata/eng.*; do TRAINEDDATA_FILENAME="$DIR/tessdata/`basename $f`" if [ `adb shell "if [ -f $TRAINEDDATA_FILENAME ]; then echo 1; fi"` ]; then echo "$TRAINEDDATA_FILENAME already present on device" continue fi echo "Copying $f to device..."; adb push -p $f $DIR/tessdata done adb push -p tess-two/jni/com_googlecode_tesseract_android/src/tessdata/pdf.ttf $DIR/tessdata # adb shell am instrument -w com.googlecode.tesseract.android.test/android.test.InstrumentationTestRunner ================================================ FILE: settings.gradle ================================================ include ':eyes-two' include ':tess-two' include ':tess-two-test' rootProject.name = 'tess-two.project' ================================================ FILE: tess-two/.classpath ================================================ ================================================ FILE: tess-two/.gitignore ================================================ /obj /gen /libs /jni/com_googlecode_tesseract_android/src/config/** /jni/com_googlecode_tesseract_android/src/m4/** /jni/com_googlecode_tesseract_android/src/vs2008/** /jni/com_googlecode_tesseract_android/src/vs2010/** ================================================ FILE: tess-two/.project ================================================ tess-two com.android.ide.eclipse.adt.ResourceManagerBuilder com.android.ide.eclipse.adt.PreCompilerBuilder org.eclipse.jdt.core.javabuilder com.android.ide.eclipse.adt.ApkBuilder com.android.ide.eclipse.adt.AndroidNature org.eclipse.jdt.core.javanature ================================================ FILE: tess-two/AndroidManifest.xml ================================================ ================================================ FILE: tess-two/COPYING ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: tess-two/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' apply plugin: 'com.jfrog.bintray' Properties properties = new Properties() properties.load(rootProject.file('local.properties').newDataInputStream()) android { compileSdkVersion 30 defaultConfig { minSdkVersion 16 targetSdkVersion 30 versionCode 1 versionName '1.0' consumerProguardFiles 'proguard-rules.pro' } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] res.srcDirs = ['res'] } } externalNativeBuild { ndkBuild { path "jni/Android.mk" } } } dependencies { implementation "androidx.annotation:annotation:1.1.0" } // Settings for uploading module AAR to Bintray for library distribution task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } task javadoc(type: Javadoc) { failOnError = false source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) options { links "http://docs.oracle.com/javase/7/docs/api/" linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference" } } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from javadoc.destinationDir } artifacts { archives javadocJar archives sourcesJar } install { repositories.mavenInstaller { pom.project { name = 'tess-two' packaging = 'aar' groupId = 'com.rmtheis' artifactId = 'tess-two' developers { developer { id = 'rmtheis' name = 'Robert Theis' email = 'robert.m.theis@gmail.com' } } licenses { license { name = 'The Apache Software License, Version 2.0' url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' distribution = 'repo' } } scm { url 'https://github.com/rmtheis/tess-two' } } } } bintray { user = properties.getProperty("bintray.user") key = properties.getProperty("bintray.apikey") configurations = ['archives'] pkg { repo = 'maven' name = 'tess-two' userOrg = user publish = true } } ================================================ FILE: tess-two/build.xml ================================================ ================================================ FILE: tess-two/jni/Android.mk ================================================ LOCAL_PATH := $(call my-dir) TESSERACT_PATH := $(LOCAL_PATH)/../../tesseract LEPTONICA_PATH := $(LOCAL_PATH)/../../leptonica LIBJPEG_PATH := $(LOCAL_PATH)/libjpeg LIBPNG_PATH := $(LOCAL_PATH)/libpng # Just build the Android.mk files in the subdirs include $(call all-subdir-makefiles) ================================================ FILE: tess-two/jni/Application.mk ================================================ APP_STL := c++_static APP_ABI := armeabi-v7a x86 arm64-v8a x86_64 APP_OPTIM := release APP_PLATFORM := android-16 APP_CPPFLAGS += -fexceptions -frtti NDK_TOOLCHAIN_VERSION := clang ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/Android.mk ================================================ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := liblept LOCAL_SRC_FILES += \ box.cpp \ boxa.cpp \ pix.cpp \ pixa.cpp \ utilities.cpp \ readfile.cpp \ writefile.cpp \ jni.cpp LOCAL_EXPORT_CFLAGS := \ -DHAVE_CONFIG_H LOCAL_EXPORT_C_INCLUDES := \ $(LOCAL_PATH) \ $(LEPTONICA_PATH)/src LOCAL_C_INCLUDES := \ $(LOCAL_EXPORT_C_INCLUDES) \ $(LIBJPEG_PATH) \ $(LIBPNG_PATH) LOCAL_LDLIBS += \ -ljnigraphics \ -llog LOCAL_STATIC_LIBRARIES:= liblept_static include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := liblept_static LOCAL_THIN_ARCHIVE := true LOCAL_EXPORT_CFLAGS := \ -DHAVE_CONFIG_H LOCAL_CFLAGS := \ $(LOCAL_EXPORT_CFLAGS) \ -include $(LOCAL_PATH)/common.h LOCAL_EXPORT_C_INCLUDES := \ $(LOCAL_PATH) \ $(LEPTONICA_PATH)/src LOCAL_PATH := $(LEPTONICA_PATH)/src get-src-file-target-cflags += $(if $(filter bmpio.c,$1),-Wno-address-of-packed-member,) # leptonica (minus freetype) BLACKLIST_SRC_FILES := \ %endiantest.c \ %freetype.c \ %xtractprotos.c LEPTONICA_SRC_FILES := \ $(subst $(LOCAL_PATH)/,,$(wildcard $(LEPTONICA_PATH)/src/*.c)) LOCAL_SRC_FILES := \ $(filter-out $(BLACKLIST_SRC_FILES),$(LEPTONICA_SRC_FILES)) LOCAL_C_INCLUDES += \ $(LOCAL_EXPORT_C_INCLUDES) \ $(LIBJPEG_PATH) \ $(LIBPNG_PATH) LOCAL_STATIC_LIBRARIES:= libjpgt_static libpngt_static include $(BUILD_STATIC_LIBRARY) ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/box.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jlong Java_com_googlecode_leptonica_android_Box_nativeCreate(JNIEnv *env, jclass clazz, jint x, jint y, jint w, jint h) { BOX *box = boxCreate((l_int32) x, (l_int32) y, (l_int32) w, (l_int32) h); return (jlong) box; } void Java_com_googlecode_leptonica_android_Box_nativeDestroy(JNIEnv *env, jclass clazz, jlong nativeBox) { BOX *box = (BOX *) nativeBox; boxDestroy(&box); } jint Java_com_googlecode_leptonica_android_Box_nativeGetX(JNIEnv *env, jclass clazz, jlong nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->x; } jint Java_com_googlecode_leptonica_android_Box_nativeGetY(JNIEnv *env, jclass clazz, jlong nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->y; } jint Java_com_googlecode_leptonica_android_Box_nativeGetWidth(JNIEnv *env, jclass clazz, jlong nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->w; } jint Java_com_googlecode_leptonica_android_Box_nativeGetHeight(JNIEnv *env, jclass clazz, jlong nativeBox) { BOX *box = (BOX *) nativeBox; return (jint) box->h; } jboolean Java_com_googlecode_leptonica_android_Box_nativeGetGeometry(JNIEnv *env, jclass clazz, jlong nativeBox, jintArray dimensions) { BOX *box = (BOX *) nativeBox; jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL); l_int32 x, y, w, h; if (boxGetGeometry(box, &x, &y, &w, &h)) { return JNI_FALSE; } dimensionArray[0] = x; dimensionArray[1] = y; dimensionArray[2] = w; dimensionArray[3] = h; env->ReleaseIntArrayElements(dimensions, dimensionArray, 0); return JNI_TRUE; } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/boxa.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void Java_com_googlecode_leptonica_android_Boxa_nativeDestroy(JNIEnv *env, jclass clazz, jlong nativeBoxa) { BOXA *boxa = (BOXA *) nativeBoxa; boxaDestroy(&boxa); } jboolean Java_com_googlecode_leptonica_android_Boxa_nativeGetGeometry(JNIEnv *env, jclass clazz, jlong nativeBoxa, jint index, jintArray dimensions) { BOXA *boxa = (BOXA *) nativeBoxa; jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL); l_int32 x, y, w, h; if (boxaGetBoxGeometry(boxa,index, &x, &y, &w, &h)) { return JNI_FALSE; } dimensionArray[0] = x; dimensionArray[1] = y; dimensionArray[2] = w; dimensionArray[3] = h; env->ReleaseIntArrayElements(dimensions, dimensionArray, 0); return JNI_TRUE; } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/common.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LEPTONICA_JNI_COMMON_H #define LEPTONICA_JNI_COMMON_H #include #include #include "allheaders.h" #include #include #ifdef __BIG_ENDIAN #define SK_A32_SHIFT 0 #define SK_R32_SHIFT 8 #define SK_G32_SHIFT 16 #define SK_B32_SHIFT 24 #else #define SK_A32_SHIFT 24 #define SK_R32_SHIFT 16 #define SK_G32_SHIFT 8 #define SK_B32_SHIFT 0 #endif /* __BIG_ENDIAN */ #define LOG_TAG "Leptonica(native)" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__) #undef L_ERROR #undef L_WARNING #undef L_INFO #define L_ERROR(a,...) \ IF_SEV(L_SEVERITY_ERROR, (void) LOGE("in %s: " a, __VA_ARGS__), (void)0) #define L_WARNING(a,...) \ IF_SEV(L_SEVERITY_WARNING, (void) LOGW("in %s: " a, __VA_ARGS__), (void)0) #define L_INFO(a,...) \ IF_SEV(L_SEVERITY_INFO, (void) LOGI("in %s: " a, __VA_ARGS__), (void)0) #endif ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/endianness.h ================================================ /* for Android, this header is intentionally left blank */ ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/jni.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("ERROR: GetEnv failed\n"); return -1; } assert(env != NULL); return JNI_VERSION_1_6; } ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/pix.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jlong Java_com_googlecode_leptonica_android_Pix_nativeCreatePix(JNIEnv *env, jclass clazz, jint w, jint h, jint d) { PIX *pix = pixCreate((l_int32) w, (l_int32) h, (l_int32) d); return (jlong) pix; } jlong Java_com_googlecode_leptonica_android_Pix_nativeCreateFromData(JNIEnv *env, jclass clazz, jbyteArray data, jint w, jint h, jint d) { PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, (l_int32) d); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix); memcpy(pixGetData(pix), byte_buffer, size); env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); return (jlong) pix; } jbyteArray Java_com_googlecode_leptonica_android_Pix_nativeGetData(JNIEnv *env, jclass clazz, jlong nativePix, jbyteArray data) { PIX *pix = (PIX *) nativePix; size_t size = 4 * pixGetWpl(pix) * pixGetHeight(pix); jbyteArray result = env->NewByteArray(size); if (result == NULL) { LOGE("Cannot allocate JNI Byte Array"); return NULL; } env->SetByteArrayRegion(result, 0, size, (jbyte *)pixGetData(pix)); return result; } jlong Java_com_googlecode_leptonica_android_Pix_nativeClone(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixClone(pixs); return (jlong) pixd; } jlong Java_com_googlecode_leptonica_android_Pix_nativeCopy(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixCopy(NULL, pixs); return (jlong) pixd; } jboolean Java_com_googlecode_leptonica_android_Pix_nativeInvert(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pixs = (PIX *) nativePix; if (pixInvert(pixs, pixs)) { return JNI_FALSE; } return JNI_TRUE; } void Java_com_googlecode_leptonica_android_Pix_nativeDestroy(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pix = (PIX *) nativePix; pixDestroy(&pix); } jboolean Java_com_googlecode_leptonica_android_Pix_nativeGetDimensions(JNIEnv *env, jclass clazz, jlong nativePix, jintArray dimensions) { PIX *pix = (PIX *) nativePix; jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL); l_int32 w, h, d; if (pixGetDimensions(pix, &w, &h, &d)) { return JNI_FALSE; } dimensionArray[0] = w; dimensionArray[1] = h; dimensionArray[2] = d; env->ReleaseIntArrayElements(dimensions, dimensionArray, 0); return JNI_TRUE; } jint Java_com_googlecode_leptonica_android_Pix_nativeGetWidth(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pix = (PIX *) nativePix; return (jint) pixGetWidth(pix); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetRefCount(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pix = (PIX *) nativePix; return (jint) pixGetRefcount(pix); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetHeight(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pix = (PIX *) nativePix; return (jint) pixGetHeight(pix); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetDepth(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pix = (PIX *) nativePix; return (jint) pixGetDepth(pix); } void Java_com_googlecode_leptonica_android_Pix_nativeSetPixel(JNIEnv *env, jclass clazz, jlong nativePix, jint xCoord, jint yCoord, jint argbColor) { PIX *pix = (PIX *) nativePix; l_int32 d = pixGetDepth(pix); l_int32 x = (l_int32) xCoord; l_int32 y = (l_int32) yCoord; // These shift values are based on RGBA_8888 l_uint8 r = (argbColor >> SK_R32_SHIFT) & 0xFF; l_uint8 g = (argbColor >> SK_G32_SHIFT) & 0xFF; l_uint8 b = (argbColor >> SK_B32_SHIFT) & 0xFF; l_uint8 a = (argbColor >> SK_A32_SHIFT) & 0xFF; l_uint8 gray = ((r + g + b) / 3) & 0xFF; l_uint32 color; switch (d) { case 1: // 1-bit binary color = gray > 128 ? 1 : 0; break; case 2: // 2-bit grayscale color = gray >> 6; break; case 4: // 4-bit grayscale color = gray >> 4; break; case 8: // 8-bit grayscale color = gray; break; case 24: // 24-bit RGB SET_DATA_BYTE(&color, COLOR_RED, r); SET_DATA_BYTE(&color, COLOR_GREEN, g); SET_DATA_BYTE(&color, COLOR_BLUE, b); break; case 32: // 32-bit ARGB SET_DATA_BYTE(&color, COLOR_RED, r); SET_DATA_BYTE(&color, COLOR_GREEN, g); SET_DATA_BYTE(&color, COLOR_BLUE, b); SET_DATA_BYTE(&color, L_ALPHA_CHANNEL, a); break; default: // unsupported LOGE("Not a supported color depth: %d", d); color = 0; break; } pixSetPixel(pix, x, y, color); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetPixel(JNIEnv *env, jclass clazz, jlong nativePix, jint xCoord, jint yCoord) { PIX *pix = (PIX *) nativePix; l_int32 d = pixGetDepth(pix); l_int32 x = (l_int32) xCoord; l_int32 y = (l_int32) yCoord; l_uint32 pixel; l_uint32 color; l_uint8 a, r, g, b; pixGetPixel(pix, x, y, &pixel); switch (d) { case 1: // 1-bit binary a = 0xFF; r = g = b = (pixel == 0 ? 0x00 : 0xFF); break; case 2: // 2-bit grayscale a = 0xFF; r = g = b = (pixel << 6 | pixel << 4 | pixel); break; case 4: // 4-bit grayscale a = 0xFF; r = g = b = (pixel << 4 | pixel); break; case 8: // 8-bit grayscale a = 0xFF; r = g = b = pixel; break; case 24: // 24-bit RGB a = 0xFF; r = (pixel >> L_RED_SHIFT) & 0xFF; g = (pixel >> L_GREEN_SHIFT) & 0xFF; b = (pixel >> L_BLUE_SHIFT) & 0xFF; break; case 32: // 32-bit RGBA r = (pixel >> L_RED_SHIFT) & 0xFF; g = (pixel >> L_GREEN_SHIFT) & 0xFF; b = (pixel >> L_BLUE_SHIFT) & 0xFF; a = (pixel >> L_ALPHA_SHIFT) & 0xFF; break; default: // Not supported LOGE("Not a supported color depth: %d", d); a = r = g = b = 0x00; break; } color = a << SK_A32_SHIFT; color |= r << SK_R32_SHIFT; color |= g << SK_G32_SHIFT; color |= b << SK_B32_SHIFT; return (jint) color; } jint Java_com_googlecode_leptonica_android_Pix_nativeGetSpp(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pix = (PIX *) nativePix; return pixGetSpp(pix); } jint Java_com_googlecode_leptonica_android_Pix_nativeGetInputFormat(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pix = (PIX *) nativePix; return pixGetInputFormat(pix); } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/pixa.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jlong Java_com_googlecode_leptonica_android_Pixa_nativeCreate(JNIEnv *env, jclass clazz, jint size) { PIXA *pixa = pixaCreate((l_int32) size); return (jlong) pixa; } jlong Java_com_googlecode_leptonica_android_Pixa_nativeCopy(JNIEnv *env, jclass clazz, jlong nativePixa) { PIXA *pixas = (PIXA *) nativePixa; PIXA *pixad = pixaCopy(pixas, L_CLONE); return (jlong) pixad; } jlong Java_com_googlecode_leptonica_android_Pixa_nativeSort(JNIEnv *env, jclass clazz, jlong nativePixa, jint field, jint order) { PIXA *pixas = (PIXA *) nativePixa; PIXA *pixad = pixaSort(pixas, field, order, NULL, L_CLONE); return (jlong) pixad; } void Java_com_googlecode_leptonica_android_Pixa_nativeDestroy(JNIEnv *env, jclass clazz, jlong nativePixa) { PIXA *pixa = (PIXA *) nativePixa; pixaDestroy(&pixa); } jboolean Java_com_googlecode_leptonica_android_Pixa_nativeJoin(JNIEnv *env, jclass clazz, jlong nativePixa, jlong otherPixa) { PIXA *pixa = (PIXA *) nativePixa; PIXA *pixas = (PIXA *) otherPixa; if (pixaJoin(pixa, pixas, 0, 0)) { return JNI_FALSE; } return JNI_TRUE; } jint Java_com_googlecode_leptonica_android_Pixa_nativeGetCount(JNIEnv *env, jclass clazz, jlong nativePixa) { PIXA *pixa = (PIXA *) nativePixa; return (jint) pixaGetCount(pixa); } void Java_com_googlecode_leptonica_android_Pixa_nativeAddPix(JNIEnv *env, jclass clazz, jlong nativePixa, jlong nativePix, jint mode) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = (PIX *) nativePix; pixaAddPix(pixa, pix, mode); } void Java_com_googlecode_leptonica_android_Pixa_nativeAddBox(JNIEnv *env, jclass clazz, jlong nativePixa, jlong nativeBox, jint mode) { PIXA *pixa = (PIXA *) nativePixa; BOX *box = (BOX *) nativeBox; pixaAddBox(pixa, box, mode); } void Java_com_googlecode_leptonica_android_Pixa_nativeAdd(JNIEnv *env, jclass clazz, jlong nativePixa, jlong nativePix, jlong nativeBox, jint mode) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = (PIX *) nativePix; BOX *box = (BOX *) nativeBox; pixaAddPix(pixa, pix, mode); pixaAddBox(pixa, box, mode); } void Java_com_googlecode_leptonica_android_Pixa_nativeReplacePix(JNIEnv *env, jclass clazz, jlong nativePixa, jint index, jlong nativePix, jlong nativeBox) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = (PIX *) nativePix; BOX *box = (BOX *) nativeBox; pixaReplacePix(pixa, index, pix, box); } void Java_com_googlecode_leptonica_android_Pixa_nativeMergeAndReplacePix(JNIEnv *env, jclass clazz, jlong nativePixa, jint indexA, jint indexB) { PIXA *pixa = (PIXA *) nativePixa; l_int32 op; l_int32 depth; l_int32 x, y, w, h; l_int32 dx, dy, dw, dh; PIX *pixA, *pixB, *pixd; BOX *boxA, *boxB, *boxd; pixA = pixaGetPix(pixa, indexA, L_CLONE); pixB = pixaGetPix(pixa, indexB, L_CLONE); boxA = pixaGetBox(pixa, indexA, L_CLONE); boxB = pixaGetBox(pixa, indexB, L_CLONE); boxd = boxBoundingRegion(boxA, boxB); depth = pixGetDepth(pixA); boxGetGeometry(boxd, &x, &y, &w, &h); pixd = pixCreate(w, h, depth); op = PIX_SRC | PIX_DST; boxGetGeometry(boxA, &dx, &dy, &dw, &dh); pixRasterop(pixd, dx - x, dy - y, dw, dh, op, pixA, 0, 0); pixDestroy(&pixA); boxDestroy(&boxA); boxGetGeometry(boxB, &dx, &dy, &dw, &dh); pixRasterop(pixd, dx - x, dy - y, dw, dh, op, pixB, 0, 0); pixDestroy(&pixB); boxDestroy(&boxB); pixaReplacePix(pixa, indexA, pixd, boxd); pixaRemovePix(pixa, indexB); } jboolean Java_com_googlecode_leptonica_android_Pixa_nativeWriteToFileRandomCmap(JNIEnv *env, jclass clazz, jlong nativePixa, jstring fileName, jint width, jint height) { PIX *pixtemp; PIXA *pixa = (PIXA *) nativePixa; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return JNI_FALSE; } if (pixaGetCount(pixa) > 0) { pixtemp = pixaDisplayRandomCmap(pixa, (l_int32) width, (l_int32) height); } else { pixtemp = pixCreate((l_int32) width, (l_int32) height, 1); } pixWrite(c_fileName, pixtemp, IFF_BMP); pixDestroy(&pixtemp); env->ReleaseStringUTFChars(fileName, c_fileName); return JNI_TRUE; } jlong Java_com_googlecode_leptonica_android_Pixa_nativeGetPix(JNIEnv *env, jclass clazz, jlong nativePixa, jint index) { PIXA *pixa = (PIXA *) nativePixa; PIX *pix = pixaGetPix(pixa, (l_int32) index, L_CLONE); return (jlong) pix; } jlong Java_com_googlecode_leptonica_android_Pixa_nativeGetBox(JNIEnv *env, jclass clazz, jlong nativePixa, jint index) { PIXA *pixa = (PIXA *) nativePixa; BOX *box = pixaGetBox(pixa, (l_int32) index, L_CLONE); return (jlong) box; } jboolean Java_com_googlecode_leptonica_android_Pixa_nativeGetBoxGeometry(JNIEnv *env, jclass clazz, jlong nativePixa, jint index, jintArray dimensions) { PIXA *pixa = (PIXA *) nativePixa; jint *dimensionArray = env->GetIntArrayElements(dimensions, NULL); l_int32 x, y, w, h; if (pixaGetBoxGeometry(pixa, (l_int32) index, &x, &y, &w, &h)) { return JNI_FALSE; } dimensionArray[0] = x; dimensionArray[1] = y; dimensionArray[2] = w; dimensionArray[3] = h; env->ReleaseIntArrayElements(dimensions, dimensionArray, 0); return JNI_TRUE; } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/readfile.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /************ * ReadFile * ************/ jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadMem(JNIEnv *env, jclass clazz, jbyteArray image, jint length) { jbyte *image_buffer = env->GetByteArrayElements(image, NULL); int buffer_length = env->GetArrayLength(image); PIX *pix = pixReadMem((const l_uint8 *) image_buffer, buffer_length); env->ReleaseByteArrayElements(image, image_buffer, JNI_ABORT); return (jlong) pix; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBytes8(JNIEnv *env, jclass clazz, jbyteArray data, jint w, jint h) { PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, 8); l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); l_int32 d; pixGetDimensions(pix, &w, &h, &d); LOGE("Created image width w=%d, h=%d, d=%d", w, h, d); return (jlong) pix; } jboolean Java_com_googlecode_leptonica_android_ReadFile_nativeReplaceBytes8(JNIEnv *env, jclass clazz, jlong nativePix, jbyteArray data, jint srcw, jint srch) { PIX *pix = (PIX *) nativePix; l_int32 w, h, d; pixGetDimensions(pix, &w, &h, &d); if (d != 8 || (l_int32) srcw != w || (l_int32) srch != h) { LOGE("Failed to replace bytes at w=%d, h=%d, d=%d with w=%d, h=%d", w, h, d, srcw, srch); return JNI_FALSE; } l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy(lineptrs[i], (byte_buffer + (i * w)), w); } env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT); pixCleanupByteProcessing(pix, lineptrs); return JNI_TRUE; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFiles(JNIEnv *env, jclass clazz, jstring dirName, jstring prefix) { PIXA *pixad = NULL; const char *c_dirName = env->GetStringUTFChars(dirName, NULL); if (c_dirName == NULL) { LOGE("could not extract dirName string!"); return JNI_FALSE; } const char *c_prefix = env->GetStringUTFChars(prefix, NULL); if (c_prefix == NULL) { LOGE("could not extract prefix string!"); return JNI_FALSE; } pixad = pixaReadFiles(c_dirName, c_prefix); env->ReleaseStringUTFChars(dirName, c_dirName); env->ReleaseStringUTFChars(prefix, c_prefix); return (jlong) pixad; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFile(JNIEnv *env, jclass clazz, jstring fileName) { PIX *pixd = NULL; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return JNI_FALSE; } pixd = pixRead(c_fileName); env->ReleaseStringUTFChars(fileName, c_fileName); return (jlong) pixd; } jlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBitmap(JNIEnv *env, jclass clazz, jobject bitmap) { LOGV(__FUNCTION__); l_int32 w, h, d; AndroidBitmapInfo info; void* pixels; int ret; if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) { LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret); return JNI_FALSE; } if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { LOGE("Bitmap format is not RGBA_8888 !"); return JNI_FALSE; } if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret); return JNI_FALSE; } PIX *pixd = pixCreate(info.width, info.height, 32); l_uint8 *src = (l_uint8 *) pixels; l_uint8 *dst = (l_uint8 *) pixGetData(pixd); l_int32 srcBpl = (info.stride); l_int32 dstBpl = pixGetWpl(pixd)*4; for (int dy = 0; dy < info.height; dy++) { memcpy(dst, src, 4 * info.width); dst += dstBpl; src += srcBpl; } pixEndianByteSwap(pixd); AndroidBitmap_unlockPixels(env, bitmap); return (jlong) pixd; } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/utilities.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /*************** * AdaptiveMap * ***************/ jlong Java_com_googlecode_leptonica_android_AdaptiveMap_nativeBackgroundNormMorph(JNIEnv *env, jclass clazz, jlong nativePix, jint reduction, jint size, jint bgval) { // Normalizes the background of each element in pixa. PIX *pixs = (PIX *) nativePix; PIX *pixd = pixBackgroundNormMorph(pixs, NULL, (l_int32) reduction, (l_int32) size, (l_int32) bgval); return jlong(pixd); } jlong Java_com_googlecode_leptonica_android_AdaptiveMap_nativePixContrastNorm(JNIEnv *env, jclass clazz, jlong nativePix, jint sizeX, jint sizeY, jint minDiff, jint smoothX, jint smoothY) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixContrastNorm(NULL, pixs, (l_int32) sizeX, (l_int32) sizeY, (l_int32) minDiff, (l_int32) smoothX, (l_int32) smoothY); return jlong(pixd); } /************ * Binarize * ************/ jlong Java_com_googlecode_leptonica_android_Binarize_nativeOtsuAdaptiveThreshold(JNIEnv *env, jclass clazz, jlong nativePix, jint sizeX, jint sizeY, jint smoothX, jint smoothY, jfloat scoreFract) { PIX *pixs = (PIX *) nativePix; PIX *pixd; if (pixOtsuAdaptiveThreshold(pixs, (l_int32) sizeX, (l_int32) sizeY, (l_int32) smoothX, (l_int32) smoothY, (l_float32) scoreFract, NULL, &pixd)) { return (jlong) 0; } return jlong(pixd); } jlong Java_com_googlecode_leptonica_android_Binarize_nativeSauvolaBinarizeTiled(JNIEnv *env, jclass clazz, jlong nativePix, jint whsize, jfloat factor, jint nx, jint ny) { PIX *pixs = (PIX *) nativePix; PIX *pixd; if (pixSauvolaBinarizeTiled(pixs, (l_int32) whsize, (l_float32) factor, (l_int32) nx, (l_int32) ny, NULL, &pixd)) { return (jlong) 0; } return jlong(pixd); } /******** * Clip * ********/ jlong Java_com_googlecode_leptonica_android_Clip_nativeClipRectangle(JNIEnv *env, jclass clazz, jlong nativePix, jlong nativeBox) { PIX *pixs = (PIX *) nativePix; BOX *box = (BOX *) nativeBox; PIX *pixd; pixd = pixClipRectangle(pixs,box,NULL); return jlong(pixd); } /*********** * Convert * ***********/ jlong Java_com_googlecode_leptonica_android_Convert_nativeConvertTo8(JNIEnv *env, jclass clazz, jlong nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixConvertTo8(pixs, FALSE); return jlong(pixd); } /******** * Edge * ********/ jlong Java_com_googlecode_leptonica_android_Edge_nativePixSobelEdgeFilter(JNIEnv *env, jclass clazz, jlong nativePix, jint orientFlag) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixSobelEdgeFilter(pixs, (l_int32) orientFlag); return jlong(pixd); } /*********** * Enhance * ***********/ jlong Java_com_googlecode_leptonica_android_Enhance_nativeUnsharpMasking(JNIEnv *env, jclass clazz, jlong nativePix, jint halfwidth, jfloat fract) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixUnsharpMasking(pixs, (l_int32) halfwidth, (l_float32) fract); return jlong(pixd); } /************* * GrayQuant * *************/ jlong Java_com_googlecode_leptonica_android_GrayQuant_nativePixThresholdToBinary(JNIEnv *env, jclass clazz, jlong nativePix, jint thresh) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixThresholdToBinary(pixs, (l_int32) thresh); return jlong(pixd); } /********** * JpegIO * **********/ jbyteArray Java_com_googlecode_leptonica_android_JpegIO_nativeCompressToJpeg(JNIEnv *env, jclass clazz, jlong nativePix, jint quality, jboolean progressive) { PIX *pix = (PIX *) nativePix; l_uint8 *data; size_t size; if (pixWriteMemJpeg(&data, &size, pix, (l_int32) quality, progressive == JNI_TRUE ? 1 : 0)) { LOGE("Failed to write JPEG data"); return NULL; } // TODO Can we just use the byte array directly? jbyteArray array = env->NewByteArray(size); env->SetByteArrayRegion(array, 0, size, (jbyte *) data); free(data); return array; } /************ * MorphApp * ************/ jlong Java_com_googlecode_leptonica_android_MorphApp_nativePixTophat(JNIEnv *env, jclass clazz, jlong nativePix, jint hsize, jint vsize, jint type) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixTophat(pixs, (l_int32) hsize, (l_int32) vsize, (l_int32) type); return jlong(pixd); } jlong Java_com_googlecode_leptonica_android_MorphApp_nativePixFastTophat(JNIEnv *env, jclass clazz, jlong nativePix, jint xsize, jint ysize, jint type) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixFastTophat(pixs, (l_int32) xsize, (l_int32) ysize, (l_int32) type); return jlong(pixd); } /********* * Scale * *********/ jlong Java_com_googlecode_leptonica_android_Scale_nativeScaleGeneral(JNIEnv *env, jclass clazz, jlong nativePix, jfloat scaleX, jfloat scaleY, jfloat sharpfract, jint sharpwidth) { PIX *pixs = (Pix *) nativePix; return (jlong) pixScaleGeneral(pixs, (l_float32) scaleX, (l_float32) scaleY,(l_float32) sharpfract, (l_int32) sharpwidth); } jlong Java_com_googlecode_leptonica_android_Scale_nativeScale(JNIEnv *env, jclass clazz, jlong nativePix, jfloat scaleX, jfloat scaleY) { PIX *pixs = (Pix *) nativePix; PIX *pixd = pixScale(pixs, (l_float32) scaleX, (l_float32) scaleY); return jlong(pixd); } /******** * Skew * ********/ jfloat Java_com_googlecode_leptonica_android_Skew_nativeFindSkew(JNIEnv *env, jclass clazz, jlong nativePix, jfloat sweepRange, jfloat sweepDelta, jint sweepReduction, jint searchReduction, jfloat searchMinDelta) { PIX *pixs = (PIX *) nativePix; l_float32 angle, conf; if (!pixFindSkewSweepAndSearch(pixs, &angle, &conf, (l_int32) sweepReduction, (l_int32) searchReduction, (l_float32) sweepRange, (l_int32) sweepDelta, (l_float32) searchMinDelta)) { if (conf <= 0) { return (jfloat) 0; } return (jfloat) angle; } return (jfloat) 0; } /********** * Rotate * **********/ jlong Java_com_googlecode_leptonica_android_Rotate_nativeRotate(JNIEnv *env, jclass clazz, jlong nativePix, jfloat degrees, jboolean quality, jboolean resize) { PIX *pixd; PIX *pixs = (PIX *) nativePix; l_float32 deg2rad = 3.1415926535 / 180.0; l_float32 radians = degrees * deg2rad; l_int32 w, h, bpp, type; pixGetDimensions(pixs, &w, &h, &bpp); if (bpp == 1 && quality == JNI_TRUE) { pixd = pixRotateBinaryNice(pixs, radians, L_BRING_IN_WHITE); } else { type = quality == JNI_TRUE ? L_ROTATE_AREA_MAP : L_ROTATE_SAMPLING; w = (resize == JNI_TRUE) ? w : 0; h = (resize == JNI_TRUE) ? h : 0; pixd = pixRotate(pixs, radians, type, L_BRING_IN_WHITE, w, h); } return jlong(pixd); } jlong Java_com_googlecode_leptonica_android_Rotate_nativeRotateOrth(JNIEnv *env, jclass clazz, jlong nativePix, jint quads) { PIX *pixs = (PIX *) nativePix; PIX *pixd; pixd = pixRotateOrth(pixs,(int)quads); return jlong(pixd); } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_leptonica_android/writefile.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /************* * WriteFile * *************/ jint Java_com_googlecode_leptonica_android_WriteFile_nativeWriteBytes8(JNIEnv *env, jclass clazz, jlong nativePix, jbyteArray data) { l_int32 w, h, d; PIX *pix = (PIX *) nativePix; pixGetDimensions(pix, &w, &h, &d); l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL); jbyte *data_buffer = env->GetByteArrayElements(data, NULL); l_uint8 *byte_buffer = (l_uint8 *) data_buffer; for (int i = 0; i < h; i++) { memcpy((byte_buffer + (i * w)), lineptrs[i], w); } env->ReleaseByteArrayElements(data, data_buffer, 0); pixCleanupByteProcessing(pix, lineptrs); return (jint)(w * h); } jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteImpliedFormat(JNIEnv *env, jclass clazz, jlong nativePix, jstring fileName) { PIX *pixs = (PIX *) nativePix; const char *c_fileName = env->GetStringUTFChars(fileName, NULL); if (c_fileName == NULL) { LOGE("could not extract fileName string!"); return JNI_FALSE; } jboolean result = JNI_TRUE; if (pixWriteImpliedFormat(c_fileName, pixs, 85, JNI_FALSE)) { LOGE("could not write pix data to %s", c_fileName); result = JNI_FALSE; } env->ReleaseStringUTFChars(fileName, c_fileName); return result; } jboolean Java_com_googlecode_leptonica_android_WriteFile_nativeWriteBitmap(JNIEnv *env, jclass clazz, jlong nativePix, jobject bitmap) { PIX *pixs = (PIX *) nativePix; l_int32 w, h, d; AndroidBitmapInfo info; void* pixels; int ret; if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) { LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret); return JNI_FALSE; } if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { LOGE("Bitmap format is not RGBA_8888 !"); return JNI_FALSE; } pixGetDimensions(pixs, &w, &h, &d); if (w != info.width || h != info.height) { LOGE("Bitmap width and height do not match Pix dimensions!"); return JNI_FALSE; } if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret); return JNI_FALSE; } pixEndianByteSwap(pixs); l_uint8 *dst = (l_uint8 *) pixels; l_uint8 *src = (l_uint8 *) pixGetData(pixs); l_int32 dstBpl = info.stride; l_int32 srcBpl = 4 * pixGetWpl(pixs); LOGI("Writing 32bpp RGBA bitmap (w=%d, h=%d, stride=%d) from %dbpp Pix (wpl=%d)", info.width, info.height, info.stride, d, pixGetWpl(pixs)); for (int dy = 0; dy < info.height; dy++) { l_uint8 *dstx = dst; l_uint8 *srcx = src; if (d == 32) { memcpy(dst, src, 4 * info.width); } else if (d == 8) { for (int dw = 0; dw < info.width; dw++) { dstx[0] = dstx[1] = dstx[2] = srcx[0]; dstx[3] = 0xFF; dstx += 4; srcx += 1; } } else if (d == 1) { for (int dw = 0; dw < info.width; dw++) { dstx[0] = dstx[1] = dstx[2] = (1 << (7 - (dw & 7)) & srcx[0]) ? 0x00 : 0xFF; dstx[3] = 0xFF; dstx += 4; srcx += ((dw % 8) == 7) ? 1 : 0; } } dst += dstBpl; src += srcBpl; } AndroidBitmap_unlockPixels(env, bitmap); return JNI_TRUE; } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_tesseract_android/Android.mk ================================================ LOCAL_PATH := $(call my-dir) TESSERACT_PATH := $(TESSERACT_PATH)/src ### jni include $(CLEAR_VARS) LOCAL_MODULE := libtess LOCAL_SRC_FILES += \ pageiterator.cpp \ resultiterator.cpp \ tessbaseapi.cpp LOCAL_C_INCLUDES += \ $(LOCAL_PATH) LOCAL_LDLIBS += \ -ljnigraphics \ -llog LOCAL_STATIC_LIBRARIES := libtess_static LOCAL_SHARED_LIBRARIES := liblept include $(BUILD_SHARED_LIBRARY) ### core static include $(CLEAR_VARS) LOCAL_MODULE := libtess_core_static LOCAL_THIN_ARCHIVE := true LOCAL_C_INCLUDES += $(LOCAL_PATH) # overriding some tesseract headers LOCAL_PATH := $(TESSERACT_PATH) TESSERACT_SRC_FILES := \ $(wildcard $(TESSERACT_PATH)/arch/*.cpp) \ $(wildcard $(TESSERACT_PATH)/ccstruct/*.cpp) \ $(wildcard $(TESSERACT_PATH)/ccutil/*.cpp) \ $(wildcard $(TESSERACT_PATH)/classify/*.cpp) \ $(wildcard $(TESSERACT_PATH)/cube/*.cpp) \ $(wildcard $(TESSERACT_PATH)/cutil/*.cpp) \ $(wildcard $(TESSERACT_PATH)/dict/*.cpp) \ BLACKLIST_SRC_FILES := \ ccutil/fileio.cpp \ %sse.cpp \ %avx2.cpp \ %avx.cpp \ LOCAL_SRC_FILES := \ $(filter-out $(BLACKLIST_SRC_FILES),$(subst $(LOCAL_PATH)/,,$(TESSERACT_SRC_FILES))) LOCAL_C_INCLUDES += \ $(TESSERACT_PATH)/api \ $(TESSERACT_PATH)/arch \ $(TESSERACT_PATH)/ccmain \ $(TESSERACT_PATH)/ccstruct \ $(TESSERACT_PATH)/ccutil \ $(TESSERACT_PATH)/classify \ $(TESSERACT_PATH)/cutil \ $(TESSERACT_PATH)/dict \ $(TESSERACT_PATH)/lstm \ $(TESSERACT_PATH)/textord \ $(TESSERACT_PATH)/training \ $(TESSERACT_PATH)/viewer \ $(TESSERACT_PATH)/wordrec LOCAL_CFLAGS := \ -DGRAPHICS_DISABLED \ -DPACKAGE_VERSION=\"4.1.0\" \ -DTESSERACT_MAJOR_VERSION=4 \ -DTESSERACT_MINOR_VERSION=1 \ -DTESSERACT_MICRO_VERSION=0 \ -Wno-shift-negative-value LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES) LOCAL_EXPORT_CFLAGS := $(LOCAL_CFLAGS) LOCAL_STATIC_LIBRARIES += liblept_static # to inherit C_INCLUDE and CFLAGS include $(BUILD_STATIC_LIBRARY) ### other static (split from _core to keep linker command line less than maximum) include $(CLEAR_VARS) LOCAL_MODULE := libtess_static LOCAL_THIN_ARCHIVE := true # tesseract (minus executable) BLACKLIST_SRC_FILES := \ %api/tesseractmain.cpp \ %viewer/svpaint.cpp TESSERACT_SRC_FILES := \ $(wildcard $(TESSERACT_PATH)/api/*.cpp) \ $(wildcard $(TESSERACT_PATH)/ccmain/*.cpp) \ $(wildcard $(TESSERACT_PATH)/lstm/*.cpp) \ $(wildcard $(TESSERACT_PATH)/textord/*.cpp) \ $(wildcard $(TESSERACT_PATH)/viewer/*.cpp) \ $(wildcard $(TESSERACT_PATH)/wordrec/*.cpp) LOCAL_PATH := $(TESSERACT_PATH) LOCAL_SRC_FILES := \ $(filter-out $(BLACKLIST_SRC_FILES),$(subst $(LOCAL_PATH)/,,$(TESSERACT_SRC_FILES))) LOCAL_STATIC_LIBRARIES := libtess_core_static LOCAL_STATIC_LIBRARIES += liblept_static # to inherit C_INCLUDE include $(BUILD_STATIC_LIBRARY) ### command line (statically linked to tesseract libs) include $(CLEAR_VARS) LOCAL_MODULE := tesseract TESSERACT_SRC_FILES := \ $(TESSERACT_PATH)/api/tesseractmain.cpp LOCAL_PATH := $(TESSERACT_PATH) LOCAL_SRC_FILES := \ $(subst $(LOCAL_PATH)/,,$(TESSERACT_SRC_FILES)) LOCAL_STATIC_LIBRARIES := libtess_static liblept_static LOCAL_LDLIBS += \ -llog include $(BUILD_EXECUTABLE) ================================================ FILE: tess-two/jni/com_googlecode_tesseract_android/common.h ================================================ /* * Copyright 2010, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TESSERACT_JNI_COMMON_H #define TESSERACT_JNI_COMMON_H #include #include #include #define LOG_TAG "Tesseract(native)" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__) #endif ================================================ FILE: tess-two/jni/com_googlecode_tesseract_android/debugpixa.h ================================================ #ifndef TESSERACT_CCSTRUCT_DEBUGPIXA_H_ #define TESSERACT_CCSTRUCT_DEBUGPIXA_H_ // dummy DebugPixa for Android #include "allheaders.h" namespace tesseract { // Class to hold a Pixa collection of debug images with captions and save them // to a PDF file. class DebugPixa { public: DebugPixa() { } // If the filename_ has been set and there are any debug images, they are // written to the set filename_. ~DebugPixa() { } // Adds the given pix to the set of pages in the PDF file, with the given // caption added to the top. void AddPix(const Pix* pix, const char* caption) { } // Sets the destination filename and enables images to be written to a PDF // on destruction. void WritePDF(const char* filename) { } }; } // namespace tesseract #endif // TESSERACT_CCSTRUCT_DEBUGPIXA_H_ ================================================ FILE: tess-two/jni/com_googlecode_tesseract_android/pageiterator.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "common.h" #include "pageiterator.h" #include "allheaders.h" #include "helpers.h" #include "pageres.h" #include "tesseractclass.h" using namespace tesseract; #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void Java_com_googlecode_tesseract_android_PageIterator_nativeBegin(JNIEnv *env, jclass clazz, jlong nativePageIterator) { ((PageIterator *) nativePageIterator)->Begin(); } jboolean Java_com_googlecode_tesseract_android_PageIterator_nativeNext(JNIEnv *env, jclass clazz, jlong nativePageIterator, jint level) { PageIterator *pageIterator = (PageIterator *) nativePageIterator; PageIteratorLevel enumLevel = (PageIteratorLevel) level; return pageIterator->Next(enumLevel) ? JNI_TRUE : JNI_FALSE; } jintArray Java_com_googlecode_tesseract_android_PageIterator_nativeBoundingBox(JNIEnv *env, jclass clazz, jlong nativePageIterator, jint level) { int size = 4; jintArray result = env->NewIntArray(size); LOG_ASSERT((result != NULL), "Could not create Java bounding box array!"); PageIterator *pageIterator = (PageIterator *) nativePageIterator; PageIteratorLevel enumLevel = (PageIteratorLevel) level; int x1, y1, x2, y2; pageIterator->BoundingBox(enumLevel, &x1, &y1, &x2, &y2); // fill a temp structure to use to populate the java int array jint fill[4]; fill[0] = x1; fill[1] = y1; fill[2] = x2; fill[3] = y2; env->SetIntArrayRegion(result, 0, size, fill); return result; } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_tesseract_android/resultiterator.cpp ================================================ /* * Copyright 2011, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "common.h" #include "resultiterator.h" #include "allheaders.h" #include "pageres.h" #include "tesseractclass.h" using namespace tesseract; #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ jstring Java_com_googlecode_tesseract_android_ResultIterator_nativeGetUTF8Text(JNIEnv *env, jclass clazz, jlong nativeResultIterator, jint level) { ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator; PageIteratorLevel enumLevel = (PageIteratorLevel) level; char *text = resultIterator->GetUTF8Text(enumLevel); jstring result = env->NewStringUTF(text); free(text); return result; } jfloat Java_com_googlecode_tesseract_android_ResultIterator_nativeConfidence(JNIEnv *env, jclass clazz, jlong nativeResultIterator, jint level) { ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator; PageIteratorLevel enumLevel = (PageIteratorLevel) level; return (jfloat) resultIterator->Confidence(enumLevel); } jobjectArray Java_com_googlecode_tesseract_android_ResultIterator_nativeGetSymbolChoices(JNIEnv *env, jclass clazz, jlong nativeResultIterator) { // Get the actual result iterator (as C object) ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator; // Create a choice iterator to determine the number of alternatives tesseract::ChoiceIterator ci(*resultIterator); int numberOfAlternatives = 0; do { numberOfAlternatives++; } while (ci.Next()); // Create a string array to hold the choices jobjectArray ret = (jobjectArray) env->NewObjectArray(numberOfAlternatives, env->FindClass("java/lang/String"), env->NewStringUTF("")); // Save each result to the output array int i = 0; tesseract::ChoiceIterator cb(*resultIterator); do { // Create the string output const char *utfText = cb.GetUTF8Text(); // Add each string to the object array elements char newString[strlen(utfText) + 7]; sprintf(newString, "%s|%.2f", utfText, cb.Confidence()); env->SetObjectArrayElement(ret, i, env->NewStringUTF(newString)); // Move to the next element in the list i++; } while(cb.Next()); // Return the string array return ret; } jboolean Java_com_googlecode_tesseract_android_ResultIterator_nativeIsAtBeginningOf(JNIEnv *env, jclass clazz, jlong nativeResultIterator, jint level) { ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator; PageIteratorLevel enumLevel = (PageIteratorLevel) level; return (jboolean) (resultIterator->IsAtBeginningOf(enumLevel) ? JNI_TRUE : JNI_FALSE); } jboolean Java_com_googlecode_tesseract_android_ResultIterator_nativeIsAtFinalElement(JNIEnv *env, jclass clazz, jlong nativeResultIterator, jint level, jint element) { ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator; PageIteratorLevel enumLevel = (PageIteratorLevel) level; PageIteratorLevel enumElement = (PageIteratorLevel) element; return (jboolean) (resultIterator->IsAtFinalElement(enumLevel, enumElement) ? JNI_TRUE : JNI_FALSE); } void Java_com_googlecode_tesseract_android_ResultIterator_nativeDelete(JNIEnv *env, jclass clazz, jlong nativeResultIterator) { ResultIterator *resultIterator = (ResultIterator *) nativeResultIterator; if (resultIterator != 0) { delete resultIterator; } } #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: tess-two/jni/com_googlecode_tesseract_android/tess_version.h ================================================ /* for Android, this header is intentionally left blank */ ================================================ FILE: tess-two/jni/com_googlecode_tesseract_android/tessbaseapi.cpp ================================================ /* * Copyright 2011, Google Inc. * Copyright 2011, Robert Theis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "android/bitmap.h" #include "common.h" #include "baseapi.h" #include "ocrclass.h" #include "allheaders.h" #include "renderer.h" static jmethodID method_onProgressValues; struct native_data_t { tesseract::TessBaseAPI api; PIX *pix; void *data; bool debug; Box* currentTextBox = NULL; l_int32 lastProgress; bool cancel_ocr; JNIEnv *cachedEnv; jobject* cachedObject; bool isStateValid() { if (cancel_ocr == false && cachedEnv != NULL && cachedObject != NULL) { return true; } else { LOGI("state is cancelled"); return false; } } void setTextBoundaries(l_uint32 x, l_uint32 y, l_uint32 width, l_uint32 height) { boxSetGeometry(currentTextBox, x, y, width, height); } void initStateVariables(JNIEnv* env, jobject *object) { cancel_ocr = false; cachedEnv = env; cachedObject = object; lastProgress = 0; } void resetStateVariables() { cancel_ocr = false; cachedEnv = NULL; cachedObject = NULL; lastProgress = 0; boxSetGeometry(currentTextBox, 0, 0, 0, 0); } native_data_t() { currentTextBox = boxCreate(0, 0, 0, 0); lastProgress = 0; pix = NULL; data = NULL; debug = false; cachedEnv = NULL; cachedObject = NULL; cancel_ocr = false; } ~native_data_t() { boxDestroy(¤tTextBox); } }; /** * Callback for Tesseract's monitor to cancel recognition. */ bool cancelFunc(void* cancel_this, int words) { native_data_t *nat = (native_data_t*)cancel_this; return nat->cancel_ocr; } /** * Callback for Tesseract's monitor to update progress. */ bool progressJavaCallback(ETEXT_DESC* monitor, int left, int right, int top, int bottom) { native_data_t *nat = (native_data_t*)monitor->cancel_this; l_int32 progress = monitor->progress; if (nat->isStateValid() && nat->currentTextBox != NULL) { if (progress > nat->lastProgress || left != 0 || right != 0 || top != 0 || bottom != 0) { int x, y, width, height; boxGetGeometry(nat->currentTextBox, &x, &y, &width, &height); nat->cachedEnv->CallVoidMethod(*(nat->cachedObject), method_onProgressValues, progress, (jint) left, (jint) right, (jint) top, (jint) bottom, (jint) x, (jint) (x + width), (jint) (y + height), (jint) y); nat->lastProgress = progress; } } return true; } #ifdef __cplusplus extern "C" { #endif jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("Failed to get the environment using GetEnv()"); return -1; } return JNI_VERSION_1_6; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClassInit(JNIEnv* env, jclass clazz) { method_onProgressValues = env->GetMethodID(clazz, "onProgressValues", "(IIIIIIIII)V"); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeConstruct(JNIEnv* env, jobject object) { native_data_t *nat = new native_data_t; if (nat == NULL) { LOGE("%s: out of memory!", __FUNCTION__); return 0; } return (jlong) nat; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeInit(JNIEnv *env, jobject thiz, jlong mNativeData, jstring dir, jstring lang) { native_data_t *nat = (native_data_t*) mNativeData; const char *c_dir = env->GetStringUTFChars(dir, NULL); const char *c_lang = env->GetStringUTFChars(lang, NULL); jboolean res = JNI_TRUE; if (nat->api.Init(c_dir, c_lang)) { LOGE("Could not initialize Tesseract API with language=%s!", c_lang); res = JNI_FALSE; } else { LOGI("Initialized Tesseract API with language=%s", c_lang); } env->ReleaseStringUTFChars(dir, c_dir); env->ReleaseStringUTFChars(lang, c_lang); return res; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeInitOem(JNIEnv *env, jobject thiz, jlong mNativeData, jstring dir, jstring lang, jint mode) { native_data_t *nat = (native_data_t*) mNativeData; const char *c_dir = env->GetStringUTFChars(dir, NULL); const char *c_lang = env->GetStringUTFChars(lang, NULL); jboolean res = JNI_TRUE; if (nat->api.Init(c_dir, c_lang, (tesseract::OcrEngineMode) mode)) { LOGE("Could not initialize Tesseract API with language=%s!", c_lang); res = JNI_FALSE; } else { LOGI("Initialized Tesseract API with language=%s", c_lang); } env->ReleaseStringUTFChars(dir, c_dir); env->ReleaseStringUTFChars(lang, c_lang); return res; } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetInitLanguagesAsString(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; const char *text = nat->api.GetInitLanguagesAsString(); jstring result = env->NewStringUTF(text); return result; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImageBytes(JNIEnv *env, jobject thiz, jlong mNativeData, jbyteArray data, jint width, jint height, jint bpp, jint bpl) { jbyte *data_array = env->GetByteArrayElements(data, NULL); int count = env->GetArrayLength(data); unsigned char* imagedata = (unsigned char *) malloc(count * sizeof(unsigned char)); // This is painfully slow, but necessary because we don't know // how many bits the JVM might be using to represent a byte for (int i = 0; i < count; i++) { imagedata[i] = (unsigned char) data_array[i]; } env->ReleaseByteArrayElements(data, data_array, JNI_ABORT); native_data_t *nat = (native_data_t*) mNativeData; nat->api.SetImage(imagedata, (int) width, (int) height, (int) bpp, (int) bpl); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = imagedata; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImagePix(JNIEnv *env, jobject thiz, jlong mNativeData, jlong nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixClone(pixs); native_data_t *nat = (native_data_t*) mNativeData; if (pixd) { l_int32 width = pixGetWidth(pixd); l_int32 height = pixGetHeight(pixd); nat->setTextBoundaries(0, 0, width, height); } nat->api.SetImage(pixd); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = pixd; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetRectangle(JNIEnv *env, jobject thiz, jlong mNativeData, jint left, jint top, jint width, jint height) { native_data_t *nat = (native_data_t*) mNativeData; nat->setTextBoundaries(left, top, width, height); nat->api.SetRectangle(left, top, width, height); } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetUTF8Text(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; nat->initStateVariables(env, &thiz); char *text = nat->api.GetUTF8Text(); jstring result = env->NewStringUTF(text); free(text); nat->resetStateVariables(); return result; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeStop(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; // Stop by setting a flag that's used by the monitor nat->resetStateVariables(); nat->cancel_ocr = true; } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeMeanConfidence(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; return (jint) nat->api.MeanTextConf(); } jintArray Java_com_googlecode_tesseract_android_TessBaseAPI_nativeWordConfidences(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; int *confs = nat->api.AllWordConfidences(); if (confs == NULL) { LOGE("Could not get word-confidence values!"); return NULL; } int len, *trav; for (len = 0, trav = confs; *trav != -1; trav++, len++) ; LOG_ASSERT((confs != NULL), "Confidence array has %d elements", len); jintArray ret = env->NewIntArray(len); LOG_ASSERT((ret != NULL), "Could not create Java confidence array!"); env->SetIntArrayRegion(ret, 0, len, confs); delete[] confs; return ret; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetVariable(JNIEnv *env, jobject thiz, jlong mNativeData, jstring var, jstring value) { native_data_t *nat = (native_data_t*) mNativeData; const char *c_var = env->GetStringUTFChars(var, NULL); const char *c_value = env->GetStringUTFChars(value, NULL); jboolean set = nat->api.SetVariable(c_var, c_value) ? JNI_TRUE : JNI_FALSE; env->ReleaseStringUTFChars(var, c_var); env->ReleaseStringUTFChars(value, c_value); return set; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClear(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; nat->api.Clear(); // Call between pages or documents etc to free up memory and forget adaptive data. nat->api.ClearAdaptiveClassifier(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeEnd(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; nat->api.End(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetDebug(JNIEnv *env, jobject thiz, jlong mNativeData, jboolean debug) { native_data_t *nat = (native_data_t*) mNativeData; nat->debug = (debug == JNI_TRUE) ? TRUE : FALSE; } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetPageSegMode(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; return nat->api.GetPageSegMode(); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetPageSegMode(JNIEnv *env, jobject thiz, jlong mNativeData, jint mode) { native_data_t *nat = (native_data_t*) mNativeData; nat->api.SetPageSegMode((tesseract::PageSegMode) mode); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetThresholdedImage(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; PIX *pix = nat->api.GetThresholdedImage(); return (jlong) pix; } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetRegions(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetRegions(&pixa); boxaDestroy(&boxa); return reinterpret_cast(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetTextlines(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetTextlines(&pixa, NULL); boxaDestroy(&boxa); return reinterpret_cast(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetStrips(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetStrips(&pixa, NULL); boxaDestroy(&boxa); return reinterpret_cast(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetWords(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetWords(&pixa); boxaDestroy(&boxa); return reinterpret_cast(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetConnectedComponents(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetConnectedComponents(&pixa); boxaDestroy(&boxa); return reinterpret_cast(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetResultIterator(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; return (jlong) nat->api.GetIterator(); } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetHOCRText(JNIEnv *env, jobject thiz, jlong mNativeData, jint page) { native_data_t *nat = (native_data_t*) mNativeData; nat->initStateVariables(env, &thiz); ETEXT_DESC monitor; monitor.progress_callback2 = progressJavaCallback; monitor.cancel = cancelFunc; monitor.cancel_this = nat; char *text = nat->api.GetHOCRText(&monitor, page); jstring result = env->NewStringUTF(text); free(text); nat->resetStateVariables(); return result; } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetBoxText(JNIEnv *env, jobject thiz, jlong mNativeData, jint page) { native_data_t *nat = (native_data_t*) mNativeData; char *text = nat->api.GetBoxText(page); jstring result = env->NewStringUTF(text); free(text); return result; } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetVersion(JNIEnv *env, jobject thiz, jlong mNativeData) { native_data_t *nat = (native_data_t*) mNativeData; const char *text = nat->api.Version(); jstring result = env->NewStringUTF(text); return result; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetInputName(JNIEnv *env, jobject thiz, jlong mNativeData, jstring name) { native_data_t *nat = (native_data_t*) mNativeData; const char *c_name = env->GetStringUTFChars(name, NULL); nat->api.SetInputName(c_name); env->ReleaseStringUTFChars(name, c_name); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetOutputName(JNIEnv *env, jobject thiz, jlong mNativeData, jstring name) { native_data_t *nat = (native_data_t*) mNativeData; const char *c_name = env->GetStringUTFChars(name, NULL); nat->api.SetOutputName(c_name); env->ReleaseStringUTFChars(name, c_name); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeReadConfigFile(JNIEnv *env, jobject thiz, jlong mNativeData, jstring fileName) { native_data_t *nat = (native_data_t*) mNativeData; const char *c_file_name = env->GetStringUTFChars(fileName, NULL); nat->api.ReadConfigFile(c_file_name); env->ReleaseStringUTFChars(fileName, c_file_name); } jlong Java_com_googlecode_tesseract_android_TessPdfRenderer_nativeCreate(JNIEnv *env, jobject thiz, jlong jTessBaseApi, jstring outputPath) { native_data_t *nat = (native_data_t*) jTessBaseApi; const char *c_output_path = env->GetStringUTFChars(outputPath, NULL); tesseract::TessPDFRenderer* result = new tesseract::TessPDFRenderer(c_output_path, nat->api.GetDatapath()); env->ReleaseStringUTFChars(outputPath, c_output_path); return (jlong) result; } void Java_com_googlecode_tesseract_android_TessPdfRenderer_nativeRecycle(JNIEnv *env, jobject thiz, jlong jPointer) { tesseract::TessPDFRenderer* renderer = (tesseract::TessPDFRenderer*) jPointer; delete renderer; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeBeginDocument(JNIEnv *env, jobject thiz, jlong jRenderer, jstring title) { const char *c_title = env->GetStringUTFChars(title, NULL); tesseract::TessPDFRenderer* pdfRenderer = (tesseract::TessPDFRenderer*) jRenderer; bool res = pdfRenderer->BeginDocument(c_title); env->ReleaseStringUTFChars(title, c_title); return (jboolean) (res ? JNI_TRUE : JNI_FALSE); } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeEndDocument(JNIEnv *env, jobject thiz, jlong jRenderer) { tesseract::TessPDFRenderer* pdfRenderer = (tesseract::TessPDFRenderer*) jRenderer; return pdfRenderer->EndDocument(); } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeAddPageToDocument(JNIEnv *env, jobject thiz, jlong mNativeData, jlong jPix, jstring jPath, jlong jRenderer) { tesseract::TessPDFRenderer* pdfRenderer = (tesseract::TessPDFRenderer*) jRenderer; native_data_t *nat = (native_data_t*) mNativeData; PIX* pix = (PIX*) jPix; const char *inputImage = env->GetStringUTFChars(jPath, NULL); nat->api.ProcessPage(pix, 0, inputImage, NULL, 0, pdfRenderer); env->ReleaseStringUTFChars(jPath, inputImage); return true; } #ifdef __cplusplus } #endif ================================================ FILE: tess-two/jni/libjpeg/Android.mk ================================================ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := libjpgt_static LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH) LOCAL_SRC_FILES := \ jaricom.c \ jcapimin.c \ jcapistd.c \ jcarith.c \ jccoefct.c \ jccolor.c \ jcdctmgr.c \ jchuff.c \ jcinit.c \ jcmainct.c \ jcmarker.c \ jcmaster.c \ jcomapi.c \ jcparam.c \ jcprepct.c \ jcsample.c \ jctrans.c \ jdapimin.c \ jdapistd.c \ jdarith.c \ jdatadst.c \ jdatasrc.c \ jdcoefct.c \ jdcolor.c \ jddctmgr.c \ jdhuff.c \ jdinput.c \ jdmainct.c \ jdmarker.c \ jdmaster.c \ jdmerge.c \ jdpostct.c \ jdsample.c \ jdtrans.c \ jerror.c \ jfdctflt.c \ jfdctfst.c \ jfdctint.c \ jidctflt.c \ jidctfst.c \ jidctint.c \ jquant1.c \ jquant2.c \ jutils.c \ jmemmgr.c \ jmemname.c LOCAL_CFLAGS := \ -include stdlib.h \ -Wno-deprecated-declarations \ -Wno-pointer-sign \ -Wno-implicit-function-declaration include $(BUILD_STATIC_LIBRARY) ================================================ FILE: tess-two/jni/libjpeg/Makefile.am ================================================ ## Process this file with automake to produce Makefile.in # # Automake Makefile for the JPEG library # # This file is written by Bob Friesenhahn, Guido Vollbeding # # Sources to build library LIBSOURCES = jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c @MEMORYMGR@.c # System dependent sources SYSDEPSOURCES = jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # Headers which are installed to support the library INSTINCLUDES = jerror.h jmorecfg.h jpeglib.h # Headers which are not installed OTHERINCLUDES = cderror.h cdjpeg.h jdct.h jinclude.h jmemsys.h jpegint.h \ jversion.h transupp.h # Manual pages (Automake uses 'MANS' for itself) DISTMANS= cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 wrjpgcom.1 # Other documentation files DOCS= README install.txt usage.txt wizard.txt example.c libjpeg.txt \ structure.txt coderules.txt filelist.txt change.log # Makefiles for various systems MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt # Configuration files CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms # Support scripts for configure CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib # Miscellaneous support files OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map # Test support files TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg # libtool libraries to build lib_LTLIBRARIES = libjpeg.la # Library sources for libjpeg.la libjpeg_la_SOURCES = $(LIBSOURCES) # LDFLAGS for libjpeg.la libjpeg_la_LDFLAGS = -no-undefined \ -version-info $(JPEG_LIB_VERSION) if HAVE_LD_VERSION_SCRIPT libjpeg_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libjpeg.map endif # Executables to build bin_PROGRAMS = cjpeg djpeg jpegtran rdjpgcom wrjpgcom # Executable sources & libs cjpeg_SOURCES = cjpeg.c rdppm.c rdgif.c rdtarga.c rdrle.c rdbmp.c \ rdswitch.c cdjpeg.c cjpeg_LDADD = libjpeg.la djpeg_SOURCES = djpeg.c wrppm.c wrgif.c wrtarga.c wrrle.c wrbmp.c \ rdcolmap.c cdjpeg.c djpeg_LDADD = libjpeg.la jpegtran_SOURCES = jpegtran.c rdswitch.c cdjpeg.c transupp.c jpegtran_LDADD = libjpeg.la rdjpgcom_SOURCES = rdjpgcom.c wrjpgcom_SOURCES = wrjpgcom.c # Manual pages to install man_MANS = $(DISTMANS) # Headers to install include_HEADERS = $(INSTINCLUDES) # Other distributed headers noinst_HEADERS = $(OTHERINCLUDES) # Other distributed files EXTRA_DIST = $(DOCS) $(DISTMANS) $(MKFILES) $(CONFIGFILES) $(SYSDEPSOURCES) \ $(OTHERFILES) $(TESTFILES) # Files to be cleaned CLEANFILES = testout.ppm testout.bmp testout.jpg testoutp.ppm testoutp.jpg \ testoutt.jpg # Install jconfig.h install-data-local: $(mkinstalldirs) $(DESTDIR)$(includedir) $(INSTALL_HEADER) jconfig.h $(DESTDIR)$(includedir)/jconfig.h # Uninstall jconfig.h uninstall-local: rm -f $(DESTDIR)$(includedir)/jconfig.h # Run tests test: check-local check-local: rm -f testout* ./djpeg -dct int -ppm -outfile testout.ppm $(srcdir)/testorig.jpg ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp $(srcdir)/testorig.jpg ./cjpeg -dct int -outfile testout.jpg $(srcdir)/testimg.ppm ./djpeg -dct int -ppm -outfile testoutp.ppm $(srcdir)/testprog.jpg ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg $(srcdir)/testimg.ppm ./jpegtran -outfile testoutt.jpg $(srcdir)/testprog.jpg cmp $(srcdir)/testimg.ppm testout.ppm cmp $(srcdir)/testimg.bmp testout.bmp cmp $(srcdir)/testimg.jpg testout.jpg cmp $(srcdir)/testimg.ppm testoutp.ppm cmp $(srcdir)/testimgp.jpg testoutp.jpg cmp $(srcdir)/testorig.jpg testoutt.jpg ================================================ FILE: tess-two/jni/libjpeg/README ================================================ The Independent JPEG Group's JPEG software ========================================== README for release 9b of 17-Jan-2016 ==================================== This distribution contains the ninth public release of the Independent JPEG Group's free JPEG software. You are welcome to redistribute this software and to use it for any purpose, subject to the conditions under LEGAL ISSUES, below. This software is the work of Tom Lane, Guido Vollbeding, Philip Gladstone, Bill Allombert, Jim Boucher, Lee Crocker, Bob Friesenhahn, Ben Jackson, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, Ge' Weijers, and other members of the Independent JPEG Group. IJG is not affiliated with the ISO/IEC JTC1/SC29/WG1 standards committee (previously known as JPEG, together with ITU-T SG16). DOCUMENTATION ROADMAP ===================== This file contains the following sections: OVERVIEW General description of JPEG and the IJG software. LEGAL ISSUES Copyright, lack of warranty, terms of distribution. REFERENCES Where to learn more about JPEG. ARCHIVE LOCATIONS Where to find newer versions of this software. ACKNOWLEDGMENTS Special thanks. FILE FORMAT WARS Software *not* to get. TO DO Plans for future IJG releases. Other documentation files in the distribution are: User documentation: install.txt How to configure and install the IJG software. usage.txt Usage instructions for cjpeg, djpeg, jpegtran, rdjpgcom, and wrjpgcom. *.1 Unix-style man pages for programs (same info as usage.txt). wizard.txt Advanced usage instructions for JPEG wizards only. change.log Version-to-version change highlights. Programmer and internal documentation: libjpeg.txt How to use the JPEG library in your own programs. example.c Sample code for calling the JPEG library. structure.txt Overview of the JPEG library's internal structure. filelist.txt Road map of IJG files. coderules.txt Coding style rules --- please read if you contribute code. Please read at least the files install.txt and usage.txt. Some information can also be found in the JPEG FAQ (Frequently Asked Questions) article. See ARCHIVE LOCATIONS below to find out where to obtain the FAQ article. If you want to understand how the JPEG code works, we suggest reading one or more of the REFERENCES, then looking at the documentation files (in roughly the order listed) before diving into the code. OVERVIEW ======== This package contains C software to implement JPEG image encoding, decoding, and transcoding. JPEG (pronounced "jay-peg") is a standardized compression method for full-color and grayscale images. This software implements JPEG baseline, extended-sequential, and progressive compression processes. Provision is made for supporting all variants of these processes, although some uncommon parameter settings aren't implemented yet. We have made no provision for supporting the hierarchical or lossless processes defined in the standard. We provide a set of library routines for reading and writing JPEG image files, plus two sample applications "cjpeg" and "djpeg", which use the library to perform conversion between JPEG and some other popular image file formats. The library is intended to be reused in other applications. In order to support file conversion and viewing software, we have included considerable functionality beyond the bare JPEG coding/decoding capability; for example, the color quantization modules are not strictly part of JPEG decoding, but they are essential for output to colormapped file formats or colormapped displays. These extra functions can be compiled out of the library if not required for a particular application. We have also included "jpegtran", a utility for lossless transcoding between different JPEG processes, and "rdjpgcom" and "wrjpgcom", two simple applications for inserting and extracting textual comments in JFIF files. The emphasis in designing this software has been on achieving portability and flexibility, while also making it fast enough to be useful. In particular, the software is not intended to be read as a tutorial on JPEG. (See the REFERENCES section for introductory material.) Rather, it is intended to be reliable, portable, industrial-strength code. We do not claim to have achieved that goal in every aspect of the software, but we strive for it. We welcome the use of this software as a component of commercial products. No royalty is required, but we do ask for an acknowledgement in product documentation, as described under LEGAL ISSUES. LEGAL ISSUES ============ In plain English: 1. We don't promise that this software works. (But if you find any bugs, please let us know!) 2. You can use this software for whatever you want. You don't have to pay us. 3. You may not pretend that you wrote this software. If you use it in a program, you must acknowledge somewhere in your documentation that you've used the IJG code. In legalese: The authors make NO WARRANTY or representation, either express or implied, with respect to this software, its quality, accuracy, merchantability, or fitness for a particular purpose. This software is provided "AS IS", and you, its user, assume the entire risk as to its quality and accuracy. This software is copyright (C) 1991-2016, Thomas G. Lane, Guido Vollbeding. All Rights Reserved except as specified below. Permission is hereby granted to use, copy, modify, and distribute this software (or portions thereof) for any purpose, without fee, subject to these conditions: (1) If any part of the source code for this software is distributed, then this README file must be included, with this copyright and no-warranty notice unaltered; and any additions, deletions, or changes to the original files must be clearly indicated in accompanying documentation. (2) If only executable code is distributed, then the accompanying documentation must state that "this software is based in part on the work of the Independent JPEG Group". (3) Permission for use of this software is granted only if the user accepts full responsibility for any undesirable consequences; the authors accept NO LIABILITY for damages of any kind. These conditions apply to any software derived from or based on the IJG code, not just to the unmodified library. If you use our work, you ought to acknowledge us. Permission is NOT granted for the use of any IJG author's name or company name in advertising or publicity relating to this software or products derived from it. This software may be referred to only as "the Independent JPEG Group's software". We specifically permit and encourage the use of this software as the basis of commercial products, provided that all warranty or liability claims are assumed by the product vendor. The Unix configuration script "configure" was produced with GNU Autoconf. It is copyright by the Free Software Foundation but is freely distributable. The same holds for its supporting scripts (config.guess, config.sub, ltmain.sh). Another support script, install-sh, is copyright by X Consortium but is also freely distributable. The IJG distribution formerly included code to read and write GIF files. To avoid entanglement with the Unisys LZW patent (now expired), GIF reading support has been removed altogether, and the GIF writer has been simplified to produce "uncompressed GIFs". This technique does not use the LZW algorithm; the resulting GIF files are larger than usual, but are readable by all standard GIF decoders. REFERENCES ========== We recommend reading one or more of these references before trying to understand the innards of the JPEG software. The best short technical introduction to the JPEG compression algorithm is Wallace, Gregory K. "The JPEG Still Picture Compression Standard", Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44. (Adjacent articles in that issue discuss MPEG motion picture compression, applications of JPEG, and related topics.) If you don't have the CACM issue handy, a PDF file containing a revised version of Wallace's article is available at http://www.ijg.org/files/Wallace.JPEG.pdf. The file (actually a preprint for an article that appeared in IEEE Trans. Consumer Electronics) omits the sample images that appeared in CACM, but it includes corrections and some added material. Note: the Wallace article is copyright ACM and IEEE, and it may not be used for commercial purposes. A somewhat less technical, more leisurely introduction to JPEG can be found in "The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides good explanations and example C code for a multitude of compression methods including JPEG. It is an excellent source if you are comfortable reading C code but don't know much about data compression in general. The book's JPEG sample code is far from industrial-strength, but when you are ready to look at a full implementation, you've got one here... The best currently available description of JPEG is the textbook "JPEG Still Image Data Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG standards (DIS 10918-1 and draft DIS 10918-2). Although this is by far the most detailed and comprehensive exposition of JPEG publicly available, we point out that it is still missing an explanation of the most essential properties and algorithms of the underlying DCT technology. If you think that you know about DCT-based JPEG after reading this book, then you are in delusion. The real fundamentals and corresponding potential of DCT-based JPEG are not publicly known so far, and that is the reason for all the mistaken developments taking place in the image coding domain. The original JPEG standard is divided into two parts, Part 1 being the actual specification, while Part 2 covers compliance testing methods. Part 1 is titled "Digital Compression and Coding of Continuous-tone Still Images, Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS 10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of Continuous-tone Still Images, Part 2: Compliance testing" and has document numbers ISO/IEC IS 10918-2, ITU-T T.83. IJG JPEG 8 introduced an implementation of the JPEG SmartScale extension which is specified in two documents: A contributed document at ITU and ISO with title "ITU-T JPEG-Plus Proposal for Extending ITU-T T.81 for Advanced Image Coding", April 2006, Geneva, Switzerland. The latest version of this document is Revision 3. And a contributed document ISO/IEC JTC1/SC29/WG1 N 5799 with title "Evolution of JPEG", June/July 2011, Berlin, Germany. IJG JPEG 9 introduces a reversible color transform for improved lossless compression which is described in a contributed document ISO/IEC JTC1/SC29/ WG1 N 6080 with title "JPEG 9 Lossless Coding", June/July 2012, Paris, France. The JPEG standard does not specify all details of an interchangeable file format. For the omitted details we follow the "JFIF" conventions, version 2. JFIF version 1 has been adopted as Recommendation ITU-T T.871 (05/2011) : Information technology - Digital compression and coding of continuous-tone still images: JPEG File Interchange Format (JFIF). It is available as a free download in PDF file format from http://www.itu.int/rec/T-REC-T.871. A PDF file of the older JFIF document is available at http://www.w3.org/Graphics/JPEG/jfif3.pdf. The TIFF 6.0 file format specification can be obtained by FTP from ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems. IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6). Instead, we recommend the JPEG design proposed by TIFF Technical Note #2 (Compression tag 7). Copies of this Note can be obtained from http://www.ijg.org/files/. It is expected that the next revision of the TIFF spec will replace the 6.0 JPEG design with the Note's design. Although IJG's own code does not support TIFF/JPEG, the free libtiff library uses our library to implement TIFF/JPEG per the Note. ARCHIVE LOCATIONS ================= The "official" archive site for this software is www.ijg.org. The most recent released version can always be found there in directory "files". This particular version will be archived as http://www.ijg.org/files/jpegsrc.v9b.tar.gz, and in Windows-compatible "zip" archive format as http://www.ijg.org/files/jpegsr9b.zip. The JPEG FAQ (Frequently Asked Questions) article is a source of some general information about JPEG. It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/ and other news.answers archive sites, including the official news.answers archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/. If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu with body send usenet/news.answers/jpeg-faq/part1 send usenet/news.answers/jpeg-faq/part2 ACKNOWLEDGMENTS =============== Thank to Juergen Bruder for providing me with a copy of the common DCT algorithm article, only to find out that I had come to the same result in a more direct and comprehensible way with a more generative approach. Thank to Istvan Sebestyen and Joan L. Mitchell for inviting me to the ITU JPEG (Study Group 16) meeting in Geneva, Switzerland. Thank to Thomas Wiegand and Gary Sullivan for inviting me to the Joint Video Team (MPEG & ITU) meeting in Geneva, Switzerland. Thank to Thomas Richter and Daniel Lee for inviting me to the ISO/IEC JTC1/SC29/WG1 (previously known as JPEG, together with ITU-T SG16) meeting in Berlin, Germany. Thank to John Korejwa and Massimo Ballerini for inviting me to fruitful consultations in Boston, MA and Milan, Italy. Thank to Hendrik Elstner, Roland Fassauer, Simone Zuck, Guenther Maier-Gerber, Walter Stoeber, Fred Schmitz, and Norbert Braunagel for corresponding business development. Thank to Nico Zschach and Dirk Stelling of the technical support team at the Digital Images company in Halle for providing me with extra equipment for configuration tests. Thank to Richard F. Lyon (then of Foveon Inc.) for fruitful communication about JPEG configuration in Sigma Photo Pro software. Thank to Andrew Finkenstadt for hosting the ijg.org site. Last but not least special thank to Thomas G. Lane for the original design and development of this singular software package. FILE FORMAT WARS ================ The ISO/IEC JTC1/SC29/WG1 standards committee (previously known as JPEG, together with ITU-T SG16) currently promotes different formats containing the name "JPEG" which is misleading because these formats are incompatible with original DCT-based JPEG and are based on faulty technologies. IJG therefore does not and will not support such momentary mistakes (see REFERENCES). There exist also distributions under the name "OpenJPEG" promoting such kind of formats which is misleading because they don't support original JPEG images. We have no sympathy for the promotion of inferior formats. Indeed, one of the original reasons for developing this free software was to help force convergence on common, interoperable format standards for JPEG files. Don't use an incompatible file format! (In any case, our decoder will remain capable of reading existing JPEG image files indefinitely.) The ISO committee pretends to be "responsible for the popular JPEG" in their public reports which is not true because they don't respond to actual requirements for the maintenance of the original JPEG specification. Furthermore, the ISO committee pretends to "ensure interoperability" with their standards which is not true because their "standards" support only application-specific and proprietary use cases and contain mathematically incorrect code. There are currently different distributions in circulation containing the name "libjpeg" which is misleading because they don't have the features and are incompatible with formats supported by actual IJG libjpeg distributions. One of those fakes is released by members of the ISO committee and just uses the name of libjpeg for misdirection of people, similar to the abuse of the name JPEG as described above, while having nothing in common with actual IJG libjpeg distributions and containing mathematically incorrect code. The other one claims to be a "derivative" or "fork" of the original libjpeg, but violates the license conditions as described under LEGAL ISSUES above and violates basic C programming properties. We have no sympathy for the release of misleading, incorrect and illegal distributions derived from obsolete code bases. Don't use an obsolete code base! According to the UCC (Uniform Commercial Code) law, IJG has the lawful and legal right to foreclose on certain standardization bodies and other institutions or corporations that knowingly perform substantial and systematic deceptive acts and practices, fraud, theft, and damaging of the value of the people of this planet without their knowing, willing and intentional consent. The titles, ownership, and rights of these institutions and all their assets are now duly secured and held in trust for the free people of this planet. People of the planet, on every country, may have a financial interest in the assets of these former principals, agents, and beneficiaries of the foreclosed institutions and corporations. IJG asserts what is: that each man, woman, and child has unalienable value and rights granted and deposited in them by the Creator and not any one of the people is subordinate to any artificial principality, corporate fiction or the special interest of another without their appropriate knowing, willing and intentional consent made by contract or accommodation agreement. IJG expresses that which already was. The people have already determined and demanded that public administration entities, national governments, and their supporting judicial systems must be fully transparent, accountable, and liable. IJG has secured the value for all concerned free people of the planet. A partial list of foreclosed institutions and corporations ("Hall of Shame") is currently prepared and will be published later. TO DO ===== Version 9 is the second release of a new generation JPEG standard to overcome the limitations of the original JPEG specification, and is the first true source reference JPEG codec. More features are being prepared for coming releases... Please send bug reports, offers of help, etc. to jpeg-info@jpegclub.org. ================================================ FILE: tess-two/jni/libjpeg/ar-lib ================================================ #! /bin/sh # Wrapper for Microsoft lib.exe me=ar-lib scriptversion=2012-03-01.08; # UTC # Copyright (C) 2010-2014 Free Software Foundation, Inc. # Written by Peter Rosin . # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . # func_error message func_error () { echo "$me: $1" 1>&2 exit 1 } file_conv= # func_file_conv build_file # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv in mingw) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin) file=`cygpath -m "$file" || echo "$file"` ;; wine) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_at_file at_file operation archive # Iterate over all members in AT_FILE performing OPERATION on ARCHIVE # for each of them. # When interpreting the content of the @FILE, do NOT use func_file_conv, # since the user would need to supply preconverted file names to # binutils ar, at least for MinGW. func_at_file () { operation=$2 archive=$3 at_file_contents=`cat "$1"` eval set x "$at_file_contents" shift for member do $AR -NOLOGO $operation:"$member" "$archive" || exit $? done } case $1 in '') func_error "no command. Try '$0 --help' for more information." ;; -h | --h*) cat < /* to declare isupper(), tolower() */ #ifdef NEED_SIGNAL_CATCHER #include /* to declare signal() */ #endif #ifdef USE_SETMODE #include /* to declare setmode()'s parameter macros */ /* If you have setmode() but not , just delete this line: */ #include /* to declare setmode() */ #endif /* * Signal catcher to ensure that temporary files are removed before aborting. * NB: for Amiga Manx C this is actually a global routine named _abort(); * we put "#define signal_catcher _abort" in jconfig.h. Talk about bogus... */ #ifdef NEED_SIGNAL_CATCHER static j_common_ptr sig_cinfo; void /* must be global for Manx C */ signal_catcher (int signum) { if (sig_cinfo != NULL) { if (sig_cinfo->err != NULL) /* turn off trace output */ sig_cinfo->err->trace_level = 0; jpeg_destroy(sig_cinfo); /* clean up memory allocation & temp files */ } exit(EXIT_FAILURE); } GLOBAL(void) enable_signal_catcher (j_common_ptr cinfo) { sig_cinfo = cinfo; #ifdef SIGINT /* not all systems have SIGINT */ signal(SIGINT, signal_catcher); #endif #ifdef SIGTERM /* not all systems have SIGTERM */ signal(SIGTERM, signal_catcher); #endif } #endif /* * Optional progress monitor: display a percent-done figure on stderr. */ #ifdef PROGRESS_REPORT METHODDEF(void) progress_monitor (j_common_ptr cinfo) { cd_progress_ptr prog = (cd_progress_ptr) cinfo->progress; int total_passes = prog->pub.total_passes + prog->total_extra_passes; int percent_done = (int) (prog->pub.pass_counter*100L/prog->pub.pass_limit); if (percent_done != prog->percent_done) { prog->percent_done = percent_done; if (total_passes > 1) { fprintf(stderr, "\rPass %d/%d: %3d%% ", prog->pub.completed_passes + prog->completed_extra_passes + 1, total_passes, percent_done); } else { fprintf(stderr, "\r %3d%% ", percent_done); } fflush(stderr); } } GLOBAL(void) start_progress_monitor (j_common_ptr cinfo, cd_progress_ptr progress) { /* Enable progress display, unless trace output is on */ if (cinfo->err->trace_level == 0) { progress->pub.progress_monitor = progress_monitor; progress->completed_extra_passes = 0; progress->total_extra_passes = 0; progress->percent_done = -1; cinfo->progress = &progress->pub; } } GLOBAL(void) end_progress_monitor (j_common_ptr cinfo) { /* Clear away progress display */ if (cinfo->err->trace_level == 0) { fprintf(stderr, "\r \r"); fflush(stderr); } } #endif /* * Case-insensitive matching of possibly-abbreviated keyword switches. * keyword is the constant keyword (must be lower case already), * minchars is length of minimum legal abbreviation. */ GLOBAL(boolean) keymatch (char * arg, const char * keyword, int minchars) { register int ca, ck; register int nmatched = 0; while ((ca = *arg++) != '\0') { if ((ck = *keyword++) == '\0') return FALSE; /* arg longer than keyword, no good */ if (isupper(ca)) /* force arg to lcase (assume ck is already) */ ca = tolower(ca); if (ca != ck) return FALSE; /* no good */ nmatched++; /* count matched characters */ } /* reached end of argument; fail if it's too short for unique abbrev */ if (nmatched < minchars) return FALSE; return TRUE; /* A-OK */ } /* * Routines to establish binary I/O mode for stdin and stdout. * Non-Unix systems often require some hacking to get out of text mode. */ GLOBAL(FILE *) read_stdin (void) { FILE * input_file = stdin; #ifdef USE_SETMODE /* need to hack file mode? */ setmode(fileno(stdin), O_BINARY); #endif #ifdef USE_FDOPEN /* need to re-open in binary mode? */ if ((input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) { fprintf(stderr, "Cannot reopen stdin\n"); exit(EXIT_FAILURE); } #endif return input_file; } GLOBAL(FILE *) write_stdout (void) { FILE * output_file = stdout; #ifdef USE_SETMODE /* need to hack file mode? */ setmode(fileno(stdout), O_BINARY); #endif #ifdef USE_FDOPEN /* need to re-open in binary mode? */ if ((output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) { fprintf(stderr, "Cannot reopen stdout\n"); exit(EXIT_FAILURE); } #endif return output_file; } ================================================ FILE: tess-two/jni/libjpeg/cdjpeg.h ================================================ /* * cdjpeg.h * * Copyright (C) 1994-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains common declarations for the sample applications * cjpeg and djpeg. It is NOT used by the core JPEG library. */ #define JPEG_CJPEG_DJPEG /* define proper options in jconfig.h */ #define JPEG_INTERNAL_OPTIONS /* cjpeg.c,djpeg.c need to see xxx_SUPPORTED */ #include "jinclude.h" #include "jpeglib.h" #include "jerror.h" /* get library error codes too */ #include "cderror.h" /* get application-specific error codes */ /* * Object interface for cjpeg's source file decoding modules */ typedef struct cjpeg_source_struct * cjpeg_source_ptr; struct cjpeg_source_struct { JMETHOD(void, start_input, (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)); JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)); JMETHOD(void, finish_input, (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)); FILE *input_file; JSAMPARRAY buffer; JDIMENSION buffer_height; }; /* * Object interface for djpeg's output file encoding modules */ typedef struct djpeg_dest_struct * djpeg_dest_ptr; struct djpeg_dest_struct { /* start_output is called after jpeg_start_decompress finishes. * The color map will be ready at this time, if one is needed. */ JMETHOD(void, start_output, (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)); /* Emit the specified number of pixel rows from the buffer. */ JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied)); /* Finish up at the end of the image. */ JMETHOD(void, finish_output, (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)); /* Target file spec; filled in by djpeg.c after object is created. */ FILE * output_file; /* Output pixel-row buffer. Created by module init or start_output. * Width is cinfo->output_width * cinfo->output_components; * height is buffer_height. */ JSAMPARRAY buffer; JDIMENSION buffer_height; }; /* * cjpeg/djpeg may need to perform extra passes to convert to or from * the source/destination file format. The JPEG library does not know * about these passes, but we'd like them to be counted by the progress * monitor. We use an expanded progress monitor object to hold the * additional pass count. */ struct cdjpeg_progress_mgr { struct jpeg_progress_mgr pub; /* fields known to JPEG library */ int completed_extra_passes; /* extra passes completed */ int total_extra_passes; /* total extra */ /* last printed percentage stored here to avoid multiple printouts */ int percent_done; }; typedef struct cdjpeg_progress_mgr * cd_progress_ptr; /* Short forms of external names for systems with brain-damaged linkers. */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jinit_read_bmp jIRdBMP #define jinit_write_bmp jIWrBMP #define jinit_read_gif jIRdGIF #define jinit_write_gif jIWrGIF #define jinit_read_ppm jIRdPPM #define jinit_write_ppm jIWrPPM #define jinit_read_rle jIRdRLE #define jinit_write_rle jIWrRLE #define jinit_read_targa jIRdTarga #define jinit_write_targa jIWrTarga #define read_quant_tables RdQTables #define read_scan_script RdScnScript #define set_quality_ratings SetQRates #define set_quant_slots SetQSlots #define set_sample_factors SetSFacts #define read_color_map RdCMap #define enable_signal_catcher EnSigCatcher #define start_progress_monitor StProgMon #define end_progress_monitor EnProgMon #define read_stdin RdStdin #define write_stdout WrStdout #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* Module selection routines for I/O modules. */ EXTERN(cjpeg_source_ptr) jinit_read_bmp JPP((j_compress_ptr cinfo)); EXTERN(djpeg_dest_ptr) jinit_write_bmp JPP((j_decompress_ptr cinfo, boolean is_os2)); EXTERN(cjpeg_source_ptr) jinit_read_gif JPP((j_compress_ptr cinfo)); EXTERN(djpeg_dest_ptr) jinit_write_gif JPP((j_decompress_ptr cinfo)); EXTERN(cjpeg_source_ptr) jinit_read_ppm JPP((j_compress_ptr cinfo)); EXTERN(djpeg_dest_ptr) jinit_write_ppm JPP((j_decompress_ptr cinfo)); EXTERN(cjpeg_source_ptr) jinit_read_rle JPP((j_compress_ptr cinfo)); EXTERN(djpeg_dest_ptr) jinit_write_rle JPP((j_decompress_ptr cinfo)); EXTERN(cjpeg_source_ptr) jinit_read_targa JPP((j_compress_ptr cinfo)); EXTERN(djpeg_dest_ptr) jinit_write_targa JPP((j_decompress_ptr cinfo)); /* cjpeg support routines (in rdswitch.c) */ EXTERN(boolean) read_quant_tables JPP((j_compress_ptr cinfo, char * filename, boolean force_baseline)); EXTERN(boolean) read_scan_script JPP((j_compress_ptr cinfo, char * filename)); EXTERN(boolean) set_quality_ratings JPP((j_compress_ptr cinfo, char *arg, boolean force_baseline)); EXTERN(boolean) set_quant_slots JPP((j_compress_ptr cinfo, char *arg)); EXTERN(boolean) set_sample_factors JPP((j_compress_ptr cinfo, char *arg)); /* djpeg support routines (in rdcolmap.c) */ EXTERN(void) read_color_map JPP((j_decompress_ptr cinfo, FILE * infile)); /* common support routines (in cdjpeg.c) */ EXTERN(void) enable_signal_catcher JPP((j_common_ptr cinfo)); EXTERN(void) start_progress_monitor JPP((j_common_ptr cinfo, cd_progress_ptr progress)); EXTERN(void) end_progress_monitor JPP((j_common_ptr cinfo)); EXTERN(boolean) keymatch JPP((char * arg, const char * keyword, int minchars)); EXTERN(FILE *) read_stdin JPP((void)); EXTERN(FILE *) write_stdout JPP((void)); /* miscellaneous useful macros */ #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */ #define READ_BINARY "r" #define WRITE_BINARY "w" #else #ifdef VMS /* VMS is very nonstandard */ #define READ_BINARY "rb", "ctx=stm" #define WRITE_BINARY "wb", "ctx=stm" #else /* standard ANSI-compliant case */ #define READ_BINARY "rb" #define WRITE_BINARY "wb" #endif #endif #ifndef EXIT_FAILURE /* define exit() codes if not provided */ #define EXIT_FAILURE 1 #endif #ifndef EXIT_SUCCESS #ifdef VMS #define EXIT_SUCCESS 1 /* VMS is very nonstandard */ #else #define EXIT_SUCCESS 0 #endif #endif #ifndef EXIT_WARNING #ifdef VMS #define EXIT_WARNING 1 /* VMS is very nonstandard */ #else #define EXIT_WARNING 2 #endif #endif ================================================ FILE: tess-two/jni/libjpeg/change.log ================================================ CHANGE LOG for Independent JPEG Group's JPEG software Version 9b 17-Jan-2016 ----------------------- Improvements and optimizations in DCT and color calculations. Normalize range limit array composition and access pattern. Thank to Sia Furler and Maddie Ziegler for inspiration. Use merged upsample with scaled DCT sizes larger than 8. Thank to Taylor Hatala for inspiration. Check for excessive comment lengths in argument parsing in wrjpgcom.c. Thank to Julian Cohen for hint. Add makefile.b32 for use with Borland C++ 32-bit (bcc32). Thank to Joe Slater for contribution. Document 'f' specifier for jpegtran -crop specification. Thank to Michele Martone for suggestion. Use defined value from header instead of hardwired number in rdswitch.c. Thank to Robert Sprowson for hint. Version 9a 19-Jan-2014 ----------------------- Add support for wide gamut color spaces (JFIF version 2). Improve clarity and accuracy in color conversion modules. Note: Requires rebuild of test images. Extend the bit depth support to all values from 8 to 12 (BITS_IN_JSAMPLE configuration option in jmorecfg.h). jpegtran now supports N bits sample data precision with all N from 8 to 12 in a single instance. Thank to Roland Fassauer for inspiration. Try to resolve issues with new boolean type definition. Thank also to v4hn for suggestion. Enable option to use default Huffman tables for lossless compression (for hardware solution), and in this case improve lossless RGB compression with reversible color transform. Thank to Benny Alexandar for hint. Extend the entropy decoding structure, so that extraneous bytes between compressed scan data and following marker can be reported correctly. Thank to Nigel Tao for hint. Add jpegtran -wipe option and extension for -crop. Thank to Andrew Senior, David Clunie, and Josef Schmid for suggestion. Version 9 13-Jan-2013 ---------------------- Add cjpeg -rgb1 option to create an RGB JPEG file, and insert a simple reversible color transform into the processing which significantly improves the compression. The recommended command for lossless coding of RGB images is now cjpeg -rgb1 -block 1 -arithmetic. As said, this option improves the compression significantly, but the files are not compatible with JPEG decoders prior to IJG v9 due to the included color transform. The used color transform and marker signaling is compatible with other JPEG standards (e.g., JPEG-LS part 2). Remove the automatic de-ANSI-fication support (Automake 1.12). Thank also to Nitin A Kamble for suggestion. Add remark for jpeg_mem_dest() in jdatadst.c. Thank to Elie-Gregoire Khoury for the hint. Support files with invalid component identifiers (created by Adobe PDF). Thank to Robin Watts for the suggestion. Adapt full buffer case in jcmainct.c for use with scaled DCT. Thank to Sergii Biloshytskyi for the suggestion. Add type identifier for declaration of noreturn functions. Thank to Brett L. Moore for the suggestion. Correct argument type in format string, avoid compiler warnings. Thank to Vincent Torri for hint. Add missing #include directives in configuration checks, avoid configuration errors. Thank to John Spencer for the hint. Version 8d 15-Jan-2012 ----------------------- Add cjpeg -rgb option to create RGB JPEG files. Using this switch suppresses the conversion from RGB colorspace input to the default YCbCr JPEG colorspace. This feature allows true lossless JPEG coding of RGB color images. The recommended command for this purpose is currently cjpeg -rgb -block 1 -arithmetic. SmartScale capable decoder (introduced with IJG JPEG 8) required. Thank to Michael Koch for the initial suggestion. Add option to disable the region adjustment in the transupp crop code. Thank to Jeffrey Friedl for the suggestion. Thank to Richard Jones and Edd Dawson for various minor corrections. Thank to Akim Demaille for configure.ac cleanup. Version 8c 16-Jan-2011 ----------------------- Add option to compression library and cjpeg (-block N) to use different DCT block size. All N from 1 to 16 are possible. Default is 8 (baseline format). Larger values produce higher compression, smaller values produce higher quality. SmartScale capable decoder (introduced with IJG JPEG 8) required. Version 8b 16-May-2010 ----------------------- Repair problem in new memory source manager with corrupt JPEG data. Thank to Ted Campbell and Samuel Chun for the report. Repair problem in Makefile.am test target. Thank to anonymous user for the report. Support MinGW installation with automatic configure. Thank to Volker Grabsch for the suggestion. Version 8a 28-Feb-2010 ----------------------- Writing tables-only datastreams via jpeg_write_tables works again. Support 32-bit BMPs (RGB image with Alpha channel) for read in cjpeg. Thank to Brett Blackham for the suggestion. Improve accuracy in floating point IDCT calculation. Thank to Robert Hooke for the hint. Version 8 10-Jan-2010 ---------------------- jpegtran now supports the same -scale option as djpeg for "lossless" resize. An implementation of the JPEG SmartScale extension is required for this feature. A (draft) specification of the JPEG SmartScale extension is available as a contributed document at ITU and ISO. Revision 2 or later of the document is required (latest document version is Revision 3). The SmartScale extension will enable more features beside lossless resize in future implementations, as described in the document (new compression options). Add sanity check in BMP reader module to avoid cjpeg crash for empty input image (thank to Isaev Ildar of ISP RAS, Moscow, RU for reporting this error). Add data source and destination managers for read from and write to memory buffers. New API functions jpeg_mem_src and jpeg_mem_dest. Thank to Roberto Boni from Italy for the suggestion. Version 7 27-Jun-2009 ---------------------- New scaled DCTs implemented. djpeg now supports scalings N/8 with all N from 1 to 16. cjpeg now supports scalings 8/N with all N from 1 to 16. Scaled DCTs with size larger than 8 are now also used for resolving the common 2x2 chroma subsampling case without additional spatial resampling. Separate spatial resampling for those kind of files is now only necessary for N>8 scaling cases. Furthermore, separate scaled DCT functions are provided for direct resolving of the common asymmetric subsampling cases (2x1 and 1x2) without additional spatial resampling. cjpeg -quality option has been extended for support of separate quality settings for luminance and chrominance (or in general, for every provided quantization table slot). New API function jpeg_default_qtables() and q_scale_factor array in library. Added -nosmooth option to cjpeg, complementary to djpeg. New variable "do_fancy_downsampling" in library, complement to fancy upsampling. Fancy upsampling now uses direct DCT scaling with sizes larger than 8. The old method is not reversible and has been removed. Support arithmetic entropy encoding and decoding. Added files jaricom.c, jcarith.c, jdarith.c. Straighten the file structure: Removed files jidctred.c, jcphuff.c, jchuff.h, jdphuff.c, jdhuff.h. jpegtran has a new "lossless" cropping feature. Implement -perfect option in jpegtran, new API function jtransform_perfect_transform() in transupp. (DP 204_perfect.dpatch) Better error messages for jpegtran fopen failure. (DP 203_jpegtran_errmsg.dpatch) Fix byte order issue with 16bit PPM/PGM files in rdppm.c/wrppm.c: according to Netpbm, the de facto standard implementation of the PNM formats, the most significant byte is first. (DP 203_rdppm.dpatch) Add -raw option to rdjpgcom not to mangle the output. (DP 205_rdjpgcom_raw.dpatch) Make rdjpgcom locale aware. (DP 201_rdjpgcom_locale.dpatch) Add extern "C" to jpeglib.h. This avoids the need to put extern "C" { ... } around #include "jpeglib.h" in your C++ application. Defining the symbol DONT_USE_EXTERN_C in the configuration prevents this. (DP 202_jpeglib.h_c++.dpatch) Version 6b 27-Mar-1998 ----------------------- jpegtran has new features for lossless image transformations (rotation and flipping) as well as "lossless" reduction to grayscale. jpegtran now copies comments by default; it has a -copy switch to enable copying all APPn blocks as well, or to suppress comments. (Formerly it always suppressed comments and APPn blocks.) jpegtran now also preserves JFIF version and resolution information. New decompressor library feature: COM and APPn markers found in the input file can be saved in memory for later use by the application. (Before, you had to code this up yourself with a custom marker processor.) There is an unused field "void * client_data" now in compress and decompress parameter structs; this may be useful in some applications. JFIF version number information is now saved by the decoder and accepted by the encoder. jpegtran uses this to copy the source file's version number, to ensure "jpegtran -copy all" won't create bogus files that contain JFXX extensions but claim to be version 1.01. Applications that generate their own JFXX extension markers also (finally) have a supported way to cause the encoder to emit JFIF version number 1.02. djpeg's trace mode reports JFIF 1.02 thumbnail images as such, rather than as unknown APP0 markers. In -verbose mode, djpeg and rdjpgcom will try to print the contents of APP12 markers as text. Some digital cameras store useful text information in APP12 markers. Handling of truncated data streams is more robust: blocks beyond the one in which the error occurs will be output as uniform gray, or left unchanged if decoding a progressive JPEG. The appearance no longer depends on the Huffman tables being used. Huffman tables are checked for validity much more carefully than before. To avoid the Unisys LZW patent, djpeg's GIF output capability has been changed to produce "uncompressed GIFs", and cjpeg's GIF input capability has been removed altogether. We're not happy about it either, but there seems to be no good alternative. The configure script now supports building libjpeg as a shared library on many flavors of Unix (all the ones that GNU libtool knows how to build shared libraries for). Use "./configure --enable-shared" to try this out. New jconfig file and makefiles for Microsoft Visual C++ and Developer Studio. Also, a jconfig file and a build script for Metrowerks CodeWarrior on Apple Macintosh. makefile.dj has been updated for DJGPP v2, and there are miscellaneous other minor improvements in the makefiles. jmemmac.c now knows how to create temporary files following Mac System 7 conventions. djpeg's -map switch is now able to read raw-format PPM files reliably. cjpeg -progressive -restart no longer generates any unnecessary DRI markers. Multiple calls to jpeg_simple_progression for a single JPEG object no longer leak memory. Version 6a 7-Feb-96 -------------------- Library initialization sequence modified to detect version mismatches and struct field packing mismatches between library and calling application. This change requires applications to be recompiled, but does not require any application source code change. All routine declarations changed to the style "GLOBAL(type) name ...", that is, GLOBAL, LOCAL, METHODDEF, EXTERN are now macros taking the routine's return type as an argument. This makes it possible to add Microsoft-style linkage keywords to all the routines by changing just these macros. Note that any application code that was using these macros will have to be changed. DCT coefficient quantization tables are now stored in normal array order rather than zigzag order. Application code that calls jpeg_add_quant_table, or otherwise manipulates quantization tables directly, will need to be changed. If you need to make such code work with either older or newer versions of the library, a test like "#if JPEG_LIB_VERSION >= 61" is recommended. djpeg's trace capability now dumps DQT tables in natural order, not zigzag order. This allows the trace output to be made into a "-qtables" file more easily. New system-dependent memory manager module for use on Apple Macintosh. Fix bug in cjpeg's -smooth option: last one or two scanlines would be duplicates of the prior line unless the image height mod 16 was 1 or 2. Repair minor problems in VMS, BCC, MC6 makefiles. New configure script based on latest GNU Autoconf. Correct the list of include files needed by MetroWerks C for ccommand(). Numerous small documentation updates. Version 6 2-Aug-95 ------------------- Progressive JPEG support: library can read and write full progressive JPEG files. A "buffered image" mode supports incremental decoding for on-the-fly display of progressive images. Simply recompiling an existing IJG-v5-based decoder with v6 should allow it to read progressive files, though of course without any special progressive display. New "jpegtran" application performs lossless transcoding between different JPEG formats; primarily, it can be used to convert baseline to progressive JPEG and vice versa. In support of jpegtran, the library now allows lossless reading and writing of JPEG files as DCT coefficient arrays. This ability may be of use in other applications. Notes for programmers: * We changed jpeg_start_decompress() to be able to suspend; this makes all decoding modes available to suspending-input applications. However, existing applications that use suspending input will need to be changed to check the return value from jpeg_start_decompress(). You don't need to do anything if you don't use a suspending data source. * We changed the interface to the virtual array routines: access_virt_array routines now take a count of the number of rows to access this time. The last parameter to request_virt_array routines is now interpreted as the maximum number of rows that may be accessed at once, but not necessarily the height of every access. Version 5b 15-Mar-95 --------------------- Correct bugs with grayscale images having v_samp_factor > 1. jpeg_write_raw_data() now supports output suspension. Correct bugs in "configure" script for case of compiling in a directory other than the one containing the source files. Repair bug in jquant1.c: sometimes didn't use as many colors as it could. Borland C makefile and jconfig file work under either MS-DOS or OS/2. Miscellaneous improvements to documentation. Version 5a 7-Dec-94 -------------------- Changed color conversion roundoff behavior so that grayscale values are represented exactly. (This causes test image files to change.) Make ordered dither use 16x16 instead of 4x4 pattern for a small quality improvement. New configure script based on latest GNU Autoconf. Fix configure script to handle CFLAGS correctly. Rename *.auto files to *.cfg, so that configure script still works if file names have been truncated for DOS. Fix bug in rdbmp.c: didn't allow for extra data between header and image. Modify rdppm.c/wrppm.c to handle 2-byte raw PPM/PGM formats for 12-bit data. Fix several bugs in rdrle.c. NEED_SHORT_EXTERNAL_NAMES option was broken. Revise jerror.h/jerror.c for more flexibility in message table. Repair oversight in jmemname.c NO_MKTEMP case: file could be there but unreadable. Version 5 24-Sep-94 -------------------- Version 5 represents a nearly complete redesign and rewrite of the IJG software. Major user-visible changes include: * Automatic configuration simplifies installation for most Unix systems. * A range of speed vs. image quality tradeoffs are supported. This includes resizing of an image during decompression: scaling down by a factor of 1/2, 1/4, or 1/8 is handled very efficiently. * New programs rdjpgcom and wrjpgcom allow insertion and extraction of text comments in a JPEG file. The application programmer's interface to the library has changed completely. Notable improvements include: * We have eliminated the use of callback routines for handling the uncompressed image data. The application now sees the library as a set of routines that it calls to read or write image data on a scanline-by-scanline basis. * The application image data is represented in a conventional interleaved- pixel format, rather than as a separate array for each color channel. This can save a copying step in many programs. * The handling of compressed data has been cleaned up: the application can supply routines to source or sink the compressed data. It is possible to suspend processing on source/sink buffer overrun, although this is not supported in all operating modes. * All static state has been eliminated from the library, so that multiple instances of compression or decompression can be active concurrently. * JPEG abbreviated datastream formats are supported, ie, quantization and Huffman tables can be stored separately from the image data. * And not only that, but the documentation of the library has improved considerably! The last widely used release before the version 5 rewrite was version 4A of 18-Feb-93. Change logs before that point have been discarded, since they are not of much interest after the rewrite. ================================================ FILE: tess-two/jni/libjpeg/cjpeg.1 ================================================ .TH CJPEG 1 "26 July 2015" .SH NAME cjpeg \- compress an image file to a JPEG file .SH SYNOPSIS .B cjpeg [ .I options ] [ .I filename ] .LP .SH DESCRIPTION .LP .B cjpeg compresses the named image file, or the standard input if no file is named, and produces a JPEG/JFIF file on the standard output. The currently supported input file formats are: PPM (PBMPLUS color format), PGM (PBMPLUS grayscale format), BMP, Targa, and RLE (Utah Raster Toolkit format). (RLE is supported only if the URT library is available.) .SH OPTIONS All switch names may be abbreviated; for example, .B \-grayscale may be written .B \-gray or .BR \-gr . Most of the "basic" switches can be abbreviated to as little as one letter. Upper and lower case are equivalent (thus .B \-BMP is the same as .BR \-bmp ). British spellings are also accepted (e.g., .BR \-greyscale ), though for brevity these are not mentioned below. .PP The basic switches are: .TP .BI \-quality " N[,...]" Scale quantization tables to adjust image quality. Quality is 0 (worst) to 100 (best); default is 75. (See below for more info.) .TP .B \-grayscale Create monochrome JPEG file from color input. Be sure to use this switch when compressing a grayscale BMP file, because .B cjpeg isn't bright enough to notice whether a BMP file uses only shades of gray. By saying .BR \-grayscale , you'll get a smaller JPEG file that takes less time to process. .TP .B \-rgb Create RGB JPEG file. Using this switch suppresses the conversion from RGB colorspace input to the default YCbCr JPEG colorspace. You can use this switch in combination with the .BI \-block " N" switch (see below) for lossless JPEG coding. See also the .B \-rgb1 switch below. .TP .B \-optimize Perform optimization of entropy encoding parameters. Without this, default encoding parameters are used. .B \-optimize usually makes the JPEG file a little smaller, but .B cjpeg runs somewhat slower and needs much more memory. Image quality and speed of decompression are unaffected by .BR \-optimize . .TP .B \-progressive Create progressive JPEG file (see below). .TP .BI \-scale " M/N" Scale the output image by a factor M/N. Currently supported scale factors are M/N with all N from 1 to 16, where M is the destination DCT size, which is 8 by default (see .BI \-block " N" switch below). .TP .B \-targa Input file is Targa format. Targa files that contain an "identification" field will not be automatically recognized by .BR cjpeg ; for such files you must specify .B \-targa to make .B cjpeg treat the input as Targa format. For most Targa files, you won't need this switch. .PP The .B \-quality switch lets you trade off compressed file size against quality of the reconstructed image: the higher the quality setting, the larger the JPEG file, and the closer the output image will be to the original input. Normally you want to use the lowest quality setting (smallest file) that decompresses into something visually indistinguishable from the original image. For this purpose the quality setting should be between 50 and 95; the default of 75 is often about right. If you see defects at .B \-quality 75, then go up 5 or 10 counts at a time until you are happy with the output image. (The optimal setting will vary from one image to another.) .PP .B \-quality 100 will generate a quantization table of all 1's, minimizing loss in the quantization step (but there is still information loss in subsampling, as well as roundoff error). This setting is mainly of interest for experimental purposes. Quality values above about 95 are .B not recommended for normal use; the compressed file size goes up dramatically for hardly any gain in output image quality. .PP In the other direction, quality values below 50 will produce very small files of low image quality. Settings around 5 to 10 might be useful in preparing an index of a large image library, for example. Try .B \-quality 2 (or so) for some amusing Cubist effects. (Note: quality values below about 25 generate 2-byte quantization tables, which are considered optional in the JPEG standard. .B cjpeg emits a warning message when you give such a quality value, because some other JPEG programs may be unable to decode the resulting file. Use .B \-baseline if you need to ensure compatibility at low quality values.) .PP The .B \-quality option has been extended in IJG version 7 for support of separate quality settings for luminance and chrominance (or in general, for every provided quantization table slot). This feature is useful for high-quality applications which cannot accept the damage of color data by coarse subsampling settings. You can now easily reduce the color data amount more smoothly with finer control without separate subsampling. The resulting file is fully compliant with standard JPEG decoders. Note that the .B \-quality ratings refer to the quantization table slots, and that the last value is replicated if there are more q-table slots than parameters. The default q-table slots are 0 for luminance and 1 for chrominance with default tables as given in the JPEG standard. This is compatible with the old behaviour in case that only one parameter is given, which is then used for both luminance and chrominance (slots 0 and 1). More or custom quantization tables can be set with .B \-qtables and assigned to components with .B \-qslots parameter (see the "wizard" switches below). .B Caution: You must explicitly add .BI \-sample " 1x1" for efficient separate color quality selection, since the default value used by library is 2x2! .PP The .B \-progressive switch creates a "progressive JPEG" file. In this type of JPEG file, the data is stored in multiple scans of increasing quality. If the file is being transmitted over a slow communications link, the decoder can use the first scan to display a low-quality image very quickly, and can then improve the display with each subsequent scan. The final image is exactly equivalent to a standard JPEG file of the same quality setting, and the total file size is about the same --- often a little smaller. .PP Switches for advanced users: .TP .B \-arithmetic Use arithmetic coding. .B Caution: arithmetic coded JPEG is not yet widely implemented, so many decoders will be unable to view an arithmetic coded JPEG file at all. .TP .BI \-block " N" Set DCT block size. All N from 1 to 16 are possible. Default is 8 (baseline format). Larger values produce higher compression, smaller values produce higher quality (exact DCT stage possible with 1 or 2; with the default quality of 75 and default Luminance qtable the DCT+Quantization stage is lossless for N=1). .B Caution: An implementation of the JPEG SmartScale extension is required for this feature. SmartScale enabled JPEG is not yet widely implemented, so many decoders will be unable to view a SmartScale extended JPEG file at all. .TP .B \-rgb1 Create RGB JPEG file with reversible color transform. Works like the .B \-rgb switch (see above) and inserts a simple reversible color transform into the processing which significantly improves the compression. Use this switch in combination with the .BI \-block " N" switch (see above) for lossless JPEG coding. .B Caution: A decoder with inverse color transform support is required for this feature. Reversible color transform support is not yet widely implemented, so many decoders will be unable to view a reversible color transformed JPEG file at all. .TP .B \-bgycc Create big gamut YCC JPEG file. In this type of encoding the color difference components are quantized further by a factor of 2 compared to the normal Cb/Cr values, thus creating space to allow larger color values with higher saturation than the normal gamut limits to be encoded. In order to compensate for the loss of color fidelity compared to a normal YCC encoded file, the color quantization tables can be adjusted accordingly. For example, .B cjpeg \-bgycc \-quality 80,90 will give similar results as .B cjpeg \-quality 80. .B Caution: For correct decompression a decoder with big gamut YCC support (JFIF version 2) is required. An old decoder may or may not display a big gamut YCC encoded JPEG file, depending on JFIF version check and corresponding warning/error configuration. In case of a granted decompression the old decoder will display the image with half saturated colors. .TP .B \-dct int Use integer DCT method (default). .TP .B \-dct fast Use fast integer DCT (less accurate). .TP .B \-dct float Use floating-point DCT method. The float method is very slightly more accurate than the int method, but is much slower unless your machine has very fast floating-point hardware. Also note that results of the floating-point method may vary slightly across machines, while the integer methods should give the same results everywhere. The fast integer method is much less accurate than the other two. .TP .B \-nosmooth Don't use high-quality downsampling. .TP .BI \-restart " N" Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if "B" is attached to the number. .B \-restart 0 (the default) means no restart markers. .TP .BI \-smooth " N" Smooth the input image to eliminate dithering noise. N, ranging from 1 to 100, indicates the strength of smoothing. 0 (the default) means no smoothing. .TP .BI \-maxmemory " N" Set limit for amount of memory to use in processing large images. Value is in thousands of bytes, or millions of bytes if "M" is attached to the number. For example, .B \-max 4m selects 4000000 bytes. If more space is needed, temporary files will be used. .TP .BI \-outfile " name" Send output image to the named file, not to standard output. .TP .B \-verbose Enable debug printout. More .BR \-v 's give more output. Also, version information is printed at startup. .TP .B \-debug Same as .BR \-verbose . .PP The .B \-restart option inserts extra markers that allow a JPEG decoder to resynchronize after a transmission error. Without restart markers, any damage to a compressed file will usually ruin the image from the point of the error to the end of the image; with restart markers, the damage is usually confined to the portion of the image up to the next restart marker. Of course, the restart markers occupy extra space. We recommend .B \-restart 1 for images that will be transmitted across unreliable networks such as Usenet. .PP The .B \-smooth option filters the input to eliminate fine-scale noise. This is often useful when converting dithered images to JPEG: a moderate smoothing factor of 10 to 50 gets rid of dithering patterns in the input file, resulting in a smaller JPEG file and a better-looking image. Too large a smoothing factor will visibly blur the image, however. .PP Switches for wizards: .TP .B \-baseline Force baseline-compatible quantization tables to be generated. This clamps quantization values to 8 bits even at low quality settings. (This switch is poorly named, since it does not ensure that the output is actually baseline JPEG. For example, you can use .B \-baseline and .B \-progressive together.) .TP .BI \-qtables " file" Use the quantization tables given in the specified text file. .TP .BI \-qslots " N[,...]" Select which quantization table to use for each color component. .TP .BI \-sample " HxV[,...]" Set JPEG sampling factors for each color component. .TP .BI \-scans " file" Use the scan script given in the specified text file. .PP The "wizard" switches are intended for experimentation with JPEG. If you don't know what you are doing, \fBdon't use them\fR. These switches are documented further in the file wizard.txt. .SH EXAMPLES .LP This example compresses the PPM file foo.ppm with a quality factor of 60 and saves the output as foo.jpg: .IP .B cjpeg \-quality .I 60 foo.ppm .B > .I foo.jpg .SH HINTS Color GIF files are not the ideal input for JPEG; JPEG is really intended for compressing full-color (24-bit) images. In particular, don't try to convert cartoons, line drawings, and other images that have only a few distinct colors. GIF works great on these, JPEG does not. If you want to convert a GIF to JPEG, you should experiment with .BR cjpeg 's .B \-quality and .B \-smooth options to get a satisfactory conversion. .B \-smooth 10 or so is often helpful. .PP Avoid running an image through a series of JPEG compression/decompression cycles. Image quality loss will accumulate; after ten or so cycles the image may be noticeably worse than it was after one cycle. It's best to use a lossless format while manipulating an image, then convert to JPEG format when you are ready to file the image away. .PP The .B \-optimize option to .B cjpeg is worth using when you are making a "final" version for posting or archiving. It's also a win when you are using low quality settings to make very small JPEG files; the percentage improvement is often a lot more than it is on larger files. (At present, .B \-optimize mode is always selected when generating progressive JPEG files.) .SH ENVIRONMENT .TP .B JPEGMEM If this environment variable is set, its value is the default memory limit. The value is specified as described for the .B \-maxmemory switch. .B JPEGMEM overrides the default value specified when the program was compiled, and itself is overridden by an explicit .BR \-maxmemory . .SH SEE ALSO .BR djpeg (1), .BR jpegtran (1), .BR rdjpgcom (1), .BR wrjpgcom (1) .br .BR ppm (5), .BR pgm (5) .br Wallace, Gregory K. "The JPEG Still Picture Compression Standard", Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44. .SH AUTHOR Independent JPEG Group .SH BUGS GIF input files are no longer supported, to avoid the Unisys LZW patent (now expired). (Conversion of GIF files to JPEG is usually a bad idea anyway.) .PP Not all variants of BMP and Targa file formats are supported. .PP The .B \-targa switch is not a bug, it's a feature. (It would be a bug if the Targa format designers had not been clueless.) ================================================ FILE: tess-two/jni/libjpeg/cjpeg.c ================================================ /* * cjpeg.c * * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2003-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a command-line user interface for the JPEG compressor. * It should work on any system with Unix- or MS-DOS-style command lines. * * Two different command line styles are permitted, depending on the * compile-time switch TWO_FILE_COMMANDLINE: * cjpeg [options] inputfile outputfile * cjpeg [options] [inputfile] * In the second style, output is always to standard output, which you'd * normally redirect to a file or pipe to some other program. Input is * either from a named file or from standard input (typically redirected). * The second style is convenient on Unix but is unhelpful on systems that * don't support pipes. Also, you MUST use the first style if your system * doesn't do binary I/O to stdin/stdout. * To simplify script writing, the "-outfile" switch is provided. The syntax * cjpeg [options] -outfile outputfile inputfile * works regardless of which command line style is used. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #include "jversion.h" /* for version message */ #ifdef USE_CCOMMAND /* command-line reader for Macintosh */ #ifdef __MWERKS__ #include /* Metrowerks needs this */ #include /* ... and this */ #endif #ifdef THINK_C #include /* Think declares it here */ #endif #endif /* Create the add-on message string table. */ #define JMESSAGE(code,string) string , static const char * const cdjpeg_message_table[] = { #include "cderror.h" NULL }; /* * This routine determines what format the input file is, * and selects the appropriate input-reading module. * * To determine which family of input formats the file belongs to, * we may look only at the first byte of the file, since C does not * guarantee that more than one character can be pushed back with ungetc. * Looking at additional bytes would require one of these approaches: * 1) assume we can fseek() the input file (fails for piped input); * 2) assume we can push back more than one character (works in * some C implementations, but unportable); * 3) provide our own buffering (breaks input readers that want to use * stdio directly, such as the RLE library); * or 4) don't put back the data, and modify the input_init methods to assume * they start reading after the start of file (also breaks RLE library). * #1 is attractive for MS-DOS but is untenable on Unix. * * The most portable solution for file types that can't be identified by their * first byte is to make the user tell us what they are. This is also the * only approach for "raw" file types that contain only arbitrary values. * We presently apply this method for Targa files. Most of the time Targa * files start with 0x00, so we recognize that case. Potentially, however, * a Targa file could start with any byte value (byte 0 is the length of the * seldom-used ID field), so we provide a switch to force Targa input mode. */ static boolean is_targa; /* records user -targa switch */ LOCAL(cjpeg_source_ptr) select_file_type (j_compress_ptr cinfo, FILE * infile) { int c; if (is_targa) { #ifdef TARGA_SUPPORTED return jinit_read_targa(cinfo); #else ERREXIT(cinfo, JERR_TGA_NOTCOMP); #endif } if ((c = getc(infile)) == EOF) ERREXIT(cinfo, JERR_INPUT_EMPTY); if (ungetc(c, infile) == EOF) ERREXIT(cinfo, JERR_UNGETC_FAILED); switch (c) { #ifdef BMP_SUPPORTED case 'B': return jinit_read_bmp(cinfo); #endif #ifdef GIF_SUPPORTED case 'G': return jinit_read_gif(cinfo); #endif #ifdef PPM_SUPPORTED case 'P': return jinit_read_ppm(cinfo); #endif #ifdef RLE_SUPPORTED case 'R': return jinit_read_rle(cinfo); #endif #ifdef TARGA_SUPPORTED case 0x00: return jinit_read_targa(cinfo); #endif default: ERREXIT(cinfo, JERR_UNKNOWN_FORMAT); break; } return NULL; /* suppress compiler warnings */ } /* * Argument-parsing code. * The switch parser is designed to be useful with DOS-style command line * syntax, ie, intermixed switches and file names, where only the switches * to the left of a given file name affect processing of that file. * The main program in this file doesn't actually use this capability... */ static const char * progname; /* program name for error messages */ static char * outfilename; /* for -outfile switch */ LOCAL(void) usage (void) /* complain about bad command line */ { fprintf(stderr, "usage: %s [switches] ", progname); #ifdef TWO_FILE_COMMANDLINE fprintf(stderr, "inputfile outputfile\n"); #else fprintf(stderr, "[inputfile]\n"); #endif fprintf(stderr, "Switches (names may be abbreviated):\n"); fprintf(stderr, " -quality N[,...] Compression quality (0..100; 5-95 is useful range)\n"); fprintf(stderr, " -grayscale Create monochrome JPEG file\n"); fprintf(stderr, " -rgb Create RGB JPEG file\n"); #ifdef ENTROPY_OPT_SUPPORTED fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n"); #endif #ifdef C_PROGRESSIVE_SUPPORTED fprintf(stderr, " -progressive Create progressive JPEG file\n"); #endif #ifdef DCT_SCALING_SUPPORTED fprintf(stderr, " -scale M/N Scale image by fraction M/N, eg, 1/2\n"); #endif #ifdef TARGA_SUPPORTED fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n"); #endif fprintf(stderr, "Switches for advanced users:\n"); #ifdef C_ARITH_CODING_SUPPORTED fprintf(stderr, " -arithmetic Use arithmetic coding\n"); #endif #ifdef DCT_SCALING_SUPPORTED fprintf(stderr, " -block N DCT block size (1..16; default is 8)\n"); #endif #if JPEG_LIB_VERSION_MAJOR >= 9 fprintf(stderr, " -rgb1 Create RGB JPEG file with reversible color transform\n"); fprintf(stderr, " -bgycc Create big gamut YCC JPEG file\n"); #endif #ifdef DCT_ISLOW_SUPPORTED fprintf(stderr, " -dct int Use integer DCT method%s\n", (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : "")); #endif #ifdef DCT_IFAST_SUPPORTED fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n", (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : "")); #endif #ifdef DCT_FLOAT_SUPPORTED fprintf(stderr, " -dct float Use floating-point DCT method%s\n", (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : "")); #endif fprintf(stderr, " -nosmooth Don't use high-quality downsampling\n"); fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n"); #ifdef INPUT_SMOOTHING_SUPPORTED fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n"); #endif fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n"); fprintf(stderr, " -outfile name Specify name for output file\n"); fprintf(stderr, " -verbose or -debug Emit debug output\n"); fprintf(stderr, "Switches for wizards:\n"); fprintf(stderr, " -baseline Force baseline quantization tables\n"); fprintf(stderr, " -qtables file Use quantization tables given in file\n"); fprintf(stderr, " -qslots N[,...] Set component quantization tables\n"); fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n"); #ifdef C_MULTISCAN_FILES_SUPPORTED fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n"); #endif exit(EXIT_FAILURE); } LOCAL(int) parse_switches (j_compress_ptr cinfo, int argc, char **argv, int last_file_arg_seen, boolean for_real) /* Parse optional switches. * Returns argv[] index of first file-name argument (== argc if none). * Any file names with indexes <= last_file_arg_seen are ignored; * they have presumably been processed in a previous iteration. * (Pass 0 for last_file_arg_seen on the first or only iteration.) * for_real is FALSE on the first (dummy) pass; we may skip any expensive * processing. */ { int argn; char * arg; boolean force_baseline; boolean simple_progressive; char * qualityarg = NULL; /* saves -quality parm if any */ char * qtablefile = NULL; /* saves -qtables filename if any */ char * qslotsarg = NULL; /* saves -qslots parm if any */ char * samplearg = NULL; /* saves -sample parm if any */ char * scansarg = NULL; /* saves -scans parm if any */ /* Set up default JPEG parameters. */ force_baseline = FALSE; /* by default, allow 16-bit quantizers */ simple_progressive = FALSE; is_targa = FALSE; outfilename = NULL; cinfo->err->trace_level = 0; /* Scan command line options, adjust parameters */ for (argn = 1; argn < argc; argn++) { arg = argv[argn]; if (*arg != '-') { /* Not a switch, must be a file name argument */ if (argn <= last_file_arg_seen) { outfilename = NULL; /* -outfile applies to just one input file */ continue; /* ignore this name if previously processed */ } break; /* else done parsing switches */ } arg++; /* advance past switch marker character */ if (keymatch(arg, "arithmetic", 1)) { /* Use arithmetic coding. */ #ifdef C_ARITH_CODING_SUPPORTED cinfo->arith_code = TRUE; #else fprintf(stderr, "%s: sorry, arithmetic coding not supported\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "baseline", 2)) { /* Force baseline-compatible output (8-bit quantizer values). */ force_baseline = TRUE; } else if (keymatch(arg, "block", 2)) { /* Set DCT block size. */ #if defined DCT_SCALING_SUPPORTED && JPEG_LIB_VERSION_MAJOR >= 8 && \ (JPEG_LIB_VERSION_MAJOR > 8 || JPEG_LIB_VERSION_MINOR >= 3) int val; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%d", &val) != 1) usage(); if (val < 1 || val > 16) usage(); cinfo->block_size = val; #else fprintf(stderr, "%s: sorry, block size setting not supported\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "dct", 2)) { /* Select DCT algorithm. */ if (++argn >= argc) /* advance to next argument */ usage(); if (keymatch(argv[argn], "int", 1)) { cinfo->dct_method = JDCT_ISLOW; } else if (keymatch(argv[argn], "fast", 2)) { cinfo->dct_method = JDCT_IFAST; } else if (keymatch(argv[argn], "float", 2)) { cinfo->dct_method = JDCT_FLOAT; } else usage(); } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) { /* Enable debug printouts. */ /* On first -d, print version identification */ static boolean printed_version = FALSE; if (! printed_version) { fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n", JVERSION, JCOPYRIGHT); printed_version = TRUE; } cinfo->err->trace_level++; } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) { /* Force a monochrome JPEG file to be generated. */ jpeg_set_colorspace(cinfo, JCS_GRAYSCALE); } else if (keymatch(arg, "rgb", 3) || keymatch(arg, "rgb1", 4)) { /* Force an RGB JPEG file to be generated. */ #if JPEG_LIB_VERSION_MAJOR >= 9 /* Note: Entropy table assignment in jpeg_set_colorspace depends * on color_transform. */ cinfo->color_transform = arg[3] ? JCT_SUBTRACT_GREEN : JCT_NONE; #endif jpeg_set_colorspace(cinfo, JCS_RGB); } else if (keymatch(arg, "bgycc", 5)) { /* Force a big gamut YCC JPEG file to be generated. */ #if JPEG_LIB_VERSION_MAJOR >= 9 && \ (JPEG_LIB_VERSION_MAJOR > 9 || JPEG_LIB_VERSION_MINOR >= 1) jpeg_set_colorspace(cinfo, JCS_BG_YCC); #else fprintf(stderr, "%s: sorry, BG_YCC colorspace not supported\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "maxmemory", 3)) { /* Maximum memory in Kb (or Mb with 'm'). */ long lval; char ch = 'x'; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1) usage(); if (ch == 'm' || ch == 'M') lval *= 1000L; cinfo->mem->max_memory_to_use = lval * 1000L; } else if (keymatch(arg, "nosmooth", 3)) { /* Suppress fancy downsampling. */ cinfo->do_fancy_downsampling = FALSE; } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) { /* Enable entropy parm optimization. */ #ifdef ENTROPY_OPT_SUPPORTED cinfo->optimize_coding = TRUE; #else fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "outfile", 4)) { /* Set output file name. */ if (++argn >= argc) /* advance to next argument */ usage(); outfilename = argv[argn]; /* save it away for later use */ } else if (keymatch(arg, "progressive", 1)) { /* Select simple progressive mode. */ #ifdef C_PROGRESSIVE_SUPPORTED simple_progressive = TRUE; /* We must postpone execution until num_components is known. */ #else fprintf(stderr, "%s: sorry, progressive output was not compiled\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "quality", 1)) { /* Quality ratings (quantization table scaling factors). */ if (++argn >= argc) /* advance to next argument */ usage(); qualityarg = argv[argn]; } else if (keymatch(arg, "qslots", 2)) { /* Quantization table slot numbers. */ if (++argn >= argc) /* advance to next argument */ usage(); qslotsarg = argv[argn]; /* Must delay setting qslots until after we have processed any * colorspace-determining switches, since jpeg_set_colorspace sets * default quant table numbers. */ } else if (keymatch(arg, "qtables", 2)) { /* Quantization tables fetched from file. */ if (++argn >= argc) /* advance to next argument */ usage(); qtablefile = argv[argn]; /* We postpone actually reading the file in case -quality comes later. */ } else if (keymatch(arg, "restart", 1)) { /* Restart interval in MCU rows (or in MCUs with 'b'). */ long lval; char ch = 'x'; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1) usage(); if (lval < 0 || lval > 65535L) usage(); if (ch == 'b' || ch == 'B') { cinfo->restart_interval = (unsigned int) lval; cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */ } else { cinfo->restart_in_rows = (int) lval; /* restart_interval will be computed during startup */ } } else if (keymatch(arg, "sample", 2)) { /* Set sampling factors. */ if (++argn >= argc) /* advance to next argument */ usage(); samplearg = argv[argn]; /* Must delay setting sample factors until after we have processed any * colorspace-determining switches, since jpeg_set_colorspace sets * default sampling factors. */ } else if (keymatch(arg, "scale", 4)) { /* Scale the image by a fraction M/N. */ if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%u/%u", &cinfo->scale_num, &cinfo->scale_denom) != 2) usage(); } else if (keymatch(arg, "scans", 4)) { /* Set scan script. */ #ifdef C_MULTISCAN_FILES_SUPPORTED if (++argn >= argc) /* advance to next argument */ usage(); scansarg = argv[argn]; /* We must postpone reading the file in case -progressive appears. */ #else fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "smooth", 2)) { /* Set input smoothing factor. */ int val; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%d", &val) != 1) usage(); if (val < 0 || val > 100) usage(); cinfo->smoothing_factor = val; } else if (keymatch(arg, "targa", 1)) { /* Input file is Targa format. */ is_targa = TRUE; } else { usage(); /* bogus switch */ } } /* Post-switch-scanning cleanup */ if (for_real) { /* Set quantization tables for selected quality. */ /* Some or all may be overridden if -qtables is present. */ if (qualityarg != NULL) /* process -quality if it was present */ if (! set_quality_ratings(cinfo, qualityarg, force_baseline)) usage(); if (qtablefile != NULL) /* process -qtables if it was present */ if (! read_quant_tables(cinfo, qtablefile, force_baseline)) usage(); if (qslotsarg != NULL) /* process -qslots if it was present */ if (! set_quant_slots(cinfo, qslotsarg)) usage(); if (samplearg != NULL) /* process -sample if it was present */ if (! set_sample_factors(cinfo, samplearg)) usage(); #ifdef C_PROGRESSIVE_SUPPORTED if (simple_progressive) /* process -progressive; -scans can override */ jpeg_simple_progression(cinfo); #endif #ifdef C_MULTISCAN_FILES_SUPPORTED if (scansarg != NULL) /* process -scans if it was present */ if (! read_scan_script(cinfo, scansarg)) usage(); #endif } return argn; /* return index of next arg (file name) */ } /* * The main program. */ int main (int argc, char **argv) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; #ifdef PROGRESS_REPORT struct cdjpeg_progress_mgr progress; #endif int file_index; cjpeg_source_ptr src_mgr; FILE * input_file; FILE * output_file; JDIMENSION num_scanlines; /* On Mac, fetch a command line. */ #ifdef USE_CCOMMAND argc = ccommand(&argv); #endif progname = argv[0]; if (progname == NULL || progname[0] == 0) progname = "cjpeg"; /* in case C library doesn't provide it */ /* Initialize the JPEG compression object with default error handling. */ cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); /* Add some application-specific error messages (from cderror.h) */ jerr.addon_message_table = cdjpeg_message_table; jerr.first_addon_message = JMSG_FIRSTADDONCODE; jerr.last_addon_message = JMSG_LASTADDONCODE; /* Now safe to enable signal catcher. */ #ifdef NEED_SIGNAL_CATCHER enable_signal_catcher((j_common_ptr) &cinfo); #endif /* Initialize JPEG parameters. * Much of this may be overridden later. * In particular, we don't yet know the input file's color space, * but we need to provide some value for jpeg_set_defaults() to work. */ cinfo.in_color_space = JCS_RGB; /* arbitrary guess */ jpeg_set_defaults(&cinfo); /* Scan command line to find file names. * It is convenient to use just one switch-parsing routine, but the switch * values read here are ignored; we will rescan the switches after opening * the input file. */ file_index = parse_switches(&cinfo, argc, argv, 0, FALSE); #ifdef TWO_FILE_COMMANDLINE /* Must have either -outfile switch or explicit output file name */ if (outfilename == NULL) { if (file_index != argc-2) { fprintf(stderr, "%s: must name one input and one output file\n", progname); usage(); } outfilename = argv[file_index+1]; } else { if (file_index != argc-1) { fprintf(stderr, "%s: must name one input and one output file\n", progname); usage(); } } #else /* Unix style: expect zero or one file name */ if (file_index < argc-1) { fprintf(stderr, "%s: only one input file\n", progname); usage(); } #endif /* TWO_FILE_COMMANDLINE */ /* Open the input file. */ if (file_index < argc) { if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]); exit(EXIT_FAILURE); } } else { /* default input file is stdin */ input_file = read_stdin(); } /* Open the output file. */ if (outfilename != NULL) { if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, outfilename); exit(EXIT_FAILURE); } } else { /* default output file is stdout */ output_file = write_stdout(); } #ifdef PROGRESS_REPORT start_progress_monitor((j_common_ptr) &cinfo, &progress); #endif /* Figure out the input file format, and set up to read it. */ src_mgr = select_file_type(&cinfo, input_file); src_mgr->input_file = input_file; /* Read the input file header to obtain file size & colorspace. */ (*src_mgr->start_input) (&cinfo, src_mgr); /* Now that we know input colorspace, fix colorspace-dependent defaults */ jpeg_default_colorspace(&cinfo); /* Adjust default compression parameters by re-parsing the options */ file_index = parse_switches(&cinfo, argc, argv, 0, TRUE); /* Specify data destination for compression */ jpeg_stdio_dest(&cinfo, output_file); /* Start compressor */ jpeg_start_compress(&cinfo, TRUE); /* Process data */ while (cinfo.next_scanline < cinfo.image_height) { num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr); (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines); } /* Finish compression and release memory */ (*src_mgr->finish_input) (&cinfo, src_mgr); jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); /* Close files, if we opened them */ if (input_file != stdin) fclose(input_file); if (output_file != stdout) fclose(output_file); #ifdef PROGRESS_REPORT end_progress_monitor((j_common_ptr) &cinfo); #endif /* All done. */ exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS); return 0; /* suppress no-return-value warnings */ } ================================================ FILE: tess-two/jni/libjpeg/ckconfig.c ================================================ /* * ckconfig.c * * Copyright (C) 1991-1994, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. */ /* * This program is intended to help you determine how to configure the JPEG * software for installation on a particular system. The idea is to try to * compile and execute this program. If your compiler fails to compile the * program, make changes as indicated in the comments below. Once you can * compile the program, run it, and it will produce a "jconfig.h" file for * your system. * * As a general rule, each time you try to compile this program, * pay attention only to the *first* error message you get from the compiler. * Many C compilers will issue lots of spurious error messages once they * have gotten confused. Go to the line indicated in the first error message, * and read the comments preceding that line to see what to change. * * Almost all of the edits you may need to make to this program consist of * changing a line that reads "#define SOME_SYMBOL" to "#undef SOME_SYMBOL", * or vice versa. This is called defining or undefining that symbol. */ /* First we must see if your system has the include files we need. * We start out with the assumption that your system has all the ANSI-standard * include files. If you get any error trying to include one of these files, * undefine the corresponding HAVE_xxx symbol. */ #define HAVE_STDDEF_H /* replace 'define' by 'undef' if error here */ #ifdef HAVE_STDDEF_H /* next line will be skipped if you undef... */ #include #endif #define HAVE_STDLIB_H /* same thing for stdlib.h */ #ifdef HAVE_STDLIB_H #include #endif #include /* If you ain't got this, you ain't got C. */ /* We have to see if your string functions are defined by * strings.h (old BSD convention) or string.h (everybody else). * We try the non-BSD convention first; define NEED_BSD_STRINGS * if the compiler says it can't find string.h. */ #undef NEED_BSD_STRINGS #ifdef NEED_BSD_STRINGS #include #else #include #endif /* On some systems (especially older Unix machines), type size_t is * defined only in the include file . If you get a failure * on the size_t test below, try defining NEED_SYS_TYPES_H. */ #undef NEED_SYS_TYPES_H /* start by assuming we don't need it */ #ifdef NEED_SYS_TYPES_H #include #endif /* Usually type size_t is defined in one of the include files we've included * above. If not, you'll get an error on the "typedef size_t my_size_t;" line. * In that case, first try defining NEED_SYS_TYPES_H just above. * If that doesn't work, you'll have to search through your system library * to figure out which include file defines "size_t". Look for a line that * says "typedef something-or-other size_t;". Then, change the line below * that says "#include " to instead include the file * you found size_t in, and define NEED_SPECIAL_INCLUDE. If you can't find * type size_t anywhere, try replacing "#include " with * "typedef unsigned int size_t;". */ #undef NEED_SPECIAL_INCLUDE /* assume we DON'T need it, for starters */ #ifdef NEED_SPECIAL_INCLUDE #include #endif typedef size_t my_size_t; /* The payoff: do we have size_t now? */ /* The next question is whether your compiler supports ANSI-style function * prototypes. You need to know this in order to choose between using * makefile.ansi and using makefile.unix. * The #define line below is set to assume you have ANSI function prototypes. * If you get an error in this group of lines, undefine HAVE_PROTOTYPES. */ #define HAVE_PROTOTYPES #ifdef HAVE_PROTOTYPES int testfunction (int arg1, int * arg2); /* check prototypes */ struct methods_struct { /* check method-pointer declarations */ int (*error_exit) (char *msgtext); int (*trace_message) (char *msgtext); int (*another_method) (void); }; int testfunction (int arg1, int * arg2) /* check definitions */ { return arg2[arg1]; } int test2function (void) /* check void arg list */ { return 0; } #endif /* Now we want to find out if your compiler knows what "unsigned char" means. * If you get an error on the "unsigned char un_char;" line, * then undefine HAVE_UNSIGNED_CHAR. */ #define HAVE_UNSIGNED_CHAR #ifdef HAVE_UNSIGNED_CHAR unsigned char un_char; #endif /* Now we want to find out if your compiler knows what "unsigned short" means. * If you get an error on the "unsigned short un_short;" line, * then undefine HAVE_UNSIGNED_SHORT. */ #define HAVE_UNSIGNED_SHORT #ifdef HAVE_UNSIGNED_SHORT unsigned short un_short; #endif /* Now we want to find out if your compiler understands type "void". * If you get an error anywhere in here, undefine HAVE_VOID. */ #define HAVE_VOID #ifdef HAVE_VOID /* Caution: a C++ compiler will insist on complete prototypes */ typedef void * void_ptr; /* check void * */ #ifdef HAVE_PROTOTYPES /* check ptr to function returning void */ typedef void (*void_func) (int a, int b); #else typedef void (*void_func) (); #endif #ifdef HAVE_PROTOTYPES /* check void function result */ void test3function (void_ptr arg1, void_func arg2) #else void test3function (arg1, arg2) void_ptr arg1; void_func arg2; #endif { char * locptr = (char *) arg1; /* check casting to and from void * */ arg1 = (void *) locptr; (*arg2) (1, 2); /* check call of fcn returning void */ } #endif /* Now we want to find out if your compiler knows what "const" means. * If you get an error here, undefine HAVE_CONST. */ #define HAVE_CONST #ifdef HAVE_CONST static const int carray[3] = {1, 2, 3}; #ifdef HAVE_PROTOTYPES int test4function (const int arg1) #else int test4function (arg1) const int arg1; #endif { return carray[arg1]; } #endif /* If you get an error or warning about this structure definition, * define INCOMPLETE_TYPES_BROKEN. */ #undef INCOMPLETE_TYPES_BROKEN #ifndef INCOMPLETE_TYPES_BROKEN typedef struct undefined_structure * undef_struct_ptr; #endif /* If you get an error about duplicate names, * define NEED_SHORT_EXTERNAL_NAMES. */ #undef NEED_SHORT_EXTERNAL_NAMES #ifndef NEED_SHORT_EXTERNAL_NAMES int possibly_duplicate_function () { return 0; } int possibly_dupli_function () { return 1; } #endif /************************************************************************ * OK, that's it. You should not have to change anything beyond this * point in order to compile and execute this program. (You might get * some warnings, but you can ignore them.) * When you run the program, it will make a couple more tests that it * can do automatically, and then it will create jconfig.h and print out * any additional suggestions it has. ************************************************************************ */ #ifdef HAVE_PROTOTYPES int is_char_signed (int arg) #else int is_char_signed (arg) int arg; #endif { if (arg == 189) { /* expected result for unsigned char */ return 0; /* type char is unsigned */ } else if (arg != -67) { /* expected result for signed char */ printf("Hmm, it seems 'char' is not eight bits wide on your machine.\n"); printf("I fear the JPEG software will not work at all.\n\n"); } return 1; /* assume char is signed otherwise */ } #ifdef HAVE_PROTOTYPES int is_shifting_signed (long arg) #else int is_shifting_signed (arg) long arg; #endif /* See whether right-shift on a long is signed or not. */ { long res = arg >> 4; if (res == -0x7F7E80CL) { /* expected result for signed shift */ return 1; /* right shift is signed */ } /* see if unsigned-shift hack will fix it. */ /* we can't just test exact value since it depends on width of long... */ res |= (~0L) << (32-4); if (res == -0x7F7E80CL) { /* expected result now? */ return 0; /* right shift is unsigned */ } printf("Right shift isn't acting as I expect it to.\n"); printf("I fear the JPEG software will not work at all.\n\n"); return 0; /* try it with unsigned anyway */ } #ifdef HAVE_PROTOTYPES int main (int argc, char ** argv) #else int main (argc, argv) int argc; char ** argv; #endif { char signed_char_check = (char) (-67); FILE *outfile; /* Attempt to write jconfig.h */ if ((outfile = fopen("jconfig.h", "w")) == NULL) { printf("Failed to write jconfig.h\n"); return 1; } /* Write out all the info */ fprintf(outfile, "/* jconfig.h --- generated by ckconfig.c */\n"); fprintf(outfile, "/* see jconfig.txt for explanations */\n\n"); #ifdef HAVE_PROTOTYPES fprintf(outfile, "#define HAVE_PROTOTYPES\n"); #else fprintf(outfile, "#undef HAVE_PROTOTYPES\n"); #endif #ifdef HAVE_UNSIGNED_CHAR fprintf(outfile, "#define HAVE_UNSIGNED_CHAR\n"); #else fprintf(outfile, "#undef HAVE_UNSIGNED_CHAR\n"); #endif #ifdef HAVE_UNSIGNED_SHORT fprintf(outfile, "#define HAVE_UNSIGNED_SHORT\n"); #else fprintf(outfile, "#undef HAVE_UNSIGNED_SHORT\n"); #endif #ifdef HAVE_VOID fprintf(outfile, "/* #define void char */\n"); #else fprintf(outfile, "#define void char\n"); #endif #ifdef HAVE_CONST fprintf(outfile, "/* #define const */\n"); #else fprintf(outfile, "#define const\n"); #endif if (is_char_signed((int) signed_char_check)) fprintf(outfile, "#undef CHAR_IS_UNSIGNED\n"); else fprintf(outfile, "#define CHAR_IS_UNSIGNED\n"); #ifdef HAVE_STDDEF_H fprintf(outfile, "#define HAVE_STDDEF_H\n"); #else fprintf(outfile, "#undef HAVE_STDDEF_H\n"); #endif #ifdef HAVE_STDLIB_H fprintf(outfile, "#define HAVE_STDLIB_H\n"); #else fprintf(outfile, "#undef HAVE_STDLIB_H\n"); #endif #ifdef NEED_BSD_STRINGS fprintf(outfile, "#define NEED_BSD_STRINGS\n"); #else fprintf(outfile, "#undef NEED_BSD_STRINGS\n"); #endif #ifdef NEED_SYS_TYPES_H fprintf(outfile, "#define NEED_SYS_TYPES_H\n"); #else fprintf(outfile, "#undef NEED_SYS_TYPES_H\n"); #endif fprintf(outfile, "#undef NEED_FAR_POINTERS\n"); #ifdef NEED_SHORT_EXTERNAL_NAMES fprintf(outfile, "#define NEED_SHORT_EXTERNAL_NAMES\n"); #else fprintf(outfile, "#undef NEED_SHORT_EXTERNAL_NAMES\n"); #endif #ifdef INCOMPLETE_TYPES_BROKEN fprintf(outfile, "#define INCOMPLETE_TYPES_BROKEN\n"); #else fprintf(outfile, "#undef INCOMPLETE_TYPES_BROKEN\n"); #endif fprintf(outfile, "\n#ifdef JPEG_INTERNALS\n\n"); if (is_shifting_signed(-0x7F7E80B1L)) fprintf(outfile, "#undef RIGHT_SHIFT_IS_UNSIGNED\n"); else fprintf(outfile, "#define RIGHT_SHIFT_IS_UNSIGNED\n"); fprintf(outfile, "\n#endif /* JPEG_INTERNALS */\n"); fprintf(outfile, "\n#ifdef JPEG_CJPEG_DJPEG\n\n"); fprintf(outfile, "#define BMP_SUPPORTED /* BMP image file format */\n"); fprintf(outfile, "#define GIF_SUPPORTED /* GIF image file format */\n"); fprintf(outfile, "#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */\n"); fprintf(outfile, "#undef RLE_SUPPORTED /* Utah RLE image file format */\n"); fprintf(outfile, "#define TARGA_SUPPORTED /* Targa image file format */\n\n"); fprintf(outfile, "#undef TWO_FILE_COMMANDLINE /* You may need this on non-Unix systems */\n"); fprintf(outfile, "#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */\n"); fprintf(outfile, "#undef DONT_USE_B_MODE\n"); fprintf(outfile, "/* #define PROGRESS_REPORT */ /* optional */\n"); fprintf(outfile, "\n#endif /* JPEG_CJPEG_DJPEG */\n"); /* Close the jconfig.h file */ fclose(outfile); /* User report */ printf("Configuration check for Independent JPEG Group's software done.\n"); printf("\nI have written the jconfig.h file for you.\n\n"); #ifdef HAVE_PROTOTYPES printf("You should use makefile.ansi as the starting point for your Makefile.\n"); #else printf("You should use makefile.unix as the starting point for your Makefile.\n"); #endif #ifdef NEED_SPECIAL_INCLUDE printf("\nYou'll need to change jconfig.h to include the system include file\n"); printf("that you found type size_t in, or add a direct definition of type\n"); printf("size_t if that's what you used. Just add it to the end.\n"); #endif return 0; } ================================================ FILE: tess-two/jni/libjpeg/coderules.txt ================================================ IJG JPEG LIBRARY: CODING RULES Copyright (C) 1991-1996, Thomas G. Lane. This file is part of the Independent JPEG Group's software. For conditions of distribution and use, see the accompanying README file. Since numerous people will be contributing code and bug fixes, it's important to establish a common coding style. The goal of using similar coding styles is much more important than the details of just what that style is. In general we follow the recommendations of "Recommended C Style and Coding Standards" revision 6.1 (Cannon et al. as modified by Spencer, Keppel and Brader). This document is available in the IJG FTP archive (see jpeg/doc/cstyle.ms.tbl.Z, or cstyle.txt.Z for those without nroff/tbl). Block comments should be laid out thusly: /* * Block comments in this style. */ We indent statements in K&R style, e.g., if (test) { then-part; } else { else-part; } with two spaces per indentation level. (This indentation convention is handled automatically by GNU Emacs and many other text editors.) Multi-word names should be written in lower case with underscores, e.g., multi_word_name (not multiWordName). Preprocessor symbols and enum constants are similar but upper case (MULTI_WORD_NAME). Names should be unique within the first fifteen characters. (On some older systems, global names must be unique within six characters. We accommodate this without cluttering the source code by using macros to substitute shorter names.) We use function prototypes everywhere; we rely on automatic source code transformation to feed prototype-less C compilers. Transformation is done by the simple and portable tool 'ansi2knr.c' (courtesy of Ghostscript). ansi2knr is not very bright, so it imposes a format requirement on function declarations: the function name MUST BEGIN IN COLUMN 1. Thus all functions should be written in the following style: LOCAL(int *) function_name (int a, char *b) { code... } Note that each function definition must begin with GLOBAL(type), LOCAL(type), or METHODDEF(type). These macros expand to "static type" or just "type" as appropriate. They provide a readable indication of the routine's usage and can readily be changed for special needs. (For instance, special linkage keywords can be inserted for use in Windows DLLs.) ansi2knr does not transform method declarations (function pointers in structs). We handle these with a macro JMETHOD, defined as #ifdef HAVE_PROTOTYPES #define JMETHOD(type,methodname,arglist) type (*methodname) arglist #else #define JMETHOD(type,methodname,arglist) type (*methodname) () #endif which is used like this: struct function_pointers { JMETHOD(void, init_entropy_encoder, (int somearg, jparms *jp)); JMETHOD(void, term_entropy_encoder, (void)); }; Note the set of parentheses surrounding the parameter list. A similar solution is used for forward and external function declarations (see the EXTERN and JPP macros). If the code is to work on non-ANSI compilers, we cannot rely on a prototype declaration to coerce actual parameters into the right types. Therefore, use explicit casts on actual parameters whenever the actual parameter type is not identical to the formal parameter. Beware of implicit conversions to "int". It seems there are some non-ANSI compilers in which the sizeof() operator is defined to return int, yet size_t is defined as long. Needless to say, this is brain-damaged. Always use the SIZEOF() macro in place of sizeof(), so that the result is guaranteed to be of type size_t. The JPEG library is intended to be used within larger programs. Furthermore, we want it to be reentrant so that it can be used by applications that process multiple images concurrently. The following rules support these requirements: 1. Avoid direct use of file I/O, "malloc", error report printouts, etc; pass these through the common routines provided. 2. Minimize global namespace pollution. Functions should be declared static wherever possible. (Note that our method-based calling conventions help this a lot: in many modules only the initialization function will ever need to be called directly, so only that function need be externally visible.) All global function names should begin with "jpeg_", and should have an abbreviated name (unique in the first six characters) substituted by macro when NEED_SHORT_EXTERNAL_NAMES is set. 3. Don't use global variables; anything that must be used in another module should be in the common data structures. 4. Don't use static variables except for read-only constant tables. Variables that should be private to a module can be placed into private structures (see the system architecture document, structure.txt). 5. Source file names should begin with "j" for files that are part of the library proper; source files that are not part of the library, such as cjpeg.c and djpeg.c, do not begin with "j". Keep source file names to eight characters (plus ".c" or ".h", etc) to make life easy for MS-DOSers. Keep compression and decompression code in separate source files --- some applications may want only one half of the library. Note: these rules (particularly #4) are not followed religiously in the modules that are used in cjpeg/djpeg but are not part of the JPEG library proper. Those modules are not really intended to be used in other applications. ================================================ FILE: tess-two/jni/libjpeg/compile ================================================ #! /bin/sh # Wrapper for compilers which do not understand '-c -o'. scriptversion=2012-10-14.11; # UTC # Copyright (C) 1999-2014 Free Software Foundation, Inc. # Written by Tom Tromey . # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . nl=' ' # We need space, tab and new line, in precisely that order. Quoting is # there to prevent tools from complaining about whitespace usage. IFS=" "" $nl" file_conv= # func_file_conv build_file lazy # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. If the determined conversion # type is listed in (the comma separated) LAZY, no conversion will # take place. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv/,$2, in *,$file_conv,*) ;; mingw/*) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin/*) file=`cygpath -m "$file" || echo "$file"` ;; wine/*) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_cl_dashL linkdir # Make cl look for libraries in LINKDIR func_cl_dashL () { func_file_conv "$1" if test -z "$lib_path"; then lib_path=$file else lib_path="$lib_path;$file" fi linker_opts="$linker_opts -LIBPATH:$file" } # func_cl_dashl library # Do a library search-path lookup for cl func_cl_dashl () { lib=$1 found=no save_IFS=$IFS IFS=';' for dir in $lib_path $LIB do IFS=$save_IFS if $shared && test -f "$dir/$lib.dll.lib"; then found=yes lib=$dir/$lib.dll.lib break fi if test -f "$dir/$lib.lib"; then found=yes lib=$dir/$lib.lib break fi if test -f "$dir/lib$lib.a"; then found=yes lib=$dir/lib$lib.a break fi done IFS=$save_IFS if test "$found" != yes; then lib=$lib.lib fi } # func_cl_wrapper cl arg... # Adjust compile command to suit cl func_cl_wrapper () { # Assume a capable shell lib_path= shared=: linker_opts= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. eat=1 case $2 in *.o | *.[oO][bB][jJ]) func_file_conv "$2" set x "$@" -Fo"$file" shift ;; *) func_file_conv "$2" set x "$@" -Fe"$file" shift ;; esac ;; -I) eat=1 func_file_conv "$2" mingw set x "$@" -I"$file" shift ;; -I*) func_file_conv "${1#-I}" mingw set x "$@" -I"$file" shift ;; -l) eat=1 func_cl_dashl "$2" set x "$@" "$lib" shift ;; -l*) func_cl_dashl "${1#-l}" set x "$@" "$lib" shift ;; -L) eat=1 func_cl_dashL "$2" ;; -L*) func_cl_dashL "${1#-L}" ;; -static) shared=false ;; -Wl,*) arg=${1#-Wl,} save_ifs="$IFS"; IFS=',' for flag in $arg; do IFS="$save_ifs" linker_opts="$linker_opts $flag" done IFS="$save_ifs" ;; -Xlinker) eat=1 linker_opts="$linker_opts $2" ;; -*) set x "$@" "$1" shift ;; *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) func_file_conv "$1" set x "$@" -Tp"$file" shift ;; *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) func_file_conv "$1" mingw set x "$@" "$file" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -n "$linker_opts"; then linker_opts="-link$linker_opts" fi exec "$@" $linker_opts exit 1 } eat= case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: compile [--help] [--version] PROGRAM [ARGS] Wrapper for compilers which do not understand '-c -o'. Remove '-o dest.o' from ARGS, run PROGRAM with the remaining arguments, and rename the output as expected. If you are trying to build a whole package this is not the right script to run: please start by reading the file 'INSTALL'. Report bugs to . EOF exit $? ;; -v | --v*) echo "compile $scriptversion" exit $? ;; cl | *[/\\]cl | cl.exe | *[/\\]cl.exe ) func_cl_wrapper "$@" # Doesn't return... ;; esac ofile= cfile= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. # So we strip '-o arg' only if arg is an object. eat=1 case $2 in *.o | *.obj) ofile=$2 ;; *) set x "$@" -o "$2" shift ;; esac ;; *.c) cfile=$1 set x "$@" "$1" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -z "$ofile" || test -z "$cfile"; then # If no '-o' option was seen then we might have been invoked from a # pattern rule where we don't need one. That is ok -- this is a # normal compilation that the losing compiler can handle. If no # '.c' file was seen then we are probably linking. That is also # ok. exec "$@" fi # Name of file we expect compiler to create. cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` # Create the lock directory. # Note: use '[/\\:.-]' here to ensure that we don't use the same name # that we are using for the .o file. Also, base the name on the expected # object file name, since that is what matters with a parallel build. lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d while true; do if mkdir "$lockdir" >/dev/null 2>&1; then break fi sleep 1 done # FIXME: race condition here if user kills between mkdir and trap. trap "rmdir '$lockdir'; exit 1" 1 2 15 # Run the compile. "$@" ret=$? if test -f "$cofile"; then test "$cofile" = "$ofile" || mv "$cofile" "$ofile" elif test -f "${cofile}bj"; then test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" fi rmdir "$lockdir" exit $ret # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: ================================================ FILE: tess-two/jni/libjpeg/config.guess ================================================ #! /bin/sh # Attempt to guess a canonical system name. # Copyright 1992-2014 Free Software Foundation, Inc. timestamp='2014-11-04' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner; maintained since 2000 by Ben Elliston. # # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD # # Please send patches to . me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright 1992-2014 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case "${UNAME_SYSTEM}" in Linux|GNU|GNU/*) # If the system lacks a compiler, then just pick glibc. # We could probably try harder. LIBC=gnu eval $set_cc_for_build cat <<-EOF > $dummy.c #include #if defined(__UCLIBC__) LIBC=uclibc #elif defined(__dietlibc__) LIBC=dietlibc #else LIBC=gnu #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` ;; esac # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently, or will in the future. case "${UNAME_MACHINE_ARCH}" in arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" exit ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE} exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; *:SolidBSD:*:*) echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE="alpha" ;; "EV4.5 (21064)") UNAME_MACHINE="alpha" ;; "LCA4 (21066/21068)") UNAME_MACHINE="alpha" ;; "EV5 (21164)") UNAME_MACHINE="alphaev5" ;; "EV5.6 (21164A)") UNAME_MACHINE="alphaev56" ;; "EV5.6 (21164PC)") UNAME_MACHINE="alphapca56" ;; "EV5.7 (21164PC)") UNAME_MACHINE="alphapca57" ;; "EV6 (21264)") UNAME_MACHINE="alphaev6" ;; "EV6.7 (21264A)") UNAME_MACHINE="alphaev67" ;; "EV6.8CB (21264C)") UNAME_MACHINE="alphaev68" ;; "EV6.8AL (21264B)") UNAME_MACHINE="alphaev68" ;; "EV6.8CX (21264D)") UNAME_MACHINE="alphaev68" ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE="alphaev69" ;; "EV7 (21364)") UNAME_MACHINE="alphaev7" ;; "EV7.9 (21364A)") UNAME_MACHINE="alphaev79" ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm*:riscos:*:*|arm*:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux${UNAME_RELEASE} exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval $set_cc_for_build SUN_ARCH="i386" # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH="x86_64" fi fi echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/lslpp ] ; then IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH="hppa2.0n" ;; 64) HP_ARCH="hppa2.0w" ;; '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = "hppa2.0w" ] then eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH="hppa2.0w" else HP_ARCH="hppa64" fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; *) echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; esac exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; *:MINGW64*:*) echo ${UNAME_MACHINE}-pc-mingw64 exit ;; *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; *:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; i*:windows32*:*) # uname -m includes "-pc" on this system. echo ${UNAME_MACHINE}-mingw32 exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; *:Interix*:*) case ${UNAME_MACHINE} in x86) echo i586-pc-interix${UNAME_RELEASE} exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix${UNAME_RELEASE} exit ;; IA64) echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks exit ;; 8664:Windows_NT:*) echo x86_64-pc-mks exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; aarch64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC="gnulibc1" ; fi echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arc:Linux:*:* | arceb:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arm*:Linux:*:*) eval $set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo ${UNAME_MACHINE}-unknown-linux-${LIBC} else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi else echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf fi fi exit ;; avr32*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; cris:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; crisv32:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; frv:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; hexagon:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:Linux:*:*) echo ${UNAME_MACHINE}-pc-linux-${LIBC} exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } ;; openrisc*:Linux:*:*) echo or1k-unknown-linux-${LIBC} exit ;; or32:Linux:*:* | or1k*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; padre:Linux:*:*) echo sparc-unknown-linux-${LIBC} exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-${LIBC} exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; *) echo hppa-unknown-linux-${LIBC} ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-${LIBC} exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-${LIBC} exit ;; ppc64le:Linux:*:*) echo powerpc64le-unknown-linux-${LIBC} exit ;; ppcle:Linux:*:*) echo powerpcle-unknown-linux-${LIBC} exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux-${LIBC} exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; tile*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; vax:Linux:*:*) echo ${UNAME_MACHINE}-dec-linux-${LIBC} exit ;; x86_64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; xtensa*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configury will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; x86_64:Haiku:*:*) echo x86_64-unknown-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux${UNAME_RELEASE} exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux${UNAME_RELEASE} exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown eval $set_cc_for_build if test "$UNAME_PROCESSOR" = unknown ; then UNAME_PROCESSOR=powerpc fi if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi fi elif test "$UNAME_PROCESSOR" = i386 ; then # Avoid executing cc on OS X 10.9, as it ships with a stub # that puts up a graphical alert prompting to install # developer tools. Any system running Mac OS X 10.7 or # later (Darwin 11 and later) is required to have a 64-bit # processor. This is not true of the ARM version of Darwin # that Apple uses in portable devices. UNAME_PROCESSOR=x86_64 fi echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = "x86"; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-?:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-*:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-?:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = "386"; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos exit ;; i*86:AROS:*:*) echo ${UNAME_MACHINE}-pc-aros exit ;; x86_64:VMkernel:*:*) echo ${UNAME_MACHINE}-unknown-esx exit ;; esac cat >&2 < in order to provide the needed information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: ================================================ FILE: tess-two/jni/libjpeg/config.sub ================================================ #! /bin/sh # Configuration validation subroutine script. # Copyright 1992-2014 Free Software Foundation, Inc. timestamp='2014-12-03' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # Please send patches to . # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS $0 [OPTION] ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright 1992-2014 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ knetbsd*-gnu* | netbsd*-gnu* | \ kopensolaris*-gnu* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; android-linux) os=-linux-android basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis | -knuth | -cray | -microblaze*) os= basic_machine=$1 ;; -bluegene*) os=-cnk ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco6) os=-sco5v6 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5v6*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*178) os=-lynxos178 ;; -lynx*5) os=-lynxos5 ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | aarch64 | aarch64_be \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ | arc | arceb \ | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \ | avr | avr32 \ | be32 | be64 \ | bfin \ | c4x | c8051 | clipper \ | d10v | d30v | dlx | dsp16xx \ | epiphany \ | fido | fr30 | frv \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | hexagon \ | i370 | i860 | i960 | ia64 \ | ip2k | iq2000 \ | k1om \ | le32 | le64 \ | lm32 \ | m32c | m32r | m32rle | m68000 | m68k | m88k \ | maxq | mb | microblaze | microblazeel | mcore | mep | metag \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ | mips64octeon | mips64octeonel \ | mips64orion | mips64orionel \ | mips64r5900 | mips64r5900el \ | mips64vr | mips64vrel \ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ | mips64vr5900 | mips64vr5900el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa32r6 | mipsisa32r6el \ | mipsisa64 | mipsisa64el \ | mipsisa64r2 | mipsisa64r2el \ | mipsisa64r6 | mipsisa64r6el \ | mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sr71k | mipsisa64sr71kel \ | mipsr5900 | mipsr5900el \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ | moxie \ | mt \ | msp430 \ | nds32 | nds32le | nds32be \ | nios | nios2 | nios2eb | nios2el \ | ns16k | ns32k \ | open8 | or1k | or1knd | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ | pyramid \ | riscv32 | riscv64 \ | rl78 | rx \ | score \ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ | spu \ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ | ubicom32 \ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ | visium \ | we32k \ | x86 | xc16x | xstormy16 | xtensa \ | z8k | z80) basic_machine=$basic_machine-unknown ;; c54x) basic_machine=tic54x-unknown ;; c55x) basic_machine=tic55x-unknown ;; c6x) basic_machine=tic6x-unknown ;; leon|leon[3-9]) basic_machine=sparc-$basic_machine ;; m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip) basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; ms1) basic_machine=mt-unknown ;; strongarm | thumb | xscale) basic_machine=arm-unknown ;; xgate) basic_machine=$basic_machine-unknown os=-none ;; xscaleeb) basic_machine=armeb-unknown ;; xscaleel) basic_machine=armel-unknown ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | aarch64-* | aarch64_be-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | avr-* | avr32-* \ | be32-* | be64-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* \ | c8051-* | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | elxsi-* \ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hexagon-* \ | i*86-* | i860-* | i960-* | ia64-* \ | ip2k-* | iq2000-* \ | k1om-* \ | le32-* | le64-* \ | lm32-* \ | m32c-* | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \ | microblaze-* | microblazeel-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips16-* \ | mips64-* | mips64el-* \ | mips64octeon-* | mips64octeonel-* \ | mips64orion-* | mips64orionel-* \ | mips64r5900-* | mips64r5900el-* \ | mips64vr-* | mips64vrel-* \ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ | mips64vr5900-* | mips64vr5900el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa32r6-* | mipsisa32r6el-* \ | mipsisa64-* | mipsisa64el-* \ | mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64r6-* | mipsisa64r6el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipsr5900-* | mipsr5900el-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ | mt-* \ | msp430-* \ | nds32-* | nds32le-* | nds32be-* \ | nios-* | nios2-* | nios2eb-* | nios2el-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | open8-* \ | or1k*-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ | pyramid-* \ | rl78-* | romp-* | rs6000-* | rx-* \ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparclite-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ | tahoe-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tile*-* \ | tron-* \ | ubicom32-* \ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ | vax-* \ | visium-* \ | we32k-* \ | x86-* | x86_64-* | xc16x-* | xps100-* \ | xstormy16-* | xtensa*-* \ | ymp-* \ | z8k-* | z80-*) ;; # Recognize the basic CPU types without company name, with glob match. xtensa*) basic_machine=$basic_machine-unknown ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; abacus) basic_machine=abacus-unknown ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amd64) basic_machine=x86_64-pc ;; amd64-*) basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aros) basic_machine=i386-pc os=-aros ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; blackfin) basic_machine=bfin-unknown os=-linux ;; blackfin-*) basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; bluegene*) basic_machine=powerpc-ibm os=-cnk ;; c54x-*) basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c55x-*) basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c6x-*) basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c90) basic_machine=c90-cray os=-unicos ;; cegcc) basic_machine=arm-unknown os=-cegcc ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | j90) basic_machine=j90-cray os=-unicos ;; craynv) basic_machine=craynv-cray os=-unicosmp ;; cr16 | cr16-*) basic_machine=cr16-unknown os=-elf ;; crds | unos) basic_machine=m68k-crds ;; crisv32 | crisv32-* | etraxfs*) basic_machine=crisv32-axis ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; crx) basic_machine=crx-unknown os=-elf ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; decsystem10* | dec10*) basic_machine=pdp10-dec os=-tops10 ;; decsystem20* | dec20*) basic_machine=pdp10-dec os=-tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; dicos) basic_machine=i686-pc os=-dicos ;; djgpp) basic_machine=i586-pc os=-msdosdjgpp ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; leon-*|leon[3-9]-*) basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'` ;; m68knommu) basic_machine=m68k-unknown os=-linux ;; m68knommu-*) basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; microblaze*) basic_machine=microblaze-xilinx ;; mingw64) basic_machine=x86_64-pc os=-mingw64 ;; mingw32) basic_machine=i686-pc os=-mingw32 ;; mingw32ce) basic_machine=arm-unknown os=-mingw32ce ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k os=-coff ;; morphos) basic_machine=powerpc-unknown os=-morphos ;; moxiebox) basic_machine=moxie-unknown os=-moxiebox ;; msdos) basic_machine=i386-pc os=-msdos ;; ms1-*) basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` ;; msys) basic_machine=i686-pc os=-msys ;; mvs) basic_machine=i370-ibm os=-mvs ;; nacl) basic_machine=le32-unknown os=-nacl ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; neo-tandem) basic_machine=neo-tandem ;; nse-tandem) basic_machine=nse-tandem ;; nsr-tandem) basic_machine=nsr-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; openrisc | openrisc-*) basic_machine=or32-unknown ;; os400) basic_machine=powerpc-ibm os=-os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; parisc) basic_machine=hppa-unknown os=-linux ;; parisc-*) basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pc98) basic_machine=i386-pc ;; pc98-*) basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon | athlon_*) basic_machine=i686-pc ;; pentiumii | pentium2 | pentiumiii | pentium3) basic_machine=i686-pc ;; pentium4) basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium4-*) basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc | ppcbe) basic_machine=powerpc-unknown ;; ppc-* | ppcbe-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle | ppc-le | powerpc-little) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little | ppc64-le | powerpc64-little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rdos | rdos64) basic_machine=x86_64-pc os=-rdos ;; rdos32) basic_machine=i386-pc os=-rdos ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; s390 | s390-*) basic_machine=s390-ibm ;; s390x | s390x-*) basic_machine=s390x-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sb1) basic_machine=mipsisa64sb1-unknown ;; sb1el) basic_machine=mipsisa64sb1el-unknown ;; sde) basic_machine=mipsisa32-sde os=-elf ;; sei) basic_machine=mips-sei os=-seiux ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sh5el) basic_machine=sh5le-unknown ;; sh64) basic_machine=sh64-unknown ;; sparclite-wrs | simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; strongarm-* | thumb-*) basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=alphaev5-cray os=-unicos ;; t90) basic_machine=t90-cray os=-unicos ;; tile*) basic_machine=$basic_machine-unknown os=-linux-gnu ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; toad1) basic_machine=pdp10-xkl os=-tops20 ;; tower | tower-32) basic_machine=m68k-ncr ;; tpf) basic_machine=s390x-ibm os=-tpf ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; xbox) basic_machine=i686-pc os=-mingw32 ;; xps | xps100) basic_machine=xps100-honeywell ;; xscale-* | xscalee[bl]-*) basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` ;; ymp) basic_machine=ymp-cray os=-unicos ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; z80-*-coff) basic_machine=z80-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; romp) basic_machine=romp-ibm ;; mmix) basic_machine=mmix-knuth ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -auroraux) os=-auroraux ;; -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ | -sym* | -kopensolaris* | -plan9* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* | -aros* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ | -bitrig* | -openbsd* | -solidbsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* | -cegcc* \ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-musl* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto-qnx*) ;; -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -os400*) os=-os400 ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -atheos*) os=-atheos ;; -syllable*) os=-syllable ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -nova*) os=-rtmk-nova ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -tpf*) os=-tpf ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -aros*) os=-aros ;; -zvmoe) os=-zvmoe ;; -dicos*) os=-dicos ;; -nacl*) ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in score-*) os=-elf ;; spu-*) os=-elf ;; *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; c4x-* | tic4x-*) os=-coff ;; c8051-*) os=-elf ;; hexagon-*) os=-elf ;; tic54x-*) os=-coff ;; tic55x-*) os=-coff ;; tic6x-*) os=-coff ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 ;; m68*-cisco) os=-aout ;; mep-*) os=-elf ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; or32-*) os=-coff ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; *-be) os=-beos ;; *-haiku) os=-haiku ;; *-ibm) os=-aix ;; *-knuth) os=-mmixware ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -cnk*|-aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -os400*) vendor=ibm ;; -ptx*) vendor=sequent ;; -tpf*) vendor=ibm ;; -vxsim* | -vxworks* | -windiss*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: ================================================ FILE: tess-two/jni/libjpeg/configure.ac ================================================ # IJG auto-configuration source file. # Process this file with autoconf to produce a configure script. # # Configure script for IJG libjpeg # AC_INIT([libjpeg], [9.2.0]) # Directory where autotools helper scripts lives. AC_CONFIG_AUX_DIR([.]) # Generate configuration headers. AC_CONFIG_HEADERS([jconfig.h:jconfig.cfg]) # Hack: disable autoheader so that it doesn't overwrite our cfg template. AUTOHEADER="echo autoheader ignored" # Check system type AC_CANONICAL_TARGET # Initialize Automake # Don't require all the GNU mandated files AM_INIT_AUTOMAKE([-Wall -Werror no-dist foreign]) # Make --enable-silent-rules the default. # To get verbose build output you may configure # with --disable-silent-rules or use "make V=1". AM_SILENT_RULES([yes]) # Add configure option --enable-maintainer-mode which enables # dependency checking and generation useful to package maintainers. # This is made an option to avoid confusing end users. AM_MAINTAINER_MODE # Check for programs AC_PROG_CC AC_PROG_CC_STDC AC_PROG_CPP AC_PROG_INSTALL AC_PROG_MAKE_SET AC_PROG_LN_S AM_PROG_AR # Check if LD supports linker scripts, # and define automake conditional HAVE_LD_VERSION_SCRIPT if so. AC_ARG_ENABLE([ld-version-script], AS_HELP_STRING([--enable-ld-version-script], [enable linker version script (default is enabled when possible)]), [have_ld_version_script=$enableval], []) if test -z "$have_ld_version_script"; then AC_MSG_CHECKING([if LD -Wl,--version-script works]) save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -Wl,--version-script=conftest.map" cat > conftest.map < rather than standard .])]) # See whether type size_t is defined in any ANSI-standard places; # if not, perhaps it is defined in . AC_MSG_CHECKING([for size_t]) AC_TRY_COMPILE([ #ifdef HAVE_STDDEF_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #include #ifdef NEED_BSD_STRINGS #include #else #include #endif typedef size_t my_size_t; ], [ my_size_t foovar; ], [ijg_size_t_ok=yes], [ijg_size_t_ok="not ANSI, perhaps it is in sys/types.h"]) AC_MSG_RESULT([$ijg_size_t_ok]) if test "$ijg_size_t_ok" != yes; then AC_CHECK_HEADER([sys/types.h], [AC_DEFINE([NEED_SYS_TYPES_H], [1], [Need to include in order to obtain size_t.]) AC_EGREP_CPP([size_t], [#include ], [ijg_size_t_ok="size_t is in sys/types.h"], [ijg_size_t_ok=no])], [ijg_size_t_ok=no]) AC_MSG_RESULT([$ijg_size_t_ok]) if test "$ijg_size_t_ok" = no; then AC_MSG_WARN([Type size_t is not defined in any of the usual places. Try putting '"typedef unsigned int size_t;"' in jconfig.h.]) fi fi # Check compiler characteristics AC_MSG_CHECKING([for type unsigned char]) AC_TRY_COMPILE([], [ unsigned char un_char; ], [AC_MSG_RESULT(yes) AC_DEFINE([HAVE_UNSIGNED_CHAR], [1], [Compiler supports 'unsigned char'.])], [AC_MSG_RESULT(no)]) AC_MSG_CHECKING([for type unsigned short]) AC_TRY_COMPILE([], [ unsigned short un_short; ], [AC_MSG_RESULT(yes) AC_DEFINE([HAVE_UNSIGNED_SHORT], [1], [Compiler supports 'unsigned short'.])], [AC_MSG_RESULT(no)]) AC_MSG_CHECKING([for type void]) AC_TRY_COMPILE([ /* Caution: a C++ compiler will insist on valid prototypes */ typedef void * void_ptr; /* check void * */ #ifdef HAVE_PROTOTYPES /* check ptr to function returning void */ typedef void (*void_func) (int a, int b); #else typedef void (*void_func) (); #endif #ifdef HAVE_PROTOTYPES /* check void function result */ void test3function (void_ptr arg1, void_func arg2) #else void test3function (arg1, arg2) void_ptr arg1; void_func arg2; #endif { char * locptr = (char *) arg1; /* check casting to and from void * */ arg1 = (void *) locptr; (*arg2) (1, 2); /* check call of fcn returning void */ } ], [ ], [AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no) AC_DEFINE([void], [char], [Define 'void' as 'char' for archaic compilers that don't understand it.])]) AC_C_CONST # Check for non-broken inline under various spellings AC_MSG_CHECKING([for inline]) ijg_cv_inline="" AC_TRY_COMPILE([], [} __inline__ int foo() { return 0; } int bar() { return foo();], ijg_cv_inline="__inline__", [AC_TRY_COMPILE(, [} __inline int foo() { return 0; } int bar() { return foo();], ijg_cv_inline="__inline", [AC_TRY_COMPILE(, [} inline int foo() { return 0; } int bar() { return foo();], ijg_cv_inline="inline")])]) AC_MSG_RESULT($ijg_cv_inline) AC_DEFINE_UNQUOTED([INLINE], [$ijg_cv_inline], [How to obtain function inlining.]) # We cannot check for bogus warnings, but at least we can check for errors AC_MSG_CHECKING([for broken incomplete types]) AC_TRY_COMPILE([ typedef struct undefined_structure * undef_struct_ptr; ], [], [AC_MSG_RESULT(ok)], [AC_MSG_RESULT(broken) AC_DEFINE([INCOMPLETE_TYPES_BROKEN], [1], [Compiler does not support pointers to unspecified structures.])]) # Test whether global names are unique to at least 15 chars AC_MSG_CHECKING([for short external names]) AC_TRY_LINK([ int possibly_duplicate_function () { return 0; } int possibly_dupli_function () { return 1; } ], [], [AC_MSG_RESULT(ok)], [AC_MSG_RESULT(short) AC_DEFINE([NEED_SHORT_EXTERNAL_NAMES], [1], [Linker requires that global names be unique in first 15 characters.])]) # Run-time checks AC_MSG_CHECKING([to see if char is signed]) AC_TRY_RUN([ #ifdef HAVE_STDLIB_H #include #endif #include #ifdef HAVE_PROTOTYPES int is_char_signed (int arg) #else int is_char_signed (arg) int arg; #endif { if (arg == 189) { /* expected result for unsigned char */ return 0; /* type char is unsigned */ } else if (arg != -67) { /* expected result for signed char */ printf("Hmm, it seems 'char' is not eight bits wide on your machine.\n"); printf("I fear the JPEG software will not work at all.\n\n"); } return 1; /* assume char is signed otherwise */ } char signed_char_check = (char) (-67); int main() { exit(is_char_signed((int) signed_char_check)); }], [AC_MSG_RESULT(no) AC_DEFINE([CHAR_IS_UNSIGNED], [1], [Characters are unsigned])], [AC_MSG_RESULT(yes)], [AC_MSG_WARN([Assuming that char is signed on target machine. If it is unsigned, this will be a little bit inefficient.]) ]) AC_MSG_CHECKING([to see if right shift is signed]) AC_TRY_RUN([ #ifdef HAVE_STDLIB_H #include #endif #include #ifdef HAVE_PROTOTYPES int is_shifting_signed (long arg) #else int is_shifting_signed (arg) long arg; #endif /* See whether right-shift on a long is signed or not. */ { long res = arg >> 4; if (res == -0x7F7E80CL) { /* expected result for signed shift */ return 1; /* right shift is signed */ } /* see if unsigned-shift hack will fix it. */ /* we can't just test exact value since it depends on width of long... */ res |= (~0L) << (32-4); if (res == -0x7F7E80CL) { /* expected result now? */ return 0; /* right shift is unsigned */ } printf("Right shift isn't acting as I expect it to.\n"); printf("I fear the JPEG software will not work at all.\n\n"); return 0; /* try it with unsigned anyway */ } int main() { exit(is_shifting_signed(-0x7F7E80B1L)); }], [AC_MSG_RESULT(no) AC_DEFINE([RIGHT_SHIFT_IS_UNSIGNED], [1], [Broken compiler shifts signed values as an unsigned shift.])], [AC_MSG_RESULT(yes)], [AC_MSG_RESULT(Assuming that right shift is signed on target machine.)]) AC_MSG_CHECKING([to see if fopen accepts b spec]) AC_TRY_RUN([ #ifdef HAVE_STDLIB_H #include #endif #include int main() { if (fopen("conftestdata", "wb") != NULL) exit(0); exit(1); }], [AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no) AC_DEFINE([DONT_USE_B_MODE], [1], [Don't open files in binary mode.])], [AC_MSG_RESULT(Assuming that it does.)]) # Configure libtool AC_LIBTOOL_WIN32_DLL AC_PROG_LIBTOOL # Select memory manager depending on user input. # If no "-enable-maxmem", use jmemnobs MEMORYMGR='jmemnobs' MAXMEM="no" AC_ARG_ENABLE([maxmem], [ --enable-maxmem[=N] enable use of temp files, set max mem usage to N MB], [MAXMEM="$enableval"]) dnl [# support --with-maxmem for backwards compatibility with IJG V5.] dnl AC_ARG_WITH(maxmem, , MAXMEM="$withval") if test "x$MAXMEM" = xyes; then MAXMEM=1 fi if test "x$MAXMEM" != xno; then if test -n "`echo $MAXMEM | sed 's/[[0-9]]//g'`"; then AC_MSG_ERROR(non-numeric argument to --enable-maxmem) fi DEFAULTMAXMEM=`expr $MAXMEM \* 1048576` AC_DEFINE_UNQUOTED([DEFAULT_MAX_MEM], [${DEFAULTMAXMEM}], [Maximum data space library will allocate.]) AC_MSG_CHECKING([for 'tmpfile()']) AC_TRY_LINK([#include ], [ FILE * tfile = tmpfile(); ], [AC_MSG_RESULT(yes) MEMORYMGR='jmemansi'], [AC_MSG_RESULT(no) dnl if tmpfile is not present, must use jmemname. MEMORYMGR='jmemname' # Test for the need to remove temporary files using a signal handler # (for cjpeg/djpeg) AC_DEFINE([NEED_SIGNAL_CATCHER], [1], [Need signal handler to clean up temporary files.]) AC_MSG_CHECKING([for 'mktemp()']) AC_TRY_LINK([], [ char fname[80]; mktemp(fname); ], [AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no) AC_DEFINE([NO_MKTEMP], [1], [The mktemp() function is not available.])])]) fi AC_SUBST([MEMORYMGR]) # Extract the library version IDs from jpeglib.h. AC_MSG_CHECKING([libjpeg version number]) [major=`sed -ne 's/^#define JPEG_LIB_VERSION_MAJOR *\([0-9][0-9]*\).*$/\1/p' $srcdir/jpeglib.h` minor=`sed -ne 's/^#define JPEG_LIB_VERSION_MINOR *\([0-9][0-9]*\).*$/\1/p' $srcdir/jpeglib.h`] AC_SUBST([JPEG_LIB_VERSION], [`expr $major + $minor`:0:$minor]) AC_MSG_RESULT([$JPEG_LIB_VERSION]) AC_CONFIG_FILES([Makefile]) AC_OUTPUT ================================================ FILE: tess-two/jni/libjpeg/depcomp ================================================ #! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2013-05-30.07; # UTC # Copyright (C) 1999-2014 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva . case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to . EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # Get the directory component of the given path, and save it in the # global variables '$dir'. Note that this directory component will # be either empty or ending with a '/' character. This is deliberate. set_dir_from () { case $1 in */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;; *) dir=;; esac } # Get the suffix-stripped basename of the given path, and save it the # global variable '$base'. set_base_from () { base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'` } # If no dependency file was actually created by the compiler invocation, # we still have to create a dummy depfile, to avoid errors with the # Makefile "include basename.Plo" scheme. make_dummy_depfile () { echo "#dummy" > "$depfile" } # Factor out some common post-processing of the generated depfile. # Requires the auxiliary global variable '$tmpdepfile' to be set. aix_post_process_depfile () { # If the compiler actually managed to produce a dependency file, # post-process it. if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependency.h'. # Do two passes, one to just change these to # $object: dependency.h # and one to simply output # dependency.h: # which is needed to avoid the deleted-header problem. { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile" sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile" } > "$depfile" rm -f "$tmpdepfile" else make_dummy_depfile fi } # A tabulation character. tab=' ' # A newline character. nl=' ' # Character ranges might be problematic outside the C locale. # These definitions help. upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ lower=abcdefghijklmnopqrstuvwxyz digits=0123456789 alpha=${upper}${lower} if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Avoid interferences from the environment. gccflag= dashmflag= # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## Note that this doesn't just cater to obsosete pre-3.x GCC compilers. ## but also to in-use compilers like IMB xlc/xlC and the HP C compiler. ## (see the conditional assignment to $gccflag above). ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). Also, it might not be ## supported by the other compilers which use the 'gcc' depmode. ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The second -e expression handles DOS-style file names with drive # letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \ | tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done aix_post_process_depfile ;; tcc) # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26 # FIXME: That version still under development at the moment of writing. # Make that this statement remains true also for stable, released # versions. # It will wrap lines (doesn't matter whether long or short) with a # trailing '\', as in: # # foo.o : \ # foo.c \ # foo.h \ # # It will put a trailing '\' even on the last line, and will use leading # spaces rather than leading tabs (at least since its commit 0394caf7 # "Emit spaces for -MD"). "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'. # We have to change lines of the first kind to '$object: \'. sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile" # And for each line of the second kind, we have to emit a 'dep.h:' # dummy dependency, to avoid the deleted-header problem. sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; ## The order of this option in the case statement is important, since the ## shell code in configure will try each of these formats in the order ## listed in this file. A plain '-MD' option would be understood by many ## compilers, so we must ensure this comes after the gcc and icc options. pgcc) # Portland's C compiler understands '-MD'. # Will always output deps to 'file.d' where file is the root name of the # source file under compilation, even if file resides in a subdirectory. # The object file name does not affect the name of the '.d' file. # pgcc 10.2 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\' : # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... set_dir_from "$object" # Use the source, not the object, to determine the base name, since # that's sadly what pgcc will do too. set_base_from "$source" tmpdepfile=$base.d # For projects that build the same source file twice into different object # files, the pgcc approach of using the *source* file root name can cause # problems in parallel builds. Use a locking strategy to avoid stomping on # the same $tmpdepfile. lockdir=$base.d-lock trap " echo '$0: caught signal, cleaning up...' >&2 rmdir '$lockdir' exit 1 " 1 2 13 15 numtries=100 i=$numtries while test $i -gt 0; do # mkdir is a portable test-and-set. if mkdir "$lockdir" 2>/dev/null; then # This process acquired the lock. "$@" -MD stat=$? # Release the lock. rmdir "$lockdir" break else # If the lock is being held by a different process, wait # until the winning process is done or we timeout. while test -d "$lockdir" && test $i -gt 0; do sleep 1 i=`expr $i - 1` done fi i=`expr $i - 1` done trap - 1 2 13 15 if test $i -le 0; then echo "$0: failed to acquire lock after $numtries attempts" >&2 echo "$0: check lockdir '$lockdir'" >&2 exit 1 fi if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form `foo.o: dependent.h', # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. # Do two passes, one to just change these to # `$object: dependent.h' and one to simply `dependent.h:'. sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this invocation # correctly. Breaking it into two sed invocations is a workaround. sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then # Libtool generates 2 separate objects for the 2 libraries. These # two compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir$base.o.d # libtool 1.5 tmpdepfile2=$dir.libs/$base.o.d # Likewise. tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d "$@" -MD fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done # Same post-processing that is required for AIX mode. aix_post_process_depfile ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" echo >> "$depfile" # make sure the fragment doesn't end with a backslash rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this sed invocation # correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process the last invocation # correctly. Breaking it into two sed invocations is a workaround. sed '1,2d' "$tmpdepfile" \ | tr ' ' "$nl" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E \ | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: ================================================ FILE: tess-two/jni/libjpeg/djpeg.1 ================================================ .TH DJPEG 1 "26 July 2015" .SH NAME djpeg \- decompress a JPEG file to an image file .SH SYNOPSIS .B djpeg [ .I options ] [ .I filename ] .LP .SH DESCRIPTION .LP .B djpeg decompresses the named JPEG file, or the standard input if no file is named, and produces an image file on the standard output. PBMPLUS (PPM/PGM), BMP, GIF, Targa, or RLE (Utah Raster Toolkit) output format can be selected. (RLE is supported only if the URT library is available.) .SH OPTIONS All switch names may be abbreviated; for example, .B \-grayscale may be written .B \-gray or .BR \-gr . Most of the "basic" switches can be abbreviated to as little as one letter. Upper and lower case are equivalent (thus .B \-BMP is the same as .BR \-bmp ). British spellings are also accepted (e.g., .BR \-greyscale ), though for brevity these are not mentioned below. .PP The basic switches are: .TP .BI \-colors " N" Reduce image to at most N colors. This reduces the number of colors used in the output image, so that it can be displayed on a colormapped display or stored in a colormapped file format. For example, if you have an 8-bit display, you'd need to reduce to 256 or fewer colors. .TP .BI \-quantize " N" Same as .BR \-colors . .B \-colors is the recommended name, .B \-quantize is provided only for backwards compatibility. .TP .B \-fast Select recommended processing options for fast, low quality output. (The default options are chosen for highest quality output.) Currently, this is equivalent to \fB\-dct fast \-nosmooth \-onepass \-dither ordered\fR. .TP .B \-grayscale Force grayscale output even if JPEG file is color. Useful for viewing on monochrome displays; also, .B djpeg runs noticeably faster in this mode. .TP .B \-rgb Force RGB output even if JPEG file is grayscale. This is provided to support applications that don't want to cope with grayscale as a separate case. .TP .BI \-scale " M/N" Scale the output image by a factor M/N. Currently supported scale factors are M/N with all M from 1 to 16, where N is the source DCT size, which is 8 for baseline JPEG. If the /N part is omitted, then M specifies the DCT scaled size to be applied on the given input. For baseline JPEG this is equivalent to M/8 scaling, since the source DCT size for baseline JPEG is 8. Scaling is handy if the image is larger than your screen; also, .B djpeg runs much faster when scaling down the output. .TP .B \-bmp Select BMP output format (Windows flavor). 8-bit colormapped format is emitted if .B \-colors or .B \-grayscale is specified, or if the JPEG file is grayscale; otherwise, 24-bit full-color format is emitted. .TP .B \-gif Select GIF output format. Since GIF does not support more than 256 colors, .B \-colors 256 is assumed (unless you specify a smaller number of colors). .TP .B \-os2 Select BMP output format (OS/2 1.x flavor). 8-bit colormapped format is emitted if .B \-colors or .B \-grayscale is specified, or if the JPEG file is grayscale; otherwise, 24-bit full-color format is emitted. .TP .B \-pnm Select PBMPLUS (PPM/PGM) output format (this is the default format). PGM is emitted if the JPEG file is grayscale or if .B \-grayscale is specified; otherwise PPM is emitted. .TP .B \-rle Select RLE output format. (Requires URT library.) .TP .B \-targa Select Targa output format. Grayscale format is emitted if the JPEG file is grayscale or if .B \-grayscale is specified; otherwise, colormapped format is emitted if .B \-colors is specified; otherwise, 24-bit full-color format is emitted. .PP Switches for advanced users: .TP .B \-dct int Use integer DCT method (default). .TP .B \-dct fast Use fast integer DCT (less accurate). .TP .B \-dct float Use floating-point DCT method. The float method is very slightly more accurate than the int method, but is much slower unless your machine has very fast floating-point hardware. Also note that results of the floating-point method may vary slightly across machines, while the integer methods should give the same results everywhere. The fast integer method is much less accurate than the other two. .TP .B \-dither fs Use Floyd-Steinberg dithering in color quantization. .TP .B \-dither ordered Use ordered dithering in color quantization. .TP .B \-dither none Do not use dithering in color quantization. By default, Floyd-Steinberg dithering is applied when quantizing colors; this is slow but usually produces the best results. Ordered dither is a compromise between speed and quality; no dithering is fast but usually looks awful. Note that these switches have no effect unless color quantization is being done. Ordered dither is only available in .B \-onepass mode. .TP .BI \-map " file" Quantize to the colors used in the specified image file. This is useful for producing multiple files with identical color maps, or for forcing a predefined set of colors to be used. The .I file must be a GIF or PPM file. This option overrides .B \-colors and .BR \-onepass . .TP .B \-nosmooth Don't use high-quality upsampling. .TP .B \-onepass Use one-pass instead of two-pass color quantization. The one-pass method is faster and needs less memory, but it produces a lower-quality image. .B \-onepass is ignored unless you also say .B \-colors .IR N . Also, the one-pass method is always used for grayscale output (the two-pass method is no improvement then). .TP .BI \-maxmemory " N" Set limit for amount of memory to use in processing large images. Value is in thousands of bytes, or millions of bytes if "M" is attached to the number. For example, .B \-max 4m selects 4000000 bytes. If more space is needed, temporary files will be used. .TP .BI \-outfile " name" Send output image to the named file, not to standard output. .TP .B \-verbose Enable debug printout. More .BR \-v 's give more output. Also, version information is printed at startup. .TP .B \-debug Same as .BR \-verbose . .SH EXAMPLES .LP This example decompresses the JPEG file foo.jpg, quantizes it to 256 colors, and saves the output in 8-bit BMP format in foo.bmp: .IP .B djpeg \-colors 256 \-bmp .I foo.jpg .B > .I foo.bmp .SH HINTS To get a quick preview of an image, use the .B \-grayscale and/or .B \-scale switches. .B \-grayscale \-scale 1/8 is the fastest case. .PP Several options are available that trade off image quality to gain speed. .B \-fast turns on the recommended settings. .PP .B \-dct fast and/or .B \-nosmooth gain speed at a small sacrifice in quality. When producing a color-quantized image, .B \-onepass \-dither ordered is fast but much lower quality than the default behavior. .B \-dither none may give acceptable results in two-pass mode, but is seldom tolerable in one-pass mode. .PP If you are fortunate enough to have very fast floating point hardware, \fB\-dct float\fR may be even faster than \fB\-dct fast\fR. But on most machines \fB\-dct float\fR is slower than \fB\-dct int\fR; in this case it is not worth using, because its theoretical accuracy advantage is too small to be significant in practice. .SH ENVIRONMENT .TP .B JPEGMEM If this environment variable is set, its value is the default memory limit. The value is specified as described for the .B \-maxmemory switch. .B JPEGMEM overrides the default value specified when the program was compiled, and itself is overridden by an explicit .BR \-maxmemory . .SH SEE ALSO .BR cjpeg (1), .BR jpegtran (1), .BR rdjpgcom (1), .BR wrjpgcom (1) .br .BR ppm (5), .BR pgm (5) .br Wallace, Gregory K. "The JPEG Still Picture Compression Standard", Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44. .SH AUTHOR Independent JPEG Group .SH BUGS To avoid the Unisys LZW patent (now expired), .B djpeg produces uncompressed GIF files. These are larger than they should be, but are readable by standard GIF decoders. ================================================ FILE: tess-two/jni/libjpeg/djpeg.c ================================================ /* * djpeg.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2009-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a command-line user interface for the JPEG decompressor. * It should work on any system with Unix- or MS-DOS-style command lines. * * Two different command line styles are permitted, depending on the * compile-time switch TWO_FILE_COMMANDLINE: * djpeg [options] inputfile outputfile * djpeg [options] [inputfile] * In the second style, output is always to standard output, which you'd * normally redirect to a file or pipe to some other program. Input is * either from a named file or from standard input (typically redirected). * The second style is convenient on Unix but is unhelpful on systems that * don't support pipes. Also, you MUST use the first style if your system * doesn't do binary I/O to stdin/stdout. * To simplify script writing, the "-outfile" switch is provided. The syntax * djpeg [options] -outfile outputfile inputfile * works regardless of which command line style is used. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #include "jversion.h" /* for version message */ #include /* to declare isprint() */ #ifdef USE_CCOMMAND /* command-line reader for Macintosh */ #ifdef __MWERKS__ #include /* Metrowerks needs this */ #include /* ... and this */ #endif #ifdef THINK_C #include /* Think declares it here */ #endif #endif /* Create the add-on message string table. */ #define JMESSAGE(code,string) string , static const char * const cdjpeg_message_table[] = { #include "cderror.h" NULL }; /* * This list defines the known output image formats * (not all of which need be supported by a given version). * You can change the default output format by defining DEFAULT_FMT; * indeed, you had better do so if you undefine PPM_SUPPORTED. */ typedef enum { FMT_BMP, /* BMP format (Windows flavor) */ FMT_GIF, /* GIF format */ FMT_OS2, /* BMP format (OS/2 flavor) */ FMT_PPM, /* PPM/PGM (PBMPLUS formats) */ FMT_RLE, /* RLE format */ FMT_TARGA, /* Targa format */ FMT_TIFF /* TIFF format */ } IMAGE_FORMATS; #ifndef DEFAULT_FMT /* so can override from CFLAGS in Makefile */ #define DEFAULT_FMT FMT_PPM #endif static IMAGE_FORMATS requested_fmt; /* * Argument-parsing code. * The switch parser is designed to be useful with DOS-style command line * syntax, ie, intermixed switches and file names, where only the switches * to the left of a given file name affect processing of that file. * The main program in this file doesn't actually use this capability... */ static const char * progname; /* program name for error messages */ static char * outfilename; /* for -outfile switch */ LOCAL(void) usage (void) /* complain about bad command line */ { fprintf(stderr, "usage: %s [switches] ", progname); #ifdef TWO_FILE_COMMANDLINE fprintf(stderr, "inputfile outputfile\n"); #else fprintf(stderr, "[inputfile]\n"); #endif fprintf(stderr, "Switches (names may be abbreviated):\n"); fprintf(stderr, " -colors N Reduce image to no more than N colors\n"); fprintf(stderr, " -fast Fast, low-quality processing\n"); fprintf(stderr, " -grayscale Force grayscale output\n"); fprintf(stderr, " -rgb Force RGB output\n"); #ifdef IDCT_SCALING_SUPPORTED fprintf(stderr, " -scale M/N Scale output image by fraction M/N, eg, 1/8\n"); #endif #ifdef BMP_SUPPORTED fprintf(stderr, " -bmp Select BMP output format (Windows style)%s\n", (DEFAULT_FMT == FMT_BMP ? " (default)" : "")); #endif #ifdef GIF_SUPPORTED fprintf(stderr, " -gif Select GIF output format%s\n", (DEFAULT_FMT == FMT_GIF ? " (default)" : "")); #endif #ifdef BMP_SUPPORTED fprintf(stderr, " -os2 Select BMP output format (OS/2 style)%s\n", (DEFAULT_FMT == FMT_OS2 ? " (default)" : "")); #endif #ifdef PPM_SUPPORTED fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n", (DEFAULT_FMT == FMT_PPM ? " (default)" : "")); #endif #ifdef RLE_SUPPORTED fprintf(stderr, " -rle Select Utah RLE output format%s\n", (DEFAULT_FMT == FMT_RLE ? " (default)" : "")); #endif #ifdef TARGA_SUPPORTED fprintf(stderr, " -targa Select Targa output format%s\n", (DEFAULT_FMT == FMT_TARGA ? " (default)" : "")); #endif fprintf(stderr, "Switches for advanced users:\n"); #ifdef DCT_ISLOW_SUPPORTED fprintf(stderr, " -dct int Use integer DCT method%s\n", (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : "")); #endif #ifdef DCT_IFAST_SUPPORTED fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n", (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : "")); #endif #ifdef DCT_FLOAT_SUPPORTED fprintf(stderr, " -dct float Use floating-point DCT method%s\n", (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : "")); #endif fprintf(stderr, " -dither fs Use F-S dithering (default)\n"); fprintf(stderr, " -dither none Don't use dithering in quantization\n"); fprintf(stderr, " -dither ordered Use ordered dither (medium speed, quality)\n"); #ifdef QUANT_2PASS_SUPPORTED fprintf(stderr, " -map FILE Map to colors used in named image file\n"); #endif fprintf(stderr, " -nosmooth Don't use high-quality upsampling\n"); #ifdef QUANT_1PASS_SUPPORTED fprintf(stderr, " -onepass Use 1-pass quantization (fast, low quality)\n"); #endif fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n"); fprintf(stderr, " -outfile name Specify name for output file\n"); fprintf(stderr, " -verbose or -debug Emit debug output\n"); exit(EXIT_FAILURE); } LOCAL(int) parse_switches (j_decompress_ptr cinfo, int argc, char **argv, int last_file_arg_seen, boolean for_real) /* Parse optional switches. * Returns argv[] index of first file-name argument (== argc if none). * Any file names with indexes <= last_file_arg_seen are ignored; * they have presumably been processed in a previous iteration. * (Pass 0 for last_file_arg_seen on the first or only iteration.) * for_real is FALSE on the first (dummy) pass; we may skip any expensive * processing. */ { int argn; char * arg; /* Set up default JPEG parameters. */ requested_fmt = DEFAULT_FMT; /* set default output file format */ outfilename = NULL; cinfo->err->trace_level = 0; /* Scan command line options, adjust parameters */ for (argn = 1; argn < argc; argn++) { arg = argv[argn]; if (*arg != '-') { /* Not a switch, must be a file name argument */ if (argn <= last_file_arg_seen) { outfilename = NULL; /* -outfile applies to just one input file */ continue; /* ignore this name if previously processed */ } break; /* else done parsing switches */ } arg++; /* advance past switch marker character */ if (keymatch(arg, "bmp", 1)) { /* BMP output format. */ requested_fmt = FMT_BMP; } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) || keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) { /* Do color quantization. */ int val; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%d", &val) != 1) usage(); cinfo->desired_number_of_colors = val; cinfo->quantize_colors = TRUE; } else if (keymatch(arg, "dct", 2)) { /* Select IDCT algorithm. */ if (++argn >= argc) /* advance to next argument */ usage(); if (keymatch(argv[argn], "int", 1)) { cinfo->dct_method = JDCT_ISLOW; } else if (keymatch(argv[argn], "fast", 2)) { cinfo->dct_method = JDCT_IFAST; } else if (keymatch(argv[argn], "float", 2)) { cinfo->dct_method = JDCT_FLOAT; } else usage(); } else if (keymatch(arg, "dither", 2)) { /* Select dithering algorithm. */ if (++argn >= argc) /* advance to next argument */ usage(); if (keymatch(argv[argn], "fs", 2)) { cinfo->dither_mode = JDITHER_FS; } else if (keymatch(argv[argn], "none", 2)) { cinfo->dither_mode = JDITHER_NONE; } else if (keymatch(argv[argn], "ordered", 2)) { cinfo->dither_mode = JDITHER_ORDERED; } else usage(); } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) { /* Enable debug printouts. */ /* On first -d, print version identification */ static boolean printed_version = FALSE; if (! printed_version) { fprintf(stderr, "Independent JPEG Group's DJPEG, version %s\n%s\n", JVERSION, JCOPYRIGHT); printed_version = TRUE; } cinfo->err->trace_level++; } else if (keymatch(arg, "fast", 1)) { /* Select recommended processing options for quick-and-dirty output. */ cinfo->two_pass_quantize = FALSE; cinfo->dither_mode = JDITHER_ORDERED; if (! cinfo->quantize_colors) /* don't override an earlier -colors */ cinfo->desired_number_of_colors = 216; cinfo->dct_method = JDCT_FASTEST; cinfo->do_fancy_upsampling = FALSE; } else if (keymatch(arg, "gif", 1)) { /* GIF output format. */ requested_fmt = FMT_GIF; } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) { /* Force monochrome output. */ cinfo->out_color_space = JCS_GRAYSCALE; } else if (keymatch(arg, "rgb", 3)) { /* Force RGB output. */ cinfo->out_color_space = JCS_RGB; } else if (keymatch(arg, "map", 3)) { /* Quantize to a color map taken from an input file. */ if (++argn >= argc) /* advance to next argument */ usage(); if (for_real) { /* too expensive to do twice! */ #ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */ FILE * mapfile; if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]); exit(EXIT_FAILURE); } read_color_map(cinfo, mapfile); fclose(mapfile); cinfo->quantize_colors = TRUE; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } } else if (keymatch(arg, "maxmemory", 3)) { /* Maximum memory in Kb (or Mb with 'm'). */ long lval; char ch = 'x'; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1) usage(); if (ch == 'm' || ch == 'M') lval *= 1000L; cinfo->mem->max_memory_to_use = lval * 1000L; } else if (keymatch(arg, "nosmooth", 3)) { /* Suppress fancy upsampling. */ cinfo->do_fancy_upsampling = FALSE; } else if (keymatch(arg, "onepass", 3)) { /* Use fast one-pass quantization. */ cinfo->two_pass_quantize = FALSE; } else if (keymatch(arg, "os2", 3)) { /* BMP output format (OS/2 flavor). */ requested_fmt = FMT_OS2; } else if (keymatch(arg, "outfile", 4)) { /* Set output file name. */ if (++argn >= argc) /* advance to next argument */ usage(); outfilename = argv[argn]; /* save it away for later use */ } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) { /* PPM/PGM output format. */ requested_fmt = FMT_PPM; } else if (keymatch(arg, "rle", 1)) { /* RLE output format. */ requested_fmt = FMT_RLE; } else if (keymatch(arg, "scale", 1)) { /* Scale the output image by a fraction M/N. */ if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%u/%u", &cinfo->scale_num, &cinfo->scale_denom) < 1) usage(); } else if (keymatch(arg, "targa", 1)) { /* Targa output format. */ requested_fmt = FMT_TARGA; } else { usage(); /* bogus switch */ } } return argn; /* return index of next arg (file name) */ } /* * Marker processor for COM and interesting APPn markers. * This replaces the library's built-in processor, which just skips the marker. * We want to print out the marker as text, to the extent possible. * Note this code relies on a non-suspending data source. */ LOCAL(unsigned int) jpeg_getc (j_decompress_ptr cinfo) /* Read next byte */ { struct jpeg_source_mgr * datasrc = cinfo->src; if (datasrc->bytes_in_buffer == 0) { if (! (*datasrc->fill_input_buffer) (cinfo)) ERREXIT(cinfo, JERR_CANT_SUSPEND); } datasrc->bytes_in_buffer--; return GETJOCTET(*datasrc->next_input_byte++); } METHODDEF(boolean) print_text_marker (j_decompress_ptr cinfo) { boolean traceit = (cinfo->err->trace_level >= 1); INT32 length; unsigned int ch; unsigned int lastch = 0; length = jpeg_getc(cinfo) << 8; length += jpeg_getc(cinfo); length -= 2; /* discount the length word itself */ if (traceit) { if (cinfo->unread_marker == JPEG_COM) fprintf(stderr, "Comment, length %ld:\n", (long) length); else /* assume it is an APPn otherwise */ fprintf(stderr, "APP%d, length %ld:\n", cinfo->unread_marker - JPEG_APP0, (long) length); } while (--length >= 0) { ch = jpeg_getc(cinfo); if (traceit) { /* Emit the character in a readable form. * Nonprintables are converted to \nnn form, * while \ is converted to \\. * Newlines in CR, CR/LF, or LF form will be printed as one newline. */ if (ch == '\r') { fprintf(stderr, "\n"); } else if (ch == '\n') { if (lastch != '\r') fprintf(stderr, "\n"); } else if (ch == '\\') { fprintf(stderr, "\\\\"); } else if (isprint(ch)) { putc(ch, stderr); } else { fprintf(stderr, "\\%03o", ch); } lastch = ch; } } if (traceit) fprintf(stderr, "\n"); return TRUE; } /* * The main program. */ int main (int argc, char **argv) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; #ifdef PROGRESS_REPORT struct cdjpeg_progress_mgr progress; #endif int file_index; djpeg_dest_ptr dest_mgr = NULL; FILE * input_file; FILE * output_file; JDIMENSION num_scanlines; /* On Mac, fetch a command line. */ #ifdef USE_CCOMMAND argc = ccommand(&argv); #endif progname = argv[0]; if (progname == NULL || progname[0] == 0) progname = "djpeg"; /* in case C library doesn't provide it */ /* Initialize the JPEG decompression object with default error handling. */ cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); /* Add some application-specific error messages (from cderror.h) */ jerr.addon_message_table = cdjpeg_message_table; jerr.first_addon_message = JMSG_FIRSTADDONCODE; jerr.last_addon_message = JMSG_LASTADDONCODE; /* Insert custom marker processor for COM and APP12. * APP12 is used by some digital camera makers for textual info, * so we provide the ability to display it as text. * If you like, additional APPn marker types can be selected for display, * but don't try to override APP0 or APP14 this way (see libjpeg.doc). */ jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker); jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker); /* Now safe to enable signal catcher. */ #ifdef NEED_SIGNAL_CATCHER enable_signal_catcher((j_common_ptr) &cinfo); #endif /* Scan command line to find file names. */ /* It is convenient to use just one switch-parsing routine, but the switch * values read here are ignored; we will rescan the switches after opening * the input file. * (Exception: tracing level set here controls verbosity for COM markers * found during jpeg_read_header...) */ file_index = parse_switches(&cinfo, argc, argv, 0, FALSE); #ifdef TWO_FILE_COMMANDLINE /* Must have either -outfile switch or explicit output file name */ if (outfilename == NULL) { if (file_index != argc-2) { fprintf(stderr, "%s: must name one input and one output file\n", progname); usage(); } outfilename = argv[file_index+1]; } else { if (file_index != argc-1) { fprintf(stderr, "%s: must name one input and one output file\n", progname); usage(); } } #else /* Unix style: expect zero or one file name */ if (file_index < argc-1) { fprintf(stderr, "%s: only one input file\n", progname); usage(); } #endif /* TWO_FILE_COMMANDLINE */ /* Open the input file. */ if (file_index < argc) { if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]); exit(EXIT_FAILURE); } } else { /* default input file is stdin */ input_file = read_stdin(); } /* Open the output file. */ if (outfilename != NULL) { if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, outfilename); exit(EXIT_FAILURE); } } else { /* default output file is stdout */ output_file = write_stdout(); } #ifdef PROGRESS_REPORT start_progress_monitor((j_common_ptr) &cinfo, &progress); #endif /* Specify data source for decompression */ jpeg_stdio_src(&cinfo, input_file); /* Read file header, set default decompression parameters */ (void) jpeg_read_header(&cinfo, TRUE); /* Adjust default decompression parameters by re-parsing the options */ file_index = parse_switches(&cinfo, argc, argv, 0, TRUE); /* Initialize the output module now to let it override any crucial * option settings (for instance, GIF wants to force color quantization). */ switch (requested_fmt) { #ifdef BMP_SUPPORTED case FMT_BMP: dest_mgr = jinit_write_bmp(&cinfo, FALSE); break; case FMT_OS2: dest_mgr = jinit_write_bmp(&cinfo, TRUE); break; #endif #ifdef GIF_SUPPORTED case FMT_GIF: dest_mgr = jinit_write_gif(&cinfo); break; #endif #ifdef PPM_SUPPORTED case FMT_PPM: dest_mgr = jinit_write_ppm(&cinfo); break; #endif #ifdef RLE_SUPPORTED case FMT_RLE: dest_mgr = jinit_write_rle(&cinfo); break; #endif #ifdef TARGA_SUPPORTED case FMT_TARGA: dest_mgr = jinit_write_targa(&cinfo); break; #endif default: ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT); break; } dest_mgr->output_file = output_file; /* Start decompressor */ (void) jpeg_start_decompress(&cinfo); /* Write output file header */ (*dest_mgr->start_output) (&cinfo, dest_mgr); /* Process data */ while (cinfo.output_scanline < cinfo.output_height) { num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer, dest_mgr->buffer_height); (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines); } #ifdef PROGRESS_REPORT /* Hack: count final pass as done in case finish_output does an extra pass. * The library won't have updated completed_passes. */ progress.pub.completed_passes = progress.pub.total_passes; #endif /* Finish decompression and release memory. * I must do it in this order because output module has allocated memory * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory. */ (*dest_mgr->finish_output) (&cinfo, dest_mgr); (void) jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); /* Close files, if we opened them */ if (input_file != stdin) fclose(input_file); if (output_file != stdout) fclose(output_file); #ifdef PROGRESS_REPORT end_progress_monitor((j_common_ptr) &cinfo); #endif /* All done. */ exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS); return 0; /* suppress no-return-value warnings */ } ================================================ FILE: tess-two/jni/libjpeg/example.c ================================================ /* * example.c * * This file illustrates how to use the IJG code as a subroutine library * to read or write JPEG image files. You should look at this code in * conjunction with the documentation file libjpeg.txt. * * This code will not do anything useful as-is, but it may be helpful as a * skeleton for constructing routines that call the JPEG library. * * We present these routines in the same coding style used in the JPEG code * (ANSI function definitions, etc); but you are of course free to code your * routines in a different style if you prefer. */ #include /* * Include file for users of JPEG library. * You will need to have included system headers that define at least * the typedefs FILE and size_t before you can include jpeglib.h. * (stdio.h is sufficient on ANSI-conforming systems.) * You may also wish to include "jerror.h". */ #include "jpeglib.h" /* * is used for the optional error recovery mechanism shown in * the second part of the example. */ #include /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/ /* This half of the example shows how to feed data into the JPEG compressor. * We present a minimal version that does not worry about refinements such * as error recovery (the JPEG code will just exit() if it gets an error). */ /* * IMAGE DATA FORMATS: * * The standard input image format is a rectangular array of pixels, with * each pixel having the same number of "component" values (color channels). * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars). * If you are working with color data, then the color values for each pixel * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit * RGB color. * * For this example, we'll assume that this data structure matches the way * our application has stored the image in memory, so we can just pass a * pointer to our image buffer. In particular, let's say that the image is * RGB color and is described by: */ extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */ extern int image_height; /* Number of rows in image */ extern int image_width; /* Number of columns in image */ /* * Sample routine for JPEG compression. We assume that the target file name * and a compression quality factor are passed in. */ GLOBAL(void) write_JPEG_file (char * filename, int quality) { /* This struct contains the JPEG compression parameters and pointers to * working space (which is allocated as needed by the JPEG library). * It is possible to have several such structures, representing multiple * compression/decompression processes, in existence at once. We refer * to any one struct (and its associated working data) as a "JPEG object". */ struct jpeg_compress_struct cinfo; /* This struct represents a JPEG error handler. It is declared separately * because applications often want to supply a specialized error handler * (see the second half of this file for an example). But here we just * take the easy way out and use the standard error handler, which will * print a message on stderr and call exit() if compression fails. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. */ struct jpeg_error_mgr jerr; /* More stuff */ FILE * outfile; /* target file */ JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ int row_stride; /* physical row width in image buffer */ /* Step 1: allocate and initialize JPEG compression object */ /* We have to set up the error handler first, in case the initialization * step fails. (Unlikely, but it could happen if you are out of memory.) * This routine fills in the contents of struct jerr, and returns jerr's * address which we place into the link field in cinfo. */ cinfo.err = jpeg_std_error(&jerr); /* Now we can initialize the JPEG compression object. */ jpeg_create_compress(&cinfo); /* Step 2: specify data destination (eg, a file) */ /* Note: steps 2 and 3 can be done in either order. */ /* Here we use the library-supplied code to send compressed data to a * stdio stream. You can also write your own code to do something else. * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that * requires it in order to write binary files. */ if ((outfile = fopen(filename, "wb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); exit(1); } jpeg_stdio_dest(&cinfo, outfile); /* Step 3: set parameters for compression */ /* First we supply a description of the input image. * Four fields of the cinfo struct must be filled in: */ cinfo.image_width = image_width; /* image width and height, in pixels */ cinfo.image_height = image_height; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ /* Now use the library's routine to set default compression parameters. * (You must set at least cinfo.in_color_space before calling this, * since the defaults depend on the source color space.) */ jpeg_set_defaults(&cinfo); /* Now you can set any non-default parameters you wish to. * Here we just illustrate the use of quality (quantization table) scaling: */ jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */); /* Step 4: Start compressor */ /* TRUE ensures that we will write a complete interchange-JPEG file. * Pass TRUE unless you are very sure of what you're doing. */ jpeg_start_compress(&cinfo, TRUE); /* Step 5: while (scan lines remain to be written) */ /* jpeg_write_scanlines(...); */ /* Here we use the library's state variable cinfo.next_scanline as the * loop counter, so that we don't have to keep track ourselves. * To keep things simple, we pass one scanline per call; you can pass * more if you wish, though. */ row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */ while (cinfo.next_scanline < cinfo.image_height) { /* jpeg_write_scanlines expects an array of pointers to scanlines. * Here the array is only one element long, but you could pass * more than one scanline at a time if that's more convenient. */ row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride]; (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); } /* Step 6: Finish compression */ jpeg_finish_compress(&cinfo); /* After finish_compress, we can close the output file. */ fclose(outfile); /* Step 7: release JPEG compression object */ /* This is an important step since it will release a good deal of memory. */ jpeg_destroy_compress(&cinfo); /* And we're done! */ } /* * SOME FINE POINTS: * * In the above loop, we ignored the return value of jpeg_write_scanlines, * which is the number of scanlines actually written. We could get away * with this because we were only relying on the value of cinfo.next_scanline, * which will be incremented correctly. If you maintain additional loop * variables then you should be careful to increment them properly. * Actually, for output to a stdio stream you needn't worry, because * then jpeg_write_scanlines will write all the lines passed (or else exit * with a fatal error). Partial writes can only occur if you use a data * destination module that can demand suspension of the compressor. * (If you don't know what that's for, you don't need it.) * * If the compressor requires full-image buffers (for entropy-coding * optimization or a multi-scan JPEG file), it will create temporary * files for anything that doesn't fit within the maximum-memory setting. * (Note that temp files are NOT needed if you use the default parameters.) * On some systems you may need to set up a signal handler to ensure that * temporary files are deleted if the program is interrupted. See libjpeg.txt. * * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG * files to be compatible with everyone else's. If you cannot readily read * your data in that order, you'll need an intermediate array to hold the * image. See rdtarga.c or rdbmp.c for examples of handling bottom-to-top * source data using the JPEG code's internal virtual-array mechanisms. */ /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/ /* This half of the example shows how to read data from the JPEG decompressor. * It's a bit more refined than the above, in that we show: * (a) how to modify the JPEG library's standard error-reporting behavior; * (b) how to allocate workspace using the library's memory manager. * * Just to make this example a little different from the first one, we'll * assume that we do not intend to put the whole image into an in-memory * buffer, but to send it line-by-line someplace else. We need a one- * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG * memory manager allocate it for us. This approach is actually quite useful * because we don't need to remember to deallocate the buffer separately: it * will go away automatically when the JPEG object is cleaned up. */ /* * ERROR HANDLING: * * The JPEG library's standard error handler (jerror.c) is divided into * several "methods" which you can override individually. This lets you * adjust the behavior without duplicating a lot of code, which you might * have to update with each future release. * * Our example here shows how to override the "error_exit" method so that * control is returned to the library's caller when a fatal error occurs, * rather than calling exit() as the standard error_exit method does. * * We use C's setjmp/longjmp facility to return control. This means that the * routine which calls the JPEG library must first execute a setjmp() call to * establish the return point. We want the replacement error_exit to do a * longjmp(). But we need to make the setjmp buffer accessible to the * error_exit routine. To do this, we make a private extension of the * standard JPEG error handler object. (If we were using C++, we'd say we * were making a subclass of the regular error handler.) * * Here's the extended error handler struct: */ struct my_error_mgr { struct jpeg_error_mgr pub; /* "public" fields */ jmp_buf setjmp_buffer; /* for return to caller */ }; typedef struct my_error_mgr * my_error_ptr; /* * Here's the routine that will replace the standard error_exit method: */ METHODDEF(void) my_error_exit (j_common_ptr cinfo) { /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */ my_error_ptr myerr = (my_error_ptr) cinfo->err; /* Always display the message. */ /* We could postpone this until after returning, if we chose. */ (*cinfo->err->output_message) (cinfo); /* Return control to the setjmp point */ longjmp(myerr->setjmp_buffer, 1); } /* * Sample routine for JPEG decompression. We assume that the source file name * is passed in. We want to return 1 on success, 0 on error. */ GLOBAL(int) read_JPEG_file (char * filename) { /* This struct contains the JPEG decompression parameters and pointers to * working space (which is allocated as needed by the JPEG library). */ struct jpeg_decompress_struct cinfo; /* We use our private extension JPEG error handler. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. */ struct my_error_mgr jerr; /* More stuff */ FILE * infile; /* source file */ JSAMPARRAY buffer; /* Output row buffer */ int row_stride; /* physical row width in output buffer */ /* In this example we want to open the input file before doing anything else, * so that the setjmp() error recovery below can assume the file is open. * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that * requires it in order to read binary files. */ if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); return 0; } /* Step 1: allocate and initialize JPEG decompression object */ /* We set up the normal JPEG error routines, then override error_exit. */ cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = my_error_exit; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp(jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object, close the input file, and return. */ jpeg_destroy_decompress(&cinfo); fclose(infile); return 0; } /* Now we can initialize the JPEG decompression object. */ jpeg_create_decompress(&cinfo); /* Step 2: specify data source (eg, a file) */ jpeg_stdio_src(&cinfo, infile); /* Step 3: 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. * See libjpeg.txt for more info. */ /* Step 4: set parameters for decompression */ /* In this example, we don't need to change any of the defaults set by * jpeg_read_header(), so we do nothing here. */ /* Step 5: Start decompressor */ (void) jpeg_start_decompress(&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ /* We may need to do some setup of our own at this point before reading * the data. After jpeg_start_decompress() we have the correct scaled * output image dimensions available, as well as the output colormap * if we asked for color quantization. * In this example, we need to make an output work buffer of the right size. */ /* JSAMPLEs per row in output buffer */ row_stride = cinfo.output_width * cinfo.output_components; /* Make a one-row-high sample array that will go away when done with image */ buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); /* Step 6: 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. */ while (cinfo.output_scanline < cinfo.output_height) { /* jpeg_read_scanlines expects an array of pointers to scanlines. * Here the array is only one element long, but you could ask for * more than one scanline at a time if that's more convenient. */ (void) jpeg_read_scanlines(&cinfo, buffer, 1); /* Assume put_scanline_someplace wants a pointer and sample count. */ put_scanline_someplace(buffer[0], row_stride); } /* 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 */ /* This is an important step since it will release a good deal of memory. */ jpeg_destroy_decompress(&cinfo); /* After finish_decompress, we can close the input file. * Here we postpone it until after no more JPEG errors are possible, * so as to simplify the setjmp error logic above. (Actually, I don't * think that jpeg_destroy can do an error exit, but why assume anything...) */ fclose(infile); /* At this point you may want to check to see whether any corrupt-data * warnings occurred (test whether jerr.pub.num_warnings is nonzero). */ /* And we're done! */ return 1; } /* * SOME FINE POINTS: * * In the above code, we ignored the return value of jpeg_read_scanlines, * which is the number of scanlines actually read. We could get away with * this because we asked for only one line at a time and we weren't using * a suspending data source. See libjpeg.txt for more info. * * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress(); * we should have done it beforehand to ensure that the space would be * counted against the JPEG max_memory setting. In some systems the above * code would risk an out-of-memory error. However, in general we don't * know the output image dimensions before jpeg_start_decompress(), unless we * call jpeg_calc_output_dimensions(). See libjpeg.txt for more about this. * * Scanlines are returned in the same order as they appear in the JPEG file, * which is standardly top-to-bottom. If you must emit data bottom-to-top, * you can use one of the virtual arrays provided by the JPEG memory manager * to invert the data. See wrbmp.c for an example. * * As with compression, some operating modes may require temporary files. * On some systems you may need to set up a signal handler to ensure that * temporary files are deleted if the program is interrupted. See libjpeg.txt. */ ================================================ FILE: tess-two/jni/libjpeg/filelist.txt ================================================ IJG JPEG LIBRARY: FILE LIST Copyright (C) 1994-2013, Thomas G. Lane, Guido Vollbeding. This file is part of the Independent JPEG Group's software. For conditions of distribution and use, see the accompanying README file. Here is a road map to the files in the IJG JPEG distribution. The distribution includes the JPEG library proper, plus two application programs ("cjpeg" and "djpeg") which use the library to convert JPEG files to and from some other popular image formats. A third application "jpegtran" uses the library to do lossless conversion between different variants of JPEG. There are also two stand-alone applications, "rdjpgcom" and "wrjpgcom". THE JPEG LIBRARY ================ Include files: jpeglib.h JPEG library's exported data and function declarations. jconfig.h Configuration declarations. Note: this file is not present in the distribution; it is generated during installation. jmorecfg.h Additional configuration declarations; need not be changed for a standard installation. jerror.h Declares JPEG library's error and trace message codes. jinclude.h Central include file used by all IJG .c files to reference system include files. jpegint.h JPEG library's internal data structures. jdct.h Private declarations for forward & reverse DCT subsystems. jmemsys.h Private declarations for memory management subsystem. jversion.h Version information. Applications using the library should include jpeglib.h (which in turn includes jconfig.h and jmorecfg.h). Optionally, jerror.h may be included if the application needs to reference individual JPEG error codes. The other include files are intended for internal use and would not normally be included by an application program. (cjpeg/djpeg/etc do use jinclude.h, since its function is to improve portability of the whole IJG distribution. Most other applications will directly include the system include files they want, and hence won't need jinclude.h.) C source code files: These files contain most of the functions intended to be called directly by an application program: jcapimin.c Application program interface: core routines for compression. jcapistd.c Application program interface: standard compression. jdapimin.c Application program interface: core routines for decompression. jdapistd.c Application program interface: standard decompression. jcomapi.c Application program interface routines common to compression and decompression. jcparam.c Compression parameter setting helper routines. jctrans.c API and library routines for transcoding compression. jdtrans.c API and library routines for transcoding decompression. Compression side of the library: jcinit.c Initialization: determines which other modules to use. jcmaster.c Master control: setup and inter-pass sequencing logic. jcmainct.c Main buffer controller (preprocessor => JPEG compressor). jcprepct.c Preprocessor buffer controller. jccoefct.c Buffer controller for DCT coefficient buffer. jccolor.c Color space conversion. jcsample.c Downsampling. jcdctmgr.c DCT manager (DCT implementation selection & control). jfdctint.c Forward DCT using slow-but-accurate integer method. jfdctfst.c Forward DCT using faster, less accurate integer method. jfdctflt.c Forward DCT using floating-point arithmetic. jchuff.c Huffman entropy coding. jcarith.c Arithmetic entropy coding. jcmarker.c JPEG marker writing. jdatadst.c Data destination managers for memory and stdio output. Decompression side of the library: jdmaster.c Master control: determines which other modules to use. jdinput.c Input controller: controls input processing modules. jdmainct.c Main buffer controller (JPEG decompressor => postprocessor). jdcoefct.c Buffer controller for DCT coefficient buffer. jdpostct.c Postprocessor buffer controller. jdmarker.c JPEG marker reading. jdhuff.c Huffman entropy decoding. jdarith.c Arithmetic entropy decoding. jddctmgr.c IDCT manager (IDCT implementation selection & control). jidctint.c Inverse DCT using slow-but-accurate integer method. jidctfst.c Inverse DCT using faster, less accurate integer method. jidctflt.c Inverse DCT using floating-point arithmetic. jdsample.c Upsampling. jdcolor.c Color space conversion. jdmerge.c Merged upsampling/color conversion (faster, lower quality). jquant1.c One-pass color quantization using a fixed-spacing colormap. jquant2.c Two-pass color quantization using a custom-generated colormap. Also handles one-pass quantization to an externally given map. jdatasrc.c Data source managers for memory and stdio input. Support files for both compression and decompression: jaricom.c Tables for common use in arithmetic entropy encoding and decoding routines. jerror.c Standard error handling routines (application replaceable). jmemmgr.c System-independent (more or less) memory management code. jutils.c Miscellaneous utility routines. jmemmgr.c relies on a system-dependent memory management module. The IJG distribution includes the following implementations of the system-dependent module: jmemnobs.c "No backing store": assumes adequate virtual memory exists. jmemansi.c Makes temporary files with ANSI-standard routine tmpfile(). jmemname.c Makes temporary files with program-generated file names. jmemdos.c Custom implementation for MS-DOS (16-bit environment only): can use extended and expanded memory as well as temp files. jmemmac.c Custom implementation for Apple Macintosh. Exactly one of the system-dependent modules should be configured into an installed JPEG library (see install.txt for hints about which one to use). On unusual systems you may find it worthwhile to make a special system-dependent memory manager. Non-C source code files: jmemdosa.asm 80x86 assembly code support for jmemdos.c; used only in MS-DOS-specific configurations of the JPEG library. CJPEG/DJPEG/JPEGTRAN ==================== Include files: cdjpeg.h Declarations shared by cjpeg/djpeg/jpegtran modules. cderror.h Additional error and trace message codes for cjpeg et al. transupp.h Declarations for jpegtran support routines in transupp.c. C source code files: cjpeg.c Main program for cjpeg. djpeg.c Main program for djpeg. jpegtran.c Main program for jpegtran. cdjpeg.c Utility routines used by all three programs. rdcolmap.c Code to read a colormap file for djpeg's "-map" switch. rdswitch.c Code to process some of cjpeg's more complex switches. Also used by jpegtran. transupp.c Support code for jpegtran: lossless image manipulations. Image file reader modules for cjpeg: rdbmp.c BMP file input. rdgif.c GIF file input (now just a stub). rdppm.c PPM/PGM file input. rdrle.c Utah RLE file input. rdtarga.c Targa file input. Image file writer modules for djpeg: wrbmp.c BMP file output. wrgif.c GIF file output (a mere shadow of its former self). wrppm.c PPM/PGM file output. wrrle.c Utah RLE file output. wrtarga.c Targa file output. RDJPGCOM/WRJPGCOM ================= C source code files: rdjpgcom.c Stand-alone rdjpgcom application. wrjpgcom.c Stand-alone wrjpgcom application. These programs do not depend on the IJG library. They do use jconfig.h and jinclude.h, only to improve portability. ADDITIONAL FILES ================ Documentation (see README for a guide to the documentation files): README Master documentation file. *.txt Other documentation files. *.1 Documentation in Unix man page format. change.log Version-to-version change highlights. example.c Sample code for calling JPEG library. Configuration/installation files and programs (see install.txt for more info): configure Unix shell script to perform automatic configuration. configure.ac Source file for use with Autoconf to generate configure. ltmain.sh Support scripts for configure (from GNU libtool). config.guess config.sub depcomp missing ar-lib compile install-sh Install shell script for those Unix systems lacking one. Makefile.in Makefile input for configure. Makefile.am Source file for use with Automake to generate Makefile.in. ckconfig.c Program to generate jconfig.h on non-Unix systems. jconfig.txt Template for making jconfig.h by hand. mak*.* Sample makefiles for particular systems. jconfig.* Sample jconfig.h for particular systems. libjpeg.map Script to generate shared library with versioned symbols. aclocal.m4 M4 macro definitions for use with Autoconf. Test files (see install.txt for test procedure): test*.* Source and comparison files for confidence test. These are binary image files, NOT text files. ================================================ FILE: tess-two/jni/libjpeg/install-sh ================================================ #!/bin/sh # install - install a program, script, or datafile scriptversion=2013-12-25.23; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # 'make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. tab=' ' nl=' ' IFS=" $tab$nl" # Set DOITPROG to "echo" to test this script. doit=${DOITPROG-} doit_exec=${doit:-exec} # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false is_target_a_directory=possibly usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) is_target_a_directory=always dst_arg=$2 # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) is_target_a_directory=never;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done # We allow the use of options -d and -T together, by making -d # take the precedence; this is for compatibility with GNU install. if test -n "$dir_arg"; then if test -n "$dst_arg"; then echo "$0: target directory not allowed when installing a directory." >&2 exit 1 fi fi if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call 'install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then if test $# -gt 1 || test "$is_target_a_directory" = always; then if test ! -d "$dst_arg"; then echo "$0: $dst_arg: Is not a directory." >&2 exit 1 fi fi fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for 'test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename; won't work # if double slashes aren't ignored. if test -d "$dst"; then if test "$is_target_a_directory" = never; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dst=$dstdir/`basename "$src"` dstdir_status=0 else dstdir=`dirname "$dst"` test -d "$dstdir" dstdir_status=$? fi fi obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac oIFS=$IFS IFS=/ set -f set fnord $dstdir shift set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=$dstdir/_inst.$$_ rmtmp=$dstdir/_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: ================================================ FILE: tess-two/jni/libjpeg/install.txt ================================================ INSTALLATION INSTRUCTIONS for the Independent JPEG Group's JPEG software Copyright (C) 1991-2015, Thomas G. Lane, Guido Vollbeding. This file is part of the Independent JPEG Group's software. For conditions of distribution and use, see the accompanying README file. This file explains how to configure and install the IJG software. We have tried to make this software extremely portable and flexible, so that it can be adapted to almost any environment. The downside of this decision is that the installation process is complicated. We have provided shortcuts to simplify the task on common systems. But in any case, you will need at least a little familiarity with C programming and program build procedures for your system. If you are only using this software as part of a larger program, the larger program's installation procedure may take care of configuring the IJG code. For example, Ghostscript's installation script will configure the IJG code. You don't need to read this file if you just want to compile Ghostscript. If you are on a Unix machine, you may not need to read this file at all. Try doing ./configure make make test If that doesn't complain, do make install (better do "make -n install" first to see if the makefile will put the files where you want them). Read further if you run into snags or want to customize the code for your system. TABLE OF CONTENTS ----------------- Before you start Configuring the software: using the automatic "configure" script using one of the supplied jconfig and makefile files by hand Building the software Testing the software Installing the software Optional stuff Optimization Hints for specific systems BEFORE YOU START ================ Before installing the software you must unpack the distributed source code. Since you are reading this file, you have probably already succeeded in this task. However, there is a potential for error if you needed to convert the files to the local standard text file format (for example, if you are on MS-DOS you may have converted LF end-of-line to CR/LF). You must apply such conversion to all the files EXCEPT those whose names begin with "test". The test files contain binary data; if you change them in any way then the self-test will give bad results. Please check the last section of this file to see if there are hints for the specific machine or compiler you are using. CONFIGURING THE SOFTWARE ======================== To configure the IJG code for your system, you need to create two files: * jconfig.h: contains values for system-dependent #define symbols. * Makefile: controls the compilation process. (On a non-Unix machine, you may create "project files" or some other substitute for a Makefile. jconfig.h is needed in any environment.) We provide three different ways to generate these files: * On a Unix system, you can just run the "configure" script. * We provide sample jconfig files and makefiles for popular machines; if your machine matches one of the samples, just copy the right sample files to jconfig.h and Makefile. * If all else fails, read the instructions below and make your own files. Configuring the software using the automatic "configure" script --------------------------------------------------------------- If you are on a Unix machine, you can just type ./configure and let the configure script construct appropriate configuration files. If you're using "csh" on an old version of System V, you might need to type sh configure instead to prevent csh from trying to execute configure itself. Expect configure to run for a few minutes, particularly on slower machines; it works by compiling a series of test programs. Configure was created with GNU Autoconf and it follows the usual conventions for GNU configure scripts. It makes a few assumptions that you may want to override. You can do this by providing optional switches to configure: * Configure will build both static and shared libraries, if possible. If you want to build libjpeg only as a static library, say ./configure --disable-shared If you want to build libjpeg only as a shared library, say ./configure --disable-static Configure uses GNU libtool to take care of system-dependent shared library building methods. * Configure will use gcc (GNU C compiler) if it's available, otherwise cc. To force a particular compiler to be selected, use the CC option, for example ./configure CC='cc' The same method can be used to include any unusual compiler switches. For example, on HP-UX you probably want to say ./configure CC='cc -Aa' to get HP's compiler to run in ANSI mode. * The default CFLAGS setting is "-g" for non-gcc compilers, "-g -O2" for gcc. You can override this by saying, for example, ./configure CFLAGS='-O2' if you want to compile without debugging support. * Configure will set up the makefile so that "make install" will install files into /usr/local/bin, /usr/local/man, etc. You can specify an installation prefix other than "/usr/local" by giving configure the option "--prefix=PATH". * If you don't have a lot of swap space, you may need to enable the IJG software's internal virtual memory mechanism. To do this, give the option "--enable-maxmem=N" where N is the default maxmemory limit in megabytes. This is discussed in more detail under "Selecting a memory manager", below. You probably don't need to worry about this on reasonably-sized Unix machines, unless you plan to process very large images. Configure has some other features that are useful if you are cross-compiling or working in a network of multiple machine types; but if you need those features, you probably already know how to use them. Configuring the software using one of the supplied jconfig and makefile files ----------------------------------------------------------------------------- If you have one of these systems, you can just use the provided configuration files: Makefile jconfig file System and/or compiler makefile.manx jconfig.manx Amiga, Manx Aztec C makefile.sas jconfig.sas Amiga, SAS C makeproj.mac jconfig.mac Apple Macintosh, Metrowerks CodeWarrior mak*jpeg.st jconfig.st Atari ST/STE/TT, Pure C or Turbo C makefile.bcc jconfig.bcc MS-DOS or OS/2, Borland C makefile.dj jconfig.dj MS-DOS, DJGPP (Delorie's port of GNU C) makefile.mc6 jconfig.mc6 MS-DOS, Microsoft C (16-bit only) makefile.wat jconfig.wat MS-DOS, OS/2, or Windows NT, Watcom C makefile.vc jconfig.vc Windows NT/9x, MS Visual C++ make*.vc6 jconfig.vc Windows NT/9x, MS Visual C++ 6 make*.v10 jconfig.vc Windows NT/9x, MS Visual C++ 2010 (v10) makefile.b32 jconfig.vc Windows NT/9x, Borland C++ 32-bit (bcc32) makefile.mms jconfig.vms Digital VMS, with MMS software makefile.vms jconfig.vms Digital VMS, without MMS software Copy the proper jconfig file to jconfig.h and the makefile to Makefile (or whatever your system uses as the standard makefile name). For more info see the appropriate system-specific hints section near the end of this file. Configuring the software by hand -------------------------------- First, generate a jconfig.h file. If you are moderately familiar with C, the comments in jconfig.txt should be enough information to do this; just copy jconfig.txt to jconfig.h and edit it appropriately. Otherwise, you may prefer to use the ckconfig.c program. You will need to compile and execute ckconfig.c by hand --- we hope you know at least enough to do that. ckconfig.c may not compile the first try (in fact, the whole idea is for it to fail if anything is going to). If you get compile errors, fix them by editing ckconfig.c according to the directions given in ckconfig.c. Once you get it to run, it will write a suitable jconfig.h file, and will also print out some advice about which makefile to use. You may also want to look at the canned jconfig files, if there is one for a system similar to yours. Second, select a makefile and copy it to Makefile (or whatever your system uses as the standard makefile name). The most generic makefiles we provide are makefile.ansi: if your C compiler supports function prototypes makefile.unix: if not. (You have function prototypes if ckconfig.c put "#define HAVE_PROTOTYPES" in jconfig.h.) You may want to start from one of the other makefiles if there is one for a system similar to yours. Look over the selected Makefile and adjust options as needed. In particular you may want to change the CC and CFLAGS definitions. For instance, if you are using GCC, set CC=gcc. If you had to use any compiler switches to get ckconfig.c to work, make sure the same switches are in CFLAGS. If you are on a system that doesn't use makefiles, you'll need to set up project files (or whatever you do use) to compile all the source files and link them into executable files cjpeg, djpeg, jpegtran, rdjpgcom, and wrjpgcom. See the file lists in any of the makefiles to find out which files go into each program. Note that the provided makefiles all make a "library" file libjpeg first, but you don't have to do that if you don't want to; the file lists identify which source files are actually needed for compression, decompression, or both. As a last resort, you can make a batch script that just compiles everything and links it all together; makefile.vms is an example of this (it's for VMS systems that have no make-like utility). Here are comments about some specific configuration decisions you'll need to make: Command line style ------------------ These programs can use a Unix-like command line style which supports redirection and piping, like this: cjpeg inputfile >outputfile cjpeg outputfile source program | cjpeg >outputfile The simpler "two file" command line style is just cjpeg inputfile outputfile You may prefer the two-file style, particularly if you don't have pipes. You MUST use two-file style on any system that doesn't cope well with binary data fed through stdin/stdout; this is true for some MS-DOS compilers, for example. If you're not on a Unix system, it's safest to assume you need two-file style. (But if your compiler provides either the Posix-standard fdopen() library routine or a Microsoft-compatible setmode() routine, you can safely use the Unix command line style, by defining USE_FDOPEN or USE_SETMODE respectively.) To use the two-file style, make jconfig.h say "#define TWO_FILE_COMMANDLINE". Selecting a memory manager -------------------------- The IJG code is capable of working on images that are too big to fit in main memory; data is swapped out to temporary files as necessary. However, the code to do this is rather system-dependent. We provide five different memory managers: * jmemansi.c This version uses the ANSI-standard library routine tmpfile(), which not all non-ANSI systems have. On some systems tmpfile() may put the temporary file in a non-optimal location; if you don't like what it does, use jmemname.c. * jmemname.c This version creates named temporary files. For anything except a Unix machine, you'll need to configure the select_file_name() routine appropriately; see the comments near the head of jmemname.c. If you use this version, define NEED_SIGNAL_CATCHER in jconfig.h to make sure the temp files are removed if the program is aborted. * jmemnobs.c (That stands for No Backing Store :-).) This will compile on almost any system, but it assumes you have enough main memory or virtual memory to hold the biggest images you work with. * jmemdos.c This should be used with most 16-bit MS-DOS compilers. See the system-specific notes about MS-DOS for more info. IMPORTANT: if you use this, define USE_MSDOS_MEMMGR in jconfig.h, and include the assembly file jmemdosa.asm in the programs. The supplied makefiles and jconfig files for 16-bit MS-DOS compilers already do both. * jmemmac.c Custom version for Apple Macintosh; see the system-specific notes for Macintosh for more info. To use a particular memory manager, change the SYSDEPMEM variable in your makefile to equal the corresponding object file name (for example, jmemansi.o or jmemansi.obj for jmemansi.c). If you have plenty of (real or virtual) main memory, just use jmemnobs.c. "Plenty" means about ten bytes for every pixel in the largest images you plan to process, so a lot of systems don't meet this criterion. If yours doesn't, try jmemansi.c first. If that doesn't compile, you'll have to use jmemname.c; be sure to adjust select_file_name() for local conditions. You may also need to change unlink() to remove() in close_backing_store(). Except with jmemnobs.c or jmemmac.c, you need to adjust the DEFAULT_MAX_MEM setting to a reasonable value for your system (either by adding a #define for DEFAULT_MAX_MEM to jconfig.h, or by adding a -D switch to the Makefile). This value limits the amount of data space the program will attempt to allocate. Code and static data space isn't counted, so the actual memory needs for cjpeg or djpeg are typically 100 to 150Kb more than the max-memory setting. Larger max-memory settings reduce the amount of I/O needed to process a large image, but too large a value can result in "insufficient memory" failures. On most Unix machines (and other systems with virtual memory), just set DEFAULT_MAX_MEM to several million and forget it. At the other end of the spectrum, for MS-DOS machines you probably can't go much above 300K to 400K. (On MS-DOS the value refers to conventional memory only. Extended/expanded memory is handled separately by jmemdos.c.) BUILDING THE SOFTWARE ===================== Now you should be able to compile the software. Just say "make" (or whatever's necessary to start the compilation). Have a cup of coffee. Here are some things that could go wrong: If your compiler complains about undefined structures, you should be able to shut it up by putting "#define INCOMPLETE_TYPES_BROKEN" in jconfig.h. If you have trouble with missing system include files or inclusion of the wrong ones, read jinclude.h. This shouldn't happen if you used configure or ckconfig.c to set up jconfig.h. There are a fair number of routines that do not use all of their parameters; some compilers will issue warnings about this, which you can ignore. There are also a few configuration checks that may give "unreachable code" warnings. Any other warning deserves investigation. If you don't have a getenv() library routine, define NO_GETENV. Also see the system-specific hints, below. TESTING THE SOFTWARE ==================== As a quick test of functionality we've included a small sample image in several forms: testorig.jpg Starting point for the djpeg tests. testimg.ppm The output of djpeg testorig.jpg testimg.bmp The output of djpeg -bmp -colors 256 testorig.jpg testimg.jpg The output of cjpeg testimg.ppm testprog.jpg Progressive-mode equivalent of testorig.jpg. testimgp.jpg The output of cjpeg -progressive -optimize testimg.ppm (The first- and second-generation .jpg files aren't identical since the default compression parameters are lossy.) If you can generate duplicates of the testimg* files then you probably have working programs. With most of the makefiles, "make test" will perform the necessary comparisons. If you're using a makefile that doesn't provide the test option, run djpeg and cjpeg by hand and compare the output files to testimg* with whatever binary file comparison tool you have. The files should be bit-for-bit identical. If the programs complain "MAX_ALLOC_CHUNK is wrong, please fix", then you need to reduce MAX_ALLOC_CHUNK to a value that fits in type size_t. Try adding "#define MAX_ALLOC_CHUNK 65520L" to jconfig.h. A less likely configuration error is "ALIGN_TYPE is wrong, please fix": defining ALIGN_TYPE as long should take care of that one. If the cjpeg test run fails with "Missing Huffman code table entry", it's a good bet that you needed to define RIGHT_SHIFT_IS_UNSIGNED. Go back to the configuration step and run ckconfig.c. (This is a good plan for any other test failure, too.) If you are using Unix (one-file) command line style on a non-Unix system, it's a good idea to check that binary I/O through stdin/stdout actually works. You should get the same results from "djpeg out.ppm" as from "djpeg -outfile out.ppm testorig.jpg". Note that the makefiles all use the latter style and therefore do not exercise stdin/stdout! If this check fails, try recompiling with USE_SETMODE or USE_FDOPEN defined. If it still doesn't work, better use two-file style. If you chose a memory manager other than jmemnobs.c, you should test that temporary-file usage works. Try "djpeg -bmp -colors 256 -max 0 testorig.jpg" and make sure its output matches testimg.bmp. If you have any really large images handy, try compressing them with -optimize and/or decompressing with -colors 256 to make sure your DEFAULT_MAX_MEM setting is not too large. NOTE: this is far from an exhaustive test of the JPEG software; some modules, such as 1-pass color quantization, are not exercised at all. It's just a quick test to give you some confidence that you haven't missed something major. INSTALLING THE SOFTWARE ======================= Once you're done with the above steps, you can install the software by copying the executable files (cjpeg, djpeg, jpegtran, rdjpgcom, and wrjpgcom) to wherever you normally install programs. On Unix systems, you'll also want to put the man pages (cjpeg.1, djpeg.1, jpegtran.1, rdjpgcom.1, wrjpgcom.1) in the man-page directory. The pre-fab makefiles don't support this step since there's such a wide variety of installation procedures on different systems. If you generated a Makefile with the "configure" script, you can just say make install to install the programs and their man pages into the standard places. (You'll probably need to be root to do this.) We recommend first saying make -n install to see where configure thought the files should go. You may need to edit the Makefile, particularly if your system's conventions for man page filenames don't match what configure expects. If you want to install the IJG library itself, for use in compiling other programs besides ours, then you need to put the four include files jpeglib.h jerror.h jconfig.h jmorecfg.h into your include-file directory, and put the library file libjpeg.a (extension may vary depending on system) wherever library files go. If you generated a Makefile with "configure", it will do what it thinks is the right thing if you say make install-lib OPTIONAL STUFF ============== Progress monitor: If you like, you can #define PROGRESS_REPORT (in jconfig.h) to enable display of percent-done progress reports. The routine provided in cdjpeg.c merely prints percentages to stderr, but you can customize it to do something fancier. Utah RLE file format support: We distribute the software with support for RLE image files (Utah Raster Toolkit format) disabled, because the RLE support won't compile without the Utah library. If you have URT version 3.1 or later, you can enable RLE support as follows: 1. #define RLE_SUPPORTED in jconfig.h. 2. Add a -I option to CFLAGS in the Makefile for the directory containing the URT .h files (typically the "include" subdirectory of the URT distribution). 3. Add -L... -lrle to LDLIBS in the Makefile, where ... specifies the directory containing the URT "librle.a" file (typically the "lib" subdirectory of the URT distribution). Support for 9-bit to 12-bit deep pixel data: The IJG code currently allows 8, 9, 10, 11, or 12 bits sample data precision. (For color, this means 8 to 12 bits per channel, of course.) If you need to work with deeper than 8-bit data, you can compile the IJG code for 9-bit to 12-bit operation. To do so: 1. In jmorecfg.h, define BITS_IN_JSAMPLE as 9, 10, 11, or 12 rather than 8. 2. In jconfig.h, undefine BMP_SUPPORTED, RLE_SUPPORTED, and TARGA_SUPPORTED, because the code for those formats doesn't handle deeper than 8-bit data and won't even compile. (The PPM code does work, as explained below. The GIF code works too; it scales 8-bit GIF data to and from 12-bit depth automatically.) 3. Compile. Don't expect "make test" to pass, since the supplied test files are for 8-bit data. Currently, 9-bit to 12-bit support does not work on 16-bit-int machines. Run-time selection and conversion of data precision are currently not supported and may be added later. Exception: The transcoding part (jpegtran) supports all settings in a single instance, since it operates on the level of DCT coefficients and not sample values. The PPM reader (rdppm.c) can read deeper than 8-bit data from either text-format or binary-format PPM and PGM files. Binary-format PPM/PGM files which have a maxval greater than 255 are assumed to use 2 bytes per sample, MSB first (big-endian order). As of early 1995, 2-byte binary format is not officially supported by the PBMPLUS library, but it is expected that a future release of PBMPLUS will support it. Note that the PPM reader will read files of any maxval regardless of the BITS_IN_JSAMPLE setting; incoming data is automatically rescaled to maxval=MAXJSAMPLE as appropriate for the cjpeg bit depth. The PPM writer (wrppm.c) will normally write 2-byte binary PPM or PGM format, maxval=MAXJSAMPLE, when compiled with BITS_IN_JSAMPLE>8. Since this format is not yet widely supported, you can disable it by compiling wrppm.c with PPM_NORAWWORD defined; then the data is scaled down to 8 bits to make a standard 1-byte/sample PPM or PGM file. (Yes, this means still another copy of djpeg to keep around. But hopefully you won't need it for very long. Poskanzer's supposed to get that new PBMPLUS release out Real Soon Now.) Of course, if you are working with 9-bit to 12-bit data, you probably have it stored in some other, nonstandard format. In that case you'll probably want to write your own I/O modules to read and write your format. Note: The standard Huffman tables are only valid for 8-bit data precision. If you selected more than 8-bit data precision, cjpeg uses arithmetic coding by default. The Huffman encoder normally uses entropy optimization to compute usable tables for higher precision. Otherwise, you'll have to supply different default Huffman tables. Removing code: If you need to make a smaller version of the JPEG software, some optional functions can be removed at compile time. See the xxx_SUPPORTED #defines in jconfig.h and jmorecfg.h. If at all possible, we recommend that you leave in decoder support for all valid JPEG files, to ensure that you can read anyone's output. Taking out support for image file formats that you don't use is the most painless way to make the programs smaller. Another possibility is to remove some of the DCT methods: in particular, the "IFAST" method may not be enough faster than the others to be worth keeping on your machine. (If you do remove ISLOW or IFAST, be sure to redefine JDCT_DEFAULT or JDCT_FASTEST to a supported method, by adding a #define in jconfig.h.) OPTIMIZATION ============ Unless you own a Cray, you'll probably be interested in making the JPEG software go as fast as possible. This section covers some machine-dependent optimizations you may want to try. We suggest that before trying any of this, you first get the basic installation to pass the self-test step. Repeat the self-test after any optimization to make sure that you haven't broken anything. The integer DCT routines perform a lot of multiplications. These multiplications must yield 32-bit results, but none of their input values are more than 16 bits wide. On many machines, notably the 680x0 and 80x86 CPUs, a 16x16=>32 bit multiply instruction is faster than a full 32x32=>32 bit multiply. Unfortunately there is no portable way to specify such a multiplication in C, but some compilers can generate one when you use the right combination of casts. See the MULTIPLYxxx macro definitions in jdct.h. If your compiler makes "int" be 32 bits and "short" be 16 bits, defining SHORTxSHORT_32 is fairly likely to work. When experimenting with alternate definitions, be sure to test not only whether the code still works (use the self-test), but also whether it is actually faster --- on some compilers, alternate definitions may compute the right answer, yet be slower than the default. Timing cjpeg on a large PGM (grayscale) input file is the best way to check this, as the DCT will be the largest fraction of the runtime in that mode. (Note: some of the distributed compiler-specific jconfig files already contain #define switches to select appropriate MULTIPLYxxx definitions.) If your machine has sufficiently fast floating point hardware, you may find that the float DCT method is faster than the integer DCT methods, even after tweaking the integer multiply macros. In that case you may want to make the float DCT be the default method. (The only objection to this is that float DCT results may vary slightly across machines.) To do that, add "#define JDCT_DEFAULT JDCT_FLOAT" to jconfig.h. Even if you don't change the default, you should redefine JDCT_FASTEST, which is the method selected by djpeg's -fast switch. Don't forget to update the documentation files (usage.txt and/or cjpeg.1, djpeg.1) to agree with what you've done. If access to "short" arrays is slow on your machine, it may be a win to define type JCOEF as int rather than short. This will cost a good deal of memory though, particularly in some multi-pass modes, so don't do it unless you have memory to burn and short is REALLY slow. If your compiler can compile function calls in-line, make sure the INLINE macro in jmorecfg.h is defined as the keyword that marks a function inline-able. Some compilers have a switch that tells the compiler to inline any function it thinks is profitable (e.g., -finline-functions for gcc). Enabling such a switch is likely to make the compiled code bigger but faster. In general, it's worth trying the maximum optimization level of your compiler, and experimenting with any optional optimizations such as loop unrolling. (Unfortunately, far too many compilers have optimizer bugs ... be prepared to back off if the code fails self-test.) If you do any experimentation along these lines, please report the optimal settings to jpeg-info@jpegclub.org so we can mention them in future releases. Be sure to specify your machine and compiler version. HINTS FOR SPECIFIC SYSTEMS ========================== We welcome reports on changes needed for systems not mentioned here. Submit 'em to jpeg-info@jpegclub.org. Also, if configure or ckconfig.c is wrong about how to configure the JPEG software for your system, please let us know. Acorn RISC OS: (Thanks to Simon Middleton for these hints on compiling with Desktop C.) After renaming the files according to Acorn conventions, take a copy of makefile.ansi, change all occurrences of 'libjpeg.a' to 'libjpeg.o' and change these definitions as indicated: CFLAGS= -throwback -IC: -Wn LDLIBS=C:o.Stubs SYSDEPMEM=jmemansi.o LN=Link AR=LibFile -c -o Also add a new line '.c.o:; $(cc) $< $(cflags) -c -o $@'. Remove the lines '$(RM) libjpeg.o' and '$(AR2) libjpeg.o' and the 'jconfig.h' dependency section. Copy jconfig.txt to jconfig.h. Edit jconfig.h to define TWO_FILE_COMMANDLINE and CHAR_IS_UNSIGNED. Run the makefile using !AMU not !Make. If you want to use the 'clean' and 'test' makefile entries then you will have to fiddle with the syntax a bit and rename the test files. Amiga: SAS C 6.50 reportedly is too buggy to compile the IJG code properly. A patch to update to 6.51 is available from SAS or AmiNet FTP sites. The supplied config files are set up to use jmemname.c as the memory manager, with temporary files being created on the device named by "JPEGTMP:". Atari ST/STE/TT: Copy the project files makcjpeg.st, makdjpeg.st, maktjpeg.st, and makljpeg.st to cjpeg.prj, djpeg.prj, jpegtran.prj, and libjpeg.prj respectively. The project files should work as-is with Pure C. For Turbo C, change library filenames "pc..." to "tc..." in each project file. Note that libjpeg.prj selects jmemansi.c as the recommended memory manager. You'll probably want to adjust the DEFAULT_MAX_MEM setting --- you want it to be a couple hundred K less than your normal free memory. Put "#define DEFAULT_MAX_MEM nnnn" into jconfig.h to do this. To use the 68881/68882 coprocessor for the floating point DCT, add the compiler option "-8" to the project files and replace pcfltlib.lib with pc881lib.lib in cjpeg.prj and djpeg.prj. Or if you don't have a coprocessor, you may prefer to remove the float DCT code by undefining DCT_FLOAT_SUPPORTED in jmorecfg.h (since without a coprocessor, the float code will be too slow to be useful). In that case, you can delete pcfltlib.lib from the project files. Note that you must make libjpeg.lib before making cjpeg.ttp, djpeg.ttp, or jpegtran.ttp. You'll have to perform the self-test by hand. We haven't bothered to include project files for rdjpgcom and wrjpgcom. Those source files should just be compiled by themselves; they don't depend on the JPEG library. You can use the default.prj project file of the Pure C distribution to make the programs. There is a bug in some older versions of the Turbo C library which causes the space used by temporary files created with "tmpfile()" not to be freed after an abnormal program exit. If you check your disk afterwards, you will find cluster chains that are allocated but not used by a file. This should not happen in cjpeg/djpeg/jpegtran, since we enable a signal catcher to explicitly close temp files before exiting. But if you use the JPEG library with your own code, be sure to supply a signal catcher, or else use a different system-dependent memory manager. Cray: Should you be so fortunate as to be running JPEG on a Cray YMP, there is a compiler bug in old versions of Cray's Standard C (prior to 3.1). If you still have an old compiler, you'll need to insert a line reading "#pragma novector" just before the loop for (i = 1; i <= (int) htbl->bits[l]; i++) huffsize[p++] = (char) l; in fix_huff_tbl (in V5beta1, line 204 of jchuff.c and line 176 of jdhuff.c). [This bug may or may not still occur with the current IJG code, but it's probably a dead issue anyway...] HP-UX: If you have HP-UX 7.05 or later with the "software development" C compiler, you should run the compiler in ANSI mode. If using the configure script, say ./configure CC='cc -Aa' (or -Ae if you prefer). If configuring by hand, use makefile.ansi and add "-Aa" to the CFLAGS line in the makefile. If you have a pre-7.05 system, or if you are using the non-ANSI C compiler delivered with a minimum HP-UX system, then you must use makefile.unix (and do NOT add -Aa); or just run configure without the CC option. On HP 9000 series 800 machines, the HP C compiler is buggy in revisions prior to A.08.07. If you get complaints about "not a typedef name", you'll have to use makefile.unix, or run configure without the CC option. Macintosh, generic comments: The supplied user-interface files (cjpeg.c, djpeg.c, etc) are set up to provide a Unix-style command line interface. You can use this interface on the Mac by means of the ccommand() library routine provided by Metrowerks CodeWarrior or Think C. This is only appropriate for testing the library, however; to make a user-friendly equivalent of cjpeg/djpeg you'd really want to develop a Mac-style user interface. There isn't a complete example available at the moment, but there are some helpful starting points: 1. Sam Bushell's free "To JPEG" applet provides drag-and-drop conversion to JPEG under System 7 and later. This only illustrates how to use the compression half of the library, but it does a very nice job of that part. The CodeWarrior source code is available from http://www.pobox.com/~jsam. 2. Jim Brunner prepared a Mac-style user interface for both compression and decompression. Unfortunately, it hasn't been updated since IJG v4, and the library's API has changed considerably since then. Still it may be of some help, particularly as a guide to compiling the IJG code under Think C. Jim's code is available from the Info-Mac archives, at sumex-aim.stanford.edu or mirrors thereof; see file /info-mac/dev/src/jpeg-convert-c.hqx. jmemmac.c is the recommended memory manager back end for Macintosh. It uses NewPtr/DisposePtr instead of malloc/free, and has a Mac-specific implementation of jpeg_mem_available(). It also creates temporary files that follow Mac conventions. (That part of the code relies on System-7-or-later OS functions. See the comments in jmemmac.c if you need to run it on System 6.) NOTE that USE_MAC_MEMMGR must be defined in jconfig.h to use jmemmac.c. You can also use jmemnobs.c, if you don't care about handling images larger than available memory. If you use any memory manager back end other than jmemmac.c, we recommend replacing "malloc" and "free" by "NewPtr" and "DisposePtr", because Mac C libraries often have peculiar implementations of malloc/free. (For instance, free() may not return the freed space to the Mac Memory Manager. This is undesirable for the IJG code because jmemmgr.c already clumps space requests.) Macintosh, Metrowerks CodeWarrior: The Unix-command-line-style interface can be used by defining USE_CCOMMAND. You'll also need to define TWO_FILE_COMMANDLINE to avoid stdin/stdout. This means that when using the cjpeg/djpeg programs, you'll have to type the input and output file names in the "Arguments" text-edit box, rather than using the file radio buttons. (Perhaps USE_FDOPEN or USE_SETMODE would eliminate the problem, but I haven't heard from anyone who's tried it.) On 680x0 Macs, Metrowerks defines type "double" as a 10-byte IEEE extended float. jmemmgr.c won't like this: it wants sizeof(ALIGN_TYPE) to be a power of 2. Add "#define ALIGN_TYPE long" to jconfig.h to eliminate the complaint. The supplied configuration file jconfig.mac can be used for your jconfig.h; it includes all the recommended symbol definitions. If you have AppleScript installed, you can run the supplied script makeproj.mac to create CodeWarrior project files for the library and the testbed applications, then build the library and applications. (Thanks to Dan Sears and Don Agro for this nifty hack, which saves us from trying to maintain CodeWarrior project files as part of the IJG distribution...) Macintosh, Think C: The documentation in Jim Brunner's "JPEG Convert" source code (see above) includes detailed build instructions for Think C; it's probably somewhat out of date for the current release, but may be helpful. If you want to build the minimal command line version, proceed as follows. You'll have to prepare project files for the programs; we don't include any in the distribution since they are not text files. Use the file lists in any of the supplied makefiles as a guide. Also add the ANSI and Unix C libraries in a separate segment. You may need to divide the JPEG files into more than one segment; we recommend dividing compression and decompression modules. Define USE_CCOMMAND in jconfig.h so that the ccommand() routine is called. You must also define TWO_FILE_COMMANDLINE because stdin/stdout don't handle binary data correctly. On 680x0 Macs, Think C defines type "double" as a 12-byte IEEE extended float. jmemmgr.c won't like this: it wants sizeof(ALIGN_TYPE) to be a power of 2. Add "#define ALIGN_TYPE long" to jconfig.h to eliminate the complaint. jconfig.mac should work as a jconfig.h configuration file for Think C, but the makeproj.mac AppleScript script is specific to CodeWarrior. Sorry. MIPS R3000: MIPS's cc version 1.31 has a rather nasty optimization bug. Don't use -O if you have that compiler version. (Use "cc -V" to check the version.) Note that the R3000 chip is found in workstations from DEC and others. MS-DOS, generic comments for 16-bit compilers: The IJG code is designed to work well in 80x86 "small" or "medium" memory models (i.e., data pointers are 16 bits unless explicitly declared "far"; code pointers can be either size). You may be able to use small model to compile cjpeg or djpeg by itself, but you will probably have to use medium model for any larger application. This won't make much difference in performance. You *will* take a noticeable performance hit if you use a large-data memory model, and you should avoid "huge" model if at all possible. Be sure that NEED_FAR_POINTERS is defined in jconfig.h if you use a small-data memory model; be sure it is NOT defined if you use a large-data model. (The supplied makefiles and jconfig files for Borland and Microsoft C compile in medium model and define NEED_FAR_POINTERS.) The DOS-specific memory manager, jmemdos.c, should be used if possible. It needs some assembly-code routines which are in jmemdosa.asm; make sure your makefile assembles that file and includes it in the library. If you don't have a suitable assembler, you can get pre-assembled object files for jmemdosa by FTP from ftp.uu.net:/graphics/jpeg/jdosaobj.zip. (DOS-oriented distributions of the IJG source code often include these object files.) When using jmemdos.c, jconfig.h must define USE_MSDOS_MEMMGR and must set MAX_ALLOC_CHUNK to less than 64K (65520L is a typical value). If your C library's far-heap malloc() can't allocate blocks that large, reduce MAX_ALLOC_CHUNK to whatever it can handle. If you can't use jmemdos.c for some reason --- for example, because you don't have an assembler to assemble jmemdosa.asm --- you'll have to fall back to jmemansi.c or jmemname.c. You'll probably still need to set MAX_ALLOC_CHUNK in jconfig.h, because most DOS C libraries won't malloc() more than 64K at a time. IMPORTANT: if you use jmemansi.c or jmemname.c, you will have to compile in a large-data memory model in order to get the right stdio library. Too bad. wrjpgcom needs to be compiled in large model, because it malloc()s a 64KB work area to hold the comment text. If your C library's malloc can't handle that, reduce MAX_COM_LENGTH as necessary in wrjpgcom.c. Most MS-DOS compilers treat stdin/stdout as text files, so you must use two-file command line style. But if your compiler has either fdopen() or setmode(), you can use one-file style if you like. To do this, define USE_SETMODE or USE_FDOPEN so that stdin/stdout will be set to binary mode. (USE_SETMODE seems to work with more DOS compilers than USE_FDOPEN.) You should test that I/O through stdin/stdout produces the same results as I/O to explicitly named files... the "make test" procedures in the supplied makefiles do NOT use stdin/stdout. MS-DOS, generic comments for 32-bit compilers: None of the above comments about memory models apply if you are using a 32-bit flat-memory-space environment, such as DJGPP or Watcom C. (And you should use one if you have it, as performance will be much better than 8086-compatible code!) For flat-memory-space compilers, do NOT define NEED_FAR_POINTERS, and do NOT use jmemdos.c. Use jmemnobs.c if the environment supplies adequate virtual memory, otherwise use jmemansi.c or jmemname.c. You'll still need to be careful about binary I/O through stdin/stdout. See the last paragraph of the previous section. MS-DOS, Borland C: Be sure to convert all the source files to DOS text format (CR/LF newlines). Although Borland C will often work OK with unmodified Unix (LF newlines) source files, sometimes it will give bogus compile errors. "Illegal character '#'" is the most common such error. (This is true with Borland C 3.1, but perhaps is fixed in newer releases.) If you want one-file command line style, just undefine TWO_FILE_COMMANDLINE. jconfig.bcc already includes #define USE_SETMODE to make this work. (fdopen does not work correctly.) MS-DOS, Microsoft C: makefile.mc6 works with Microsoft C, DOS Visual C++, etc. It should only be used if you want to build a 16-bit (small or medium memory model) program. If you want one-file command line style, just undefine TWO_FILE_COMMANDLINE. jconfig.mc6 already includes #define USE_SETMODE to make this work. (fdopen does not work correctly.) Note that this makefile assumes that the working copy of itself is called "makefile". If you want to call it something else, say "makefile.mak", be sure to adjust the dependency line that reads "$(RFILE) : makefile". Otherwise the make will fail because it doesn't know how to create "makefile". Worse, some releases of Microsoft's make utilities give an incorrect error message in this situation. Old versions of MS C fail with an "out of macro expansion space" error because they can't cope with the macro TRACEMS8 (defined in jerror.h). If this happens to you, the easiest solution is to change TRACEMS8 to expand to nothing. You'll lose the ability to dump out JPEG coefficient tables with djpeg -debug -debug, but at least you can compile. Original MS C 6.0 is very buggy; it compiles incorrect code unless you turn off optimization entirely (remove -O from CFLAGS). 6.00A is better, but it still generates bad code if you enable loop optimizations (-Ol or -Ox). MS C 8.0 crashes when compiling jquant1.c with optimization switch /Oo ... which is on by default. To work around this bug, compile that one file with /Oo-. Microsoft Windows (all versions), generic comments: Some Windows system include files define typedef boolean as "unsigned char". The IJG code also defines typedef boolean, but we make it an "enum" by default. This doesn't affect the IJG programs because we don't import those Windows include files. But if you use the JPEG library in your own program, and some of your program's files import one definition of boolean while some import the other, you can get all sorts of mysterious problems. A good preventive step is to make the IJG library use "unsigned char" for boolean. To do that, add something like this to your jconfig.h file: /* Define "boolean" as unsigned char, not enum, per Windows custom */ #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */ typedef unsigned char boolean; #endif #ifndef FALSE /* in case these macros already exist */ #define FALSE 0 /* values of boolean */ #endif #ifndef TRUE #define TRUE 1 #endif #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ (This is already in jconfig.vc, by the way.) windef.h contains the declarations #define far #define FAR far Since jmorecfg.h tries to define FAR as empty, you may get a compiler warning if you include both jpeglib.h and windef.h (which windows.h includes). To suppress the warning, you can put "#ifndef FAR"/"#endif" around the line "#define FAR" in jmorecfg.h. (Something like this is already in jmorecfg.h, by the way.) When using the library in a Windows application, you will almost certainly want to modify or replace the error handler module jerror.c, since our default error handler does a couple of inappropriate things: 1. it tries to write error and warning messages on stderr; 2. in event of a fatal error, it exits by calling exit(). A simple stopgap solution for problem 1 is to replace the line fprintf(stderr, "%s\n", buffer); (in output_message in jerror.c) with MessageBox(GetActiveWindow(),buffer,"JPEG Error",MB_OK|MB_ICONERROR); It's highly recommended that you at least do that much, since otherwise error messages will disappear into nowhere. (Beginning with IJG v6b, this code is already present in jerror.c; just define USE_WINDOWS_MESSAGEBOX in jconfig.h to enable it.) The proper solution for problem 2 is to return control to your calling application after a library error. This can be done with the setjmp/longjmp technique discussed in libjpeg.txt and illustrated in example.c. (NOTE: some older Windows C compilers provide versions of setjmp/longjmp that don't actually work under Windows. You may need to use the Windows system functions Catch and Throw instead.) The recommended memory manager under Windows is jmemnobs.c; in other words, let Windows do any virtual memory management needed. You should NOT use jmemdos.c nor jmemdosa.asm under Windows. For Windows 3.1, we recommend compiling in medium or large memory model; for newer Windows versions, use a 32-bit flat memory model. (See the MS-DOS sections above for more info about memory models.) In the 16-bit memory models only, you'll need to put #define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */ into jconfig.h to limit allocation chunks to 64Kb. (Without that, you'd have to use huge memory model, which slows things down unnecessarily.) jmemnobs.c works without modification in large or flat memory models, but to use medium model, you need to modify its jpeg_get_large and jpeg_free_large routines to allocate far memory. In any case, you might like to replace its calls to malloc and free with direct calls on Windows memory allocation functions. You may also want to modify jdatasrc.c and jdatadst.c to use Windows file operations rather than fread/fwrite. This is only necessary if your C compiler doesn't provide a competent implementation of C stdio functions. You might want to tweak the RGB_xxx macros in jmorecfg.h so that the library will accept or deliver color pixels in BGR sample order, not RGB; BGR order is usually more convenient under Windows. Note that this change will break the sample applications cjpeg/djpeg, but the library itself works fine. Many people want to convert the IJG library into a DLL. This is reasonably straightforward, but watch out for the following: 1. Don't try to compile as a DLL in small or medium memory model; use large model, or even better, 32-bit flat model. Many places in the IJG code assume the address of a local variable is an ordinary (not FAR) pointer; that isn't true in a medium-model DLL. 2. Microsoft C cannot pass file pointers between applications and DLLs. (See Microsoft Knowledge Base, PSS ID Number Q50336.) So jdatasrc.c and jdatadst.c don't work if you open a file in your application and then pass the pointer to the DLL. One workaround is to make jdatasrc.c/jdatadst.c part of your main application rather than part of the DLL. 3. You'll probably need to modify the macros GLOBAL() and EXTERN() to attach suitable linkage keywords to the exported routine names. Similarly, you'll want to modify METHODDEF() and JMETHOD() to ensure function pointers are declared in a way that lets application routines be called back through the function pointers. These macros are in jmorecfg.h. Typical definitions for a 16-bit DLL are: #define GLOBAL(type) type _far _pascal _loadds _export #define EXTERN(type) extern type _far _pascal _loadds #define METHODDEF(type) static type _far _pascal #define JMETHOD(type,methodname,arglist) \ type (_far _pascal *methodname) arglist For a 32-bit DLL you may want something like #define GLOBAL(type) __declspec(dllexport) type #define EXTERN(type) extern __declspec(dllexport) type Although not all the GLOBAL routines are actually intended to be called by the application, the performance cost of making them all DLL entry points is negligible. The unmodified IJG library presents a very C-specific application interface, so the resulting DLL is only usable from C or C++ applications. There has been some talk of writing wrapper code that would present a simpler interface usable from other languages, such as Visual Basic. This is on our to-do list but hasn't been very high priority --- any volunteers out there? Microsoft Windows, Borland C: The provided jconfig.bcc should work OK in a 32-bit Windows environment, but you'll need to tweak it in a 16-bit environment (you'd need to define NEED_FAR_POINTERS and MAX_ALLOC_CHUNK). Beware that makefile.bcc will need alteration if you want to use it for Windows --- in particular, you should use jmemnobs.c not jmemdos.c under Windows. Borland C++ 4.5 fails with an internal compiler error when trying to compile jdmerge.c in 32-bit mode. If enough people complain, perhaps Borland will fix it. In the meantime, the simplest known workaround is to add a redundant definition of the variable range_limit in h2v1_merged_upsample(), at the head of the block that handles odd image width (about line 268 in v6 jdmerge.c): /* If image width is odd, do the last output column separately */ if (cinfo->output_width & 1) { register JSAMPLE * range_limit = cinfo->sample_range_limit; /* ADD THIS */ cb = GETJSAMPLE(*inptr1); Pretty bizarre, especially since the very similar routine h2v2_merged_upsample doesn't trigger the bug. Recent reports suggest that this bug does not occur with "bcc32a" (the Pentium-optimized version of the compiler). Another report from a user of Borland C 4.5 was that incorrect code (leading to a color shift in processed images) was produced if any of the following optimization switch combinations were used: -Ot -Og -Ot -Op -Ot -Om So try backing off on optimization if you see such a problem. (Are there several different releases all numbered "4.5"??) Microsoft Windows, Microsoft Visual C++: jconfig.vc should work OK with any Microsoft compiler for a 32-bit memory model. makefile.vc is intended for command-line use. (If you are using the Developer Studio environment, you may prefer the DevStudio project files; see below.) IJG JPEG 7 adds extern "C" to jpeglib.h. This avoids the need to put extern "C" { ... } around #include "jpeglib.h" in your C++ application. You can also force VC++ to treat the library as C++ code by renaming all the *.c files to *.cpp (and adjusting the makefile to match). In this case you also need to define the symbol DONT_USE_EXTERN_C in the configuration to prevent jpeglib.h from using extern "C". Microsoft Windows, Microsoft Visual C++ 6 Developer Studio: We include makefiles that should work as project files in DevStudio 6.0 or later. There is a library makefile that builds the IJG library as a static Win32 library, and application makefiles that build the sample applications as Win32 console applications. (Even if you only want the library, we recommend building the applications so that you can run the self-test.) To use: 1. Open the command prompt, change to the main directory and execute the command line NMAKE /f makefile.vc setup-vc6 This will move jconfig.vc to jconfig.h and makefiles to project files. (Note that the renaming is critical!) 2. Open the workspace file jpeg.dsw, build the library project. (If you are using DevStudio more recent than 6.0, you'll probably get a message saying that the project files are being updated.) 3. Open the workspace file apps.dsw, build the application projects. 4. To perform the self-test, execute the command line NMAKE /f makefile.vc test-build 5. Move the application .exe files from `app`\Release to an appropriate location on your path. Microsoft Windows, Microsoft Visual C++ 2010 Developer Studio (v10): We include makefiles that should work as project files in Visual Studio 2010 or later. There is a library makefile that builds the IJG library as a static Win32 library, and application makefiles that build the sample applications as Win32 console applications. (Even if you only want the library, we recommend building the applications so that you can run the self-test.) To use: 1. Open the command prompt, change to the main directory and execute the command line NMAKE /f makefile.vc setup-v10 This will move jconfig.vc to jconfig.h and makefiles to project files. (Note that the renaming is critical!) 2. Open the solution file jpeg.sln, build the library project. (If you are using Visual Studio more recent than 2010 (v10), you'll probably get a message saying that the project files are being updated.) 3. Open the solution file apps.sln, build the application projects. 4. To perform the self-test, execute the command line NMAKE /f makefile.vc test-build 5. Move the application .exe files from `app`\Release to an appropriate location on your path. Note: There seems to be an optimization bug in the compiler which causes the self-test to fail with the color quantization option. We have disabled optimization for the file jquant2.c in the library project file which causes the self-test to pass properly. OS/2, Borland C++: Watch out for optimization bugs in older Borland compilers; you may need to back off the optimization switch settings. See the comments in makefile.bcc. SGI: On some SGI systems, you may need to set "AR2= ar -ts" in the Makefile. If you are using configure, you can do this by saying ./configure RANLIB='ar -ts' This change is not needed on all SGIs. Use it only if the make fails at the stage of linking the completed programs. On the MIPS R4000 architecture (Indy, etc.), the compiler option "-mips2" reportedly speeds up the float DCT method substantially, enough to make it faster than the default int method (but still slower than the fast int method). If you use -mips2, you may want to alter the default DCT method to be float. To do this, put "#define JDCT_DEFAULT JDCT_FLOAT" in jconfig.h. VMS: On an Alpha/VMS system with MMS, be sure to use the "/Marco=Alpha=1" qualifier with MMS when building the JPEG package. VAX/VMS v5.5-1 may have problems with the test step of the build procedure reporting differences when it compares the original and test images. If the error points to the last block of the files, it is most likely bogus and may be safely ignored. It seems to be because the files are Stream_LF and Backup/Compare has difficulty with the (presumably) null padded files. This problem was not observed on VAX/VMS v6.1 or AXP/VMS v6.1. ================================================ FILE: tess-two/jni/libjpeg/jaricom.c ================================================ /* * jaricom.c * * Developed 1997-2011 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains probability estimation tables for common use in * arithmetic entropy encoding and decoding routines. * * This data represents Table D.3 in the JPEG spec (D.2 in the draft), * ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81, and Table 24 * in the JBIG spec, ISO/IEC IS 11544 and CCITT Recommendation ITU-T T.82. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* The following #define specifies the packing of the four components * into the compact INT32 representation. * Note that this formula must match the actual arithmetic encoder * and decoder implementation. The implementation has to be changed * if this formula is changed. * The current organization is leaned on Markus Kuhn's JBIG * implementation (jbig_tab.c). */ #define V(i,a,b,c,d) (((INT32)a << 16) | ((INT32)c << 8) | ((INT32)d << 7) | b) const INT32 jpeg_aritab[113+1] = { /* * Index, Qe_Value, Next_Index_LPS, Next_Index_MPS, Switch_MPS */ V( 0, 0x5a1d, 1, 1, 1 ), V( 1, 0x2586, 14, 2, 0 ), V( 2, 0x1114, 16, 3, 0 ), V( 3, 0x080b, 18, 4, 0 ), V( 4, 0x03d8, 20, 5, 0 ), V( 5, 0x01da, 23, 6, 0 ), V( 6, 0x00e5, 25, 7, 0 ), V( 7, 0x006f, 28, 8, 0 ), V( 8, 0x0036, 30, 9, 0 ), V( 9, 0x001a, 33, 10, 0 ), V( 10, 0x000d, 35, 11, 0 ), V( 11, 0x0006, 9, 12, 0 ), V( 12, 0x0003, 10, 13, 0 ), V( 13, 0x0001, 12, 13, 0 ), V( 14, 0x5a7f, 15, 15, 1 ), V( 15, 0x3f25, 36, 16, 0 ), V( 16, 0x2cf2, 38, 17, 0 ), V( 17, 0x207c, 39, 18, 0 ), V( 18, 0x17b9, 40, 19, 0 ), V( 19, 0x1182, 42, 20, 0 ), V( 20, 0x0cef, 43, 21, 0 ), V( 21, 0x09a1, 45, 22, 0 ), V( 22, 0x072f, 46, 23, 0 ), V( 23, 0x055c, 48, 24, 0 ), V( 24, 0x0406, 49, 25, 0 ), V( 25, 0x0303, 51, 26, 0 ), V( 26, 0x0240, 52, 27, 0 ), V( 27, 0x01b1, 54, 28, 0 ), V( 28, 0x0144, 56, 29, 0 ), V( 29, 0x00f5, 57, 30, 0 ), V( 30, 0x00b7, 59, 31, 0 ), V( 31, 0x008a, 60, 32, 0 ), V( 32, 0x0068, 62, 33, 0 ), V( 33, 0x004e, 63, 34, 0 ), V( 34, 0x003b, 32, 35, 0 ), V( 35, 0x002c, 33, 9, 0 ), V( 36, 0x5ae1, 37, 37, 1 ), V( 37, 0x484c, 64, 38, 0 ), V( 38, 0x3a0d, 65, 39, 0 ), V( 39, 0x2ef1, 67, 40, 0 ), V( 40, 0x261f, 68, 41, 0 ), V( 41, 0x1f33, 69, 42, 0 ), V( 42, 0x19a8, 70, 43, 0 ), V( 43, 0x1518, 72, 44, 0 ), V( 44, 0x1177, 73, 45, 0 ), V( 45, 0x0e74, 74, 46, 0 ), V( 46, 0x0bfb, 75, 47, 0 ), V( 47, 0x09f8, 77, 48, 0 ), V( 48, 0x0861, 78, 49, 0 ), V( 49, 0x0706, 79, 50, 0 ), V( 50, 0x05cd, 48, 51, 0 ), V( 51, 0x04de, 50, 52, 0 ), V( 52, 0x040f, 50, 53, 0 ), V( 53, 0x0363, 51, 54, 0 ), V( 54, 0x02d4, 52, 55, 0 ), V( 55, 0x025c, 53, 56, 0 ), V( 56, 0x01f8, 54, 57, 0 ), V( 57, 0x01a4, 55, 58, 0 ), V( 58, 0x0160, 56, 59, 0 ), V( 59, 0x0125, 57, 60, 0 ), V( 60, 0x00f6, 58, 61, 0 ), V( 61, 0x00cb, 59, 62, 0 ), V( 62, 0x00ab, 61, 63, 0 ), V( 63, 0x008f, 61, 32, 0 ), V( 64, 0x5b12, 65, 65, 1 ), V( 65, 0x4d04, 80, 66, 0 ), V( 66, 0x412c, 81, 67, 0 ), V( 67, 0x37d8, 82, 68, 0 ), V( 68, 0x2fe8, 83, 69, 0 ), V( 69, 0x293c, 84, 70, 0 ), V( 70, 0x2379, 86, 71, 0 ), V( 71, 0x1edf, 87, 72, 0 ), V( 72, 0x1aa9, 87, 73, 0 ), V( 73, 0x174e, 72, 74, 0 ), V( 74, 0x1424, 72, 75, 0 ), V( 75, 0x119c, 74, 76, 0 ), V( 76, 0x0f6b, 74, 77, 0 ), V( 77, 0x0d51, 75, 78, 0 ), V( 78, 0x0bb6, 77, 79, 0 ), V( 79, 0x0a40, 77, 48, 0 ), V( 80, 0x5832, 80, 81, 1 ), V( 81, 0x4d1c, 88, 82, 0 ), V( 82, 0x438e, 89, 83, 0 ), V( 83, 0x3bdd, 90, 84, 0 ), V( 84, 0x34ee, 91, 85, 0 ), V( 85, 0x2eae, 92, 86, 0 ), V( 86, 0x299a, 93, 87, 0 ), V( 87, 0x2516, 86, 71, 0 ), V( 88, 0x5570, 88, 89, 1 ), V( 89, 0x4ca9, 95, 90, 0 ), V( 90, 0x44d9, 96, 91, 0 ), V( 91, 0x3e22, 97, 92, 0 ), V( 92, 0x3824, 99, 93, 0 ), V( 93, 0x32b4, 99, 94, 0 ), V( 94, 0x2e17, 93, 86, 0 ), V( 95, 0x56a8, 95, 96, 1 ), V( 96, 0x4f46, 101, 97, 0 ), V( 97, 0x47e5, 102, 98, 0 ), V( 98, 0x41cf, 103, 99, 0 ), V( 99, 0x3c3d, 104, 100, 0 ), V( 100, 0x375e, 99, 93, 0 ), V( 101, 0x5231, 105, 102, 0 ), V( 102, 0x4c0f, 106, 103, 0 ), V( 103, 0x4639, 107, 104, 0 ), V( 104, 0x415e, 103, 99, 0 ), V( 105, 0x5627, 105, 106, 1 ), V( 106, 0x50e7, 108, 107, 0 ), V( 107, 0x4b85, 109, 103, 0 ), V( 108, 0x5597, 110, 109, 0 ), V( 109, 0x504f, 111, 107, 0 ), V( 110, 0x5a10, 110, 111, 1 ), V( 111, 0x5522, 112, 109, 0 ), V( 112, 0x59eb, 112, 111, 1 ), /* * This last entry is used for fixed probability estimate of 0.5 * as suggested in Section 10.3 Table 5 of ITU-T Rec. T.851. */ V( 113, 0x5a1d, 113, 113, 0 ) }; ================================================ FILE: tess-two/jni/libjpeg/jcapimin.c ================================================ /* * jcapimin.c * * Copyright (C) 1994-1998, Thomas G. Lane. * Modified 2003-2010 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains application interface code for the compression half * of the JPEG library. These are the "minimum" API routines that may be * needed in either the normal full-compression case or the transcoding-only * case. * * Most of the routines intended to be called directly by an application * are in this file or in jcapistd.c. But also see jcparam.c for * parameter-setup helper routines, jcomapi.c for routines shared by * compression and decompression, and jctrans.c for the transcoding case. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * Initialization of a JPEG compression object. * The error manager must already be set up (in case memory manager fails). */ GLOBAL(void) jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize) { int i; /* Guard against version mismatches between library and caller. */ cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */ if (version != JPEG_LIB_VERSION) ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version); if (structsize != SIZEOF(struct jpeg_compress_struct)) ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, (int) SIZEOF(struct jpeg_compress_struct), (int) structsize); /* For debugging purposes, we zero the whole master structure. * But the application has already set the err pointer, and may have set * client_data, so we have to save and restore those fields. * Note: if application hasn't set client_data, tools like Purify may * complain here. */ { struct jpeg_error_mgr * err = cinfo->err; void * client_data = cinfo->client_data; /* ignore Purify complaint here */ MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct)); cinfo->err = err; cinfo->client_data = client_data; } cinfo->is_decompressor = FALSE; /* Initialize a memory manager instance for this object */ jinit_memory_mgr((j_common_ptr) cinfo); /* Zero out pointers to permanent structures. */ cinfo->progress = NULL; cinfo->dest = NULL; cinfo->comp_info = NULL; for (i = 0; i < NUM_QUANT_TBLS; i++) { cinfo->quant_tbl_ptrs[i] = NULL; cinfo->q_scale_factor[i] = 100; } for (i = 0; i < NUM_HUFF_TBLS; i++) { cinfo->dc_huff_tbl_ptrs[i] = NULL; cinfo->ac_huff_tbl_ptrs[i] = NULL; } /* Must do it here for emit_dqt in case jpeg_write_tables is used */ cinfo->block_size = DCTSIZE; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; cinfo->script_space = NULL; cinfo->input_gamma = 1.0; /* in case application forgets */ /* OK, I'm ready */ cinfo->global_state = CSTATE_START; } /* * Destruction of a JPEG compression object */ GLOBAL(void) jpeg_destroy_compress (j_compress_ptr cinfo) { jpeg_destroy((j_common_ptr) cinfo); /* use common routine */ } /* * Abort processing of a JPEG compression operation, * but don't destroy the object itself. */ GLOBAL(void) jpeg_abort_compress (j_compress_ptr cinfo) { jpeg_abort((j_common_ptr) cinfo); /* use common routine */ } /* * Forcibly suppress or un-suppress all quantization and Huffman tables. * Marks all currently defined tables as already written (if suppress) * or not written (if !suppress). This will control whether they get emitted * by a subsequent jpeg_start_compress call. * * This routine is exported for use by applications that want to produce * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but * since it is called by jpeg_start_compress, we put it here --- otherwise * jcparam.o would be linked whether the application used it or not. */ GLOBAL(void) jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress) { int i; JQUANT_TBL * qtbl; JHUFF_TBL * htbl; for (i = 0; i < NUM_QUANT_TBLS; i++) { if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL) qtbl->sent_table = suppress; } for (i = 0; i < NUM_HUFF_TBLS; i++) { if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL) htbl->sent_table = suppress; if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL) htbl->sent_table = suppress; } } /* * Finish JPEG compression. * * If a multipass operating mode was selected, this may do a great deal of * work including most of the actual output. */ GLOBAL(void) jpeg_finish_compress (j_compress_ptr cinfo) { JDIMENSION iMCU_row; if (cinfo->global_state == CSTATE_SCANNING || cinfo->global_state == CSTATE_RAW_OK) { /* Terminate first pass */ if (cinfo->next_scanline < cinfo->image_height) ERREXIT(cinfo, JERR_TOO_LITTLE_DATA); (*cinfo->master->finish_pass) (cinfo); } else if (cinfo->global_state != CSTATE_WRCOEFS) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Perform any remaining passes */ while (! cinfo->master->is_last_pass) { (*cinfo->master->prepare_for_pass) (cinfo); for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) { if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) iMCU_row; cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* We bypass the main controller and invoke coef controller directly; * all work is being done from the coefficient buffer. */ if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL)) ERREXIT(cinfo, JERR_CANT_SUSPEND); } (*cinfo->master->finish_pass) (cinfo); } /* Write EOI, do final cleanup */ (*cinfo->marker->write_file_trailer) (cinfo); (*cinfo->dest->term_destination) (cinfo); /* We can use jpeg_abort to release memory and reset global_state */ jpeg_abort((j_common_ptr) cinfo); } /* * Write a special marker. * This is only recommended for writing COM or APPn markers. * Must be called after jpeg_start_compress() and before * first call to jpeg_write_scanlines() or jpeg_write_raw_data(). */ GLOBAL(void) jpeg_write_marker (j_compress_ptr cinfo, int marker, const JOCTET *dataptr, unsigned int datalen) { JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val)); if (cinfo->next_scanline != 0 || (cinfo->global_state != CSTATE_SCANNING && cinfo->global_state != CSTATE_RAW_OK && cinfo->global_state != CSTATE_WRCOEFS)) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); (*cinfo->marker->write_marker_header) (cinfo, marker, datalen); write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */ while (datalen--) { (*write_marker_byte) (cinfo, *dataptr); dataptr++; } } /* Same, but piecemeal. */ GLOBAL(void) jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen) { if (cinfo->next_scanline != 0 || (cinfo->global_state != CSTATE_SCANNING && cinfo->global_state != CSTATE_RAW_OK && cinfo->global_state != CSTATE_WRCOEFS)) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); (*cinfo->marker->write_marker_header) (cinfo, marker, datalen); } GLOBAL(void) jpeg_write_m_byte (j_compress_ptr cinfo, int val) { (*cinfo->marker->write_marker_byte) (cinfo, val); } /* * Alternate compression function: just write an abbreviated table file. * Before calling this, all parameters and a data destination must be set up. * * To produce a pair of files containing abbreviated tables and abbreviated * image data, one would proceed as follows: * * initialize JPEG object * set JPEG parameters * set destination to table file * jpeg_write_tables(cinfo); * set destination to image file * jpeg_start_compress(cinfo, FALSE); * write data... * jpeg_finish_compress(cinfo); * * jpeg_write_tables has the side effect of marking all tables written * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress * will not re-emit the tables unless it is passed write_all_tables=TRUE. */ GLOBAL(void) jpeg_write_tables (j_compress_ptr cinfo) { if (cinfo->global_state != CSTATE_START) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* (Re)initialize error mgr and destination modules */ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); (*cinfo->dest->init_destination) (cinfo); /* Initialize the marker writer ... bit of a crock to do it here. */ jinit_marker_writer(cinfo); /* Write them tables! */ (*cinfo->marker->write_tables_only) (cinfo); /* And clean up. */ (*cinfo->dest->term_destination) (cinfo); /* * In library releases up through v6a, we called jpeg_abort() here to free * any working memory allocated by the destination manager and marker * writer. Some applications had a problem with that: they allocated space * of their own from the library memory manager, and didn't want it to go * away during write_tables. So now we do nothing. This will cause a * memory leak if an app calls write_tables repeatedly without doing a full * compression cycle or otherwise resetting the JPEG object. However, that * seems less bad than unexpectedly freeing memory in the normal case. * An app that prefers the old behavior can call jpeg_abort for itself after * each call to jpeg_write_tables(). */ } ================================================ FILE: tess-two/jni/libjpeg/jcapistd.c ================================================ /* * jcapistd.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains application interface code for the compression half * of the JPEG library. These are the "standard" API routines that are * used in the normal full-compression case. They are not used by a * transcoding-only application. Note that if an application links in * jpeg_start_compress, it will end up linking in the entire compressor. * We thus must separate this file from jcapimin.c to avoid linking the * whole compression library into a transcoder. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * Compression initialization. * Before calling this, all parameters and a data destination must be set up. * * We require a write_all_tables parameter as a failsafe check when writing * multiple datastreams from the same compression object. Since prior runs * will have left all the tables marked sent_table=TRUE, a subsequent run * would emit an abbreviated stream (no tables) by default. This may be what * is wanted, but for safety's sake it should not be the default behavior: * programmers should have to make a deliberate choice to emit abbreviated * images. Therefore the documentation and examples should encourage people * to pass write_all_tables=TRUE; then it will take active thought to do the * wrong thing. */ GLOBAL(void) jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables) { if (cinfo->global_state != CSTATE_START) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (write_all_tables) jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */ /* (Re)initialize error mgr and destination modules */ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); (*cinfo->dest->init_destination) (cinfo); /* Perform master selection of active modules */ jinit_compress_master(cinfo); /* Set up for the first pass */ (*cinfo->master->prepare_for_pass) (cinfo); /* Ready for application to drive first pass through jpeg_write_scanlines * or jpeg_write_raw_data. */ cinfo->next_scanline = 0; cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING); } /* * Write some scanlines of data to the JPEG compressor. * * The return value will be the number of lines actually written. * This should be less than the supplied num_lines only in case that * the data destination module has requested suspension of the compressor, * or if more than image_height scanlines are passed in. * * Note: we warn about excess calls to jpeg_write_scanlines() since * this likely signals an application programmer error. However, * excess scanlines passed in the last valid call are *silently* ignored, * so that the application need not adjust num_lines for end-of-image * when using a multiple-scanline buffer. */ GLOBAL(JDIMENSION) jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION num_lines) { JDIMENSION row_ctr, rows_left; if (cinfo->global_state != CSTATE_SCANNING) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (cinfo->next_scanline >= cinfo->image_height) WARNMS(cinfo, JWRN_TOO_MUCH_DATA); /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->next_scanline; cinfo->progress->pass_limit = (long) cinfo->image_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Give master control module another chance if this is first call to * jpeg_write_scanlines. This lets output of the frame/scan headers be * delayed so that application can write COM, etc, markers between * jpeg_start_compress and jpeg_write_scanlines. */ if (cinfo->master->call_pass_startup) (*cinfo->master->pass_startup) (cinfo); /* Ignore any extra scanlines at bottom of image. */ rows_left = cinfo->image_height - cinfo->next_scanline; if (num_lines > rows_left) num_lines = rows_left; row_ctr = 0; (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines); cinfo->next_scanline += row_ctr; return row_ctr; } /* * Alternate entry point to write raw data. * Processes exactly one iMCU row per call, unless suspended. */ GLOBAL(JDIMENSION) jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data, JDIMENSION num_lines) { JDIMENSION lines_per_iMCU_row; if (cinfo->global_state != CSTATE_RAW_OK) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (cinfo->next_scanline >= cinfo->image_height) { WARNMS(cinfo, JWRN_TOO_MUCH_DATA); return 0; } /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->next_scanline; cinfo->progress->pass_limit = (long) cinfo->image_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Give master control module another chance if this is first call to * jpeg_write_raw_data. This lets output of the frame/scan headers be * delayed so that application can write COM, etc, markers between * jpeg_start_compress and jpeg_write_raw_data. */ if (cinfo->master->call_pass_startup) (*cinfo->master->pass_startup) (cinfo); /* Verify that at least one iMCU row has been passed. */ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_v_scaled_size; if (num_lines < lines_per_iMCU_row) ERREXIT(cinfo, JERR_BUFFER_SIZE); /* Directly compress the row. */ if (! (*cinfo->coef->compress_data) (cinfo, data)) { /* If compressor did not consume the whole row, suspend processing. */ return 0; } /* OK, we processed one iMCU row. */ cinfo->next_scanline += lines_per_iMCU_row; return lines_per_iMCU_row; } ================================================ FILE: tess-two/jni/libjpeg/jcarith.c ================================================ /* * jcarith.c * * Developed 1997-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains portable arithmetic entropy encoding routines for JPEG * (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81). * * Both sequential and progressive modes are supported in this single module. * * Suspension is not currently supported in this module. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Expanded entropy encoder object for arithmetic encoding. */ typedef struct { struct jpeg_entropy_encoder pub; /* public fields */ INT32 c; /* C register, base of coding interval, layout as in sec. D.1.3 */ INT32 a; /* A register, normalized size of coding interval */ INT32 sc; /* counter for stacked 0xFF values which might overflow */ INT32 zc; /* counter for pending 0x00 output values which might * * be discarded at the end ("Pacman" termination) */ int ct; /* bit shift counter, determines when next byte will be written */ int buffer; /* buffer for most recent output byte != 0xFF */ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */ unsigned int restarts_to_go; /* MCUs left in this restart interval */ int next_restart_num; /* next restart number to write (0-7) */ /* Pointers to statistics areas (these workspaces have image lifespan) */ unsigned char * dc_stats[NUM_ARITH_TBLS]; unsigned char * ac_stats[NUM_ARITH_TBLS]; /* Statistics bin for coding with fixed probability 0.5 */ unsigned char fixed_bin[4]; } arith_entropy_encoder; typedef arith_entropy_encoder * arith_entropy_ptr; /* The following two definitions specify the allocation chunk size * for the statistics area. * According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least * 49 statistics bins for DC, and 245 statistics bins for AC coding. * * We use a compact representation with 1 byte per statistics bin, * thus the numbers directly represent byte sizes. * This 1 byte per statistics bin contains the meaning of the MPS * (more probable symbol) in the highest bit (mask 0x80), and the * index into the probability estimation state machine table * in the lower bits (mask 0x7F). */ #define DC_STAT_BINS 64 #define AC_STAT_BINS 256 /* NOTE: Uncomment the following #define if you want to use the * given formula for calculating the AC conditioning parameter Kx * for spectral selection progressive coding in section G.1.3.2 * of the spec (Kx = Kmin + SRL (8 + Se - Kmin) 4). * Although the spec and P&M authors claim that this "has proven * to give good results for 8 bit precision samples", I'm not * convinced yet that this is really beneficial. * Early tests gave only very marginal compression enhancements * (a few - around 5 or so - bytes even for very large files), * which would turn out rather negative if we'd suppress the * DAC (Define Arithmetic Conditioning) marker segments for * the default parameters in the future. * Note that currently the marker writing module emits 12-byte * DAC segments for a full-component scan in a color image. * This is not worth worrying about IMHO. However, since the * spec defines the default values to be used if the tables * are omitted (unlike Huffman tables, which are required * anyway), one might optimize this behaviour in the future, * and then it would be disadvantageous to use custom tables if * they don't provide sufficient gain to exceed the DAC size. * * On the other hand, I'd consider it as a reasonable result * that the conditioning has no significant influence on the * compression performance. This means that the basic * statistical model is already rather stable. * * Thus, at the moment, we use the default conditioning values * anyway, and do not use the custom formula. * #define CALCULATE_SPECTRAL_CONDITIONING */ /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32. * We assume that int right shift is unsigned if INT32 right shift is, * which should be safe. */ #ifdef RIGHT_SHIFT_IS_UNSIGNED #define ISHIFT_TEMPS int ishift_temp; #define IRIGHT_SHIFT(x,shft) \ ((ishift_temp = (x)) < 0 ? \ (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \ (ishift_temp >> (shft))) #else #define ISHIFT_TEMPS #define IRIGHT_SHIFT(x,shft) ((x) >> (shft)) #endif LOCAL(void) emit_byte (int val, j_compress_ptr cinfo) /* Write next output byte; we do not support suspension in this module. */ { struct jpeg_destination_mgr * dest = cinfo->dest; *dest->next_output_byte++ = (JOCTET) val; if (--dest->free_in_buffer == 0) if (! (*dest->empty_output_buffer) (cinfo)) ERREXIT(cinfo, JERR_CANT_SUSPEND); } /* * Finish up at the end of an arithmetic-compressed scan. */ METHODDEF(void) finish_pass (j_compress_ptr cinfo) { arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy; INT32 temp; /* Section D.1.8: Termination of encoding */ /* Find the e->c in the coding interval with the largest * number of trailing zero bits */ if ((temp = (e->a - 1 + e->c) & 0xFFFF0000L) < e->c) e->c = temp + 0x8000L; else e->c = temp; /* Send remaining bytes to output */ e->c <<= e->ct; if (e->c & 0xF8000000L) { /* One final overflow has to be handled */ if (e->buffer >= 0) { if (e->zc) do emit_byte(0x00, cinfo); while (--e->zc); emit_byte(e->buffer + 1, cinfo); if (e->buffer + 1 == 0xFF) emit_byte(0x00, cinfo); } e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */ e->sc = 0; } else { if (e->buffer == 0) ++e->zc; else if (e->buffer >= 0) { if (e->zc) do emit_byte(0x00, cinfo); while (--e->zc); emit_byte(e->buffer, cinfo); } if (e->sc) { if (e->zc) do emit_byte(0x00, cinfo); while (--e->zc); do { emit_byte(0xFF, cinfo); emit_byte(0x00, cinfo); } while (--e->sc); } } /* Output final bytes only if they are not 0x00 */ if (e->c & 0x7FFF800L) { if (e->zc) /* output final pending zero bytes */ do emit_byte(0x00, cinfo); while (--e->zc); emit_byte((e->c >> 19) & 0xFF, cinfo); if (((e->c >> 19) & 0xFF) == 0xFF) emit_byte(0x00, cinfo); if (e->c & 0x7F800L) { emit_byte((e->c >> 11) & 0xFF, cinfo); if (((e->c >> 11) & 0xFF) == 0xFF) emit_byte(0x00, cinfo); } } } /* * The core arithmetic encoding routine (common in JPEG and JBIG). * This needs to go as fast as possible. * Machine-dependent optimization facilities * are not utilized in this portable implementation. * However, this code should be fairly efficient and * may be a good base for further optimizations anyway. * * Parameter 'val' to be encoded may be 0 or 1 (binary decision). * * Note: I've added full "Pacman" termination support to the * byte output routines, which is equivalent to the optional * Discard_final_zeros procedure (Figure D.15) in the spec. * Thus, we always produce the shortest possible output * stream compliant to the spec (no trailing zero bytes, * except for FF stuffing). * * I've also introduced a new scheme for accessing * the probability estimation state machine table, * derived from Markus Kuhn's JBIG implementation. */ LOCAL(void) arith_encode (j_compress_ptr cinfo, unsigned char *st, int val) { register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy; register unsigned char nl, nm; register INT32 qe, temp; register int sv; /* Fetch values from our compact representation of Table D.3(D.2): * Qe values and probability estimation state machine */ sv = *st; qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */ nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */ nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */ /* Encode & estimation procedures per sections D.1.4 & D.1.5 */ e->a -= qe; if (val != (sv >> 7)) { /* Encode the less probable symbol */ if (e->a >= qe) { /* If the interval size (qe) for the less probable symbol (LPS) * is larger than the interval size for the MPS, then exchange * the two symbols for coding efficiency, otherwise code the LPS * as usual: */ e->c += e->a; e->a = qe; } *st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */ } else { /* Encode the more probable symbol */ if (e->a >= 0x8000L) return; /* A >= 0x8000 -> ready, no renormalization required */ if (e->a < qe) { /* If the interval size (qe) for the less probable symbol (LPS) * is larger than the interval size for the MPS, then exchange * the two symbols for coding efficiency: */ e->c += e->a; e->a = qe; } *st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */ } /* Renormalization & data output per section D.1.6 */ do { e->a <<= 1; e->c <<= 1; if (--e->ct == 0) { /* Another byte is ready for output */ temp = e->c >> 19; if (temp > 0xFF) { /* Handle overflow over all stacked 0xFF bytes */ if (e->buffer >= 0) { if (e->zc) do emit_byte(0x00, cinfo); while (--e->zc); emit_byte(e->buffer + 1, cinfo); if (e->buffer + 1 == 0xFF) emit_byte(0x00, cinfo); } e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */ e->sc = 0; /* Note: The 3 spacer bits in the C register guarantee * that the new buffer byte can't be 0xFF here * (see page 160 in the P&M JPEG book). */ e->buffer = temp & 0xFF; /* new output byte, might overflow later */ } else if (temp == 0xFF) { ++e->sc; /* stack 0xFF byte (which might overflow later) */ } else { /* Output all stacked 0xFF bytes, they will not overflow any more */ if (e->buffer == 0) ++e->zc; else if (e->buffer >= 0) { if (e->zc) do emit_byte(0x00, cinfo); while (--e->zc); emit_byte(e->buffer, cinfo); } if (e->sc) { if (e->zc) do emit_byte(0x00, cinfo); while (--e->zc); do { emit_byte(0xFF, cinfo); emit_byte(0x00, cinfo); } while (--e->sc); } e->buffer = temp & 0xFF; /* new output byte (can still overflow) */ } e->c &= 0x7FFFFL; e->ct += 8; } } while (e->a < 0x8000L); } /* * Emit a restart marker & resynchronize predictions. */ LOCAL(void) emit_restart (j_compress_ptr cinfo, int restart_num) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; int ci; jpeg_component_info * compptr; finish_pass(cinfo); emit_byte(0xFF, cinfo); emit_byte(JPEG_RST0 + restart_num, cinfo); /* Re-initialize statistics areas */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* DC needs no table for refinement scan */ if (cinfo->Ss == 0 && cinfo->Ah == 0) { MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS); /* Reset DC predictions to 0 */ entropy->last_dc_val[ci] = 0; entropy->dc_context[ci] = 0; } /* AC needs no table when not present */ if (cinfo->Se) { MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS); } } /* Reset arithmetic encoding variables */ entropy->c = 0; entropy->a = 0x10000L; entropy->sc = 0; entropy->zc = 0; entropy->ct = 11; entropy->buffer = -1; /* empty */ } /* * MCU encoding for DC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; unsigned char *st; int blkn, ci, tbl; int v, v2, m; ISHIFT_TEMPS /* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { emit_restart(cinfo, entropy->next_restart_num); entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } /* Encode the MCU data blocks */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { ci = cinfo->MCU_membership[blkn]; tbl = cinfo->cur_comp_info[ci]->dc_tbl_no; /* Compute the DC value after the required point transform by Al. * This is simply an arithmetic right shift. */ m = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al); /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */ /* Table F.4: Point to statistics bin S0 for DC coefficient coding */ st = entropy->dc_stats[tbl] + entropy->dc_context[ci]; /* Figure F.4: Encode_DC_DIFF */ if ((v = m - entropy->last_dc_val[ci]) == 0) { arith_encode(cinfo, st, 0); entropy->dc_context[ci] = 0; /* zero diff category */ } else { entropy->last_dc_val[ci] = m; arith_encode(cinfo, st, 1); /* Figure F.6: Encoding nonzero value v */ /* Figure F.7: Encoding the sign of v */ if (v > 0) { arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */ st += 2; /* Table F.4: SP = S0 + 2 */ entropy->dc_context[ci] = 4; /* small positive diff category */ } else { v = -v; arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */ st += 3; /* Table F.4: SN = S0 + 3 */ entropy->dc_context[ci] = 8; /* small negative diff category */ } /* Figure F.8: Encoding the magnitude category of v */ m = 0; if (v -= 1) { arith_encode(cinfo, st, 1); m = 1; v2 = v; st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */ while (v2 >>= 1) { arith_encode(cinfo, st, 1); m <<= 1; st += 1; } } arith_encode(cinfo, st, 0); /* Section F.1.4.4.1.2: Establish dc_context conditioning category */ if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1)) entropy->dc_context[ci] = 0; /* zero diff category */ else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1)) entropy->dc_context[ci] += 8; /* large diff category */ /* Figure F.9: Encoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) arith_encode(cinfo, st, (m & v) ? 1 : 0); } } return TRUE; } /* * MCU encoding for AC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; const int * natural_order; JBLOCKROW block; unsigned char *st; int tbl, k, ke; int v, v2, m; /* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { emit_restart(cinfo, entropy->next_restart_num); entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } natural_order = cinfo->natural_order; /* Encode the MCU data block */ block = MCU_data[0]; tbl = cinfo->cur_comp_info[0]->ac_tbl_no; /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */ /* Establish EOB (end-of-block) index */ ke = cinfo->Se; do { /* We must apply the point transform by Al. For AC coefficients this * is an integer division with rounding towards 0. To do this portably * in C, we shift after obtaining the absolute value. */ if ((v = (*block)[natural_order[ke]]) >= 0) { if (v >>= cinfo->Al) break; } else { v = -v; if (v >>= cinfo->Al) break; } } while (--ke); /* Figure F.5: Encode_AC_Coefficients */ for (k = cinfo->Ss - 1; k < ke;) { st = entropy->ac_stats[tbl] + 3 * k; arith_encode(cinfo, st, 0); /* EOB decision */ for (;;) { if ((v = (*block)[natural_order[++k]]) >= 0) { if (v >>= cinfo->Al) { arith_encode(cinfo, st + 1, 1); arith_encode(cinfo, entropy->fixed_bin, 0); break; } } else { v = -v; if (v >>= cinfo->Al) { arith_encode(cinfo, st + 1, 1); arith_encode(cinfo, entropy->fixed_bin, 1); break; } } arith_encode(cinfo, st + 1, 0); st += 3; } st += 2; /* Figure F.8: Encoding the magnitude category of v */ m = 0; if (v -= 1) { arith_encode(cinfo, st, 1); m = 1; v2 = v; if (v2 >>= 1) { arith_encode(cinfo, st, 1); m <<= 1; st = entropy->ac_stats[tbl] + (k <= cinfo->arith_ac_K[tbl] ? 189 : 217); while (v2 >>= 1) { arith_encode(cinfo, st, 1); m <<= 1; st += 1; } } } arith_encode(cinfo, st, 0); /* Figure F.9: Encoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) arith_encode(cinfo, st, (m & v) ? 1 : 0); } /* Encode EOB decision only if k < cinfo->Se */ if (k < cinfo->Se) { st = entropy->ac_stats[tbl] + 3 * k; arith_encode(cinfo, st, 1); } return TRUE; } /* * MCU encoding for DC successive approximation refinement scan. * Note: we assume such scans can be multi-component, * although the spec is not very clear on the point. */ METHODDEF(boolean) encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; unsigned char *st; int Al, blkn; /* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { emit_restart(cinfo, entropy->next_restart_num); entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } st = entropy->fixed_bin; /* use fixed probability estimation */ Al = cinfo->Al; /* Encode the MCU data blocks */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { /* We simply emit the Al'th bit of the DC coefficient value. */ arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1); } return TRUE; } /* * MCU encoding for AC successive approximation refinement scan. */ METHODDEF(boolean) encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; const int * natural_order; JBLOCKROW block; unsigned char *st; int tbl, k, ke, kex; int v; /* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { emit_restart(cinfo, entropy->next_restart_num); entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } natural_order = cinfo->natural_order; /* Encode the MCU data block */ block = MCU_data[0]; tbl = cinfo->cur_comp_info[0]->ac_tbl_no; /* Section G.1.3.3: Encoding of AC coefficients */ /* Establish EOB (end-of-block) index */ ke = cinfo->Se; do { /* We must apply the point transform by Al. For AC coefficients this * is an integer division with rounding towards 0. To do this portably * in C, we shift after obtaining the absolute value. */ if ((v = (*block)[natural_order[ke]]) >= 0) { if (v >>= cinfo->Al) break; } else { v = -v; if (v >>= cinfo->Al) break; } } while (--ke); /* Establish EOBx (previous stage end-of-block) index */ for (kex = ke; kex > 0; kex--) if ((v = (*block)[natural_order[kex]]) >= 0) { if (v >>= cinfo->Ah) break; } else { v = -v; if (v >>= cinfo->Ah) break; } /* Figure G.10: Encode_AC_Coefficients_SA */ for (k = cinfo->Ss - 1; k < ke;) { st = entropy->ac_stats[tbl] + 3 * k; if (k >= kex) arith_encode(cinfo, st, 0); /* EOB decision */ for (;;) { if ((v = (*block)[natural_order[++k]]) >= 0) { if (v >>= cinfo->Al) { if (v >> 1) /* previously nonzero coef */ arith_encode(cinfo, st + 2, (v & 1)); else { /* newly nonzero coef */ arith_encode(cinfo, st + 1, 1); arith_encode(cinfo, entropy->fixed_bin, 0); } break; } } else { v = -v; if (v >>= cinfo->Al) { if (v >> 1) /* previously nonzero coef */ arith_encode(cinfo, st + 2, (v & 1)); else { /* newly nonzero coef */ arith_encode(cinfo, st + 1, 1); arith_encode(cinfo, entropy->fixed_bin, 1); } break; } } arith_encode(cinfo, st + 1, 0); st += 3; } } /* Encode EOB decision only if k < cinfo->Se */ if (k < cinfo->Se) { st = entropy->ac_stats[tbl] + 3 * k; arith_encode(cinfo, st, 1); } return TRUE; } /* * Encode and output one MCU's worth of arithmetic-compressed coefficients. */ METHODDEF(boolean) encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; const int * natural_order; JBLOCKROW block; unsigned char *st; int tbl, k, ke; int v, v2, m; int blkn, ci; jpeg_component_info * compptr; /* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { emit_restart(cinfo, entropy->next_restart_num); entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } natural_order = cinfo->natural_order; /* Encode the MCU data blocks */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { block = MCU_data[blkn]; ci = cinfo->MCU_membership[blkn]; compptr = cinfo->cur_comp_info[ci]; /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */ tbl = compptr->dc_tbl_no; /* Table F.4: Point to statistics bin S0 for DC coefficient coding */ st = entropy->dc_stats[tbl] + entropy->dc_context[ci]; /* Figure F.4: Encode_DC_DIFF */ if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) { arith_encode(cinfo, st, 0); entropy->dc_context[ci] = 0; /* zero diff category */ } else { entropy->last_dc_val[ci] = (*block)[0]; arith_encode(cinfo, st, 1); /* Figure F.6: Encoding nonzero value v */ /* Figure F.7: Encoding the sign of v */ if (v > 0) { arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */ st += 2; /* Table F.4: SP = S0 + 2 */ entropy->dc_context[ci] = 4; /* small positive diff category */ } else { v = -v; arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */ st += 3; /* Table F.4: SN = S0 + 3 */ entropy->dc_context[ci] = 8; /* small negative diff category */ } /* Figure F.8: Encoding the magnitude category of v */ m = 0; if (v -= 1) { arith_encode(cinfo, st, 1); m = 1; v2 = v; st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */ while (v2 >>= 1) { arith_encode(cinfo, st, 1); m <<= 1; st += 1; } } arith_encode(cinfo, st, 0); /* Section F.1.4.4.1.2: Establish dc_context conditioning category */ if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1)) entropy->dc_context[ci] = 0; /* zero diff category */ else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1)) entropy->dc_context[ci] += 8; /* large diff category */ /* Figure F.9: Encoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) arith_encode(cinfo, st, (m & v) ? 1 : 0); } /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */ if ((ke = cinfo->lim_Se) == 0) continue; tbl = compptr->ac_tbl_no; /* Establish EOB (end-of-block) index */ do { if ((*block)[natural_order[ke]]) break; } while (--ke); /* Figure F.5: Encode_AC_Coefficients */ for (k = 0; k < ke;) { st = entropy->ac_stats[tbl] + 3 * k; arith_encode(cinfo, st, 0); /* EOB decision */ while ((v = (*block)[natural_order[++k]]) == 0) { arith_encode(cinfo, st + 1, 0); st += 3; } arith_encode(cinfo, st + 1, 1); /* Figure F.6: Encoding nonzero value v */ /* Figure F.7: Encoding the sign of v */ if (v > 0) { arith_encode(cinfo, entropy->fixed_bin, 0); } else { v = -v; arith_encode(cinfo, entropy->fixed_bin, 1); } st += 2; /* Figure F.8: Encoding the magnitude category of v */ m = 0; if (v -= 1) { arith_encode(cinfo, st, 1); m = 1; v2 = v; if (v2 >>= 1) { arith_encode(cinfo, st, 1); m <<= 1; st = entropy->ac_stats[tbl] + (k <= cinfo->arith_ac_K[tbl] ? 189 : 217); while (v2 >>= 1) { arith_encode(cinfo, st, 1); m <<= 1; st += 1; } } } arith_encode(cinfo, st, 0); /* Figure F.9: Encoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) arith_encode(cinfo, st, (m & v) ? 1 : 0); } /* Encode EOB decision only if k < cinfo->lim_Se */ if (k < cinfo->lim_Se) { st = entropy->ac_stats[tbl] + 3 * k; arith_encode(cinfo, st, 1); } } return TRUE; } /* * Initialize for an arithmetic-compressed scan. */ METHODDEF(void) start_pass (j_compress_ptr cinfo, boolean gather_statistics) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; int ci, tbl; jpeg_component_info * compptr; if (gather_statistics) /* Make sure to avoid that in the master control logic! * We are fully adaptive here and need no extra * statistics gathering pass! */ ERREXIT(cinfo, JERR_NOT_COMPILED); /* We assume jcmaster.c already validated the progressive scan parameters. */ /* Select execution routines */ if (cinfo->progressive_mode) { if (cinfo->Ah == 0) { if (cinfo->Ss == 0) entropy->pub.encode_mcu = encode_mcu_DC_first; else entropy->pub.encode_mcu = encode_mcu_AC_first; } else { if (cinfo->Ss == 0) entropy->pub.encode_mcu = encode_mcu_DC_refine; else entropy->pub.encode_mcu = encode_mcu_AC_refine; } } else entropy->pub.encode_mcu = encode_mcu; /* Allocate & initialize requested statistics areas */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* DC needs no table for refinement scan */ if (cinfo->Ss == 0 && cinfo->Ah == 0) { tbl = compptr->dc_tbl_no; if (tbl < 0 || tbl >= NUM_ARITH_TBLS) ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl); if (entropy->dc_stats[tbl] == NULL) entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS); MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS); /* Initialize DC predictions to 0 */ entropy->last_dc_val[ci] = 0; entropy->dc_context[ci] = 0; } /* AC needs no table when not present */ if (cinfo->Se) { tbl = compptr->ac_tbl_no; if (tbl < 0 || tbl >= NUM_ARITH_TBLS) ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl); if (entropy->ac_stats[tbl] == NULL) entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS); MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS); #ifdef CALCULATE_SPECTRAL_CONDITIONING if (cinfo->progressive_mode) /* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */ cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4); #endif } } /* Initialize arithmetic encoding variables */ entropy->c = 0; entropy->a = 0x10000L; entropy->sc = 0; entropy->zc = 0; entropy->ct = 11; entropy->buffer = -1; /* empty */ /* Initialize restart stuff */ entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num = 0; } /* * Module initialization routine for arithmetic entropy encoding. */ GLOBAL(void) jinit_arith_encoder (j_compress_ptr cinfo) { arith_entropy_ptr entropy; int i; entropy = (arith_entropy_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(arith_entropy_encoder)); cinfo->entropy = &entropy->pub; entropy->pub.start_pass = start_pass; entropy->pub.finish_pass = finish_pass; /* Mark tables unallocated */ for (i = 0; i < NUM_ARITH_TBLS; i++) { entropy->dc_stats[i] = NULL; entropy->ac_stats[i] = NULL; } /* Initialize index for fixed probability estimation */ entropy->fixed_bin[0] = 113; } ================================================ FILE: tess-two/jni/libjpeg/jccoefct.c ================================================ /* * jccoefct.c * * Copyright (C) 1994-1997, Thomas G. Lane. * Modified 2003-2011 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the coefficient buffer controller for compression. * This controller is the top level of the JPEG compressor proper. * The coefficient buffer lies between forward-DCT and entropy encoding steps. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* We use a full-image coefficient buffer when doing Huffman optimization, * and also for writing multiple-scan JPEG files. In all cases, the DCT * step is run during the first pass, and subsequent passes need only read * the buffered coefficients. */ #ifdef ENTROPY_OPT_SUPPORTED #define FULL_COEF_BUFFER_SUPPORTED #else #ifdef C_MULTISCAN_FILES_SUPPORTED #define FULL_COEF_BUFFER_SUPPORTED #endif #endif /* Private buffer controller object */ typedef struct { struct jpeg_c_coef_controller pub; /* public fields */ JDIMENSION iMCU_row_num; /* iMCU row # within image */ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */ int MCU_vert_offset; /* counts MCU rows within iMCU row */ int MCU_rows_per_iMCU_row; /* number of such rows needed */ /* For single-pass compression, it's sufficient to buffer just one MCU * (although this may prove a bit slow in practice). We allocate a * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each * MCU constructed and sent. (On 80x86, the workspace is FAR even though * it's not really very big; this is to keep the module interfaces unchanged * when a large coefficient buffer is necessary.) * In multi-pass modes, this array points to the current MCU's blocks * within the virtual arrays. */ JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU]; /* In multi-pass modes, we need a virtual block array for each component. */ jvirt_barray_ptr whole_image[MAX_COMPONENTS]; } my_coef_controller; typedef my_coef_controller * my_coef_ptr; /* Forward declarations */ METHODDEF(boolean) compress_data JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); #ifdef FULL_COEF_BUFFER_SUPPORTED METHODDEF(boolean) compress_first_pass JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); METHODDEF(boolean) compress_output JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); #endif LOCAL(void) start_iMCU_row (j_compress_ptr cinfo) /* Reset within-iMCU-row counters for a new row */ { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; /* In an interleaved scan, an MCU row is the same as an iMCU row. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. * But at the bottom of the image, process only what's left. */ if (cinfo->comps_in_scan > 1) { coef->MCU_rows_per_iMCU_row = 1; } else { if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1)) coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; else coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; } coef->mcu_ctr = 0; coef->MCU_vert_offset = 0; } /* * Initialize for a processing pass. */ METHODDEF(void) start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; coef->iMCU_row_num = 0; start_iMCU_row(cinfo); switch (pass_mode) { case JBUF_PASS_THRU: if (coef->whole_image[0] != NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); coef->pub.compress_data = compress_data; break; #ifdef FULL_COEF_BUFFER_SUPPORTED case JBUF_SAVE_AND_PASS: if (coef->whole_image[0] == NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); coef->pub.compress_data = compress_first_pass; break; case JBUF_CRANK_DEST: if (coef->whole_image[0] == NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); coef->pub.compress_data = compress_output; break; #endif default: ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); break; } } /* * Process some data in the single-pass case. * We process the equivalent of one fully interleaved MCU row ("iMCU" row) * per call, ie, v_samp_factor block rows for each component in the image. * Returns TRUE if the iMCU row is completed, FALSE if suspended. * * NB: input_buf contains a plane for each component in image, * which we index according to the component's SOF position. */ METHODDEF(boolean) compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; int blkn, bi, ci, yindex, yoffset, blockcnt; JDIMENSION ypos, xpos; jpeg_component_info *compptr; forward_DCT_ptr forward_DCT; /* Loop to write as much as one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) { /* Determine where data comes from in input_buf and do the DCT thing. * Each call on forward_DCT processes a horizontal row of DCT blocks * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks * sequentially. Dummy blocks at the right or bottom edge are filled in * specially. The data in them does not matter for image reconstruction, * so we fill them with values that will encode to the smallest amount of * data, viz: all zeroes in the AC entries, DC entries equal to previous * block's DC value. (Thanks to Thomas Kinsman for this idea.) */ blkn = 0; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; forward_DCT = cinfo->fdct->forward_DCT[compptr->component_index]; blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width : compptr->last_col_width; xpos = MCU_col_num * compptr->MCU_sample_width; ypos = yoffset * compptr->DCT_v_scaled_size; /* ypos == (yoffset+yindex) * DCTSIZE */ for (yindex = 0; yindex < compptr->MCU_height; yindex++) { if (coef->iMCU_row_num < last_iMCU_row || yoffset+yindex < compptr->last_row_height) { (*forward_DCT) (cinfo, compptr, input_buf[compptr->component_index], coef->MCU_buffer[blkn], ypos, xpos, (JDIMENSION) blockcnt); if (blockcnt < compptr->MCU_width) { /* Create some dummy blocks at the right edge of the image. */ FMEMZERO((void FAR *) coef->MCU_buffer[blkn + blockcnt], (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK)); for (bi = blockcnt; bi < compptr->MCU_width; bi++) { coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0]; } } } else { /* Create a row of dummy blocks at the bottom of the image. */ FMEMZERO((void FAR *) coef->MCU_buffer[blkn], compptr->MCU_width * SIZEOF(JBLOCK)); for (bi = 0; bi < compptr->MCU_width; bi++) { coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0]; } } blkn += compptr->MCU_width; ypos += compptr->DCT_v_scaled_size; } } /* Try to write the MCU. In event of a suspension failure, we will * re-DCT the MCU on restart (a bit inefficient, could be fixed...) */ if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->mcu_ctr = MCU_col_num; return FALSE; } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->mcu_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ coef->iMCU_row_num++; start_iMCU_row(cinfo); return TRUE; } #ifdef FULL_COEF_BUFFER_SUPPORTED /* * Process some data in the first pass of a multi-pass case. * We process the equivalent of one fully interleaved MCU row ("iMCU" row) * per call, ie, v_samp_factor block rows for each component in the image. * This amount of data is read from the source buffer, DCT'd and quantized, * and saved into the virtual arrays. We also generate suitable dummy blocks * as needed at the right and lower edges. (The dummy blocks are constructed * in the virtual arrays, which have been padded appropriately.) This makes * it possible for subsequent passes not to worry about real vs. dummy blocks. * * We must also emit the data to the entropy encoder. This is conveniently * done by calling compress_output() after we've loaded the current strip * of the virtual arrays. * * NB: input_buf contains a plane for each component in image. All * components are DCT'd and loaded into the virtual arrays in this pass. * However, it may be that only a subset of the components are emitted to * the entropy encoder during this first pass; be careful about looking * at the scan-dependent variables (MCU dimensions, etc). */ METHODDEF(boolean) compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; JDIMENSION blocks_across, MCUs_across, MCUindex; int bi, ci, h_samp_factor, block_row, block_rows, ndummy; JCOEF lastDC; jpeg_component_info *compptr; JBLOCKARRAY buffer; JBLOCKROW thisblockrow, lastblockrow; forward_DCT_ptr forward_DCT; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Align the virtual buffer for this component. */ buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], coef->iMCU_row_num * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, TRUE); /* Count non-dummy DCT block rows in this iMCU row. */ if (coef->iMCU_row_num < last_iMCU_row) block_rows = compptr->v_samp_factor; else { /* NB: can't use last_row_height here, since may not be set! */ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (block_rows == 0) block_rows = compptr->v_samp_factor; } blocks_across = compptr->width_in_blocks; h_samp_factor = compptr->h_samp_factor; /* Count number of dummy blocks to be added at the right margin. */ ndummy = (int) (blocks_across % h_samp_factor); if (ndummy > 0) ndummy = h_samp_factor - ndummy; forward_DCT = cinfo->fdct->forward_DCT[ci]; /* Perform DCT for all non-dummy blocks in this iMCU row. Each call * on forward_DCT processes a complete horizontal row of DCT blocks. */ for (block_row = 0; block_row < block_rows; block_row++) { thisblockrow = buffer[block_row]; (*forward_DCT) (cinfo, compptr, input_buf[ci], thisblockrow, (JDIMENSION) (block_row * compptr->DCT_v_scaled_size), (JDIMENSION) 0, blocks_across); if (ndummy > 0) { /* Create dummy blocks at the right edge of the image. */ thisblockrow += blocks_across; /* => first dummy block */ FMEMZERO((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK)); lastDC = thisblockrow[-1][0]; for (bi = 0; bi < ndummy; bi++) { thisblockrow[bi][0] = lastDC; } } } /* If at end of image, create dummy block rows as needed. * The tricky part here is that within each MCU, we want the DC values * of the dummy blocks to match the last real block's DC value. * This squeezes a few more bytes out of the resulting file... */ if (coef->iMCU_row_num == last_iMCU_row) { blocks_across += ndummy; /* include lower right corner */ MCUs_across = blocks_across / h_samp_factor; for (block_row = block_rows; block_row < compptr->v_samp_factor; block_row++) { thisblockrow = buffer[block_row]; lastblockrow = buffer[block_row-1]; FMEMZERO((void FAR *) thisblockrow, (size_t) (blocks_across * SIZEOF(JBLOCK))); for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) { lastDC = lastblockrow[h_samp_factor-1][0]; for (bi = 0; bi < h_samp_factor; bi++) { thisblockrow[bi][0] = lastDC; } thisblockrow += h_samp_factor; /* advance to next MCU in row */ lastblockrow += h_samp_factor; } } } } /* NB: compress_output will increment iMCU_row_num if successful. * A suspension return will result in redoing all the work above next time. */ /* Emit data to the entropy encoder, sharing code with subsequent passes */ return compress_output(cinfo, input_buf); } /* * Process some data in subsequent passes of a multi-pass case. * We process the equivalent of one fully interleaved MCU row ("iMCU" row) * per call, ie, v_samp_factor block rows for each component in the scan. * The data is obtained from the virtual arrays and fed to the entropy coder. * Returns TRUE if the iMCU row is completed, FALSE if suspended. * * NB: input_buf is ignored; it is likely to be a NULL pointer. */ METHODDEF(boolean) compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ int blkn, ci, xindex, yindex, yoffset; JDIMENSION start_col; JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; JBLOCKROW buffer_ptr; jpeg_component_info *compptr; /* Align the virtual buffers for the components used in this scan. * NB: during first pass, this is safe only because the buffers will * already be aligned properly, so jmemmgr.c won't need to do any I/O. */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; buffer[ci] = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], coef->iMCU_row_num * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, FALSE); } /* Loop to process one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row; MCU_col_num++) { /* Construct list of pointers to DCT blocks belonging to this MCU */ blkn = 0; /* index of current DCT block within MCU */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; start_col = MCU_col_num * compptr->MCU_width; for (yindex = 0; yindex < compptr->MCU_height; yindex++) { buffer_ptr = buffer[ci][yindex+yoffset] + start_col; for (xindex = 0; xindex < compptr->MCU_width; xindex++) { coef->MCU_buffer[blkn++] = buffer_ptr++; } } } /* Try to write the MCU. */ if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->mcu_ctr = MCU_col_num; return FALSE; } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->mcu_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ coef->iMCU_row_num++; start_iMCU_row(cinfo); return TRUE; } #endif /* FULL_COEF_BUFFER_SUPPORTED */ /* * Initialize coefficient buffer controller. */ GLOBAL(void) jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer) { my_coef_ptr coef; coef = (my_coef_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_coef_controller)); cinfo->coef = (struct jpeg_c_coef_controller *) coef; coef->pub.start_pass = start_pass_coef; /* Create the coefficient buffer. */ if (need_full_buffer) { #ifdef FULL_COEF_BUFFER_SUPPORTED /* Allocate a full-image virtual array for each component, */ /* padded to a multiple of samp_factor DCT blocks in each direction. */ int ci; jpeg_component_info *compptr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { coef->whole_image[ci] = (*cinfo->mem->request_virt_barray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, (JDIMENSION) jround_up((long) compptr->width_in_blocks, (long) compptr->h_samp_factor), (JDIMENSION) jround_up((long) compptr->height_in_blocks, (long) compptr->v_samp_factor), (JDIMENSION) compptr->v_samp_factor); } #else ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); #endif } else { /* We only need a single-MCU buffer. */ JBLOCKROW buffer; int i; buffer = (JBLOCKROW) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) { coef->MCU_buffer[i] = buffer + i; } coef->whole_image[0] = NULL; /* flag for no virtual arrays */ } } ================================================ FILE: tess-two/jni/libjpeg/jccolor.c ================================================ /* * jccolor.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2011-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains input colorspace conversion routines. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Private subobject */ typedef struct { struct jpeg_color_converter pub; /* public fields */ /* Private state for RGB->YCC conversion */ INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */ } my_color_converter; typedef my_color_converter * my_cconvert_ptr; /**************** RGB -> YCbCr conversion: most common case **************/ /* * YCbCr is defined per Recommendation ITU-R BT.601-7 (03/2011), * previously known as Recommendation CCIR 601-1, except that Cb and Cr * are normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. * sRGB (standard RGB color space) is defined per IEC 61966-2-1:1999. * sYCC (standard luma-chroma-chroma color space with extended gamut) * is defined per IEC 61966-2-1:1999 Amendment A1:2003 Annex F. * bg-sRGB and bg-sYCC (big gamut standard color spaces) * are defined per IEC 61966-2-1:1999 Amendment A1:2003 Annex G. * Note that the derived conversion coefficients given in some of these * documents are imprecise. The general conversion equations are * Y = Kr * R + (1 - Kr - Kb) * G + Kb * B * Cb = 0.5 * (B - Y) / (1 - Kb) * Cr = 0.5 * (R - Y) / (1 - Kr) * With Kr = 0.299 and Kb = 0.114 (derived according to SMPTE RP 177-1993 * from the 1953 FCC NTSC primaries and CIE Illuminant C), * the conversion equations to be implemented are therefore * Y = 0.299 * R + 0.587 * G + 0.114 * B * Cb = -0.168735892 * R - 0.331264108 * G + 0.5 * B + CENTERJSAMPLE * Cr = 0.5 * R - 0.418687589 * G - 0.081312411 * B + CENTERJSAMPLE * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2, * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0) * were not represented exactly. Now we sacrifice exact representation of * maximum red and maximum blue in order to get exact grayscales. * * To avoid floating-point arithmetic, we represent the fractional constants * as integers scaled up by 2^16 (about 4 digits precision); we have to divide * the products by 2^16, with appropriate rounding, to get the correct answer. * * For even more speed, we avoid doing any multiplications in the inner loop * by precalculating the constants times R,G,B for all possible values. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); * for 9-bit to 12-bit samples it is still acceptable. It's not very * reasonable for 16-bit samples, but if you want lossless storage you * shouldn't be changing colorspace anyway. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included * in the tables to save adding them separately in the inner loop. */ #define SCALEBITS 16 /* speediest right-shift on some machines */ #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS) #define ONE_HALF ((INT32) 1 << (SCALEBITS-1)) #define FIX(x) ((INT32) ((x) * (1L< Y section */ #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */ #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */ #define R_CB_OFF (3*(MAXJSAMPLE+1)) #define G_CB_OFF (4*(MAXJSAMPLE+1)) #define B_CB_OFF (5*(MAXJSAMPLE+1)) #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */ #define G_CR_OFF (6*(MAXJSAMPLE+1)) #define B_CR_OFF (7*(MAXJSAMPLE+1)) #define TABLE_SIZE (8*(MAXJSAMPLE+1)) /* * Initialize for RGB->YCC colorspace conversion. */ METHODDEF(void) rgb_ycc_start (j_compress_ptr cinfo) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; INT32 * rgb_ycc_tab; INT32 i; /* Allocate and fill in the conversion tables. */ cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (TABLE_SIZE * SIZEOF(INT32))); for (i = 0; i <= MAXJSAMPLE; i++) { rgb_ycc_tab[i+R_Y_OFF] = FIX(0.299) * i; rgb_ycc_tab[i+G_Y_OFF] = FIX(0.587) * i; rgb_ycc_tab[i+B_Y_OFF] = FIX(0.114) * i + ONE_HALF; rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.168735892)) * i; rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.331264108)) * i; /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr. * This ensures that the maximum output will round to MAXJSAMPLE * not MAXJSAMPLE+1, and thus that we don't have to range-limit. */ rgb_ycc_tab[i+B_CB_OFF] = FIX(0.5) * i + CBCR_OFFSET + ONE_HALF-1; /* B=>Cb and R=>Cr tables are the same rgb_ycc_tab[i+R_CR_OFF] = FIX(0.5) * i + CBCR_OFFSET + ONE_HALF-1; */ rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.418687589)) * i; rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.081312411)) * i; } } /* * Convert some rows of samples to the JPEG colorspace. * * Note that we change from the application's interleaved-pixel format * to our internal noninterleaved, one-plane-per-component format. * The input buffer is therefore three times as wide as the output buffer. * * A starting row offset is provided only for the output buffer. The caller * can easily adjust the passed input_buf value to accommodate any row * offset required on that side. */ METHODDEF(void) rgb_ycc_convert (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register INT32 * ctab = cconvert->rgb_ycc_tab; register int r, g, b; register JSAMPROW inptr; register JSAMPROW outptr0, outptr1, outptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->image_width; while (--num_rows >= 0) { inptr = *input_buf++; outptr0 = output_buf[0][output_row]; outptr1 = output_buf[1][output_row]; outptr2 = output_buf[2][output_row]; output_row++; for (col = 0; col < num_cols; col++) { r = GETJSAMPLE(inptr[RGB_RED]); g = GETJSAMPLE(inptr[RGB_GREEN]); b = GETJSAMPLE(inptr[RGB_BLUE]); /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations * must be too; we do not need an explicit range-limiting operation. * Hence the value being shifted is never negative, and we don't * need the general RIGHT_SHIFT macro. */ /* Y */ outptr0[col] = (JSAMPLE) ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) >> SCALEBITS); /* Cb */ outptr1[col] = (JSAMPLE) ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF]) >> SCALEBITS); /* Cr */ outptr2[col] = (JSAMPLE) ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF]) >> SCALEBITS); inptr += RGB_PIXELSIZE; } } } /**************** Cases other than RGB -> YCbCr **************/ /* * Convert some rows of samples to the JPEG colorspace. * This version handles RGB->grayscale conversion, which is the same * as the RGB->Y portion of RGB->YCbCr. * We assume rgb_ycc_start has been called (we only use the Y tables). */ METHODDEF(void) rgb_gray_convert (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register INT32 * ctab = cconvert->rgb_ycc_tab; register int r, g, b; register JSAMPROW inptr; register JSAMPROW outptr; register JDIMENSION col; JDIMENSION num_cols = cinfo->image_width; while (--num_rows >= 0) { inptr = *input_buf++; outptr = output_buf[0][output_row++]; for (col = 0; col < num_cols; col++) { r = GETJSAMPLE(inptr[RGB_RED]); g = GETJSAMPLE(inptr[RGB_GREEN]); b = GETJSAMPLE(inptr[RGB_BLUE]); /* Y */ outptr[col] = (JSAMPLE) ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) >> SCALEBITS); inptr += RGB_PIXELSIZE; } } } /* * Convert some rows of samples to the JPEG colorspace. * This version handles Adobe-style CMYK->YCCK conversion, * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same * conversion as above, while passing K (black) unchanged. * We assume rgb_ycc_start has been called. */ METHODDEF(void) cmyk_ycck_convert (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register INT32 * ctab = cconvert->rgb_ycc_tab; register int r, g, b; register JSAMPROW inptr; register JSAMPROW outptr0, outptr1, outptr2, outptr3; register JDIMENSION col; JDIMENSION num_cols = cinfo->image_width; while (--num_rows >= 0) { inptr = *input_buf++; outptr0 = output_buf[0][output_row]; outptr1 = output_buf[1][output_row]; outptr2 = output_buf[2][output_row]; outptr3 = output_buf[3][output_row]; output_row++; for (col = 0; col < num_cols; col++) { r = MAXJSAMPLE - GETJSAMPLE(inptr[0]); g = MAXJSAMPLE - GETJSAMPLE(inptr[1]); b = MAXJSAMPLE - GETJSAMPLE(inptr[2]); /* K passes through as-is */ outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */ /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations * must be too; we do not need an explicit range-limiting operation. * Hence the value being shifted is never negative, and we don't * need the general RIGHT_SHIFT macro. */ /* Y */ outptr0[col] = (JSAMPLE) ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) >> SCALEBITS); /* Cb */ outptr1[col] = (JSAMPLE) ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF]) >> SCALEBITS); /* Cr */ outptr2[col] = (JSAMPLE) ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF]) >> SCALEBITS); inptr += 4; } } } /* * Convert some rows of samples to the JPEG colorspace. * [R,G,B] to [R-G,G,B-G] conversion with modulo calculation * (forward reversible color transform). * This can be seen as an adaption of the general RGB->YCbCr * conversion equation with Kr = Kb = 0, while replacing the * normalization by modulo calculation. */ METHODDEF(void) rgb_rgb1_convert (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows) { register int r, g, b; register JSAMPROW inptr; register JSAMPROW outptr0, outptr1, outptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->image_width; while (--num_rows >= 0) { inptr = *input_buf++; outptr0 = output_buf[0][output_row]; outptr1 = output_buf[1][output_row]; outptr2 = output_buf[2][output_row]; output_row++; for (col = 0; col < num_cols; col++) { r = GETJSAMPLE(inptr[RGB_RED]); g = GETJSAMPLE(inptr[RGB_GREEN]); b = GETJSAMPLE(inptr[RGB_BLUE]); /* Assume that MAXJSAMPLE+1 is a power of 2, so that the MOD * (modulo) operator is equivalent to the bitmask operator AND. */ outptr0[col] = (JSAMPLE) ((r - g + CENTERJSAMPLE) & MAXJSAMPLE); outptr1[col] = (JSAMPLE) g; outptr2[col] = (JSAMPLE) ((b - g + CENTERJSAMPLE) & MAXJSAMPLE); inptr += RGB_PIXELSIZE; } } } /* * Convert some rows of samples to the JPEG colorspace. * This version handles grayscale output with no conversion. * The source can be either plain grayscale or YCC (since Y == gray). */ METHODDEF(void) grayscale_convert (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows) { int instride = cinfo->input_components; register JSAMPROW inptr; register JSAMPROW outptr; register JDIMENSION col; JDIMENSION num_cols = cinfo->image_width; while (--num_rows >= 0) { inptr = *input_buf++; outptr = output_buf[0][output_row++]; for (col = 0; col < num_cols; col++) { outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */ inptr += instride; } } } /* * Convert some rows of samples to the JPEG colorspace. * No colorspace conversion, but change from interleaved * to separate-planes representation. */ METHODDEF(void) rgb_convert (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows) { register JSAMPROW inptr; register JSAMPROW outptr0, outptr1, outptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->image_width; while (--num_rows >= 0) { inptr = *input_buf++; outptr0 = output_buf[0][output_row]; outptr1 = output_buf[1][output_row]; outptr2 = output_buf[2][output_row]; output_row++; for (col = 0; col < num_cols; col++) { /* We can dispense with GETJSAMPLE() here */ outptr0[col] = inptr[RGB_RED]; outptr1[col] = inptr[RGB_GREEN]; outptr2[col] = inptr[RGB_BLUE]; inptr += RGB_PIXELSIZE; } } } /* * Convert some rows of samples to the JPEG colorspace. * This version handles multi-component colorspaces without conversion. * We assume input_components == num_components. */ METHODDEF(void) null_convert (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows) { int ci; register int nc = cinfo->num_components; register JSAMPROW inptr; register JSAMPROW outptr; register JDIMENSION col; JDIMENSION num_cols = cinfo->image_width; while (--num_rows >= 0) { /* It seems fastest to make a separate pass for each component. */ for (ci = 0; ci < nc; ci++) { inptr = input_buf[0] + ci; outptr = output_buf[ci][output_row]; for (col = 0; col < num_cols; col++) { *outptr++ = *inptr; /* don't need GETJSAMPLE() here */ inptr += nc; } } input_buf++; output_row++; } } /* * Empty method for start_pass. */ METHODDEF(void) null_method (j_compress_ptr cinfo) { /* no work needed */ } /* * Module initialization routine for input colorspace conversion. */ GLOBAL(void) jinit_color_converter (j_compress_ptr cinfo) { my_cconvert_ptr cconvert; cconvert = (my_cconvert_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_color_converter)); cinfo->cconvert = &cconvert->pub; /* set start_pass to null method until we find out differently */ cconvert->pub.start_pass = null_method; /* Make sure input_components agrees with in_color_space */ switch (cinfo->in_color_space) { case JCS_GRAYSCALE: if (cinfo->input_components != 1) ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); break; case JCS_RGB: case JCS_BG_RGB: if (cinfo->input_components != RGB_PIXELSIZE) ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); break; case JCS_YCbCr: case JCS_BG_YCC: if (cinfo->input_components != 3) ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); break; case JCS_CMYK: case JCS_YCCK: if (cinfo->input_components != 4) ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); break; default: /* JCS_UNKNOWN can be anything */ if (cinfo->input_components < 1) ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); break; } /* Support color transform only for RGB colorspaces */ if (cinfo->color_transform && cinfo->jpeg_color_space != JCS_RGB && cinfo->jpeg_color_space != JCS_BG_RGB) ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); /* Check num_components, set conversion method based on requested space */ switch (cinfo->jpeg_color_space) { case JCS_GRAYSCALE: if (cinfo->num_components != 1) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); switch (cinfo->in_color_space) { case JCS_GRAYSCALE: case JCS_YCbCr: case JCS_BG_YCC: cconvert->pub.color_convert = grayscale_convert; break; case JCS_RGB: cconvert->pub.start_pass = rgb_ycc_start; cconvert->pub.color_convert = rgb_gray_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; case JCS_RGB: case JCS_BG_RGB: if (cinfo->num_components != 3) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); if (cinfo->in_color_space == cinfo->jpeg_color_space) { switch (cinfo->color_transform) { case JCT_NONE: cconvert->pub.color_convert = rgb_convert; break; case JCT_SUBTRACT_GREEN: cconvert->pub.color_convert = rgb_rgb1_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } } else ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; case JCS_YCbCr: if (cinfo->num_components != 3) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); switch (cinfo->in_color_space) { case JCS_RGB: cconvert->pub.start_pass = rgb_ycc_start; cconvert->pub.color_convert = rgb_ycc_convert; break; case JCS_YCbCr: cconvert->pub.color_convert = null_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; case JCS_BG_YCC: if (cinfo->num_components != 3) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); switch (cinfo->in_color_space) { case JCS_RGB: /* For conversion from normal RGB input to BG_YCC representation, * the Cb/Cr values are first computed as usual, and then * quantized further after DCT processing by a factor of * 2 in reference to the nominal quantization factor. */ /* need quantization scale by factor of 2 after DCT */ cinfo->comp_info[1].component_needed = TRUE; cinfo->comp_info[2].component_needed = TRUE; /* compute normal YCC first */ cconvert->pub.start_pass = rgb_ycc_start; cconvert->pub.color_convert = rgb_ycc_convert; break; case JCS_YCbCr: /* need quantization scale by factor of 2 after DCT */ cinfo->comp_info[1].component_needed = TRUE; cinfo->comp_info[2].component_needed = TRUE; /*FALLTHROUGH*/ case JCS_BG_YCC: /* Pass through for BG_YCC input */ cconvert->pub.color_convert = null_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; case JCS_CMYK: if (cinfo->num_components != 4) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); if (cinfo->in_color_space == JCS_CMYK) cconvert->pub.color_convert = null_convert; else ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; case JCS_YCCK: if (cinfo->num_components != 4) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); switch (cinfo->in_color_space) { case JCS_CMYK: cconvert->pub.start_pass = rgb_ycc_start; cconvert->pub.color_convert = cmyk_ycck_convert; break; case JCS_YCCK: cconvert->pub.color_convert = null_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; default: /* allow null conversion of JCS_UNKNOWN */ if (cinfo->jpeg_color_space != cinfo->in_color_space || cinfo->num_components != cinfo->input_components) ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); cconvert->pub.color_convert = null_convert; break; } } ================================================ FILE: tess-two/jni/libjpeg/jcdctmgr.c ================================================ /* * jcdctmgr.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2003-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the forward-DCT management logic. * This code selects a particular DCT implementation to be used, * and it performs related housekeeping chores including coefficient * quantization. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ /* Private subobject for this module */ typedef struct { struct jpeg_forward_dct pub; /* public fields */ /* Pointer to the DCT routine actually in use */ forward_DCT_method_ptr do_dct[MAX_COMPONENTS]; #ifdef DCT_FLOAT_SUPPORTED /* Same as above for the floating-point case. */ float_DCT_method_ptr do_float_dct[MAX_COMPONENTS]; #endif } my_fdct_controller; typedef my_fdct_controller * my_fdct_ptr; /* The allocated post-DCT divisor tables -- big enough for any * supported variant and not identical to the quant table entries, * because of scaling (especially for an unnormalized DCT) -- * are pointed to by dct_table in the per-component comp_info * structures. Each table is given in normal array order. */ typedef union { DCTELEM int_array[DCTSIZE2]; #ifdef DCT_FLOAT_SUPPORTED FAST_FLOAT float_array[DCTSIZE2]; #endif } divisor_table; /* The current scaled-DCT routines require ISLOW-style divisor tables, * so be sure to compile that code if either ISLOW or SCALING is requested. */ #ifdef DCT_ISLOW_SUPPORTED #define PROVIDE_ISLOW_TABLES #else #ifdef DCT_SCALING_SUPPORTED #define PROVIDE_ISLOW_TABLES #endif #endif /* * Perform forward DCT on one or more blocks of a component. * * The input samples are taken from the sample_data[] array starting at * position start_row/start_col, and moving to the right for any additional * blocks. The quantized coefficients are returned in coef_blocks[]. */ METHODDEF(void) forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY sample_data, JBLOCKROW coef_blocks, JDIMENSION start_row, JDIMENSION start_col, JDIMENSION num_blocks) /* This version is used for integer DCT implementations. */ { /* This routine is heavily used, so it's worth coding it tightly. */ my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; forward_DCT_method_ptr do_dct = fdct->do_dct[compptr->component_index]; DCTELEM * divisors = (DCTELEM *) compptr->dct_table; DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */ JDIMENSION bi; sample_data += start_row; /* fold in the vertical offset once */ for (bi = 0; bi < num_blocks; bi++, start_col += compptr->DCT_h_scaled_size) { /* Perform the DCT */ (*do_dct) (workspace, sample_data, start_col); /* Quantize/descale the coefficients, and store into coef_blocks[] */ { register DCTELEM temp, qval; register int i; register JCOEFPTR output_ptr = coef_blocks[bi]; for (i = 0; i < DCTSIZE2; i++) { qval = divisors[i]; temp = workspace[i]; /* Divide the coefficient value by qval, ensuring proper rounding. * Since C does not specify the direction of rounding for negative * quotients, we have to force the dividend positive for portability. * * In most files, at least half of the output values will be zero * (at default quantization settings, more like three-quarters...) * so we should ensure that this case is fast. On many machines, * a comparison is enough cheaper than a divide to make a special test * a win. Since both inputs will be nonnegative, we need only test * for a < b to discover whether a/b is 0. * If your machine's division is fast enough, define FAST_DIVIDE. */ #ifdef FAST_DIVIDE #define DIVIDE_BY(a,b) a /= b #else #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0 #endif if (temp < 0) { temp = -temp; temp += qval>>1; /* for rounding */ DIVIDE_BY(temp, qval); temp = -temp; } else { temp += qval>>1; /* for rounding */ DIVIDE_BY(temp, qval); } output_ptr[i] = (JCOEF) temp; } } } } #ifdef DCT_FLOAT_SUPPORTED METHODDEF(void) forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY sample_data, JBLOCKROW coef_blocks, JDIMENSION start_row, JDIMENSION start_col, JDIMENSION num_blocks) /* This version is used for floating-point DCT implementations. */ { /* This routine is heavily used, so it's worth coding it tightly. */ my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; float_DCT_method_ptr do_dct = fdct->do_float_dct[compptr->component_index]; FAST_FLOAT * divisors = (FAST_FLOAT *) compptr->dct_table; FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */ JDIMENSION bi; sample_data += start_row; /* fold in the vertical offset once */ for (bi = 0; bi < num_blocks; bi++, start_col += compptr->DCT_h_scaled_size) { /* Perform the DCT */ (*do_dct) (workspace, sample_data, start_col); /* Quantize/descale the coefficients, and store into coef_blocks[] */ { register FAST_FLOAT temp; register int i; register JCOEFPTR output_ptr = coef_blocks[bi]; for (i = 0; i < DCTSIZE2; i++) { /* Apply the quantization and scaling factor */ temp = workspace[i] * divisors[i]; /* Round to nearest integer. * Since C does not specify the direction of rounding for negative * quotients, we have to force the dividend positive for portability. * The maximum coefficient size is +-16K (for 12-bit data), so this * code should work for either 16-bit or 32-bit ints. */ output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384); } } } } #endif /* DCT_FLOAT_SUPPORTED */ /* * Initialize for a processing pass. * Verify that all referenced Q-tables are present, and set up * the divisor table for each one. * In the current implementation, DCT of all components is done during * the first pass, even if only some components will be output in the * first scan. Hence all components should be examined here. */ METHODDEF(void) start_pass_fdctmgr (j_compress_ptr cinfo) { my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; int ci, qtblno, i; jpeg_component_info *compptr; int method = 0; JQUANT_TBL * qtbl; DCTELEM * dtbl; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Select the proper DCT routine for this component's scaling */ switch ((compptr->DCT_h_scaled_size << 8) + compptr->DCT_v_scaled_size) { #ifdef DCT_SCALING_SUPPORTED case ((1 << 8) + 1): fdct->do_dct[ci] = jpeg_fdct_1x1; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((2 << 8) + 2): fdct->do_dct[ci] = jpeg_fdct_2x2; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((3 << 8) + 3): fdct->do_dct[ci] = jpeg_fdct_3x3; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((4 << 8) + 4): fdct->do_dct[ci] = jpeg_fdct_4x4; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((5 << 8) + 5): fdct->do_dct[ci] = jpeg_fdct_5x5; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((6 << 8) + 6): fdct->do_dct[ci] = jpeg_fdct_6x6; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((7 << 8) + 7): fdct->do_dct[ci] = jpeg_fdct_7x7; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((9 << 8) + 9): fdct->do_dct[ci] = jpeg_fdct_9x9; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((10 << 8) + 10): fdct->do_dct[ci] = jpeg_fdct_10x10; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((11 << 8) + 11): fdct->do_dct[ci] = jpeg_fdct_11x11; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((12 << 8) + 12): fdct->do_dct[ci] = jpeg_fdct_12x12; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((13 << 8) + 13): fdct->do_dct[ci] = jpeg_fdct_13x13; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((14 << 8) + 14): fdct->do_dct[ci] = jpeg_fdct_14x14; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((15 << 8) + 15): fdct->do_dct[ci] = jpeg_fdct_15x15; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((16 << 8) + 16): fdct->do_dct[ci] = jpeg_fdct_16x16; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((16 << 8) + 8): fdct->do_dct[ci] = jpeg_fdct_16x8; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((14 << 8) + 7): fdct->do_dct[ci] = jpeg_fdct_14x7; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((12 << 8) + 6): fdct->do_dct[ci] = jpeg_fdct_12x6; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((10 << 8) + 5): fdct->do_dct[ci] = jpeg_fdct_10x5; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((8 << 8) + 4): fdct->do_dct[ci] = jpeg_fdct_8x4; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((6 << 8) + 3): fdct->do_dct[ci] = jpeg_fdct_6x3; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((4 << 8) + 2): fdct->do_dct[ci] = jpeg_fdct_4x2; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((2 << 8) + 1): fdct->do_dct[ci] = jpeg_fdct_2x1; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((8 << 8) + 16): fdct->do_dct[ci] = jpeg_fdct_8x16; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((7 << 8) + 14): fdct->do_dct[ci] = jpeg_fdct_7x14; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((6 << 8) + 12): fdct->do_dct[ci] = jpeg_fdct_6x12; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((5 << 8) + 10): fdct->do_dct[ci] = jpeg_fdct_5x10; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((4 << 8) + 8): fdct->do_dct[ci] = jpeg_fdct_4x8; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((3 << 8) + 6): fdct->do_dct[ci] = jpeg_fdct_3x6; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((2 << 8) + 4): fdct->do_dct[ci] = jpeg_fdct_2x4; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; case ((1 << 8) + 2): fdct->do_dct[ci] = jpeg_fdct_1x2; method = JDCT_ISLOW; /* jfdctint uses islow-style table */ break; #endif case ((DCTSIZE << 8) + DCTSIZE): switch (cinfo->dct_method) { #ifdef DCT_ISLOW_SUPPORTED case JDCT_ISLOW: fdct->do_dct[ci] = jpeg_fdct_islow; method = JDCT_ISLOW; break; #endif #ifdef DCT_IFAST_SUPPORTED case JDCT_IFAST: fdct->do_dct[ci] = jpeg_fdct_ifast; method = JDCT_IFAST; break; #endif #ifdef DCT_FLOAT_SUPPORTED case JDCT_FLOAT: fdct->do_float_dct[ci] = jpeg_fdct_float; method = JDCT_FLOAT; break; #endif default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } break; default: ERREXIT2(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_h_scaled_size, compptr->DCT_v_scaled_size); break; } qtblno = compptr->quant_tbl_no; /* Make sure specified quantization table is present */ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || cinfo->quant_tbl_ptrs[qtblno] == NULL) ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno); qtbl = cinfo->quant_tbl_ptrs[qtblno]; /* Create divisor table from quant table */ switch (method) { #ifdef PROVIDE_ISLOW_TABLES case JDCT_ISLOW: /* For LL&M IDCT method, divisors are equal to raw quantization * coefficients multiplied by 8 (to counteract scaling). */ dtbl = (DCTELEM *) compptr->dct_table; for (i = 0; i < DCTSIZE2; i++) { dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << (compptr->component_needed ? 4 : 3); } fdct->pub.forward_DCT[ci] = forward_DCT; break; #endif #ifdef DCT_IFAST_SUPPORTED case JDCT_IFAST: { /* For AA&N IDCT method, divisors are equal to quantization * coefficients scaled by scalefactor[row]*scalefactor[col], where * scalefactor[0] = 1 * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 * We apply a further scale factor of 8. */ #define CONST_BITS 14 static const INT16 aanscales[DCTSIZE2] = { /* precomputed values scaled up by 14 bits */ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 }; SHIFT_TEMPS dtbl = (DCTELEM *) compptr->dct_table; for (i = 0; i < DCTSIZE2; i++) { dtbl[i] = (DCTELEM) DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i], (INT32) aanscales[i]), compptr->component_needed ? CONST_BITS-4 : CONST_BITS-3); } } fdct->pub.forward_DCT[ci] = forward_DCT; break; #endif #ifdef DCT_FLOAT_SUPPORTED case JDCT_FLOAT: { /* For float AA&N IDCT method, divisors are equal to quantization * coefficients scaled by scalefactor[row]*scalefactor[col], where * scalefactor[0] = 1 * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 * We apply a further scale factor of 8. * What's actually stored is 1/divisor so that the inner loop can * use a multiplication rather than a division. */ FAST_FLOAT * fdtbl = (FAST_FLOAT *) compptr->dct_table; int row, col; static const double aanscalefactor[DCTSIZE] = { 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 }; i = 0; for (row = 0; row < DCTSIZE; row++) { for (col = 0; col < DCTSIZE; col++) { fdtbl[i] = (FAST_FLOAT) (1.0 / ((double) qtbl->quantval[i] * aanscalefactor[row] * aanscalefactor[col] * (compptr->component_needed ? 16.0 : 8.0))); i++; } } } fdct->pub.forward_DCT[ci] = forward_DCT_float; break; #endif default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } } } /* * Initialize FDCT manager. */ GLOBAL(void) jinit_forward_dct (j_compress_ptr cinfo) { my_fdct_ptr fdct; int ci; jpeg_component_info *compptr; fdct = (my_fdct_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_fdct_controller)); cinfo->fdct = &fdct->pub; fdct->pub.start_pass = start_pass_fdctmgr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Allocate a divisor table for each component */ compptr->dct_table = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(divisor_table)); } } ================================================ FILE: tess-two/jni/libjpeg/jchuff.c ================================================ /* * jchuff.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2006-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains Huffman entropy encoding routines. * Both sequential and progressive modes are supported in this single module. * * Much of the complexity here has to do with supporting output suspension. * If the data destination module demands suspension, we want to be able to * back up to the start of the current MCU. To do this, we copy state * variables into local working storage, and update them back to the * permanent JPEG objects only upon successful completion of an MCU. * * We do not support output suspension for the progressive JPEG mode, since * the library currently does not allow multiple-scan files to be written * with output suspension. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* The legal range of a DCT coefficient is * -1024 .. +1023 for 8-bit data; * -16384 .. +16383 for 12-bit data. * Hence the magnitude should always fit in 10 or 14 bits respectively. */ #if BITS_IN_JSAMPLE == 8 #define MAX_COEF_BITS 10 #else #define MAX_COEF_BITS 14 #endif /* Derived data constructed for each Huffman table */ typedef struct { unsigned int ehufco[256]; /* code for each symbol */ char ehufsi[256]; /* length of code for each symbol */ /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */ } c_derived_tbl; /* Expanded entropy encoder object for Huffman encoding. * * The savable_state subrecord contains fields that change within an MCU, * but must not be updated permanently until we complete the MCU. */ typedef struct { INT32 put_buffer; /* current bit-accumulation buffer */ int put_bits; /* # of bits now in it */ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ } savable_state; /* This macro is to work around compilers with missing or broken * structure assignment. You'll need to fix this code if you have * such a compiler and you change MAX_COMPS_IN_SCAN. */ #ifndef NO_STRUCT_ASSIGN #define ASSIGN_STATE(dest,src) ((dest) = (src)) #else #if MAX_COMPS_IN_SCAN == 4 #define ASSIGN_STATE(dest,src) \ ((dest).put_buffer = (src).put_buffer, \ (dest).put_bits = (src).put_bits, \ (dest).last_dc_val[0] = (src).last_dc_val[0], \ (dest).last_dc_val[1] = (src).last_dc_val[1], \ (dest).last_dc_val[2] = (src).last_dc_val[2], \ (dest).last_dc_val[3] = (src).last_dc_val[3]) #endif #endif typedef struct { struct jpeg_entropy_encoder pub; /* public fields */ savable_state saved; /* Bit buffer & DC state at start of MCU */ /* These fields are NOT loaded into local working state. */ unsigned int restarts_to_go; /* MCUs left in this restart interval */ int next_restart_num; /* next restart number to write (0-7) */ /* Pointers to derived tables (these workspaces have image lifespan) */ c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; /* Statistics tables for optimization */ long * dc_count_ptrs[NUM_HUFF_TBLS]; long * ac_count_ptrs[NUM_HUFF_TBLS]; /* Following fields used only in progressive mode */ /* Mode flag: TRUE for optimization, FALSE for actual data output */ boolean gather_statistics; /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields. */ JOCTET * next_output_byte; /* => next byte to write in buffer */ size_t free_in_buffer; /* # of byte spaces remaining in buffer */ j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */ /* Coding status for AC components */ int ac_tbl_no; /* the table number of the single component */ unsigned int EOBRUN; /* run length of EOBs */ unsigned int BE; /* # of buffered correction bits before MCU */ char * bit_buffer; /* buffer for correction bits (1 per char) */ /* packing correction bits tightly would save some space but cost time... */ } huff_entropy_encoder; typedef huff_entropy_encoder * huff_entropy_ptr; /* Working state while writing an MCU (sequential mode). * This struct contains all the fields that are needed by subroutines. */ typedef struct { JOCTET * next_output_byte; /* => next byte to write in buffer */ size_t free_in_buffer; /* # of byte spaces remaining in buffer */ savable_state cur; /* Current bit buffer & DC state */ j_compress_ptr cinfo; /* dump_buffer needs access to this */ } working_state; /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit * buffer can hold. Larger sizes may slightly improve compression, but * 1000 is already well into the realm of overkill. * The minimum safe size is 64 bits. */ #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */ /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32. * We assume that int right shift is unsigned if INT32 right shift is, * which should be safe. */ #ifdef RIGHT_SHIFT_IS_UNSIGNED #define ISHIFT_TEMPS int ishift_temp; #define IRIGHT_SHIFT(x,shft) \ ((ishift_temp = (x)) < 0 ? \ (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \ (ishift_temp >> (shft))) #else #define ISHIFT_TEMPS #define IRIGHT_SHIFT(x,shft) ((x) >> (shft)) #endif /* * Compute the derived values for a Huffman table. * This routine also performs some validation checks on the table. */ LOCAL(void) jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno, c_derived_tbl ** pdtbl) { JHUFF_TBL *htbl; c_derived_tbl *dtbl; int p, i, l, lastp, si, maxsymbol; char huffsize[257]; unsigned int huffcode[257]; unsigned int code; /* Note that huffsize[] and huffcode[] are filled in code-length order, * paralleling the order of the symbols themselves in htbl->huffval[]. */ /* Find the input Huffman table */ if (tblno < 0 || tblno >= NUM_HUFF_TBLS) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); htbl = isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno]; if (htbl == NULL) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); /* Allocate a workspace if we haven't already done so. */ if (*pdtbl == NULL) *pdtbl = (c_derived_tbl *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(c_derived_tbl)); dtbl = *pdtbl; /* Figure C.1: make table of Huffman code length for each symbol */ p = 0; for (l = 1; l <= 16; l++) { i = (int) htbl->bits[l]; if (i < 0 || p + i > 256) /* protect against table overrun */ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); while (i--) huffsize[p++] = (char) l; } huffsize[p] = 0; lastp = p; /* Figure C.2: generate the codes themselves */ /* We also validate that the counts represent a legal Huffman code tree. */ code = 0; si = huffsize[0]; p = 0; while (huffsize[p]) { while (((int) huffsize[p]) == si) { huffcode[p++] = code; code++; } /* code is now 1 more than the last code used for codelength si; but * it must still fit in si bits, since no code is allowed to be all ones. */ if (((INT32) code) >= (((INT32) 1) << si)) ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); code <<= 1; si++; } /* Figure C.3: generate encoding tables */ /* These are code and size indexed by symbol value */ /* Set all codeless symbols to have code length 0; * this lets us detect duplicate VAL entries here, and later * allows emit_bits to detect any attempt to emit such symbols. */ MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi)); /* This is also a convenient place to check for out-of-range * and duplicated VAL entries. We allow 0..255 for AC symbols * but only 0..15 for DC. (We could constrain them further * based on data depth and mode, but this seems enough.) */ maxsymbol = isDC ? 15 : 255; for (p = 0; p < lastp; p++) { i = htbl->huffval[p]; if (i < 0 || i > maxsymbol || dtbl->ehufsi[i]) ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); dtbl->ehufco[i] = huffcode[p]; dtbl->ehufsi[i] = huffsize[p]; } } /* Outputting bytes to the file. * NB: these must be called only when actually outputting, * that is, entropy->gather_statistics == FALSE. */ /* Emit a byte, taking 'action' if must suspend. */ #define emit_byte_s(state,val,action) \ { *(state)->next_output_byte++ = (JOCTET) (val); \ if (--(state)->free_in_buffer == 0) \ if (! dump_buffer_s(state)) \ { action; } } /* Emit a byte */ #define emit_byte_e(entropy,val) \ { *(entropy)->next_output_byte++ = (JOCTET) (val); \ if (--(entropy)->free_in_buffer == 0) \ dump_buffer_e(entropy); } LOCAL(boolean) dump_buffer_s (working_state * state) /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */ { struct jpeg_destination_mgr * dest = state->cinfo->dest; if (! (*dest->empty_output_buffer) (state->cinfo)) return FALSE; /* After a successful buffer dump, must reset buffer pointers */ state->next_output_byte = dest->next_output_byte; state->free_in_buffer = dest->free_in_buffer; return TRUE; } LOCAL(void) dump_buffer_e (huff_entropy_ptr entropy) /* Empty the output buffer; we do not support suspension in this case. */ { struct jpeg_destination_mgr * dest = entropy->cinfo->dest; if (! (*dest->empty_output_buffer) (entropy->cinfo)) ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND); /* After a successful buffer dump, must reset buffer pointers */ entropy->next_output_byte = dest->next_output_byte; entropy->free_in_buffer = dest->free_in_buffer; } /* Outputting bits to the file */ /* Only the right 24 bits of put_buffer are used; the valid bits are * left-justified in this part. At most 16 bits can be passed to emit_bits * in one call, and we never retain more than 7 bits in put_buffer * between calls, so 24 bits are sufficient. */ INLINE LOCAL(boolean) emit_bits_s (working_state * state, unsigned int code, int size) /* Emit some bits; return TRUE if successful, FALSE if must suspend */ { /* This routine is heavily used, so it's worth coding tightly. */ register INT32 put_buffer; register int put_bits; /* if size is 0, caller used an invalid Huffman table entry */ if (size == 0) ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE); /* mask off any extra bits in code */ put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1); /* new number of bits in buffer */ put_bits = size + state->cur.put_bits; put_buffer <<= 24 - put_bits; /* align incoming bits */ /* and merge with old buffer contents */ put_buffer |= state->cur.put_buffer; while (put_bits >= 8) { int c = (int) ((put_buffer >> 16) & 0xFF); emit_byte_s(state, c, return FALSE); if (c == 0xFF) { /* need to stuff a zero byte? */ emit_byte_s(state, 0, return FALSE); } put_buffer <<= 8; put_bits -= 8; } state->cur.put_buffer = put_buffer; /* update state variables */ state->cur.put_bits = put_bits; return TRUE; } INLINE LOCAL(void) emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size) /* Emit some bits, unless we are in gather mode */ { /* This routine is heavily used, so it's worth coding tightly. */ register INT32 put_buffer; register int put_bits; /* if size is 0, caller used an invalid Huffman table entry */ if (size == 0) ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE); if (entropy->gather_statistics) return; /* do nothing if we're only getting stats */ /* mask off any extra bits in code */ put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1); /* new number of bits in buffer */ put_bits = size + entropy->saved.put_bits; put_buffer <<= 24 - put_bits; /* align incoming bits */ /* and merge with old buffer contents */ put_buffer |= entropy->saved.put_buffer; while (put_bits >= 8) { int c = (int) ((put_buffer >> 16) & 0xFF); emit_byte_e(entropy, c); if (c == 0xFF) { /* need to stuff a zero byte? */ emit_byte_e(entropy, 0); } put_buffer <<= 8; put_bits -= 8; } entropy->saved.put_buffer = put_buffer; /* update variables */ entropy->saved.put_bits = put_bits; } LOCAL(boolean) flush_bits_s (working_state * state) { if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */ return FALSE; state->cur.put_buffer = 0; /* and reset bit-buffer to empty */ state->cur.put_bits = 0; return TRUE; } LOCAL(void) flush_bits_e (huff_entropy_ptr entropy) { emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */ entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */ entropy->saved.put_bits = 0; } /* * Emit (or just count) a Huffman symbol. */ INLINE LOCAL(void) emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol) { if (entropy->gather_statistics) entropy->dc_count_ptrs[tbl_no][symbol]++; else { c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no]; emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]); } } INLINE LOCAL(void) emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol) { if (entropy->gather_statistics) entropy->ac_count_ptrs[tbl_no][symbol]++; else { c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no]; emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]); } } /* * Emit bits from a correction bit buffer. */ LOCAL(void) emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart, unsigned int nbits) { if (entropy->gather_statistics) return; /* no real work */ while (nbits > 0) { emit_bits_e(entropy, (unsigned int) (*bufstart), 1); bufstart++; nbits--; } } /* * Emit any pending EOBRUN symbol. */ LOCAL(void) emit_eobrun (huff_entropy_ptr entropy) { register int temp, nbits; if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */ temp = entropy->EOBRUN; nbits = 0; while ((temp >>= 1)) nbits++; /* safety check: shouldn't happen given limited correction-bit buffer */ if (nbits > 14) ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE); emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4); if (nbits) emit_bits_e(entropy, entropy->EOBRUN, nbits); entropy->EOBRUN = 0; /* Emit any buffered correction bits */ emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE); entropy->BE = 0; } } /* * Emit a restart marker & resynchronize predictions. */ LOCAL(boolean) emit_restart_s (working_state * state, int restart_num) { int ci; if (! flush_bits_s(state)) return FALSE; emit_byte_s(state, 0xFF, return FALSE); emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE); /* Re-initialize DC predictions to 0 */ for (ci = 0; ci < state->cinfo->comps_in_scan; ci++) state->cur.last_dc_val[ci] = 0; /* The restart counter is not updated until we successfully write the MCU. */ return TRUE; } LOCAL(void) emit_restart_e (huff_entropy_ptr entropy, int restart_num) { int ci; emit_eobrun(entropy); if (! entropy->gather_statistics) { flush_bits_e(entropy); emit_byte_e(entropy, 0xFF); emit_byte_e(entropy, JPEG_RST0 + restart_num); } if (entropy->cinfo->Ss == 0) { /* Re-initialize DC predictions to 0 */ for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++) entropy->saved.last_dc_val[ci] = 0; } else { /* Re-initialize all AC-related fields to 0 */ entropy->EOBRUN = 0; entropy->BE = 0; } } /* * MCU encoding for DC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; register int temp, temp2; register int nbits; int blkn, ci, tbl; ISHIFT_TEMPS entropy->next_output_byte = cinfo->dest->next_output_byte; entropy->free_in_buffer = cinfo->dest->free_in_buffer; /* Emit restart marker if needed */ if (cinfo->restart_interval) if (entropy->restarts_to_go == 0) emit_restart_e(entropy, entropy->next_restart_num); /* Encode the MCU data blocks */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { ci = cinfo->MCU_membership[blkn]; tbl = cinfo->cur_comp_info[ci]->dc_tbl_no; /* Compute the DC value after the required point transform by Al. * This is simply an arithmetic right shift. */ temp = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al); /* DC differences are figured on the point-transformed values. */ temp2 = temp - entropy->saved.last_dc_val[ci]; entropy->saved.last_dc_val[ci] = temp; /* Encode the DC coefficient difference per section G.1.2.1 */ temp = temp2; if (temp < 0) { temp = -temp; /* temp is abs value of input */ /* For a negative input, want temp2 = bitwise complement of abs(input) */ /* This code assumes we are on a two's complement machine */ temp2--; } /* Find the number of bits needed for the magnitude of the coefficient */ nbits = 0; while (temp) { nbits++; temp >>= 1; } /* Check for out-of-range coefficient values. * Since we're encoding a difference, the range limit is twice as much. */ if (nbits > MAX_COEF_BITS+1) ERREXIT(cinfo, JERR_BAD_DCT_COEF); /* Count/emit the Huffman-coded symbol for the number of bits */ emit_dc_symbol(entropy, tbl, nbits); /* Emit that number of bits of the value, if positive, */ /* or the complement of its magnitude, if negative. */ if (nbits) /* emit_bits rejects calls with size 0 */ emit_bits_e(entropy, (unsigned int) temp2, nbits); } cinfo->dest->next_output_byte = entropy->next_output_byte; cinfo->dest->free_in_buffer = entropy->free_in_buffer; /* Update restart-interval state too */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } return TRUE; } /* * MCU encoding for AC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; const int * natural_order; JBLOCKROW block; register int temp, temp2; register int nbits; register int r, k; int Se, Al; entropy->next_output_byte = cinfo->dest->next_output_byte; entropy->free_in_buffer = cinfo->dest->free_in_buffer; /* Emit restart marker if needed */ if (cinfo->restart_interval) if (entropy->restarts_to_go == 0) emit_restart_e(entropy, entropy->next_restart_num); Se = cinfo->Se; Al = cinfo->Al; natural_order = cinfo->natural_order; /* Encode the MCU data block */ block = MCU_data[0]; /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */ r = 0; /* r = run length of zeros */ for (k = cinfo->Ss; k <= Se; k++) { if ((temp = (*block)[natural_order[k]]) == 0) { r++; continue; } /* We must apply the point transform by Al. For AC coefficients this * is an integer division with rounding towards 0. To do this portably * in C, we shift after obtaining the absolute value; so the code is * interwoven with finding the abs value (temp) and output bits (temp2). */ if (temp < 0) { temp = -temp; /* temp is abs value of input */ temp >>= Al; /* apply the point transform */ /* For a negative coef, want temp2 = bitwise complement of abs(coef) */ temp2 = ~temp; } else { temp >>= Al; /* apply the point transform */ temp2 = temp; } /* Watch out for case that nonzero coef is zero after point transform */ if (temp == 0) { r++; continue; } /* Emit any pending EOBRUN */ if (entropy->EOBRUN > 0) emit_eobrun(entropy); /* if run length > 15, must emit special run-length-16 codes (0xF0) */ while (r > 15) { emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0); r -= 16; } /* Find the number of bits needed for the magnitude of the coefficient */ nbits = 1; /* there must be at least one 1 bit */ while ((temp >>= 1)) nbits++; /* Check for out-of-range coefficient values */ if (nbits > MAX_COEF_BITS) ERREXIT(cinfo, JERR_BAD_DCT_COEF); /* Count/emit Huffman symbol for run length / number of bits */ emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits); /* Emit that number of bits of the value, if positive, */ /* or the complement of its magnitude, if negative. */ emit_bits_e(entropy, (unsigned int) temp2, nbits); r = 0; /* reset zero run length */ } if (r > 0) { /* If there are trailing zeroes, */ entropy->EOBRUN++; /* count an EOB */ if (entropy->EOBRUN == 0x7FFF) emit_eobrun(entropy); /* force it out to avoid overflow */ } cinfo->dest->next_output_byte = entropy->next_output_byte; cinfo->dest->free_in_buffer = entropy->free_in_buffer; /* Update restart-interval state too */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } return TRUE; } /* * MCU encoding for DC successive approximation refinement scan. * Note: we assume such scans can be multi-component, * although the spec is not very clear on the point. */ METHODDEF(boolean) encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int Al, blkn; entropy->next_output_byte = cinfo->dest->next_output_byte; entropy->free_in_buffer = cinfo->dest->free_in_buffer; /* Emit restart marker if needed */ if (cinfo->restart_interval) if (entropy->restarts_to_go == 0) emit_restart_e(entropy, entropy->next_restart_num); Al = cinfo->Al; /* Encode the MCU data blocks */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { /* We simply emit the Al'th bit of the DC coefficient value. */ emit_bits_e(entropy, (unsigned int) (MCU_data[blkn][0][0] >> Al), 1); } cinfo->dest->next_output_byte = entropy->next_output_byte; cinfo->dest->free_in_buffer = entropy->free_in_buffer; /* Update restart-interval state too */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } return TRUE; } /* * MCU encoding for AC successive approximation refinement scan. */ METHODDEF(boolean) encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; const int * natural_order; JBLOCKROW block; register int temp; register int r, k; int Se, Al; int EOB; char *BR_buffer; unsigned int BR; int absvalues[DCTSIZE2]; entropy->next_output_byte = cinfo->dest->next_output_byte; entropy->free_in_buffer = cinfo->dest->free_in_buffer; /* Emit restart marker if needed */ if (cinfo->restart_interval) if (entropy->restarts_to_go == 0) emit_restart_e(entropy, entropy->next_restart_num); Se = cinfo->Se; Al = cinfo->Al; natural_order = cinfo->natural_order; /* Encode the MCU data block */ block = MCU_data[0]; /* It is convenient to make a pre-pass to determine the transformed * coefficients' absolute values and the EOB position. */ EOB = 0; for (k = cinfo->Ss; k <= Se; k++) { temp = (*block)[natural_order[k]]; /* We must apply the point transform by Al. For AC coefficients this * is an integer division with rounding towards 0. To do this portably * in C, we shift after obtaining the absolute value. */ if (temp < 0) temp = -temp; /* temp is abs value of input */ temp >>= Al; /* apply the point transform */ absvalues[k] = temp; /* save abs value for main pass */ if (temp == 1) EOB = k; /* EOB = index of last newly-nonzero coef */ } /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */ r = 0; /* r = run length of zeros */ BR = 0; /* BR = count of buffered bits added now */ BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */ for (k = cinfo->Ss; k <= Se; k++) { if ((temp = absvalues[k]) == 0) { r++; continue; } /* Emit any required ZRLs, but not if they can be folded into EOB */ while (r > 15 && k <= EOB) { /* emit any pending EOBRUN and the BE correction bits */ emit_eobrun(entropy); /* Emit ZRL */ emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0); r -= 16; /* Emit buffered correction bits that must be associated with ZRL */ emit_buffered_bits(entropy, BR_buffer, BR); BR_buffer = entropy->bit_buffer; /* BE bits are gone now */ BR = 0; } /* If the coef was previously nonzero, it only needs a correction bit. * NOTE: a straight translation of the spec's figure G.7 would suggest * that we also need to test r > 15. But if r > 15, we can only get here * if k > EOB, which implies that this coefficient is not 1. */ if (temp > 1) { /* The correction bit is the next bit of the absolute value. */ BR_buffer[BR++] = (char) (temp & 1); continue; } /* Emit any pending EOBRUN and the BE correction bits */ emit_eobrun(entropy); /* Count/emit Huffman symbol for run length / number of bits */ emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1); /* Emit output bit for newly-nonzero coef */ temp = ((*block)[natural_order[k]] < 0) ? 0 : 1; emit_bits_e(entropy, (unsigned int) temp, 1); /* Emit buffered correction bits that must be associated with this code */ emit_buffered_bits(entropy, BR_buffer, BR); BR_buffer = entropy->bit_buffer; /* BE bits are gone now */ BR = 0; r = 0; /* reset zero run length */ } if (r > 0 || BR > 0) { /* If there are trailing zeroes, */ entropy->EOBRUN++; /* count an EOB */ entropy->BE += BR; /* concat my correction bits to older ones */ /* We force out the EOB if we risk either: * 1. overflow of the EOB counter; * 2. overflow of the correction bit buffer during the next MCU. */ if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1)) emit_eobrun(entropy); } cinfo->dest->next_output_byte = entropy->next_output_byte; cinfo->dest->free_in_buffer = entropy->free_in_buffer; /* Update restart-interval state too */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } return TRUE; } /* Encode a single block's worth of coefficients */ LOCAL(boolean) encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val, c_derived_tbl *dctbl, c_derived_tbl *actbl) { register int temp, temp2; register int nbits; register int r, k; int Se = state->cinfo->lim_Se; const int * natural_order = state->cinfo->natural_order; /* Encode the DC coefficient difference per section F.1.2.1 */ temp = temp2 = block[0] - last_dc_val; if (temp < 0) { temp = -temp; /* temp is abs value of input */ /* For a negative input, want temp2 = bitwise complement of abs(input) */ /* This code assumes we are on a two's complement machine */ temp2--; } /* Find the number of bits needed for the magnitude of the coefficient */ nbits = 0; while (temp) { nbits++; temp >>= 1; } /* Check for out-of-range coefficient values. * Since we're encoding a difference, the range limit is twice as much. */ if (nbits > MAX_COEF_BITS+1) ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); /* Emit the Huffman-coded symbol for the number of bits */ if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits])) return FALSE; /* Emit that number of bits of the value, if positive, */ /* or the complement of its magnitude, if negative. */ if (nbits) /* emit_bits rejects calls with size 0 */ if (! emit_bits_s(state, (unsigned int) temp2, nbits)) return FALSE; /* Encode the AC coefficients per section F.1.2.2 */ r = 0; /* r = run length of zeros */ for (k = 1; k <= Se; k++) { if ((temp2 = block[natural_order[k]]) == 0) { r++; } else { /* if run length > 15, must emit special run-length-16 codes (0xF0) */ while (r > 15) { if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0])) return FALSE; r -= 16; } temp = temp2; if (temp < 0) { temp = -temp; /* temp is abs value of input */ /* This code assumes we are on a two's complement machine */ temp2--; } /* Find the number of bits needed for the magnitude of the coefficient */ nbits = 1; /* there must be at least one 1 bit */ while ((temp >>= 1)) nbits++; /* Check for out-of-range coefficient values */ if (nbits > MAX_COEF_BITS) ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); /* Emit Huffman symbol for run length / number of bits */ temp = (r << 4) + nbits; if (! emit_bits_s(state, actbl->ehufco[temp], actbl->ehufsi[temp])) return FALSE; /* Emit that number of bits of the value, if positive, */ /* or the complement of its magnitude, if negative. */ if (! emit_bits_s(state, (unsigned int) temp2, nbits)) return FALSE; r = 0; } } /* If the last coef(s) were zero, emit an end-of-block code */ if (r > 0) if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0])) return FALSE; return TRUE; } /* * Encode and output one MCU's worth of Huffman-compressed coefficients. */ METHODDEF(boolean) encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; working_state state; int blkn, ci; jpeg_component_info * compptr; /* Load up working state */ state.next_output_byte = cinfo->dest->next_output_byte; state.free_in_buffer = cinfo->dest->free_in_buffer; ASSIGN_STATE(state.cur, entropy->saved); state.cinfo = cinfo; /* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! emit_restart_s(&state, entropy->next_restart_num)) return FALSE; } /* Encode the MCU data blocks */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { ci = cinfo->MCU_membership[blkn]; compptr = cinfo->cur_comp_info[ci]; if (! encode_one_block(&state, MCU_data[blkn][0], state.cur.last_dc_val[ci], entropy->dc_derived_tbls[compptr->dc_tbl_no], entropy->ac_derived_tbls[compptr->ac_tbl_no])) return FALSE; /* Update last_dc_val */ state.cur.last_dc_val[ci] = MCU_data[blkn][0][0]; } /* Completed MCU, so update state */ cinfo->dest->next_output_byte = state.next_output_byte; cinfo->dest->free_in_buffer = state.free_in_buffer; ASSIGN_STATE(entropy->saved, state.cur); /* Update restart-interval state too */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } return TRUE; } /* * Finish up at the end of a Huffman-compressed scan. */ METHODDEF(void) finish_pass_huff (j_compress_ptr cinfo) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; working_state state; if (cinfo->progressive_mode) { entropy->next_output_byte = cinfo->dest->next_output_byte; entropy->free_in_buffer = cinfo->dest->free_in_buffer; /* Flush out any buffered data */ emit_eobrun(entropy); flush_bits_e(entropy); cinfo->dest->next_output_byte = entropy->next_output_byte; cinfo->dest->free_in_buffer = entropy->free_in_buffer; } else { /* Load up working state ... flush_bits needs it */ state.next_output_byte = cinfo->dest->next_output_byte; state.free_in_buffer = cinfo->dest->free_in_buffer; ASSIGN_STATE(state.cur, entropy->saved); state.cinfo = cinfo; /* Flush out the last data */ if (! flush_bits_s(&state)) ERREXIT(cinfo, JERR_CANT_SUSPEND); /* Update state */ cinfo->dest->next_output_byte = state.next_output_byte; cinfo->dest->free_in_buffer = state.free_in_buffer; ASSIGN_STATE(entropy->saved, state.cur); } } /* * Huffman coding optimization. * * We first scan the supplied data and count the number of uses of each symbol * that is to be Huffman-coded. (This process MUST agree with the code above.) * Then we build a Huffman coding tree for the observed counts. * Symbols which are not needed at all for the particular image are not * assigned any code, which saves space in the DHT marker as well as in * the compressed data. */ /* Process a single block's worth of coefficients */ LOCAL(void) htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val, long dc_counts[], long ac_counts[]) { register int temp; register int nbits; register int r, k; int Se = cinfo->lim_Se; const int * natural_order = cinfo->natural_order; /* Encode the DC coefficient difference per section F.1.2.1 */ temp = block[0] - last_dc_val; if (temp < 0) temp = -temp; /* Find the number of bits needed for the magnitude of the coefficient */ nbits = 0; while (temp) { nbits++; temp >>= 1; } /* Check for out-of-range coefficient values. * Since we're encoding a difference, the range limit is twice as much. */ if (nbits > MAX_COEF_BITS+1) ERREXIT(cinfo, JERR_BAD_DCT_COEF); /* Count the Huffman symbol for the number of bits */ dc_counts[nbits]++; /* Encode the AC coefficients per section F.1.2.2 */ r = 0; /* r = run length of zeros */ for (k = 1; k <= Se; k++) { if ((temp = block[natural_order[k]]) == 0) { r++; } else { /* if run length > 15, must emit special run-length-16 codes (0xF0) */ while (r > 15) { ac_counts[0xF0]++; r -= 16; } /* Find the number of bits needed for the magnitude of the coefficient */ if (temp < 0) temp = -temp; /* Find the number of bits needed for the magnitude of the coefficient */ nbits = 1; /* there must be at least one 1 bit */ while ((temp >>= 1)) nbits++; /* Check for out-of-range coefficient values */ if (nbits > MAX_COEF_BITS) ERREXIT(cinfo, JERR_BAD_DCT_COEF); /* Count Huffman symbol for run length / number of bits */ ac_counts[(r << 4) + nbits]++; r = 0; } } /* If the last coef(s) were zero, emit an end-of-block code */ if (r > 0) ac_counts[0]++; } /* * Trial-encode one MCU's worth of Huffman-compressed coefficients. * No data is actually output, so no suspension return is possible. */ METHODDEF(boolean) encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int blkn, ci; jpeg_component_info * compptr; /* Take care of restart intervals if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { /* Re-initialize DC predictions to 0 */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) entropy->saved.last_dc_val[ci] = 0; /* Update restart state */ entropy->restarts_to_go = cinfo->restart_interval; } entropy->restarts_to_go--; } for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { ci = cinfo->MCU_membership[blkn]; compptr = cinfo->cur_comp_info[ci]; htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci], entropy->dc_count_ptrs[compptr->dc_tbl_no], entropy->ac_count_ptrs[compptr->ac_tbl_no]); entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0]; } return TRUE; } /* * Generate the best Huffman code table for the given counts, fill htbl. * * The JPEG standard requires that no symbol be assigned a codeword of all * one bits (so that padding bits added at the end of a compressed segment * can't look like a valid code). Because of the canonical ordering of * codewords, this just means that there must be an unused slot in the * longest codeword length category. Section K.2 of the JPEG spec suggests * reserving such a slot by pretending that symbol 256 is a valid symbol * with count 1. In theory that's not optimal; giving it count zero but * including it in the symbol set anyway should give a better Huffman code. * But the theoretically better code actually seems to come out worse in * practice, because it produces more all-ones bytes (which incur stuffed * zero bytes in the final file). In any case the difference is tiny. * * The JPEG standard requires Huffman codes to be no more than 16 bits long. * If some symbols have a very small but nonzero probability, the Huffman tree * must be adjusted to meet the code length restriction. We currently use * the adjustment method suggested in JPEG section K.2. This method is *not* * optimal; it may not choose the best possible limited-length code. But * typically only very-low-frequency symbols will be given less-than-optimal * lengths, so the code is almost optimal. Experimental comparisons against * an optimal limited-length-code algorithm indicate that the difference is * microscopic --- usually less than a hundredth of a percent of total size. * So the extra complexity of an optimal algorithm doesn't seem worthwhile. */ LOCAL(void) jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]) { #define MAX_CLEN 32 /* assumed maximum initial code length */ UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */ int codesize[257]; /* codesize[k] = code length of symbol k */ int others[257]; /* next symbol in current branch of tree */ int c1, c2; int p, i, j; long v; /* This algorithm is explained in section K.2 of the JPEG standard */ MEMZERO(bits, SIZEOF(bits)); MEMZERO(codesize, SIZEOF(codesize)); for (i = 0; i < 257; i++) others[i] = -1; /* init links to empty */ freq[256] = 1; /* make sure 256 has a nonzero count */ /* Including the pseudo-symbol 256 in the Huffman procedure guarantees * that no real symbol is given code-value of all ones, because 256 * will be placed last in the largest codeword category. */ /* Huffman's basic algorithm to assign optimal code lengths to symbols */ for (;;) { /* Find the smallest nonzero frequency, set c1 = its symbol */ /* In case of ties, take the larger symbol number */ c1 = -1; v = 1000000000L; for (i = 0; i <= 256; i++) { if (freq[i] && freq[i] <= v) { v = freq[i]; c1 = i; } } /* Find the next smallest nonzero frequency, set c2 = its symbol */ /* In case of ties, take the larger symbol number */ c2 = -1; v = 1000000000L; for (i = 0; i <= 256; i++) { if (freq[i] && freq[i] <= v && i != c1) { v = freq[i]; c2 = i; } } /* Done if we've merged everything into one frequency */ if (c2 < 0) break; /* Else merge the two counts/trees */ freq[c1] += freq[c2]; freq[c2] = 0; /* Increment the codesize of everything in c1's tree branch */ codesize[c1]++; while (others[c1] >= 0) { c1 = others[c1]; codesize[c1]++; } others[c1] = c2; /* chain c2 onto c1's tree branch */ /* Increment the codesize of everything in c2's tree branch */ codesize[c2]++; while (others[c2] >= 0) { c2 = others[c2]; codesize[c2]++; } } /* Now count the number of symbols of each code length */ for (i = 0; i <= 256; i++) { if (codesize[i]) { /* The JPEG standard seems to think that this can't happen, */ /* but I'm paranoid... */ if (codesize[i] > MAX_CLEN) ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW); bits[codesize[i]]++; } } /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure * Huffman procedure assigned any such lengths, we must adjust the coding. * Here is what the JPEG spec says about how this next bit works: * Since symbols are paired for the longest Huffman code, the symbols are * removed from this length category two at a time. The prefix for the pair * (which is one bit shorter) is allocated to one of the pair; then, * skipping the BITS entry for that prefix length, a code word from the next * shortest nonzero BITS entry is converted into a prefix for two code words * one bit longer. */ for (i = MAX_CLEN; i > 16; i--) { while (bits[i] > 0) { j = i - 2; /* find length of new prefix to be used */ while (bits[j] == 0) j--; bits[i] -= 2; /* remove two symbols */ bits[i-1]++; /* one goes in this length */ bits[j+1] += 2; /* two new symbols in this length */ bits[j]--; /* symbol of this length is now a prefix */ } } /* Remove the count for the pseudo-symbol 256 from the largest codelength */ while (bits[i] == 0) /* find largest codelength still in use */ i--; bits[i]--; /* Return final symbol counts (only for lengths 0..16) */ MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits)); /* Return a list of the symbols sorted by code length */ /* It's not real clear to me why we don't need to consider the codelength * changes made above, but the JPEG spec seems to think this works. */ p = 0; for (i = 1; i <= MAX_CLEN; i++) { for (j = 0; j <= 255; j++) { if (codesize[j] == i) { htbl->huffval[p] = (UINT8) j; p++; } } } /* Set sent_table FALSE so updated table will be written to JPEG file. */ htbl->sent_table = FALSE; } /* * Finish up a statistics-gathering pass and create the new Huffman tables. */ METHODDEF(void) finish_pass_gather (j_compress_ptr cinfo) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int ci, tbl; jpeg_component_info * compptr; JHUFF_TBL **htblptr; boolean did_dc[NUM_HUFF_TBLS]; boolean did_ac[NUM_HUFF_TBLS]; /* It's important not to apply jpeg_gen_optimal_table more than once * per table, because it clobbers the input frequency counts! */ if (cinfo->progressive_mode) /* Flush out buffered data (all we care about is counting the EOB symbol) */ emit_eobrun(entropy); MEMZERO(did_dc, SIZEOF(did_dc)); MEMZERO(did_ac, SIZEOF(did_ac)); for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* DC needs no table for refinement scan */ if (cinfo->Ss == 0 && cinfo->Ah == 0) { tbl = compptr->dc_tbl_no; if (! did_dc[tbl]) { htblptr = & cinfo->dc_huff_tbl_ptrs[tbl]; if (*htblptr == NULL) *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]); did_dc[tbl] = TRUE; } } /* AC needs no table when not present */ if (cinfo->Se) { tbl = compptr->ac_tbl_no; if (! did_ac[tbl]) { htblptr = & cinfo->ac_huff_tbl_ptrs[tbl]; if (*htblptr == NULL) *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]); did_ac[tbl] = TRUE; } } } } /* * Initialize for a Huffman-compressed scan. * If gather_statistics is TRUE, we do not output anything during the scan, * just count the Huffman symbols used and generate Huffman code tables. */ METHODDEF(void) start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int ci, tbl; jpeg_component_info * compptr; if (gather_statistics) entropy->pub.finish_pass = finish_pass_gather; else entropy->pub.finish_pass = finish_pass_huff; if (cinfo->progressive_mode) { entropy->cinfo = cinfo; entropy->gather_statistics = gather_statistics; /* We assume jcmaster.c already validated the scan parameters. */ /* Select execution routine */ if (cinfo->Ah == 0) { if (cinfo->Ss == 0) entropy->pub.encode_mcu = encode_mcu_DC_first; else entropy->pub.encode_mcu = encode_mcu_AC_first; } else { if (cinfo->Ss == 0) entropy->pub.encode_mcu = encode_mcu_DC_refine; else { entropy->pub.encode_mcu = encode_mcu_AC_refine; /* AC refinement needs a correction bit buffer */ if (entropy->bit_buffer == NULL) entropy->bit_buffer = (char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, MAX_CORR_BITS * SIZEOF(char)); } } /* Initialize AC stuff */ entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no; entropy->EOBRUN = 0; entropy->BE = 0; } else { if (gather_statistics) entropy->pub.encode_mcu = encode_mcu_gather; else entropy->pub.encode_mcu = encode_mcu_huff; } for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* DC needs no table for refinement scan */ if (cinfo->Ss == 0 && cinfo->Ah == 0) { tbl = compptr->dc_tbl_no; if (gather_statistics) { /* Check for invalid table index */ /* (make_c_derived_tbl does this in the other path) */ if (tbl < 0 || tbl >= NUM_HUFF_TBLS) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl); /* Allocate and zero the statistics tables */ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */ if (entropy->dc_count_ptrs[tbl] == NULL) entropy->dc_count_ptrs[tbl] = (long *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 257 * SIZEOF(long)); MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long)); } else { /* Compute derived values for Huffman tables */ /* We may do this more than once for a table, but it's not expensive */ jpeg_make_c_derived_tbl(cinfo, TRUE, tbl, & entropy->dc_derived_tbls[tbl]); } /* Initialize DC predictions to 0 */ entropy->saved.last_dc_val[ci] = 0; } /* AC needs no table when not present */ if (cinfo->Se) { tbl = compptr->ac_tbl_no; if (gather_statistics) { if (tbl < 0 || tbl >= NUM_HUFF_TBLS) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl); if (entropy->ac_count_ptrs[tbl] == NULL) entropy->ac_count_ptrs[tbl] = (long *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 257 * SIZEOF(long)); MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long)); } else { jpeg_make_c_derived_tbl(cinfo, FALSE, tbl, & entropy->ac_derived_tbls[tbl]); } } } /* Initialize bit buffer to empty */ entropy->saved.put_buffer = 0; entropy->saved.put_bits = 0; /* Initialize restart stuff */ entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num = 0; } /* * Module initialization routine for Huffman entropy encoding. */ GLOBAL(void) jinit_huff_encoder (j_compress_ptr cinfo) { huff_entropy_ptr entropy; int i; entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_encoder)); cinfo->entropy = &entropy->pub; entropy->pub.start_pass = start_pass_huff; /* Mark tables unallocated */ for (i = 0; i < NUM_HUFF_TBLS; i++) { entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL; } if (cinfo->progressive_mode) entropy->bit_buffer = NULL; /* needed only in AC refinement scan */ } ================================================ FILE: tess-two/jni/libjpeg/jcinit.c ================================================ /* * jcinit.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2003-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains initialization logic for the JPEG compressor. * This routine is in charge of selecting the modules to be executed and * making an initialization call to each one. * * Logically, this code belongs in jcmaster.c. It's split out because * linking this routine implies linking the entire compression library. * For a transcoding-only application, we want to be able to use jcmaster.c * without linking in the whole library. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * Master selection of compression modules. * This is done once at the start of processing an image. We determine * which modules will be used and give them appropriate initialization calls. */ GLOBAL(void) jinit_compress_master (j_compress_ptr cinfo) { long samplesperrow; JDIMENSION jd_samplesperrow; /* For now, precision must match compiled-in value... */ if (cinfo->data_precision != BITS_IN_JSAMPLE) ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); /* Sanity check on image dimensions */ if (cinfo->image_height <= 0 || cinfo->image_width <= 0 || cinfo->input_components <= 0) ERREXIT(cinfo, JERR_EMPTY_IMAGE); /* Width of an input scanline must be representable as JDIMENSION. */ samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components; jd_samplesperrow = (JDIMENSION) samplesperrow; if ((long) jd_samplesperrow != samplesperrow) ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); /* Initialize master control (includes parameter checking/processing) */ jinit_c_master_control(cinfo, FALSE /* full compression */); /* Preprocessing */ if (! cinfo->raw_data_in) { jinit_color_converter(cinfo); jinit_downsampler(cinfo); jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */); } /* Forward DCT */ jinit_forward_dct(cinfo); /* Entropy encoding: either Huffman or arithmetic coding. */ if (cinfo->arith_code) jinit_arith_encoder(cinfo); else { jinit_huff_encoder(cinfo); } /* Need a full-image coefficient buffer in any multi-pass mode. */ jinit_c_coef_controller(cinfo, (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding)); jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */); jinit_marker_writer(cinfo); /* We can now tell the memory manager to allocate virtual arrays. */ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); /* Write the datastream header (SOI) immediately. * Frame and scan headers are postponed till later. * This lets application insert special markers after the SOI. */ (*cinfo->marker->write_file_header) (cinfo); } ================================================ FILE: tess-two/jni/libjpeg/jcmainct.c ================================================ /* * jcmainct.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2003-2012 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the main buffer controller for compression. * The main buffer lies between the pre-processor and the JPEG * compressor proper; it holds downsampled data in the JPEG colorspace. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Note: currently, there is no operating mode in which a full-image buffer * is needed at this step. If there were, that mode could not be used with * "raw data" input, since this module is bypassed in that case. However, * we've left the code here for possible use in special applications. */ #undef FULL_MAIN_BUFFER_SUPPORTED /* Private buffer controller object */ typedef struct { struct jpeg_c_main_controller pub; /* public fields */ JDIMENSION cur_iMCU_row; /* number of current iMCU row */ JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */ boolean suspended; /* remember if we suspended output */ J_BUF_MODE pass_mode; /* current operating mode */ /* If using just a strip buffer, this points to the entire set of buffers * (we allocate one for each component). In the full-image case, this * points to the currently accessible strips of the virtual arrays. */ JSAMPARRAY buffer[MAX_COMPONENTS]; #ifdef FULL_MAIN_BUFFER_SUPPORTED /* If using full-image storage, this array holds pointers to virtual-array * control blocks for each component. Unused if not full-image storage. */ jvirt_sarray_ptr whole_image[MAX_COMPONENTS]; #endif } my_main_controller; typedef my_main_controller * my_main_ptr; /* Forward declarations */ METHODDEF(void) process_data_simple_main JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail)); #ifdef FULL_MAIN_BUFFER_SUPPORTED METHODDEF(void) process_data_buffer_main JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail)); #endif /* * Initialize for a processing pass. */ METHODDEF(void) start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode) { my_main_ptr mainp = (my_main_ptr) cinfo->main; /* Do nothing in raw-data mode. */ if (cinfo->raw_data_in) return; mainp->cur_iMCU_row = 0; /* initialize counters */ mainp->rowgroup_ctr = 0; mainp->suspended = FALSE; mainp->pass_mode = pass_mode; /* save mode for use by process_data */ switch (pass_mode) { case JBUF_PASS_THRU: #ifdef FULL_MAIN_BUFFER_SUPPORTED if (mainp->whole_image[0] != NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); #endif mainp->pub.process_data = process_data_simple_main; break; #ifdef FULL_MAIN_BUFFER_SUPPORTED case JBUF_SAVE_SOURCE: case JBUF_CRANK_DEST: case JBUF_SAVE_AND_PASS: if (mainp->whole_image[0] == NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); mainp->pub.process_data = process_data_buffer_main; break; #endif default: ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); break; } } /* * Process some data. * This routine handles the simple pass-through mode, * where we have only a strip buffer. */ METHODDEF(void) process_data_simple_main (j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail) { my_main_ptr mainp = (my_main_ptr) cinfo->main; while (mainp->cur_iMCU_row < cinfo->total_iMCU_rows) { /* Read input data if we haven't filled the main buffer yet */ if (mainp->rowgroup_ctr < (JDIMENSION) cinfo->min_DCT_v_scaled_size) (*cinfo->prep->pre_process_data) (cinfo, input_buf, in_row_ctr, in_rows_avail, mainp->buffer, &mainp->rowgroup_ctr, (JDIMENSION) cinfo->min_DCT_v_scaled_size); /* If we don't have a full iMCU row buffered, return to application for * more data. Note that preprocessor will always pad to fill the iMCU row * at the bottom of the image. */ if (mainp->rowgroup_ctr != (JDIMENSION) cinfo->min_DCT_v_scaled_size) return; /* Send the completed row to the compressor */ if (! (*cinfo->coef->compress_data) (cinfo, mainp->buffer)) { /* If compressor did not consume the whole row, then we must need to * suspend processing and return to the application. In this situation * we pretend we didn't yet consume the last input row; otherwise, if * it happened to be the last row of the image, the application would * think we were done. */ if (! mainp->suspended) { (*in_row_ctr)--; mainp->suspended = TRUE; } return; } /* We did finish the row. Undo our little suspension hack if a previous * call suspended; then mark the main buffer empty. */ if (mainp->suspended) { (*in_row_ctr)++; mainp->suspended = FALSE; } mainp->rowgroup_ctr = 0; mainp->cur_iMCU_row++; } } #ifdef FULL_MAIN_BUFFER_SUPPORTED /* * Process some data. * This routine handles all of the modes that use a full-size buffer. */ METHODDEF(void) process_data_buffer_main (j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail) { my_main_ptr mainp = (my_main_ptr) cinfo->main; int ci; jpeg_component_info *compptr; boolean writing = (mainp->pass_mode != JBUF_CRANK_DEST); while (mainp->cur_iMCU_row < cinfo->total_iMCU_rows) { /* Realign the virtual buffers if at the start of an iMCU row. */ if (mainp->rowgroup_ctr == 0) { for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { mainp->buffer[ci] = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, mainp->whole_image[ci], mainp->cur_iMCU_row * ((JDIMENSION) (compptr->v_samp_factor * cinfo->min_DCT_v_scaled_size)), (JDIMENSION) (compptr->v_samp_factor * cinfo->min_DCT_v_scaled_size), writing); } /* In a read pass, pretend we just read some source data. */ if (! writing) { *in_row_ctr += (JDIMENSION) (cinfo->max_v_samp_factor * cinfo->min_DCT_v_scaled_size); mainp->rowgroup_ctr = (JDIMENSION) cinfo->min_DCT_v_scaled_size; } } /* If a write pass, read input data until the current iMCU row is full. */ /* Note: preprocessor will pad if necessary to fill the last iMCU row. */ if (writing) { (*cinfo->prep->pre_process_data) (cinfo, input_buf, in_row_ctr, in_rows_avail, mainp->buffer, &mainp->rowgroup_ctr, (JDIMENSION) cinfo->min_DCT_v_scaled_size); /* Return to application if we need more data to fill the iMCU row. */ if (mainp->rowgroup_ctr < (JDIMENSION) cinfo->min_DCT_v_scaled_size) return; } /* Emit data, unless this is a sink-only pass. */ if (mainp->pass_mode != JBUF_SAVE_SOURCE) { if (! (*cinfo->coef->compress_data) (cinfo, mainp->buffer)) { /* If compressor did not consume the whole row, then we must need to * suspend processing and return to the application. In this situation * we pretend we didn't yet consume the last input row; otherwise, if * it happened to be the last row of the image, the application would * think we were done. */ if (! mainp->suspended) { (*in_row_ctr)--; mainp->suspended = TRUE; } return; } /* We did finish the row. Undo our little suspension hack if a previous * call suspended; then mark the main buffer empty. */ if (mainp->suspended) { (*in_row_ctr)++; mainp->suspended = FALSE; } } /* If get here, we are done with this iMCU row. Mark buffer empty. */ mainp->rowgroup_ctr = 0; mainp->cur_iMCU_row++; } } #endif /* FULL_MAIN_BUFFER_SUPPORTED */ /* * Initialize main buffer controller. */ GLOBAL(void) jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer) { my_main_ptr mainp; int ci; jpeg_component_info *compptr; mainp = (my_main_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_main_controller)); cinfo->main = &mainp->pub; mainp->pub.start_pass = start_pass_main; /* We don't need to create a buffer in raw-data mode. */ if (cinfo->raw_data_in) return; /* Create the buffer. It holds downsampled data, so each component * may be of a different size. */ if (need_full_buffer) { #ifdef FULL_MAIN_BUFFER_SUPPORTED /* Allocate a full-image virtual array for each component */ /* Note we pad the bottom to a multiple of the iMCU height */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { mainp->whole_image[ci] = (*cinfo->mem->request_virt_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, compptr->width_in_blocks * ((JDIMENSION) compptr->DCT_h_scaled_size), ((JDIMENSION) jround_up((long) compptr->height_in_blocks, (long) compptr->v_samp_factor)) * ((JDIMENSION) cinfo->min_DCT_v_scaled_size), (JDIMENSION) (compptr->v_samp_factor * compptr->DCT_v_scaled_size)); } #else ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); #endif } else { #ifdef FULL_MAIN_BUFFER_SUPPORTED mainp->whole_image[0] = NULL; /* flag for no virtual arrays */ #endif /* Allocate a strip buffer for each component */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { mainp->buffer[ci] = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, compptr->width_in_blocks * ((JDIMENSION) compptr->DCT_h_scaled_size), (JDIMENSION) (compptr->v_samp_factor * compptr->DCT_v_scaled_size)); } } } ================================================ FILE: tess-two/jni/libjpeg/jcmarker.c ================================================ /* * jcmarker.c * * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2003-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to write JPEG datastream markers. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" typedef enum { /* JPEG marker codes */ M_SOF0 = 0xc0, M_SOF1 = 0xc1, M_SOF2 = 0xc2, M_SOF3 = 0xc3, M_SOF5 = 0xc5, M_SOF6 = 0xc6, M_SOF7 = 0xc7, M_JPG = 0xc8, M_SOF9 = 0xc9, M_SOF10 = 0xca, M_SOF11 = 0xcb, M_SOF13 = 0xcd, M_SOF14 = 0xce, M_SOF15 = 0xcf, M_DHT = 0xc4, M_DAC = 0xcc, M_RST0 = 0xd0, M_RST1 = 0xd1, M_RST2 = 0xd2, M_RST3 = 0xd3, M_RST4 = 0xd4, M_RST5 = 0xd5, M_RST6 = 0xd6, M_RST7 = 0xd7, M_SOI = 0xd8, M_EOI = 0xd9, M_SOS = 0xda, M_DQT = 0xdb, M_DNL = 0xdc, M_DRI = 0xdd, M_DHP = 0xde, M_EXP = 0xdf, M_APP0 = 0xe0, M_APP1 = 0xe1, M_APP2 = 0xe2, M_APP3 = 0xe3, M_APP4 = 0xe4, M_APP5 = 0xe5, M_APP6 = 0xe6, M_APP7 = 0xe7, M_APP8 = 0xe8, M_APP9 = 0xe9, M_APP10 = 0xea, M_APP11 = 0xeb, M_APP12 = 0xec, M_APP13 = 0xed, M_APP14 = 0xee, M_APP15 = 0xef, M_JPG0 = 0xf0, M_JPG8 = 0xf8, M_JPG13 = 0xfd, M_COM = 0xfe, M_TEM = 0x01, M_ERROR = 0x100 } JPEG_MARKER; /* Private state */ typedef struct { struct jpeg_marker_writer pub; /* public fields */ unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */ } my_marker_writer; typedef my_marker_writer * my_marker_ptr; /* * Basic output routines. * * Note that we do not support suspension while writing a marker. * Therefore, an application using suspension must ensure that there is * enough buffer space for the initial markers (typ. 600-700 bytes) before * calling jpeg_start_compress, and enough space to write the trailing EOI * (a few bytes) before calling jpeg_finish_compress. Multipass compression * modes are not supported at all with suspension, so those two are the only * points where markers will be written. */ LOCAL(void) emit_byte (j_compress_ptr cinfo, int val) /* Emit a byte */ { struct jpeg_destination_mgr * dest = cinfo->dest; *(dest->next_output_byte)++ = (JOCTET) val; if (--dest->free_in_buffer == 0) { if (! (*dest->empty_output_buffer) (cinfo)) ERREXIT(cinfo, JERR_CANT_SUSPEND); } } LOCAL(void) emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark) /* Emit a marker code */ { emit_byte(cinfo, 0xFF); emit_byte(cinfo, (int) mark); } LOCAL(void) emit_2bytes (j_compress_ptr cinfo, int value) /* Emit a 2-byte integer; these are always MSB first in JPEG files */ { emit_byte(cinfo, (value >> 8) & 0xFF); emit_byte(cinfo, value & 0xFF); } /* * Routines to write specific marker types. */ LOCAL(int) emit_dqt (j_compress_ptr cinfo, int index) /* Emit a DQT marker */ /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */ { JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index]; int prec; int i; if (qtbl == NULL) ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index); prec = 0; for (i = 0; i <= cinfo->lim_Se; i++) { if (qtbl->quantval[cinfo->natural_order[i]] > 255) prec = 1; } if (! qtbl->sent_table) { emit_marker(cinfo, M_DQT); emit_2bytes(cinfo, prec ? cinfo->lim_Se * 2 + 2 + 1 + 2 : cinfo->lim_Se + 1 + 1 + 2); emit_byte(cinfo, index + (prec<<4)); for (i = 0; i <= cinfo->lim_Se; i++) { /* The table entries must be emitted in zigzag order. */ unsigned int qval = qtbl->quantval[cinfo->natural_order[i]]; if (prec) emit_byte(cinfo, (int) (qval >> 8)); emit_byte(cinfo, (int) (qval & 0xFF)); } qtbl->sent_table = TRUE; } return prec; } LOCAL(void) emit_dht (j_compress_ptr cinfo, int index, boolean is_ac) /* Emit a DHT marker */ { JHUFF_TBL * htbl; int length, i; if (is_ac) { htbl = cinfo->ac_huff_tbl_ptrs[index]; index += 0x10; /* output index has AC bit set */ } else { htbl = cinfo->dc_huff_tbl_ptrs[index]; } if (htbl == NULL) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index); if (! htbl->sent_table) { emit_marker(cinfo, M_DHT); length = 0; for (i = 1; i <= 16; i++) length += htbl->bits[i]; emit_2bytes(cinfo, length + 2 + 1 + 16); emit_byte(cinfo, index); for (i = 1; i <= 16; i++) emit_byte(cinfo, htbl->bits[i]); for (i = 0; i < length; i++) emit_byte(cinfo, htbl->huffval[i]); htbl->sent_table = TRUE; } } LOCAL(void) emit_dac (j_compress_ptr cinfo) /* Emit a DAC marker */ /* Since the useful info is so small, we want to emit all the tables in */ /* one DAC marker. Therefore this routine does its own scan of the table. */ { #ifdef C_ARITH_CODING_SUPPORTED char dc_in_use[NUM_ARITH_TBLS]; char ac_in_use[NUM_ARITH_TBLS]; int length, i; jpeg_component_info *compptr; for (i = 0; i < NUM_ARITH_TBLS; i++) dc_in_use[i] = ac_in_use[i] = 0; for (i = 0; i < cinfo->comps_in_scan; i++) { compptr = cinfo->cur_comp_info[i]; /* DC needs no table for refinement scan */ if (cinfo->Ss == 0 && cinfo->Ah == 0) dc_in_use[compptr->dc_tbl_no] = 1; /* AC needs no table when not present */ if (cinfo->Se) ac_in_use[compptr->ac_tbl_no] = 1; } length = 0; for (i = 0; i < NUM_ARITH_TBLS; i++) length += dc_in_use[i] + ac_in_use[i]; if (length) { emit_marker(cinfo, M_DAC); emit_2bytes(cinfo, length*2 + 2); for (i = 0; i < NUM_ARITH_TBLS; i++) { if (dc_in_use[i]) { emit_byte(cinfo, i); emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4)); } if (ac_in_use[i]) { emit_byte(cinfo, i + 0x10); emit_byte(cinfo, cinfo->arith_ac_K[i]); } } } #endif /* C_ARITH_CODING_SUPPORTED */ } LOCAL(void) emit_dri (j_compress_ptr cinfo) /* Emit a DRI marker */ { emit_marker(cinfo, M_DRI); emit_2bytes(cinfo, 4); /* fixed length */ emit_2bytes(cinfo, (int) cinfo->restart_interval); } LOCAL(void) emit_lse_ict (j_compress_ptr cinfo) /* Emit an LSE inverse color transform specification marker */ { /* Support only 1 transform */ if (cinfo->color_transform != JCT_SUBTRACT_GREEN || cinfo->num_components < 3) ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); emit_marker(cinfo, M_JPG8); emit_2bytes(cinfo, 24); /* fixed length */ emit_byte(cinfo, 0x0D); /* ID inverse transform specification */ emit_2bytes(cinfo, MAXJSAMPLE); /* MAXTRANS */ emit_byte(cinfo, 3); /* Nt=3 */ emit_byte(cinfo, cinfo->comp_info[1].component_id); emit_byte(cinfo, cinfo->comp_info[0].component_id); emit_byte(cinfo, cinfo->comp_info[2].component_id); emit_byte(cinfo, 0x80); /* F1: CENTER1=1, NORM1=0 */ emit_2bytes(cinfo, 0); /* A(1,1)=0 */ emit_2bytes(cinfo, 0); /* A(1,2)=0 */ emit_byte(cinfo, 0); /* F2: CENTER2=0, NORM2=0 */ emit_2bytes(cinfo, 1); /* A(2,1)=1 */ emit_2bytes(cinfo, 0); /* A(2,2)=0 */ emit_byte(cinfo, 0); /* F3: CENTER3=0, NORM3=0 */ emit_2bytes(cinfo, 1); /* A(3,1)=1 */ emit_2bytes(cinfo, 0); /* A(3,2)=0 */ } LOCAL(void) emit_sof (j_compress_ptr cinfo, JPEG_MARKER code) /* Emit a SOF marker */ { int ci; jpeg_component_info *compptr; emit_marker(cinfo, code); emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */ /* Make sure image isn't bigger than SOF field can handle */ if ((long) cinfo->jpeg_height > 65535L || (long) cinfo->jpeg_width > 65535L) ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535); emit_byte(cinfo, cinfo->data_precision); emit_2bytes(cinfo, (int) cinfo->jpeg_height); emit_2bytes(cinfo, (int) cinfo->jpeg_width); emit_byte(cinfo, cinfo->num_components); for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { emit_byte(cinfo, compptr->component_id); emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor); emit_byte(cinfo, compptr->quant_tbl_no); } } LOCAL(void) emit_sos (j_compress_ptr cinfo) /* Emit a SOS marker */ { int i, td, ta; jpeg_component_info *compptr; emit_marker(cinfo, M_SOS); emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */ emit_byte(cinfo, cinfo->comps_in_scan); for (i = 0; i < cinfo->comps_in_scan; i++) { compptr = cinfo->cur_comp_info[i]; emit_byte(cinfo, compptr->component_id); /* We emit 0 for unused field(s); this is recommended by the P&M text * but does not seem to be specified in the standard. */ /* DC needs no table for refinement scan */ td = cinfo->Ss == 0 && cinfo->Ah == 0 ? compptr->dc_tbl_no : 0; /* AC needs no table when not present */ ta = cinfo->Se ? compptr->ac_tbl_no : 0; emit_byte(cinfo, (td << 4) + ta); } emit_byte(cinfo, cinfo->Ss); emit_byte(cinfo, cinfo->Se); emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al); } LOCAL(void) emit_pseudo_sos (j_compress_ptr cinfo) /* Emit a pseudo SOS marker */ { emit_marker(cinfo, M_SOS); emit_2bytes(cinfo, 2 + 1 + 3); /* length */ emit_byte(cinfo, 0); /* Ns */ emit_byte(cinfo, 0); /* Ss */ emit_byte(cinfo, cinfo->block_size * cinfo->block_size - 1); /* Se */ emit_byte(cinfo, 0); /* Ah/Al */ } LOCAL(void) emit_jfif_app0 (j_compress_ptr cinfo) /* Emit a JFIF-compliant APP0 marker */ { /* * Length of APP0 block (2 bytes) * Block ID (4 bytes - ASCII "JFIF") * Zero byte (1 byte to terminate the ID string) * Version Major, Minor (2 bytes - major first) * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm) * Xdpu (2 bytes - dots per unit horizontal) * Ydpu (2 bytes - dots per unit vertical) * Thumbnail X size (1 byte) * Thumbnail Y size (1 byte) */ emit_marker(cinfo, M_APP0); emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */ emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */ emit_byte(cinfo, 0x46); emit_byte(cinfo, 0x49); emit_byte(cinfo, 0x46); emit_byte(cinfo, 0); emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */ emit_byte(cinfo, cinfo->JFIF_minor_version); emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */ emit_2bytes(cinfo, (int) cinfo->X_density); emit_2bytes(cinfo, (int) cinfo->Y_density); emit_byte(cinfo, 0); /* No thumbnail image */ emit_byte(cinfo, 0); } LOCAL(void) emit_adobe_app14 (j_compress_ptr cinfo) /* Emit an Adobe APP14 marker */ { /* * Length of APP14 block (2 bytes) * Block ID (5 bytes - ASCII "Adobe") * Version Number (2 bytes - currently 100) * Flags0 (2 bytes - currently 0) * Flags1 (2 bytes - currently 0) * Color transform (1 byte) * * Although Adobe TN 5116 mentions Version = 101, all the Adobe files * now in circulation seem to use Version = 100, so that's what we write. * * We write the color transform byte as 1 if the JPEG color space is * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with * whether the encoder performed a transformation, which is pretty useless. */ emit_marker(cinfo, M_APP14); emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */ emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */ emit_byte(cinfo, 0x64); emit_byte(cinfo, 0x6F); emit_byte(cinfo, 0x62); emit_byte(cinfo, 0x65); emit_2bytes(cinfo, 100); /* Version */ emit_2bytes(cinfo, 0); /* Flags0 */ emit_2bytes(cinfo, 0); /* Flags1 */ switch (cinfo->jpeg_color_space) { case JCS_YCbCr: emit_byte(cinfo, 1); /* Color transform = 1 */ break; case JCS_YCCK: emit_byte(cinfo, 2); /* Color transform = 2 */ break; default: emit_byte(cinfo, 0); /* Color transform = 0 */ break; } } /* * These routines allow writing an arbitrary marker with parameters. * The only intended use is to emit COM or APPn markers after calling * write_file_header and before calling write_frame_header. * Other uses are not guaranteed to produce desirable results. * Counting the parameter bytes properly is the caller's responsibility. */ METHODDEF(void) write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen) /* Emit an arbitrary marker header */ { if (datalen > (unsigned int) 65533) /* safety check */ ERREXIT(cinfo, JERR_BAD_LENGTH); emit_marker(cinfo, (JPEG_MARKER) marker); emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */ } METHODDEF(void) write_marker_byte (j_compress_ptr cinfo, int val) /* Emit one byte of marker parameters following write_marker_header */ { emit_byte(cinfo, val); } /* * Write datastream header. * This consists of an SOI and optional APPn markers. * We recommend use of the JFIF marker, but not the Adobe marker, * when using YCbCr or grayscale data. The JFIF marker is also used * for other standard JPEG colorspaces. The Adobe marker is helpful * to distinguish RGB, CMYK, and YCCK colorspaces. * Note that an application can write additional header markers after * jpeg_start_compress returns. */ METHODDEF(void) write_file_header (j_compress_ptr cinfo) { my_marker_ptr marker = (my_marker_ptr) cinfo->marker; emit_marker(cinfo, M_SOI); /* first the SOI */ /* SOI is defined to reset restart interval to 0 */ marker->last_restart_interval = 0; if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */ emit_jfif_app0(cinfo); if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */ emit_adobe_app14(cinfo); } /* * Write frame header. * This consists of DQT and SOFn markers, * a conditional LSE marker and a conditional pseudo SOS marker. * Note that we do not emit the SOF until we have emitted the DQT(s). * This avoids compatibility problems with incorrect implementations that * try to error-check the quant table numbers as soon as they see the SOF. */ METHODDEF(void) write_frame_header (j_compress_ptr cinfo) { int ci, prec; boolean is_baseline; jpeg_component_info *compptr; /* Emit DQT for each quantization table. * Note that emit_dqt() suppresses any duplicate tables. */ prec = 0; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { prec += emit_dqt(cinfo, compptr->quant_tbl_no); } /* now prec is nonzero iff there are any 16-bit quant tables. */ /* Check for a non-baseline specification. * Note we assume that Huffman table numbers won't be changed later. */ if (cinfo->arith_code || cinfo->progressive_mode || cinfo->data_precision != 8 || cinfo->block_size != DCTSIZE) { is_baseline = FALSE; } else { is_baseline = TRUE; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1) is_baseline = FALSE; } if (prec && is_baseline) { is_baseline = FALSE; /* If it's baseline except for quantizer size, warn the user */ TRACEMS(cinfo, 0, JTRC_16BIT_TABLES); } } /* Emit the proper SOF marker */ if (cinfo->arith_code) { if (cinfo->progressive_mode) emit_sof(cinfo, M_SOF10); /* SOF code for progressive arithmetic */ else emit_sof(cinfo, M_SOF9); /* SOF code for sequential arithmetic */ } else { if (cinfo->progressive_mode) emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */ else if (is_baseline) emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */ else emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */ } /* Check to emit LSE inverse color transform specification marker */ if (cinfo->color_transform) emit_lse_ict(cinfo); /* Check to emit pseudo SOS marker */ if (cinfo->progressive_mode && cinfo->block_size != DCTSIZE) emit_pseudo_sos(cinfo); } /* * Write scan header. * This consists of DHT or DAC markers, optional DRI, and SOS. * Compressed data will be written following the SOS. */ METHODDEF(void) write_scan_header (j_compress_ptr cinfo) { my_marker_ptr marker = (my_marker_ptr) cinfo->marker; int i; jpeg_component_info *compptr; if (cinfo->arith_code) { /* Emit arith conditioning info. We may have some duplication * if the file has multiple scans, but it's so small it's hardly * worth worrying about. */ emit_dac(cinfo); } else { /* Emit Huffman tables. * Note that emit_dht() suppresses any duplicate tables. */ for (i = 0; i < cinfo->comps_in_scan; i++) { compptr = cinfo->cur_comp_info[i]; /* DC needs no table for refinement scan */ if (cinfo->Ss == 0 && cinfo->Ah == 0) emit_dht(cinfo, compptr->dc_tbl_no, FALSE); /* AC needs no table when not present */ if (cinfo->Se) emit_dht(cinfo, compptr->ac_tbl_no, TRUE); } } /* Emit DRI if required --- note that DRI value could change for each scan. * We avoid wasting space with unnecessary DRIs, however. */ if (cinfo->restart_interval != marker->last_restart_interval) { emit_dri(cinfo); marker->last_restart_interval = cinfo->restart_interval; } emit_sos(cinfo); } /* * Write datastream trailer. */ METHODDEF(void) write_file_trailer (j_compress_ptr cinfo) { emit_marker(cinfo, M_EOI); } /* * Write an abbreviated table-specification datastream. * This consists of SOI, DQT and DHT tables, and EOI. * Any table that is defined and not marked sent_table = TRUE will be * emitted. Note that all tables will be marked sent_table = TRUE at exit. */ METHODDEF(void) write_tables_only (j_compress_ptr cinfo) { int i; emit_marker(cinfo, M_SOI); for (i = 0; i < NUM_QUANT_TBLS; i++) { if (cinfo->quant_tbl_ptrs[i] != NULL) (void) emit_dqt(cinfo, i); } if (! cinfo->arith_code) { for (i = 0; i < NUM_HUFF_TBLS; i++) { if (cinfo->dc_huff_tbl_ptrs[i] != NULL) emit_dht(cinfo, i, FALSE); if (cinfo->ac_huff_tbl_ptrs[i] != NULL) emit_dht(cinfo, i, TRUE); } } emit_marker(cinfo, M_EOI); } /* * Initialize the marker writer module. */ GLOBAL(void) jinit_marker_writer (j_compress_ptr cinfo) { my_marker_ptr marker; /* Create the subobject */ marker = (my_marker_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_marker_writer)); cinfo->marker = &marker->pub; /* Initialize method pointers */ marker->pub.write_file_header = write_file_header; marker->pub.write_frame_header = write_frame_header; marker->pub.write_scan_header = write_scan_header; marker->pub.write_file_trailer = write_file_trailer; marker->pub.write_tables_only = write_tables_only; marker->pub.write_marker_header = write_marker_header; marker->pub.write_marker_byte = write_marker_byte; /* Initialize private state */ marker->last_restart_interval = 0; } ================================================ FILE: tess-two/jni/libjpeg/jcmaster.c ================================================ /* * jcmaster.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2003-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains master control logic for the JPEG compressor. * These routines are concerned with parameter validation, initial setup, * and inter-pass control (determining the number of passes and the work * to be done in each pass). */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Private state */ typedef enum { main_pass, /* input data, also do first output step */ huff_opt_pass, /* Huffman code optimization pass */ output_pass /* data output pass */ } c_pass_type; typedef struct { struct jpeg_comp_master pub; /* public fields */ c_pass_type pass_type; /* the type of the current pass */ int pass_number; /* # of passes completed */ int total_passes; /* total # of passes needed */ int scan_number; /* current index in scan_info[] */ } my_comp_master; typedef my_comp_master * my_master_ptr; /* * Support routines that do various essential calculations. */ /* * Compute JPEG image dimensions and related values. * NOTE: this is exported for possible use by application. * Hence it mustn't do anything that can't be done twice. */ GLOBAL(void) jpeg_calc_jpeg_dimensions (j_compress_ptr cinfo) /* Do computations that are needed before master selection phase */ { #ifdef DCT_SCALING_SUPPORTED /* Sanity check on input image dimensions to prevent overflow in * following calculation. * We do check jpeg_width and jpeg_height in initial_setup below, * but image_width and image_height can come from arbitrary data, * and we need some space for multiplication by block_size. */ if (((long) cinfo->image_width >> 24) || ((long) cinfo->image_height >> 24)) ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); /* Compute actual JPEG image dimensions and DCT scaling choices. */ if (cinfo->scale_num >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/1 scaling */ cinfo->jpeg_width = cinfo->image_width * cinfo->block_size; cinfo->jpeg_height = cinfo->image_height * cinfo->block_size; cinfo->min_DCT_h_scaled_size = 1; cinfo->min_DCT_v_scaled_size = 1; } else if (cinfo->scale_num * 2 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/2 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 2L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 2L); cinfo->min_DCT_h_scaled_size = 2; cinfo->min_DCT_v_scaled_size = 2; } else if (cinfo->scale_num * 3 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/3 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 3L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 3L); cinfo->min_DCT_h_scaled_size = 3; cinfo->min_DCT_v_scaled_size = 3; } else if (cinfo->scale_num * 4 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/4 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 4L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 4L); cinfo->min_DCT_h_scaled_size = 4; cinfo->min_DCT_v_scaled_size = 4; } else if (cinfo->scale_num * 5 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/5 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 5L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 5L); cinfo->min_DCT_h_scaled_size = 5; cinfo->min_DCT_v_scaled_size = 5; } else if (cinfo->scale_num * 6 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/6 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 6L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 6L); cinfo->min_DCT_h_scaled_size = 6; cinfo->min_DCT_v_scaled_size = 6; } else if (cinfo->scale_num * 7 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/7 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 7L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 7L); cinfo->min_DCT_h_scaled_size = 7; cinfo->min_DCT_v_scaled_size = 7; } else if (cinfo->scale_num * 8 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/8 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 8L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 8L); cinfo->min_DCT_h_scaled_size = 8; cinfo->min_DCT_v_scaled_size = 8; } else if (cinfo->scale_num * 9 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/9 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 9L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 9L); cinfo->min_DCT_h_scaled_size = 9; cinfo->min_DCT_v_scaled_size = 9; } else if (cinfo->scale_num * 10 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/10 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 10L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 10L); cinfo->min_DCT_h_scaled_size = 10; cinfo->min_DCT_v_scaled_size = 10; } else if (cinfo->scale_num * 11 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/11 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 11L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 11L); cinfo->min_DCT_h_scaled_size = 11; cinfo->min_DCT_v_scaled_size = 11; } else if (cinfo->scale_num * 12 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/12 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 12L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 12L); cinfo->min_DCT_h_scaled_size = 12; cinfo->min_DCT_v_scaled_size = 12; } else if (cinfo->scale_num * 13 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/13 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 13L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 13L); cinfo->min_DCT_h_scaled_size = 13; cinfo->min_DCT_v_scaled_size = 13; } else if (cinfo->scale_num * 14 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/14 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 14L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 14L); cinfo->min_DCT_h_scaled_size = 14; cinfo->min_DCT_v_scaled_size = 14; } else if (cinfo->scale_num * 15 >= cinfo->scale_denom * cinfo->block_size) { /* Provide block_size/15 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 15L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 15L); cinfo->min_DCT_h_scaled_size = 15; cinfo->min_DCT_v_scaled_size = 15; } else { /* Provide block_size/16 scaling */ cinfo->jpeg_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * cinfo->block_size, 16L); cinfo->jpeg_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * cinfo->block_size, 16L); cinfo->min_DCT_h_scaled_size = 16; cinfo->min_DCT_v_scaled_size = 16; } #else /* !DCT_SCALING_SUPPORTED */ /* Hardwire it to "no scaling" */ cinfo->jpeg_width = cinfo->image_width; cinfo->jpeg_height = cinfo->image_height; cinfo->min_DCT_h_scaled_size = DCTSIZE; cinfo->min_DCT_v_scaled_size = DCTSIZE; #endif /* DCT_SCALING_SUPPORTED */ } LOCAL(void) jpeg_calc_trans_dimensions (j_compress_ptr cinfo) { if (cinfo->min_DCT_h_scaled_size != cinfo->min_DCT_v_scaled_size) ERREXIT2(cinfo, JERR_BAD_DCTSIZE, cinfo->min_DCT_h_scaled_size, cinfo->min_DCT_v_scaled_size); cinfo->block_size = cinfo->min_DCT_h_scaled_size; } LOCAL(void) initial_setup (j_compress_ptr cinfo, boolean transcode_only) /* Do computations that are needed before master selection phase */ { int ci, ssize; jpeg_component_info *compptr; if (transcode_only) jpeg_calc_trans_dimensions(cinfo); else jpeg_calc_jpeg_dimensions(cinfo); /* Sanity check on block_size */ if (cinfo->block_size < 1 || cinfo->block_size > 16) ERREXIT2(cinfo, JERR_BAD_DCTSIZE, cinfo->block_size, cinfo->block_size); /* Derive natural_order from block_size */ switch (cinfo->block_size) { case 2: cinfo->natural_order = jpeg_natural_order2; break; case 3: cinfo->natural_order = jpeg_natural_order3; break; case 4: cinfo->natural_order = jpeg_natural_order4; break; case 5: cinfo->natural_order = jpeg_natural_order5; break; case 6: cinfo->natural_order = jpeg_natural_order6; break; case 7: cinfo->natural_order = jpeg_natural_order7; break; default: cinfo->natural_order = jpeg_natural_order; break; } /* Derive lim_Se from block_size */ cinfo->lim_Se = cinfo->block_size < DCTSIZE ? cinfo->block_size * cinfo->block_size - 1 : DCTSIZE2-1; /* Sanity check on image dimensions */ if (cinfo->jpeg_height <= 0 || cinfo->jpeg_width <= 0 || cinfo->num_components <= 0) ERREXIT(cinfo, JERR_EMPTY_IMAGE); /* Make sure image isn't bigger than I can handle */ if ((long) cinfo->jpeg_height > (long) JPEG_MAX_DIMENSION || (long) cinfo->jpeg_width > (long) JPEG_MAX_DIMENSION) ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); /* Only 8 to 12 bits data precision are supported for DCT based JPEG */ if (cinfo->data_precision < 8 || cinfo->data_precision > 12) ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); /* Check that number of components won't exceed internal array sizes */ if (cinfo->num_components > MAX_COMPONENTS) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPONENTS); /* Compute maximum sampling factors; check factor validity */ cinfo->max_h_samp_factor = 1; cinfo->max_v_samp_factor = 1; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR || compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR) ERREXIT(cinfo, JERR_BAD_SAMPLING); cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor, compptr->h_samp_factor); cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor, compptr->v_samp_factor); } /* Compute dimensions of components */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Fill in the correct component_index value; don't rely on application */ compptr->component_index = ci; /* In selecting the actual DCT scaling for each component, we try to * scale down the chroma components via DCT scaling rather than downsampling. * This saves time if the downsampler gets to use 1:1 scaling. * Note this code adapts subsampling ratios which are powers of 2. */ ssize = 1; #ifdef DCT_SCALING_SUPPORTED while (cinfo->min_DCT_h_scaled_size * ssize <= (cinfo->do_fancy_downsampling ? DCTSIZE : DCTSIZE / 2) && (cinfo->max_h_samp_factor % (compptr->h_samp_factor * ssize * 2)) == 0) { ssize = ssize * 2; } #endif compptr->DCT_h_scaled_size = cinfo->min_DCT_h_scaled_size * ssize; ssize = 1; #ifdef DCT_SCALING_SUPPORTED while (cinfo->min_DCT_v_scaled_size * ssize <= (cinfo->do_fancy_downsampling ? DCTSIZE : DCTSIZE / 2) && (cinfo->max_v_samp_factor % (compptr->v_samp_factor * ssize * 2)) == 0) { ssize = ssize * 2; } #endif compptr->DCT_v_scaled_size = cinfo->min_DCT_v_scaled_size * ssize; /* We don't support DCT ratios larger than 2. */ if (compptr->DCT_h_scaled_size > compptr->DCT_v_scaled_size * 2) compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size * 2; else if (compptr->DCT_v_scaled_size > compptr->DCT_h_scaled_size * 2) compptr->DCT_v_scaled_size = compptr->DCT_h_scaled_size * 2; /* Size in DCT blocks */ compptr->width_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->jpeg_width * (long) compptr->h_samp_factor, (long) (cinfo->max_h_samp_factor * cinfo->block_size)); compptr->height_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->jpeg_height * (long) compptr->v_samp_factor, (long) (cinfo->max_v_samp_factor * cinfo->block_size)); /* Size in samples */ compptr->downsampled_width = (JDIMENSION) jdiv_round_up((long) cinfo->jpeg_width * (long) (compptr->h_samp_factor * compptr->DCT_h_scaled_size), (long) (cinfo->max_h_samp_factor * cinfo->block_size)); compptr->downsampled_height = (JDIMENSION) jdiv_round_up((long) cinfo->jpeg_height * (long) (compptr->v_samp_factor * compptr->DCT_v_scaled_size), (long) (cinfo->max_v_samp_factor * cinfo->block_size)); /* Don't need quantization scale after DCT, * until color conversion says otherwise. */ compptr->component_needed = FALSE; } /* Compute number of fully interleaved MCU rows (number of times that * main controller will call coefficient controller). */ cinfo->total_iMCU_rows = (JDIMENSION) jdiv_round_up((long) cinfo->jpeg_height, (long) (cinfo->max_v_samp_factor * cinfo->block_size)); } #ifdef C_MULTISCAN_FILES_SUPPORTED LOCAL(void) validate_script (j_compress_ptr cinfo) /* Verify that the scan script in cinfo->scan_info[] is valid; also * determine whether it uses progressive JPEG, and set cinfo->progressive_mode. */ { const jpeg_scan_info * scanptr; int scanno, ncomps, ci, coefi, thisi; int Ss, Se, Ah, Al; boolean component_sent[MAX_COMPONENTS]; #ifdef C_PROGRESSIVE_SUPPORTED int * last_bitpos_ptr; int last_bitpos[MAX_COMPONENTS][DCTSIZE2]; /* -1 until that coefficient has been seen; then last Al for it */ #endif if (cinfo->num_scans <= 0) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0); /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1; * for progressive JPEG, no scan can have this. */ scanptr = cinfo->scan_info; if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) { #ifdef C_PROGRESSIVE_SUPPORTED cinfo->progressive_mode = TRUE; last_bitpos_ptr = & last_bitpos[0][0]; for (ci = 0; ci < cinfo->num_components; ci++) for (coefi = 0; coefi < DCTSIZE2; coefi++) *last_bitpos_ptr++ = -1; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { cinfo->progressive_mode = FALSE; for (ci = 0; ci < cinfo->num_components; ci++) component_sent[ci] = FALSE; } for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) { /* Validate component indexes */ ncomps = scanptr->comps_in_scan; if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN); for (ci = 0; ci < ncomps; ci++) { thisi = scanptr->component_index[ci]; if (thisi < 0 || thisi >= cinfo->num_components) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); /* Components must appear in SOF order within each scan */ if (ci > 0 && thisi <= scanptr->component_index[ci-1]) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); } /* Validate progression parameters */ Ss = scanptr->Ss; Se = scanptr->Se; Ah = scanptr->Ah; Al = scanptr->Al; if (cinfo->progressive_mode) { #ifdef C_PROGRESSIVE_SUPPORTED /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that * seems wrong: the upper bound ought to depend on data precision. * Perhaps they really meant 0..N+1 for N-bit precision. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in * out-of-range reconstructed DC values during the first DC scan, * which might cause problems for some decoders. */ #if BITS_IN_JSAMPLE == 8 #define MAX_AH_AL 10 #else #define MAX_AH_AL 13 #endif if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 || Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); if (Ss == 0) { if (Se != 0) /* DC and AC together not OK */ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } else { if (ncomps != 1) /* AC scans must be for only one component */ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } for (ci = 0; ci < ncomps; ci++) { last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0]; if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); for (coefi = Ss; coefi <= Se; coefi++) { if (last_bitpos_ptr[coefi] < 0) { /* first scan of this coefficient */ if (Ah != 0) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } else { /* not first scan */ if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } last_bitpos_ptr[coefi] = Al; } } #endif } else { /* For sequential JPEG, all progression parameters must be these: */ if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); /* Make sure components are not sent twice */ for (ci = 0; ci < ncomps; ci++) { thisi = scanptr->component_index[ci]; if (component_sent[thisi]) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); component_sent[thisi] = TRUE; } } } /* Now verify that everything got sent. */ if (cinfo->progressive_mode) { #ifdef C_PROGRESSIVE_SUPPORTED /* For progressive mode, we only check that at least some DC data * got sent for each component; the spec does not require that all bits * of all coefficients be transmitted. Would it be wiser to enforce * transmission of all coefficient bits?? */ for (ci = 0; ci < cinfo->num_components; ci++) { if (last_bitpos[ci][0] < 0) ERREXIT(cinfo, JERR_MISSING_DATA); } #endif } else { for (ci = 0; ci < cinfo->num_components; ci++) { if (! component_sent[ci]) ERREXIT(cinfo, JERR_MISSING_DATA); } } } LOCAL(void) reduce_script (j_compress_ptr cinfo) /* Adapt scan script for use with reduced block size; * assume that script has been validated before. */ { jpeg_scan_info * scanptr; int idxout, idxin; /* Circumvent const declaration for this function */ scanptr = (jpeg_scan_info *) cinfo->scan_info; idxout = 0; for (idxin = 0; idxin < cinfo->num_scans; idxin++) { /* After skipping, idxout becomes smaller than idxin */ if (idxin != idxout) /* Copy rest of data; * note we stay in given chunk of allocated memory. */ scanptr[idxout] = scanptr[idxin]; if (scanptr[idxout].Ss > cinfo->lim_Se) /* Entire scan out of range - skip this entry */ continue; if (scanptr[idxout].Se > cinfo->lim_Se) /* Limit scan to end of block */ scanptr[idxout].Se = cinfo->lim_Se; idxout++; } cinfo->num_scans = idxout; } #endif /* C_MULTISCAN_FILES_SUPPORTED */ LOCAL(void) select_scan_parameters (j_compress_ptr cinfo) /* Set up the scan parameters for the current scan */ { int ci; #ifdef C_MULTISCAN_FILES_SUPPORTED if (cinfo->scan_info != NULL) { /* Prepare for current scan --- the script is already validated */ my_master_ptr master = (my_master_ptr) cinfo->master; const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number; cinfo->comps_in_scan = scanptr->comps_in_scan; for (ci = 0; ci < scanptr->comps_in_scan; ci++) { cinfo->cur_comp_info[ci] = &cinfo->comp_info[scanptr->component_index[ci]]; } if (cinfo->progressive_mode) { cinfo->Ss = scanptr->Ss; cinfo->Se = scanptr->Se; cinfo->Ah = scanptr->Ah; cinfo->Al = scanptr->Al; return; } } else #endif { /* Prepare for single sequential-JPEG scan containing all components */ if (cinfo->num_components > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPS_IN_SCAN); cinfo->comps_in_scan = cinfo->num_components; for (ci = 0; ci < cinfo->num_components; ci++) { cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci]; } } cinfo->Ss = 0; cinfo->Se = cinfo->block_size * cinfo->block_size - 1; cinfo->Ah = 0; cinfo->Al = 0; } LOCAL(void) per_scan_setup (j_compress_ptr cinfo) /* Do computations that are needed before processing a JPEG scan */ /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */ { int ci, mcublks, tmp; jpeg_component_info *compptr; if (cinfo->comps_in_scan == 1) { /* Noninterleaved (single-component) scan */ compptr = cinfo->cur_comp_info[0]; /* Overall image size in MCUs */ cinfo->MCUs_per_row = compptr->width_in_blocks; cinfo->MCU_rows_in_scan = compptr->height_in_blocks; /* For noninterleaved scan, always one block per MCU */ compptr->MCU_width = 1; compptr->MCU_height = 1; compptr->MCU_blocks = 1; compptr->MCU_sample_width = compptr->DCT_h_scaled_size; compptr->last_col_width = 1; /* For noninterleaved scans, it is convenient to define last_row_height * as the number of block rows present in the last iMCU row. */ tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (tmp == 0) tmp = compptr->v_samp_factor; compptr->last_row_height = tmp; /* Prepare array describing MCU composition */ cinfo->blocks_in_MCU = 1; cinfo->MCU_membership[0] = 0; } else { /* Interleaved (multi-component) scan */ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan, MAX_COMPS_IN_SCAN); /* Overall image size in MCUs */ cinfo->MCUs_per_row = (JDIMENSION) jdiv_round_up((long) cinfo->jpeg_width, (long) (cinfo->max_h_samp_factor * cinfo->block_size)); cinfo->MCU_rows_in_scan = (JDIMENSION) jdiv_round_up((long) cinfo->jpeg_height, (long) (cinfo->max_v_samp_factor * cinfo->block_size)); cinfo->blocks_in_MCU = 0; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Sampling factors give # of blocks of component in each MCU */ compptr->MCU_width = compptr->h_samp_factor; compptr->MCU_height = compptr->v_samp_factor; compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height; compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_h_scaled_size; /* Figure number of non-dummy blocks in last MCU column & row */ tmp = (int) (compptr->width_in_blocks % compptr->MCU_width); if (tmp == 0) tmp = compptr->MCU_width; compptr->last_col_width = tmp; tmp = (int) (compptr->height_in_blocks % compptr->MCU_height); if (tmp == 0) tmp = compptr->MCU_height; compptr->last_row_height = tmp; /* Prepare array describing MCU composition */ mcublks = compptr->MCU_blocks; if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU) ERREXIT(cinfo, JERR_BAD_MCU_SIZE); while (mcublks-- > 0) { cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci; } } } /* Convert restart specified in rows to actual MCU count. */ /* Note that count must fit in 16 bits, so we provide limiting. */ if (cinfo->restart_in_rows > 0) { long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row; cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L); } } /* * Per-pass setup. * This is called at the beginning of each pass. We determine which modules * will be active during this pass and give them appropriate start_pass calls. * We also set is_last_pass to indicate whether any more passes will be * required. */ METHODDEF(void) prepare_for_pass (j_compress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; switch (master->pass_type) { case main_pass: /* Initial pass: will collect input data, and do either Huffman * optimization or data output for the first scan. */ select_scan_parameters(cinfo); per_scan_setup(cinfo); if (! cinfo->raw_data_in) { (*cinfo->cconvert->start_pass) (cinfo); (*cinfo->downsample->start_pass) (cinfo); (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU); } (*cinfo->fdct->start_pass) (cinfo); (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding); (*cinfo->coef->start_pass) (cinfo, (master->total_passes > 1 ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU)); (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU); if (cinfo->optimize_coding) { /* No immediate data output; postpone writing frame/scan headers */ master->pub.call_pass_startup = FALSE; } else { /* Will write frame/scan headers at first jpeg_write_scanlines call */ master->pub.call_pass_startup = TRUE; } break; #ifdef ENTROPY_OPT_SUPPORTED case huff_opt_pass: /* Do Huffman optimization for a scan after the first one. */ select_scan_parameters(cinfo); per_scan_setup(cinfo); if (cinfo->Ss != 0 || cinfo->Ah == 0) { (*cinfo->entropy->start_pass) (cinfo, TRUE); (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST); master->pub.call_pass_startup = FALSE; break; } /* Special case: Huffman DC refinement scans need no Huffman table * and therefore we can skip the optimization pass for them. */ master->pass_type = output_pass; master->pass_number++; /*FALLTHROUGH*/ #endif case output_pass: /* Do a data-output pass. */ /* We need not repeat per-scan setup if prior optimization pass did it. */ if (! cinfo->optimize_coding) { select_scan_parameters(cinfo); per_scan_setup(cinfo); } (*cinfo->entropy->start_pass) (cinfo, FALSE); (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST); /* We emit frame/scan headers now */ if (master->scan_number == 0) (*cinfo->marker->write_frame_header) (cinfo); (*cinfo->marker->write_scan_header) (cinfo); master->pub.call_pass_startup = FALSE; break; default: ERREXIT(cinfo, JERR_NOT_COMPILED); } master->pub.is_last_pass = (master->pass_number == master->total_passes-1); /* Set up progress monitor's pass info if present */ if (cinfo->progress != NULL) { cinfo->progress->completed_passes = master->pass_number; cinfo->progress->total_passes = master->total_passes; } } /* * Special start-of-pass hook. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE. * In single-pass processing, we need this hook because we don't want to * write frame/scan headers during jpeg_start_compress; we want to let the * application write COM markers etc. between jpeg_start_compress and the * jpeg_write_scanlines loop. * In multi-pass processing, this routine is not used. */ METHODDEF(void) pass_startup (j_compress_ptr cinfo) { cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */ (*cinfo->marker->write_frame_header) (cinfo); (*cinfo->marker->write_scan_header) (cinfo); } /* * Finish up at end of pass. */ METHODDEF(void) finish_pass_master (j_compress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; /* The entropy coder always needs an end-of-pass call, * either to analyze statistics or to flush its output buffer. */ (*cinfo->entropy->finish_pass) (cinfo); /* Update state for next pass */ switch (master->pass_type) { case main_pass: /* next pass is either output of scan 0 (after optimization) * or output of scan 1 (if no optimization). */ master->pass_type = output_pass; if (! cinfo->optimize_coding) master->scan_number++; break; case huff_opt_pass: /* next pass is always output of current scan */ master->pass_type = output_pass; break; case output_pass: /* next pass is either optimization or output of next scan */ if (cinfo->optimize_coding) master->pass_type = huff_opt_pass; master->scan_number++; break; } master->pass_number++; } /* * Initialize master compression control. */ GLOBAL(void) jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only) { my_master_ptr master; master = (my_master_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_comp_master)); cinfo->master = &master->pub; master->pub.prepare_for_pass = prepare_for_pass; master->pub.pass_startup = pass_startup; master->pub.finish_pass = finish_pass_master; master->pub.is_last_pass = FALSE; /* Validate parameters, determine derived values */ initial_setup(cinfo, transcode_only); if (cinfo->scan_info != NULL) { #ifdef C_MULTISCAN_FILES_SUPPORTED validate_script(cinfo); if (cinfo->block_size < DCTSIZE) reduce_script(cinfo); #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { cinfo->progressive_mode = FALSE; cinfo->num_scans = 1; } if (cinfo->optimize_coding) cinfo->arith_code = FALSE; /* disable arithmetic coding */ else if (! cinfo->arith_code && (cinfo->progressive_mode || (cinfo->block_size > 1 && cinfo->block_size < DCTSIZE))) /* TEMPORARY HACK ??? */ /* assume default tables no good for progressive or reduced AC mode */ cinfo->optimize_coding = TRUE; /* force Huffman optimization */ /* Initialize my private state */ if (transcode_only) { /* no main pass in transcoding */ if (cinfo->optimize_coding) master->pass_type = huff_opt_pass; else master->pass_type = output_pass; } else { /* for normal compression, first pass is always this type: */ master->pass_type = main_pass; } master->scan_number = 0; master->pass_number = 0; if (cinfo->optimize_coding) master->total_passes = cinfo->num_scans * 2; else master->total_passes = cinfo->num_scans; } ================================================ FILE: tess-two/jni/libjpeg/jcomapi.c ================================================ /* * jcomapi.c * * Copyright (C) 1994-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains application interface routines that are used for both * compression and decompression. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * Abort processing of a JPEG compression or decompression operation, * but don't destroy the object itself. * * For this, we merely clean up all the nonpermanent memory pools. * Note that temp files (virtual arrays) are not allowed to belong to * the permanent pool, so we will be able to close all temp files here. * Closing a data source or destination, if necessary, is the application's * responsibility. */ GLOBAL(void) jpeg_abort (j_common_ptr cinfo) { int pool; /* Do nothing if called on a not-initialized or destroyed JPEG object. */ if (cinfo->mem == NULL) return; /* Releasing pools in reverse order might help avoid fragmentation * with some (brain-damaged) malloc libraries. */ for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) { (*cinfo->mem->free_pool) (cinfo, pool); } /* Reset overall state for possible reuse of object */ if (cinfo->is_decompressor) { cinfo->global_state = DSTATE_START; /* Try to keep application from accessing now-deleted marker list. * A bit kludgy to do it here, but this is the most central place. */ ((j_decompress_ptr) cinfo)->marker_list = NULL; } else { cinfo->global_state = CSTATE_START; } } /* * Destruction of a JPEG object. * * Everything gets deallocated except the master jpeg_compress_struct itself * and the error manager struct. Both of these are supplied by the application * and must be freed, if necessary, by the application. (Often they are on * the stack and so don't need to be freed anyway.) * Closing a data source or destination, if necessary, is the application's * responsibility. */ GLOBAL(void) jpeg_destroy (j_common_ptr cinfo) { /* We need only tell the memory manager to release everything. */ /* NB: mem pointer is NULL if memory mgr failed to initialize. */ if (cinfo->mem != NULL) (*cinfo->mem->self_destruct) (cinfo); cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */ cinfo->global_state = 0; /* mark it destroyed */ } /* * Convenience routines for allocating quantization and Huffman tables. * (Would jutils.c be a more reasonable place to put these?) */ GLOBAL(JQUANT_TBL *) jpeg_alloc_quant_table (j_common_ptr cinfo) { JQUANT_TBL *tbl; tbl = (JQUANT_TBL *) (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL)); tbl->sent_table = FALSE; /* make sure this is false in any new table */ return tbl; } GLOBAL(JHUFF_TBL *) jpeg_alloc_huff_table (j_common_ptr cinfo) { JHUFF_TBL *tbl; tbl = (JHUFF_TBL *) (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL)); tbl->sent_table = FALSE; /* make sure this is false in any new table */ return tbl; } ================================================ FILE: tess-two/jni/libjpeg/jconfig.bcc ================================================ /* jconfig.bcc --- jconfig.h for Borland C (Turbo C) on MS-DOS or OS/2. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #ifdef __MSDOS__ #define NEED_FAR_POINTERS /* for small or medium memory model */ #endif #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN /* this assumes you have -w-stu in CFLAGS */ #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #ifdef __MSDOS__ #define USE_MSDOS_MEMMGR /* Define this if you use jmemdos.c */ #define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */ #define USE_FMEM /* Borland has _fmemcpy() and _fmemset() */ #endif #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE #define USE_SETMODE /* Borland has setmode() */ #ifdef __MSDOS__ #define NEED_SIGNAL_CATCHER /* Define this if you use jmemdos.c */ #endif #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.cfg ================================================ /* jconfig.cfg --- source file edited by configure script */ /* see jconfig.txt for explanations */ #undef HAVE_PROTOTYPES #undef HAVE_UNSIGNED_CHAR #undef HAVE_UNSIGNED_SHORT #undef void #undef const #undef CHAR_IS_UNSIGNED #undef HAVE_STDDEF_H #undef HAVE_STDLIB_H #undef HAVE_LOCALE_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS #undef NEED_SHORT_EXTERNAL_NAMES /* Define this if you get warnings about undefined structures. */ #undef INCOMPLETE_TYPES_BROKEN /* Define "boolean" as unsigned char, not enum, on Windows systems. */ #ifdef _WIN32 #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */ typedef unsigned char boolean; #endif #ifndef FALSE /* in case these macros already exist */ #define FALSE 0 /* values of boolean */ #endif #ifndef TRUE #define TRUE 1 #endif #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ #endif #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #undef INLINE /* These are for configuring the JPEG memory manager. */ #undef DEFAULT_MAX_MEM #undef NO_MKTEMP #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #undef TWO_FILE_COMMANDLINE #undef NEED_SIGNAL_CATCHER #undef DONT_USE_B_MODE /* Define this if you want percent-done progress reports from cjpeg/djpeg. */ #undef PROGRESS_REPORT #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.dj ================================================ /* jconfig.dj --- jconfig.h for DJGPP (Delorie's GNU C port) on MS-DOS. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS /* DJGPP uses flat 32-bit addressing */ #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #undef TWO_FILE_COMMANDLINE /* optional */ #define USE_SETMODE /* Needed to make one-file style work in DJGPP */ #undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */ #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.h ================================================ ================================================ FILE: tess-two/jni/libjpeg/jconfig.mac ================================================ /* jconfig.mac --- jconfig.h for CodeWarrior on Apple Macintosh */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #define USE_MAC_MEMMGR /* Define this if you use jmemmac.c */ #define ALIGN_TYPE long /* Needed for 680x0 Macs */ #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define USE_CCOMMAND /* Command line reader for Macintosh */ #define TWO_FILE_COMMANDLINE /* Binary I/O thru stdin/stdout doesn't work */ #undef NEED_SIGNAL_CATCHER #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.manx ================================================ /* jconfig.manx --- jconfig.h for Amiga systems using Manx Aztec C ver 5.x. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #define TEMP_DIRECTORY "JPEGTMP:" /* recommended setting for Amiga */ #define SHORTxSHORT_32 /* produces better DCT code with Aztec C */ #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE #define NEED_SIGNAL_CATCHER #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #define signal_catcher _abort /* hack for Aztec C naming requirements */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.mc6 ================================================ /* jconfig.mc6 --- jconfig.h for Microsoft C on MS-DOS, version 6.00A & up. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #define NEED_FAR_POINTERS /* for small or medium memory model */ #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #define USE_MSDOS_MEMMGR /* Define this if you use jmemdos.c */ #define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */ #define USE_FMEM /* Microsoft has _fmemcpy() and _fmemset() */ #define NEED_FHEAPMIN /* far heap management routines are broken */ #define SHORTxLCONST_32 /* enable compiler-specific DCT optimization */ /* Note: the above define is known to improve the code with Microsoft C 6.00A. * I do not know whether it is good for later compiler versions. * Please report any info on this point to jpeg-info@jpegclub.org. */ #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE #define USE_SETMODE /* Microsoft has setmode() */ #define NEED_SIGNAL_CATCHER /* Define this if you use jmemdos.c */ #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.sas ================================================ /* jconfig.sas --- jconfig.h for Amiga systems using SAS C 6.0 and up. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #define TEMP_DIRECTORY "JPEGTMP:" /* recommended setting for Amiga */ #define NO_MKTEMP /* SAS C doesn't have mktemp() */ #define SHORTxSHORT_32 /* produces better DCT code with SAS C */ #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE #define NEED_SIGNAL_CATCHER #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.st ================================================ /* jconfig.st --- jconfig.h for Atari ST/STE/TT using Pure C or Turbo C. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS #undef NEED_SHORT_EXTERNAL_NAMES #define INCOMPLETE_TYPES_BROKEN /* suppress undefined-structure warnings */ #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #define ALIGN_TYPE long /* apparently double is a weird size? */ #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE /* optional -- undef if you like Unix style */ /* Note: if you undef TWO_FILE_COMMANDLINE, you may need to define * USE_SETMODE. Some Atari compilers require it, some do not. */ #define NEED_SIGNAL_CATCHER /* needed if you use jmemname.c */ #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.txt ================================================ /* * jconfig.txt * * Copyright (C) 1991-1994, Thomas G. Lane. * Modified 2009-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file documents the configuration options that are required to * customize the JPEG software for a particular system. * * The actual configuration options for a particular installation are stored * in jconfig.h. On many machines, jconfig.h can be generated automatically * or copied from one of the "canned" jconfig files that we supply. But if * you need to generate a jconfig.h file by hand, this file tells you how. * * DO NOT EDIT THIS FILE --- IT WON'T ACCOMPLISH ANYTHING. * EDIT A COPY NAMED JCONFIG.H. */ /* * These symbols indicate the properties of your machine or compiler. * #define the symbol if yes, #undef it if no. */ /* Does your compiler support function prototypes? * (If not, you also need to use ansi2knr, see install.txt) */ #define HAVE_PROTOTYPES /* Does your compiler support the declaration "unsigned char" ? * How about "unsigned short" ? */ #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* Define "void" as "char" if your compiler doesn't know about type void. * NOTE: be sure to define void such that "void *" represents the most general * pointer type, e.g., that returned by malloc(). */ /* #define void char */ /* Define "const" as empty if your compiler doesn't know the "const" keyword. */ /* #define const */ /* Define this if an ordinary "char" type is unsigned. * If you're not sure, leaving it undefined will work at some cost in speed. * If you defined HAVE_UNSIGNED_CHAR then the speed difference is minimal. */ #undef CHAR_IS_UNSIGNED /* Define this if your system has an ANSI-conforming file. */ #define HAVE_STDDEF_H /* Define this if your system has an ANSI-conforming file. */ #define HAVE_STDLIB_H /* Define this if your system does not have an ANSI/SysV , * but does have a BSD-style . */ #undef NEED_BSD_STRINGS /* Define this if your system does not provide typedef size_t in any of the * ANSI-standard places (stddef.h, stdlib.h, or stdio.h), but places it in * instead. */ #undef NEED_SYS_TYPES_H /* For 80x86 machines, you need to define NEED_FAR_POINTERS, * unless you are using a large-data memory model or 80386 flat-memory mode. * On less brain-damaged CPUs this symbol must not be defined. * (Defining this symbol causes large data structures to be referenced through * "far" pointers and to be allocated with a special version of malloc.) */ #undef NEED_FAR_POINTERS /* Define this if your linker needs global names to be unique in less * than the first 15 characters. */ #undef NEED_SHORT_EXTERNAL_NAMES /* Although a real ANSI C compiler can deal perfectly well with pointers to * unspecified structures (see "incomplete types" in the spec), a few pre-ANSI * and pseudo-ANSI compilers get confused. To keep one of these bozos happy, * define INCOMPLETE_TYPES_BROKEN. This is not recommended unless you * actually get "missing structure definition" warnings or errors while * compiling the JPEG code. */ #undef INCOMPLETE_TYPES_BROKEN /* Define "boolean" as unsigned char, not enum, on Windows systems. */ #ifdef _WIN32 #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */ typedef unsigned char boolean; #endif #ifndef FALSE /* in case these macros already exist */ #define FALSE 0 /* values of boolean */ #endif #ifndef TRUE #define TRUE 1 #endif #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ #endif /* * The following options affect code selection within the JPEG library, * but they don't need to be visible to applications using the library. * To minimize application namespace pollution, the symbols won't be * defined unless JPEG_INTERNALS has been defined. */ #ifdef JPEG_INTERNALS /* Define this if your compiler implements ">>" on signed values as a logical * (unsigned) shift; leave it undefined if ">>" is a signed (arithmetic) shift, * which is the normal and rational definition. */ #undef RIGHT_SHIFT_IS_UNSIGNED #endif /* JPEG_INTERNALS */ /* * The remaining options do not affect the JPEG library proper, * but only the sample applications cjpeg/djpeg (see cjpeg.c, djpeg.c). * Other applications can ignore these. */ #ifdef JPEG_CJPEG_DJPEG /* These defines indicate which image (non-JPEG) file formats are allowed. */ #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ /* Define this if you want to name both input and output files on the command * line, rather than using stdout and optionally stdin. You MUST do this if * your system can't cope with binary I/O to stdin/stdout. See comments at * head of cjpeg.c or djpeg.c. */ #undef TWO_FILE_COMMANDLINE /* Define this if your system needs explicit cleanup of temporary files. * This is crucial under MS-DOS, where the temporary "files" may be areas * of extended memory; on most other systems it's not as important. */ #undef NEED_SIGNAL_CATCHER /* By default, we open image files with fopen(...,"rb") or fopen(...,"wb"). * This is necessary on systems that distinguish text files from binary files, * and is harmless on most systems that don't. If you have one of the rare * systems that complains about the "b" spec, define this symbol. */ #undef DONT_USE_B_MODE /* Define this if you want percent-done progress reports from cjpeg/djpeg. */ #undef PROGRESS_REPORT #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.vc ================================================ /* jconfig.vc --- jconfig.h for Microsoft Visual C++ on Windows 9x or NT. */ /* This file also works for Borland C++ 32-bit (bcc32) on Windows 9x or NT. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */ #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN /* Define "boolean" as unsigned char, not enum, per Windows custom */ #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */ typedef unsigned char boolean; #endif #ifndef FALSE /* in case these macros already exist */ #define FALSE 0 /* values of boolean */ #endif #ifndef TRUE #define TRUE 1 #endif #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE /* optional */ #define USE_SETMODE /* Microsoft has setmode() */ #undef NEED_SIGNAL_CATCHER #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.vms ================================================ /* jconfig.vms --- jconfig.h for use on Digital VMS. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE /* Needed on VMS */ #undef NEED_SIGNAL_CATCHER #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jconfig.wat ================================================ /* jconfig.wat --- jconfig.h for Watcom C/C++ on MS-DOS or OS/2. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #define CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #undef NEED_FAR_POINTERS /* Watcom uses flat 32-bit addressing */ #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #undef TWO_FILE_COMMANDLINE /* optional */ #define USE_SETMODE /* Needed to make one-file style work in Watcom */ #undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */ #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */ ================================================ FILE: tess-two/jni/libjpeg/jcparam.c ================================================ /* * jcparam.c * * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2003-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains optional default-setting code for the JPEG compressor. * Applications do not have to use this file, but those that don't use it * must know a lot more about the innards of the JPEG code. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * Quantization table setup routines */ GLOBAL(void) jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl, const unsigned int *basic_table, int scale_factor, boolean force_baseline) /* Define a quantization table equal to the basic_table times * a scale factor (given as a percentage). * If force_baseline is TRUE, the computed quantization table entries * are limited to 1..255 for JPEG baseline compatibility. */ { JQUANT_TBL ** qtblptr; int i; long temp; /* Safety check to ensure start_compress not called yet. */ if (cinfo->global_state != CSTATE_START) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS) ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl); qtblptr = & cinfo->quant_tbl_ptrs[which_tbl]; if (*qtblptr == NULL) *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo); for (i = 0; i < DCTSIZE2; i++) { temp = ((long) basic_table[i] * scale_factor + 50L) / 100L; /* limit the values to the valid range */ if (temp <= 0L) temp = 1L; if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */ if (force_baseline && temp > 255L) temp = 255L; /* limit to baseline range if requested */ (*qtblptr)->quantval[i] = (UINT16) temp; } /* Initialize sent_table FALSE so table will be written to JPEG file. */ (*qtblptr)->sent_table = FALSE; } /* These are the sample quantization tables given in JPEG spec section K.1. * The spec says that the values given produce "good" quality, and * when divided by 2, "very good" quality. */ static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = { 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 }; static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = { 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 }; GLOBAL(void) jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline) /* Set or change the 'quality' (quantization) setting, using default tables * and straight percentage-scaling quality scales. * This entry point allows different scalings for luminance and chrominance. */ { /* Set up two quantization tables using the specified scaling */ jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl, cinfo->q_scale_factor[0], force_baseline); jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl, cinfo->q_scale_factor[1], force_baseline); } GLOBAL(void) jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor, boolean force_baseline) /* Set or change the 'quality' (quantization) setting, using default tables * and a straight percentage-scaling quality scale. In most cases it's better * to use jpeg_set_quality (below); this entry point is provided for * applications that insist on a linear percentage scaling. */ { /* Set up two quantization tables using the specified scaling */ jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl, scale_factor, force_baseline); jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl, scale_factor, force_baseline); } GLOBAL(int) jpeg_quality_scaling (int quality) /* Convert a user-specified quality rating to a percentage scaling factor * for an underlying quantization table, using our recommended scaling curve. * The input 'quality' factor should be 0 (terrible) to 100 (very good). */ { /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */ if (quality <= 0) quality = 1; if (quality > 100) quality = 100; /* The basic table is used as-is (scaling 100) for a quality of 50. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q; * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table * to make all the table entries 1 (hence, minimum quantization loss). * Qualities 1..50 are converted to scaling percentage 5000/Q. */ if (quality < 50) quality = 5000 / quality; else quality = 200 - quality*2; return quality; } GLOBAL(void) jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline) /* Set or change the 'quality' (quantization) setting, using default tables. * This is the standard quality-adjusting entry point for typical user * interfaces; only those who want detailed control over quantization tables * would use the preceding routines directly. */ { /* Convert user 0-100 rating to percentage scaling */ quality = jpeg_quality_scaling(quality); /* Set up standard quality tables */ jpeg_set_linear_quality(cinfo, quality, force_baseline); } /* * Huffman table setup routines */ LOCAL(void) add_huff_table (j_compress_ptr cinfo, JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val) /* Define a Huffman table */ { int nsymbols, len; if (*htblptr == NULL) *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); /* Copy the number-of-symbols-of-each-code-length counts */ MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits)); /* Validate the counts. We do this here mainly so we can copy the right * number of symbols from the val[] array, without risking marching off * the end of memory. jchuff.c will do a more thorough test later. */ nsymbols = 0; for (len = 1; len <= 16; len++) nsymbols += bits[len]; if (nsymbols < 1 || nsymbols > 256) ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8)); /* Initialize sent_table FALSE so table will be written to JPEG file. */ (*htblptr)->sent_table = FALSE; } LOCAL(void) std_huff_tables (j_compress_ptr cinfo) /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */ /* IMPORTANT: these are only valid for 8-bit data precision! */ { static const UINT8 bits_dc_luminance[17] = { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }; static const UINT8 val_dc_luminance[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; static const UINT8 bits_dc_chrominance[17] = { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }; static const UINT8 val_dc_chrominance[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; static const UINT8 bits_ac_luminance[17] = { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }; static const UINT8 val_ac_luminance[] = { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa }; static const UINT8 bits_ac_chrominance[17] = { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }; static const UINT8 val_ac_chrominance[] = { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa }; add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0], bits_dc_luminance, val_dc_luminance); add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0], bits_ac_luminance, val_ac_luminance); add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1], bits_dc_chrominance, val_dc_chrominance); add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1], bits_ac_chrominance, val_ac_chrominance); } /* * Default parameter setup for compression. * * Applications that don't choose to use this routine must do their * own setup of all these parameters. Alternately, you can call this * to establish defaults and then alter parameters selectively. This * is the recommended approach since, if we add any new parameters, * your code will still work (they'll be set to reasonable defaults). */ GLOBAL(void) jpeg_set_defaults (j_compress_ptr cinfo) { int i; /* Safety check to ensure start_compress not called yet. */ if (cinfo->global_state != CSTATE_START) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Allocate comp_info array large enough for maximum component count. * Array is made permanent in case application wants to compress * multiple images at same param settings. */ if (cinfo->comp_info == NULL) cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, MAX_COMPONENTS * SIZEOF(jpeg_component_info)); /* Initialize everything not dependent on the color space */ cinfo->scale_num = 1; /* 1:1 scaling */ cinfo->scale_denom = 1; cinfo->data_precision = BITS_IN_JSAMPLE; /* Set up two quantization tables using default quality of 75 */ jpeg_set_quality(cinfo, 75, TRUE); /* Set up two Huffman tables */ std_huff_tables(cinfo); /* Initialize default arithmetic coding conditioning */ for (i = 0; i < NUM_ARITH_TBLS; i++) { cinfo->arith_dc_L[i] = 0; cinfo->arith_dc_U[i] = 1; cinfo->arith_ac_K[i] = 5; } /* Default is no multiple-scan output */ cinfo->scan_info = NULL; cinfo->num_scans = 0; /* Expect normal source image, not raw downsampled data */ cinfo->raw_data_in = FALSE; /* The standard Huffman tables are only valid for 8-bit data precision. * If the precision is higher, use arithmetic coding. * (Alternatively, using Huffman coding would be possible with forcing * optimization on so that usable tables will be computed, or by * supplying default tables that are valid for the desired precision.) * Otherwise, use Huffman coding by default. */ cinfo->arith_code = cinfo->data_precision > 8 ? TRUE : FALSE; /* By default, don't do extra passes to optimize entropy coding */ cinfo->optimize_coding = FALSE; /* By default, use the simpler non-cosited sampling alignment */ cinfo->CCIR601_sampling = FALSE; /* By default, apply fancy downsampling */ cinfo->do_fancy_downsampling = TRUE; /* No input smoothing */ cinfo->smoothing_factor = 0; /* DCT algorithm preference */ cinfo->dct_method = JDCT_DEFAULT; /* No restart markers */ cinfo->restart_interval = 0; cinfo->restart_in_rows = 0; /* Fill in default JFIF marker parameters. Note that whether the marker * will actually be written is determined by jpeg_set_colorspace. * * By default, the library emits JFIF version code 1.01. * An application that wants to emit JFIF 1.02 extension markers should set * JFIF_minor_version to 2. We could probably get away with just defaulting * to 1.02, but there may still be some decoders in use that will complain * about that; saying 1.01 should minimize compatibility problems. * * For wide gamut colorspaces (BG_RGB and BG_YCC), the major version will be * overridden by jpeg_set_colorspace and set to 2. */ cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */ cinfo->JFIF_minor_version = 1; cinfo->density_unit = 0; /* Pixel size is unknown by default */ cinfo->X_density = 1; /* Pixel aspect ratio is square by default */ cinfo->Y_density = 1; /* No color transform */ cinfo->color_transform = JCT_NONE; /* Choose JPEG colorspace based on input space, set defaults accordingly */ jpeg_default_colorspace(cinfo); } /* * Select an appropriate JPEG colorspace for in_color_space. */ GLOBAL(void) jpeg_default_colorspace (j_compress_ptr cinfo) { switch (cinfo->in_color_space) { case JCS_UNKNOWN: jpeg_set_colorspace(cinfo, JCS_UNKNOWN); break; case JCS_GRAYSCALE: jpeg_set_colorspace(cinfo, JCS_GRAYSCALE); break; case JCS_RGB: jpeg_set_colorspace(cinfo, JCS_YCbCr); break; case JCS_YCbCr: jpeg_set_colorspace(cinfo, JCS_YCbCr); break; case JCS_CMYK: jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */ break; case JCS_YCCK: jpeg_set_colorspace(cinfo, JCS_YCCK); break; case JCS_BG_RGB: /* No translation for now -- conversion to BG_YCC not yet supportet */ jpeg_set_colorspace(cinfo, JCS_BG_RGB); break; case JCS_BG_YCC: jpeg_set_colorspace(cinfo, JCS_BG_YCC); break; default: ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); } } /* * Set the JPEG colorspace, and choose colorspace-dependent default values. */ GLOBAL(void) jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace) { jpeg_component_info * compptr; int ci; #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \ (compptr = &cinfo->comp_info[index], \ compptr->component_id = (id), \ compptr->h_samp_factor = (hsamp), \ compptr->v_samp_factor = (vsamp), \ compptr->quant_tbl_no = (quant), \ compptr->dc_tbl_no = (dctbl), \ compptr->ac_tbl_no = (actbl) ) /* Safety check to ensure start_compress not called yet. */ if (cinfo->global_state != CSTATE_START) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* For all colorspaces, we use Q and Huff tables 0 for luminance components, * tables 1 for chrominance components. */ cinfo->jpeg_color_space = colorspace; cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */ cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */ switch (colorspace) { case JCS_UNKNOWN: cinfo->num_components = cinfo->input_components; if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPONENTS); for (ci = 0; ci < cinfo->num_components; ci++) { SET_COMP(ci, ci, 1,1, 0, 0,0); } break; case JCS_GRAYSCALE: cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */ cinfo->num_components = 1; /* JFIF specifies component ID 1 */ SET_COMP(0, 0x01, 1,1, 0, 0,0); break; case JCS_RGB: cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */ cinfo->num_components = 3; SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0); SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0); SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0); break; case JCS_YCbCr: cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */ cinfo->num_components = 3; /* JFIF specifies component IDs 1,2,3 */ /* We default to 2x2 subsamples of chrominance */ SET_COMP(0, 0x01, 2,2, 0, 0,0); SET_COMP(1, 0x02, 1,1, 1, 1,1); SET_COMP(2, 0x03, 1,1, 1, 1,1); break; case JCS_CMYK: cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */ cinfo->num_components = 4; SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0); SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0); SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0); SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0); break; case JCS_YCCK: cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */ cinfo->num_components = 4; SET_COMP(0, 0x01, 2,2, 0, 0,0); SET_COMP(1, 0x02, 1,1, 1, 1,1); SET_COMP(2, 0x03, 1,1, 1, 1,1); SET_COMP(3, 0x04, 2,2, 0, 0,0); break; case JCS_BG_RGB: cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */ cinfo->JFIF_major_version = 2; /* Set JFIF major version = 2 */ cinfo->num_components = 3; /* Add offset 0x20 to the normal R/G/B component IDs */ SET_COMP(0, 0x72 /* 'r' */, 1,1, 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0); SET_COMP(1, 0x67 /* 'g' */, 1,1, 0, 0,0); SET_COMP(2, 0x62 /* 'b' */, 1,1, 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0, cinfo->color_transform == JCT_SUBTRACT_GREEN ? 1 : 0); break; case JCS_BG_YCC: cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */ cinfo->JFIF_major_version = 2; /* Set JFIF major version = 2 */ cinfo->num_components = 3; /* Add offset 0x20 to the normal Cb/Cr component IDs */ /* We default to 2x2 subsamples of chrominance */ SET_COMP(0, 0x01, 2,2, 0, 0,0); SET_COMP(1, 0x22, 1,1, 1, 1,1); SET_COMP(2, 0x23, 1,1, 1, 1,1); break; default: ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); } } #ifdef C_PROGRESSIVE_SUPPORTED LOCAL(jpeg_scan_info *) fill_a_scan (jpeg_scan_info * scanptr, int ci, int Ss, int Se, int Ah, int Al) /* Support routine: generate one scan for specified component */ { scanptr->comps_in_scan = 1; scanptr->component_index[0] = ci; scanptr->Ss = Ss; scanptr->Se = Se; scanptr->Ah = Ah; scanptr->Al = Al; scanptr++; return scanptr; } LOCAL(jpeg_scan_info *) fill_scans (jpeg_scan_info * scanptr, int ncomps, int Ss, int Se, int Ah, int Al) /* Support routine: generate one scan for each component */ { int ci; for (ci = 0; ci < ncomps; ci++) { scanptr->comps_in_scan = 1; scanptr->component_index[0] = ci; scanptr->Ss = Ss; scanptr->Se = Se; scanptr->Ah = Ah; scanptr->Al = Al; scanptr++; } return scanptr; } LOCAL(jpeg_scan_info *) fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al) /* Support routine: generate interleaved DC scan if possible, else N scans */ { int ci; if (ncomps <= MAX_COMPS_IN_SCAN) { /* Single interleaved DC scan */ scanptr->comps_in_scan = ncomps; for (ci = 0; ci < ncomps; ci++) scanptr->component_index[ci] = ci; scanptr->Ss = scanptr->Se = 0; scanptr->Ah = Ah; scanptr->Al = Al; scanptr++; } else { /* Noninterleaved DC scan for each component */ scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al); } return scanptr; } /* * Create a recommended progressive-JPEG script. * cinfo->num_components and cinfo->jpeg_color_space must be correct. */ GLOBAL(void) jpeg_simple_progression (j_compress_ptr cinfo) { int ncomps = cinfo->num_components; int nscans; jpeg_scan_info * scanptr; /* Safety check to ensure start_compress not called yet. */ if (cinfo->global_state != CSTATE_START) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Figure space needed for script. Calculation must match code below! */ if (ncomps == 3 && (cinfo->jpeg_color_space == JCS_YCbCr || cinfo->jpeg_color_space == JCS_BG_YCC)) { /* Custom script for YCC color images. */ nscans = 10; } else { /* All-purpose script for other color spaces. */ if (ncomps > MAX_COMPS_IN_SCAN) nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */ else nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */ } /* Allocate space for script. * We need to put it in the permanent pool in case the application performs * multiple compressions without changing the settings. To avoid a memory * leak if jpeg_simple_progression is called repeatedly for the same JPEG * object, we try to re-use previously allocated space, and we allocate * enough space to handle YCC even if initially asked for grayscale. */ if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) { cinfo->script_space_size = MAX(nscans, 10); cinfo->script_space = (jpeg_scan_info *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, cinfo->script_space_size * SIZEOF(jpeg_scan_info)); } scanptr = cinfo->script_space; cinfo->scan_info = scanptr; cinfo->num_scans = nscans; if (ncomps == 3 && (cinfo->jpeg_color_space == JCS_YCbCr || cinfo->jpeg_color_space == JCS_BG_YCC)) { /* Custom script for YCC color images. */ /* Initial DC scan */ scanptr = fill_dc_scans(scanptr, ncomps, 0, 1); /* Initial AC scan: get some luma data out in a hurry */ scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2); /* Chroma data is too small to be worth expending many scans on */ scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1); scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1); /* Complete spectral selection for luma AC */ scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2); /* Refine next bit of luma AC */ scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1); /* Finish DC successive approximation */ scanptr = fill_dc_scans(scanptr, ncomps, 1, 0); /* Finish AC successive approximation */ scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0); scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0); /* Luma bottom bit comes last since it's usually largest scan */ scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0); } else { /* All-purpose script for other color spaces. */ /* Successive approximation first pass */ scanptr = fill_dc_scans(scanptr, ncomps, 0, 1); scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2); scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2); /* Successive approximation second pass */ scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1); /* Successive approximation final pass */ scanptr = fill_dc_scans(scanptr, ncomps, 1, 0); scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0); } } #endif /* C_PROGRESSIVE_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jcprepct.c ================================================ /* * jcprepct.c * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the compression preprocessing controller. * This controller manages the color conversion, downsampling, * and edge expansion steps. * * Most of the complexity here is associated with buffering input rows * as required by the downsampler. See the comments at the head of * jcsample.c for the downsampler's needs. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* At present, jcsample.c can request context rows only for smoothing. * In the future, we might also need context rows for CCIR601 sampling * or other more-complex downsampling procedures. The code to support * context rows should be compiled only if needed. */ #ifdef INPUT_SMOOTHING_SUPPORTED #define CONTEXT_ROWS_SUPPORTED #endif /* * For the simple (no-context-row) case, we just need to buffer one * row group's worth of pixels for the downsampling step. At the bottom of * the image, we pad to a full row group by replicating the last pixel row. * The downsampler's last output row is then replicated if needed to pad * out to a full iMCU row. * * When providing context rows, we must buffer three row groups' worth of * pixels. Three row groups are physically allocated, but the row pointer * arrays are made five row groups high, with the extra pointers above and * below "wrapping around" to point to the last and first real row groups. * This allows the downsampler to access the proper context rows. * At the top and bottom of the image, we create dummy context rows by * copying the first or last real pixel row. This copying could be avoided * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the * trouble on the compression side. */ /* Private buffer controller object */ typedef struct { struct jpeg_c_prep_controller pub; /* public fields */ /* Downsampling input buffer. This buffer holds color-converted data * until we have enough to do a downsample step. */ JSAMPARRAY color_buf[MAX_COMPONENTS]; JDIMENSION rows_to_go; /* counts rows remaining in source image */ int next_buf_row; /* index of next row to store in color_buf */ #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */ int this_row_group; /* starting row index of group to process */ int next_buf_stop; /* downsample when we reach this index */ #endif } my_prep_controller; typedef my_prep_controller * my_prep_ptr; /* * Initialize for a processing pass. */ METHODDEF(void) start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode) { my_prep_ptr prep = (my_prep_ptr) cinfo->prep; if (pass_mode != JBUF_PASS_THRU) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); /* Initialize total-height counter for detecting bottom of image */ prep->rows_to_go = cinfo->image_height; /* Mark the conversion buffer empty */ prep->next_buf_row = 0; #ifdef CONTEXT_ROWS_SUPPORTED /* Preset additional state variables for context mode. * These aren't used in non-context mode, so we needn't test which mode. */ prep->this_row_group = 0; /* Set next_buf_stop to stop after two row groups have been read in. */ prep->next_buf_stop = 2 * cinfo->max_v_samp_factor; #endif } /* * Expand an image vertically from height input_rows to height output_rows, * by duplicating the bottom row. */ LOCAL(void) expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols, int input_rows, int output_rows) { register int row; for (row = input_rows; row < output_rows; row++) { jcopy_sample_rows(image_data, input_rows-1, image_data, row, 1, num_cols); } } /* * Process some data in the simple no-context case. * * Preprocessor output data is counted in "row groups". A row group * is defined to be v_samp_factor sample rows of each component. * Downsampling will produce this much data from each max_v_samp_factor * input rows. */ METHODDEF(void) pre_process_data (j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail, JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr, JDIMENSION out_row_groups_avail) { my_prep_ptr prep = (my_prep_ptr) cinfo->prep; int numrows, ci; JDIMENSION inrows; jpeg_component_info * compptr; while (*in_row_ctr < in_rows_avail && *out_row_group_ctr < out_row_groups_avail) { /* Do color conversion to fill the conversion buffer. */ inrows = in_rows_avail - *in_row_ctr; numrows = cinfo->max_v_samp_factor - prep->next_buf_row; numrows = (int) MIN((JDIMENSION) numrows, inrows); (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr, prep->color_buf, (JDIMENSION) prep->next_buf_row, numrows); *in_row_ctr += numrows; prep->next_buf_row += numrows; prep->rows_to_go -= numrows; /* If at bottom of image, pad to fill the conversion buffer. */ if (prep->rows_to_go == 0 && prep->next_buf_row < cinfo->max_v_samp_factor) { for (ci = 0; ci < cinfo->num_components; ci++) { expand_bottom_edge(prep->color_buf[ci], cinfo->image_width, prep->next_buf_row, cinfo->max_v_samp_factor); } prep->next_buf_row = cinfo->max_v_samp_factor; } /* If we've filled the conversion buffer, empty it. */ if (prep->next_buf_row == cinfo->max_v_samp_factor) { (*cinfo->downsample->downsample) (cinfo, prep->color_buf, (JDIMENSION) 0, output_buf, *out_row_group_ctr); prep->next_buf_row = 0; (*out_row_group_ctr)++; } /* If at bottom of image, pad the output to a full iMCU height. * Note we assume the caller is providing a one-iMCU-height output buffer! */ if (prep->rows_to_go == 0 && *out_row_group_ctr < out_row_groups_avail) { for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { numrows = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) / cinfo->min_DCT_v_scaled_size; expand_bottom_edge(output_buf[ci], compptr->width_in_blocks * compptr->DCT_h_scaled_size, (int) (*out_row_group_ctr * numrows), (int) (out_row_groups_avail * numrows)); } *out_row_group_ctr = out_row_groups_avail; break; /* can exit outer loop without test */ } } } #ifdef CONTEXT_ROWS_SUPPORTED /* * Process some data in the context case. */ METHODDEF(void) pre_process_context (j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail, JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr, JDIMENSION out_row_groups_avail) { my_prep_ptr prep = (my_prep_ptr) cinfo->prep; int numrows, ci; int buf_height = cinfo->max_v_samp_factor * 3; JDIMENSION inrows; while (*out_row_group_ctr < out_row_groups_avail) { if (*in_row_ctr < in_rows_avail) { /* Do color conversion to fill the conversion buffer. */ inrows = in_rows_avail - *in_row_ctr; numrows = prep->next_buf_stop - prep->next_buf_row; numrows = (int) MIN((JDIMENSION) numrows, inrows); (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr, prep->color_buf, (JDIMENSION) prep->next_buf_row, numrows); /* Pad at top of image, if first time through */ if (prep->rows_to_go == cinfo->image_height) { for (ci = 0; ci < cinfo->num_components; ci++) { int row; for (row = 1; row <= cinfo->max_v_samp_factor; row++) { jcopy_sample_rows(prep->color_buf[ci], 0, prep->color_buf[ci], -row, 1, cinfo->image_width); } } } *in_row_ctr += numrows; prep->next_buf_row += numrows; prep->rows_to_go -= numrows; } else { /* Return for more data, unless we are at the bottom of the image. */ if (prep->rows_to_go != 0) break; /* When at bottom of image, pad to fill the conversion buffer. */ if (prep->next_buf_row < prep->next_buf_stop) { for (ci = 0; ci < cinfo->num_components; ci++) { expand_bottom_edge(prep->color_buf[ci], cinfo->image_width, prep->next_buf_row, prep->next_buf_stop); } prep->next_buf_row = prep->next_buf_stop; } } /* If we've gotten enough data, downsample a row group. */ if (prep->next_buf_row == prep->next_buf_stop) { (*cinfo->downsample->downsample) (cinfo, prep->color_buf, (JDIMENSION) prep->this_row_group, output_buf, *out_row_group_ctr); (*out_row_group_ctr)++; /* Advance pointers with wraparound as necessary. */ prep->this_row_group += cinfo->max_v_samp_factor; if (prep->this_row_group >= buf_height) prep->this_row_group = 0; if (prep->next_buf_row >= buf_height) prep->next_buf_row = 0; prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor; } } } /* * Create the wrapped-around downsampling input buffer needed for context mode. */ LOCAL(void) create_context_buffer (j_compress_ptr cinfo) { my_prep_ptr prep = (my_prep_ptr) cinfo->prep; int rgroup_height = cinfo->max_v_samp_factor; int ci, i; jpeg_component_info * compptr; JSAMPARRAY true_buffer, fake_buffer; /* Grab enough space for fake row pointers for all the components; * we need five row groups' worth of pointers for each component. */ fake_buffer = (JSAMPARRAY) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (cinfo->num_components * 5 * rgroup_height) * SIZEOF(JSAMPROW)); for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Allocate the actual buffer space (3 row groups) for this component. * We make the buffer wide enough to allow the downsampler to edge-expand * horizontally within the buffer, if it so chooses. */ true_buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) (((long) compptr->width_in_blocks * cinfo->min_DCT_h_scaled_size * cinfo->max_h_samp_factor) / compptr->h_samp_factor), (JDIMENSION) (3 * rgroup_height)); /* Copy true buffer row pointers into the middle of the fake row array */ MEMCOPY(fake_buffer + rgroup_height, true_buffer, 3 * rgroup_height * SIZEOF(JSAMPROW)); /* Fill in the above and below wraparound pointers */ for (i = 0; i < rgroup_height; i++) { fake_buffer[i] = true_buffer[2 * rgroup_height + i]; fake_buffer[4 * rgroup_height + i] = true_buffer[i]; } prep->color_buf[ci] = fake_buffer + rgroup_height; fake_buffer += 5 * rgroup_height; /* point to space for next component */ } } #endif /* CONTEXT_ROWS_SUPPORTED */ /* * Initialize preprocessing controller. */ GLOBAL(void) jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer) { my_prep_ptr prep; int ci; jpeg_component_info * compptr; if (need_full_buffer) /* safety check */ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); prep = (my_prep_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_prep_controller)); cinfo->prep = (struct jpeg_c_prep_controller *) prep; prep->pub.start_pass = start_pass_prep; /* Allocate the color conversion buffer. * We make the buffer wide enough to allow the downsampler to edge-expand * horizontally within the buffer, if it so chooses. */ if (cinfo->downsample->need_context_rows) { /* Set up to provide context rows */ #ifdef CONTEXT_ROWS_SUPPORTED prep->pub.pre_process_data = pre_process_context; create_context_buffer(cinfo); #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { /* No context, just make it tall enough for one row group */ prep->pub.pre_process_data = pre_process_data; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { prep->color_buf[ci] = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) (((long) compptr->width_in_blocks * cinfo->min_DCT_h_scaled_size * cinfo->max_h_samp_factor) / compptr->h_samp_factor), (JDIMENSION) cinfo->max_v_samp_factor); } } } ================================================ FILE: tess-two/jni/libjpeg/jcsample.c ================================================ /* * jcsample.c * * Copyright (C) 1991-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains downsampling routines. * * Downsampling input data is counted in "row groups". A row group * is defined to be max_v_samp_factor pixel rows of each component, * from which the downsampler produces v_samp_factor sample rows. * A single row group is processed in each call to the downsampler module. * * The downsampler is responsible for edge-expansion of its output data * to fill an integral number of DCT blocks horizontally. The source buffer * may be modified if it is helpful for this purpose (the source buffer is * allocated wide enough to correspond to the desired output width). * The caller (the prep controller) is responsible for vertical padding. * * The downsampler may request "context rows" by setting need_context_rows * during startup. In this case, the input arrays will contain at least * one row group's worth of pixels above and below the passed-in data; * the caller will create dummy rows at image top and bottom by replicating * the first or last real pixel row. * * An excellent reference for image resampling is * Digital Image Warping, George Wolberg, 1990. * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7. * * The downsampling algorithm used here is a simple average of the source * pixels covered by the output pixel. The hi-falutin sampling literature * refers to this as a "box filter". In general the characteristics of a box * filter are not very good, but for the specific cases we normally use (1:1 * and 2:1 ratios) the box is equivalent to a "triangle filter" which is not * nearly so bad. If you intend to use other sampling ratios, you'd be well * advised to improve this code. * * A simple input-smoothing capability is provided. This is mainly intended * for cleaning up color-dithered GIF input files (if you find it inadequate, * we suggest using an external filtering program such as pnmconvol). When * enabled, each input pixel P is replaced by a weighted sum of itself and its * eight neighbors. P's weight is 1-8*SF and each neighbor's weight is SF, * where SF = (smoothing_factor / 1024). * Currently, smoothing is only supported for 2h2v sampling factors. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Pointer to routine to downsample a single component */ typedef JMETHOD(void, downsample1_ptr, (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data)); /* Private subobject */ typedef struct { struct jpeg_downsampler pub; /* public fields */ /* Downsampling method pointers, one per component */ downsample1_ptr methods[MAX_COMPONENTS]; /* Height of an output row group for each component. */ int rowgroup_height[MAX_COMPONENTS]; /* These arrays save pixel expansion factors so that int_downsample need not * recompute them each time. They are unused for other downsampling methods. */ UINT8 h_expand[MAX_COMPONENTS]; UINT8 v_expand[MAX_COMPONENTS]; } my_downsampler; typedef my_downsampler * my_downsample_ptr; /* * Initialize for a downsampling pass. */ METHODDEF(void) start_pass_downsample (j_compress_ptr cinfo) { /* no work for now */ } /* * Expand a component horizontally from width input_cols to width output_cols, * by duplicating the rightmost samples. */ LOCAL(void) expand_right_edge (JSAMPARRAY image_data, int num_rows, JDIMENSION input_cols, JDIMENSION output_cols) { register JSAMPROW ptr; register JSAMPLE pixval; register int count; int row; int numcols = (int) (output_cols - input_cols); if (numcols > 0) { for (row = 0; row < num_rows; row++) { ptr = image_data[row] + input_cols; pixval = ptr[-1]; /* don't need GETJSAMPLE() here */ for (count = numcols; count > 0; count--) *ptr++ = pixval; } } } /* * Do downsampling for a whole row group (all components). * * In this version we simply downsample each component independently. */ METHODDEF(void) sep_downsample (j_compress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION in_row_index, JSAMPIMAGE output_buf, JDIMENSION out_row_group_index) { my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample; int ci; jpeg_component_info * compptr; JSAMPARRAY in_ptr, out_ptr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { in_ptr = input_buf[ci] + in_row_index; out_ptr = output_buf[ci] + (out_row_group_index * downsample->rowgroup_height[ci]); (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr); } } /* * Downsample pixel values of a single component. * One row group is processed per call. * This version handles arbitrary integral sampling ratios, without smoothing. * Note that this version is not actually used for customary sampling ratios. */ METHODDEF(void) int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample; int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v; JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */ JDIMENSION output_cols = compptr->width_in_blocks * compptr->DCT_h_scaled_size; JSAMPROW inptr, outptr; INT32 outvalue; h_expand = downsample->h_expand[compptr->component_index]; v_expand = downsample->v_expand[compptr->component_index]; numpix = h_expand * v_expand; numpix2 = numpix/2; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * h_expand); inrow = outrow = 0; while (inrow < cinfo->max_v_samp_factor) { outptr = output_data[outrow]; for (outcol = 0, outcol_h = 0; outcol < output_cols; outcol++, outcol_h += h_expand) { outvalue = 0; for (v = 0; v < v_expand; v++) { inptr = input_data[inrow+v] + outcol_h; for (h = 0; h < h_expand; h++) { outvalue += (INT32) GETJSAMPLE(*inptr++); } } *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix); } inrow += v_expand; outrow++; } } /* * Downsample pixel values of a single component. * This version handles the special case of a full-size component, * without smoothing. */ METHODDEF(void) fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { /* Copy the data */ jcopy_sample_rows(input_data, 0, output_data, 0, cinfo->max_v_samp_factor, cinfo->image_width); /* Edge-expand */ expand_right_edge(output_data, cinfo->max_v_samp_factor, cinfo->image_width, compptr->width_in_blocks * compptr->DCT_h_scaled_size); } /* * Downsample pixel values of a single component. * This version handles the common case of 2:1 horizontal and 1:1 vertical, * without smoothing. * * A note about the "bias" calculations: when rounding fractional values to * integer, we do not want to always round 0.5 up to the next integer. * If we did that, we'd introduce a noticeable bias towards larger values. * Instead, this code is arranged so that 0.5 will be rounded up or down at * alternate pixel locations (a simple ordered dither pattern). */ METHODDEF(void) h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow; JDIMENSION outcol; JDIMENSION output_cols = compptr->width_in_blocks * compptr->DCT_h_scaled_size; register JSAMPROW inptr, outptr; register int bias; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * 2); for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) { outptr = output_data[inrow]; inptr = input_data[inrow]; bias = 0; /* bias = 0,1,0,1,... for successive samples */ for (outcol = 0; outcol < output_cols; outcol++) { *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1]) + bias) >> 1); bias ^= 1; /* 0=>1, 1=>0 */ inptr += 2; } } } /* * Downsample pixel values of a single component. * This version handles the standard case of 2:1 horizontal and 2:1 vertical, * without smoothing. */ METHODDEF(void) h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow; JDIMENSION outcol; JDIMENSION output_cols = compptr->width_in_blocks * compptr->DCT_h_scaled_size; register JSAMPROW inptr0, inptr1, outptr; register int bias; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * 2); inrow = outrow = 0; while (inrow < cinfo->max_v_samp_factor) { outptr = output_data[outrow]; inptr0 = input_data[inrow]; inptr1 = input_data[inrow+1]; bias = 1; /* bias = 1,2,1,2,... for successive samples */ for (outcol = 0; outcol < output_cols; outcol++) { *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]) + bias) >> 2); bias ^= 3; /* 1=>2, 2=>1 */ inptr0 += 2; inptr1 += 2; } inrow += 2; outrow++; } } #ifdef INPUT_SMOOTHING_SUPPORTED /* * Downsample pixel values of a single component. * This version handles the standard case of 2:1 horizontal and 2:1 vertical, * with smoothing. One row of context is required. */ METHODDEF(void) h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow; JDIMENSION colctr; JDIMENSION output_cols = compptr->width_in_blocks * compptr->DCT_h_scaled_size; register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr; INT32 membersum, neighsum, memberscale, neighscale; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, cinfo->image_width, output_cols * 2); /* We don't bother to form the individual "smoothed" input pixel values; * we can directly compute the output which is the average of the four * smoothed values. Each of the four member pixels contributes a fraction * (1-8*SF) to its own smoothed image and a fraction SF to each of the three * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final * output. The four corner-adjacent neighbor pixels contribute a fraction * SF to just one smoothed pixel, or SF/4 to the final output; while the * eight edge-adjacent neighbors contribute SF to each of two smoothed * pixels, or SF/2 overall. In order to use integer arithmetic, these * factors are scaled by 2^16 = 65536. * Also recall that SF = smoothing_factor / 1024. */ memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */ neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */ inrow = outrow = 0; while (inrow < cinfo->max_v_samp_factor) { outptr = output_data[outrow]; inptr0 = input_data[inrow]; inptr1 = input_data[inrow+1]; above_ptr = input_data[inrow-1]; below_ptr = input_data[inrow+2]; /* Special case for first column: pretend column -1 is same as column 0 */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]); neighsum += neighsum; neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]); membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; for (colctr = output_cols - 2; colctr > 0; colctr--) { /* sum of pixels directly mapped to this output element */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); /* sum of edge-neighbor pixels */ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]); /* The edge-neighbors count twice as much as corner-neighbors */ neighsum += neighsum; /* Add in the corner-neighbors */ neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]); /* form final output scaled up by 2^16 */ membersum = membersum * memberscale + neighsum * neighscale; /* round, descale and output it */ *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; } /* Special case for last column */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]); neighsum += neighsum; neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]); membersum = membersum * memberscale + neighsum * neighscale; *outptr = (JSAMPLE) ((membersum + 32768) >> 16); inrow += 2; outrow++; } } /* * Downsample pixel values of a single component. * This version handles the special case of a full-size component, * with smoothing. One row of context is required. */ METHODDEF(void) fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow; JDIMENSION colctr; JDIMENSION output_cols = compptr->width_in_blocks * compptr->DCT_h_scaled_size; register JSAMPROW inptr, above_ptr, below_ptr, outptr; INT32 membersum, neighsum, memberscale, neighscale; int colsum, lastcolsum, nextcolsum; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, cinfo->image_width, output_cols); /* Each of the eight neighbor pixels contributes a fraction SF to the * smoothed pixel, while the main pixel contributes (1-8*SF). In order * to use integer arithmetic, these factors are multiplied by 2^16 = 65536. * Also recall that SF = smoothing_factor / 1024. */ memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */ neighscale = cinfo->smoothing_factor * 64; /* scaled SF */ for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) { outptr = output_data[inrow]; inptr = input_data[inrow]; above_ptr = input_data[inrow-1]; below_ptr = input_data[inrow+1]; /* Special case for first column */ colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) + GETJSAMPLE(*inptr); membersum = GETJSAMPLE(*inptr++); nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(*inptr); neighsum = colsum + (colsum - membersum) + nextcolsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); lastcolsum = colsum; colsum = nextcolsum; for (colctr = output_cols - 2; colctr > 0; colctr--) { membersum = GETJSAMPLE(*inptr++); above_ptr++; below_ptr++; nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(*inptr); neighsum = lastcolsum + (colsum - membersum) + nextcolsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); lastcolsum = colsum; colsum = nextcolsum; } /* Special case for last column */ membersum = GETJSAMPLE(*inptr); neighsum = lastcolsum + (colsum - membersum) + colsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr = (JSAMPLE) ((membersum + 32768) >> 16); } } #endif /* INPUT_SMOOTHING_SUPPORTED */ /* * Module initialization routine for downsampling. * Note that we must select a routine for each component. */ GLOBAL(void) jinit_downsampler (j_compress_ptr cinfo) { my_downsample_ptr downsample; int ci; jpeg_component_info * compptr; boolean smoothok = TRUE; int h_in_group, v_in_group, h_out_group, v_out_group; downsample = (my_downsample_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_downsampler)); cinfo->downsample = (struct jpeg_downsampler *) downsample; downsample->pub.start_pass = start_pass_downsample; downsample->pub.downsample = sep_downsample; downsample->pub.need_context_rows = FALSE; if (cinfo->CCIR601_sampling) ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); /* Verify we can handle the sampling factors, and set up method pointers */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Compute size of an "output group" for DCT scaling. This many samples * are to be converted from max_h_samp_factor * max_v_samp_factor pixels. */ h_out_group = (compptr->h_samp_factor * compptr->DCT_h_scaled_size) / cinfo->min_DCT_h_scaled_size; v_out_group = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) / cinfo->min_DCT_v_scaled_size; h_in_group = cinfo->max_h_samp_factor; v_in_group = cinfo->max_v_samp_factor; downsample->rowgroup_height[ci] = v_out_group; /* save for use later */ if (h_in_group == h_out_group && v_in_group == v_out_group) { #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor) { downsample->methods[ci] = fullsize_smooth_downsample; downsample->pub.need_context_rows = TRUE; } else #endif downsample->methods[ci] = fullsize_downsample; } else if (h_in_group == h_out_group * 2 && v_in_group == v_out_group) { smoothok = FALSE; downsample->methods[ci] = h2v1_downsample; } else if (h_in_group == h_out_group * 2 && v_in_group == v_out_group * 2) { #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor) { downsample->methods[ci] = h2v2_smooth_downsample; downsample->pub.need_context_rows = TRUE; } else #endif downsample->methods[ci] = h2v2_downsample; } else if ((h_in_group % h_out_group) == 0 && (v_in_group % v_out_group) == 0) { smoothok = FALSE; downsample->methods[ci] = int_downsample; downsample->h_expand[ci] = (UINT8) (h_in_group / h_out_group); downsample->v_expand[ci] = (UINT8) (v_in_group / v_out_group); } else ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); } #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor && !smoothok) TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL); #endif } ================================================ FILE: tess-two/jni/libjpeg/jctrans.c ================================================ /* * jctrans.c * * Copyright (C) 1995-1998, Thomas G. Lane. * Modified 2000-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains library routines for transcoding compression, * that is, writing raw DCT coefficient arrays to an output JPEG file. * The routines in jcapimin.c will also be needed by a transcoder. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Forward declarations */ LOCAL(void) transencode_master_selection JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)); LOCAL(void) transencode_coef_controller JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)); /* * Compression initialization for writing raw-coefficient data. * Before calling this, all parameters and a data destination must be set up. * Call jpeg_finish_compress() to actually write the data. * * The number of passed virtual arrays must match cinfo->num_components. * Note that the virtual arrays need not be filled or even realized at * the time write_coefficients is called; indeed, if the virtual arrays * were requested from this compression object's memory manager, they * typically will be realized during this routine and filled afterwards. */ GLOBAL(void) jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays) { if (cinfo->global_state != CSTATE_START) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Mark all tables to be written */ jpeg_suppress_tables(cinfo, FALSE); /* (Re)initialize error mgr and destination modules */ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); (*cinfo->dest->init_destination) (cinfo); /* Perform master selection of active modules */ transencode_master_selection(cinfo, coef_arrays); /* Wait for jpeg_finish_compress() call */ cinfo->next_scanline = 0; /* so jpeg_write_marker works */ cinfo->global_state = CSTATE_WRCOEFS; } /* * Initialize the compression object with default parameters, * then copy from the source object all parameters needed for lossless * transcoding. Parameters that can be varied without loss (such as * scan script and Huffman optimization) are left in their default states. */ GLOBAL(void) jpeg_copy_critical_parameters (j_decompress_ptr srcinfo, j_compress_ptr dstinfo) { JQUANT_TBL ** qtblptr; jpeg_component_info *incomp, *outcomp; JQUANT_TBL *c_quant, *slot_quant; int tblno, ci, coefi; /* Safety check to ensure start_compress not called yet. */ if (dstinfo->global_state != CSTATE_START) ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state); /* Copy fundamental image dimensions */ dstinfo->image_width = srcinfo->image_width; dstinfo->image_height = srcinfo->image_height; dstinfo->input_components = srcinfo->num_components; dstinfo->in_color_space = srcinfo->jpeg_color_space; dstinfo->jpeg_width = srcinfo->output_width; dstinfo->jpeg_height = srcinfo->output_height; dstinfo->min_DCT_h_scaled_size = srcinfo->min_DCT_h_scaled_size; dstinfo->min_DCT_v_scaled_size = srcinfo->min_DCT_v_scaled_size; /* Initialize all parameters to default values */ jpeg_set_defaults(dstinfo); /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB. * Fix it to get the right header markers for the image colorspace. * Note: Entropy table assignment in jpeg_set_colorspace depends * on color_transform. */ dstinfo->color_transform = srcinfo->color_transform; jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space); dstinfo->data_precision = srcinfo->data_precision; dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling; /* Copy the source's quantization tables. */ for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) { if (srcinfo->quant_tbl_ptrs[tblno] != NULL) { qtblptr = & dstinfo->quant_tbl_ptrs[tblno]; if (*qtblptr == NULL) *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo); MEMCOPY((*qtblptr)->quantval, srcinfo->quant_tbl_ptrs[tblno]->quantval, SIZEOF((*qtblptr)->quantval)); (*qtblptr)->sent_table = FALSE; } } /* Copy the source's per-component info. * Note we assume jpeg_set_defaults has allocated the dest comp_info array. */ dstinfo->num_components = srcinfo->num_components; if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS) ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components, MAX_COMPONENTS); for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info; ci < dstinfo->num_components; ci++, incomp++, outcomp++) { outcomp->component_id = incomp->component_id; outcomp->h_samp_factor = incomp->h_samp_factor; outcomp->v_samp_factor = incomp->v_samp_factor; outcomp->quant_tbl_no = incomp->quant_tbl_no; /* Make sure saved quantization table for component matches the qtable * slot. If not, the input file re-used this qtable slot. * IJG encoder currently cannot duplicate this. */ tblno = outcomp->quant_tbl_no; if (tblno < 0 || tblno >= NUM_QUANT_TBLS || srcinfo->quant_tbl_ptrs[tblno] == NULL) ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno); slot_quant = srcinfo->quant_tbl_ptrs[tblno]; c_quant = incomp->quant_table; if (c_quant != NULL) { for (coefi = 0; coefi < DCTSIZE2; coefi++) { if (c_quant->quantval[coefi] != slot_quant->quantval[coefi]) ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno); } } /* Note: we do not copy the source's entropy table assignments; * instead we rely on jpeg_set_colorspace to have made a suitable choice. */ } /* Also copy JFIF version and resolution information, if available. * Strictly speaking this isn't "critical" info, but it's nearly * always appropriate to copy it if available. In particular, * if the application chooses to copy JFIF 1.02 extension markers from * the source file, we need to copy the version to make sure we don't * emit a file that has 1.02 extensions but a claimed version of 1.01. */ if (srcinfo->saw_JFIF_marker) { if (srcinfo->JFIF_major_version == 1 || srcinfo->JFIF_major_version == 2) { dstinfo->JFIF_major_version = srcinfo->JFIF_major_version; dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version; } dstinfo->density_unit = srcinfo->density_unit; dstinfo->X_density = srcinfo->X_density; dstinfo->Y_density = srcinfo->Y_density; } } /* * Master selection of compression modules for transcoding. * This substitutes for jcinit.c's initialization of the full compressor. */ LOCAL(void) transencode_master_selection (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays) { /* Initialize master control (includes parameter checking/processing) */ jinit_c_master_control(cinfo, TRUE /* transcode only */); /* Entropy encoding: either Huffman or arithmetic coding. */ if (cinfo->arith_code) jinit_arith_encoder(cinfo); else { jinit_huff_encoder(cinfo); } /* We need a special coefficient buffer controller. */ transencode_coef_controller(cinfo, coef_arrays); jinit_marker_writer(cinfo); /* We can now tell the memory manager to allocate virtual arrays. */ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); /* Write the datastream header (SOI, JFIF) immediately. * Frame and scan headers are postponed till later. * This lets application insert special markers after the SOI. */ (*cinfo->marker->write_file_header) (cinfo); } /* * The rest of this file is a special implementation of the coefficient * buffer controller. This is similar to jccoefct.c, but it handles only * output from presupplied virtual arrays. Furthermore, we generate any * dummy padding blocks on-the-fly rather than expecting them to be present * in the arrays. */ /* Private buffer controller object */ typedef struct { struct jpeg_c_coef_controller pub; /* public fields */ JDIMENSION iMCU_row_num; /* iMCU row # within image */ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */ int MCU_vert_offset; /* counts MCU rows within iMCU row */ int MCU_rows_per_iMCU_row; /* number of such rows needed */ /* Virtual block array for each component. */ jvirt_barray_ptr * whole_image; /* Workspace for constructing dummy blocks at right/bottom edges. */ JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU]; } my_coef_controller; typedef my_coef_controller * my_coef_ptr; LOCAL(void) start_iMCU_row (j_compress_ptr cinfo) /* Reset within-iMCU-row counters for a new row */ { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; /* In an interleaved scan, an MCU row is the same as an iMCU row. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. * But at the bottom of the image, process only what's left. */ if (cinfo->comps_in_scan > 1) { coef->MCU_rows_per_iMCU_row = 1; } else { if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1)) coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; else coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; } coef->mcu_ctr = 0; coef->MCU_vert_offset = 0; } /* * Initialize for a processing pass. */ METHODDEF(void) start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; if (pass_mode != JBUF_CRANK_DEST) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); coef->iMCU_row_num = 0; start_iMCU_row(cinfo); } /* * Process some data. * We process the equivalent of one fully interleaved MCU row ("iMCU" row) * per call, ie, v_samp_factor block rows for each component in the scan. * The data is obtained from the virtual arrays and fed to the entropy coder. * Returns TRUE if the iMCU row is completed, FALSE if suspended. * * NB: input_buf is ignored; it is likely to be a NULL pointer. */ METHODDEF(boolean) compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; int blkn, ci, xindex, yindex, yoffset, blockcnt; JDIMENSION start_col; JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU]; JBLOCKROW buffer_ptr; jpeg_component_info *compptr; /* Align the virtual buffers for the components used in this scan. */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; buffer[ci] = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], coef->iMCU_row_num * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, FALSE); } /* Loop to process one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row; MCU_col_num++) { /* Construct list of pointers to DCT blocks belonging to this MCU */ blkn = 0; /* index of current DCT block within MCU */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; start_col = MCU_col_num * compptr->MCU_width; blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width : compptr->last_col_width; for (yindex = 0; yindex < compptr->MCU_height; yindex++) { if (coef->iMCU_row_num < last_iMCU_row || yindex+yoffset < compptr->last_row_height) { /* Fill in pointers to real blocks in this row */ buffer_ptr = buffer[ci][yindex+yoffset] + start_col; for (xindex = 0; xindex < blockcnt; xindex++) MCU_buffer[blkn++] = buffer_ptr++; } else { /* At bottom of image, need a whole row of dummy blocks */ xindex = 0; } /* Fill in any dummy blocks needed in this row. * Dummy blocks are filled in the same way as in jccoefct.c: * all zeroes in the AC entries, DC entries equal to previous * block's DC value. The init routine has already zeroed the * AC entries, so we need only set the DC entries correctly. */ for (; xindex < compptr->MCU_width; xindex++) { MCU_buffer[blkn] = coef->dummy_buffer[blkn]; MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0]; blkn++; } } } /* Try to write the MCU. */ if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->mcu_ctr = MCU_col_num; return FALSE; } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->mcu_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ coef->iMCU_row_num++; start_iMCU_row(cinfo); return TRUE; } /* * Initialize coefficient buffer controller. * * Each passed coefficient array must be the right size for that * coefficient: width_in_blocks wide and height_in_blocks high, * with unitheight at least v_samp_factor. */ LOCAL(void) transencode_coef_controller (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays) { my_coef_ptr coef; JBLOCKROW buffer; int i; coef = (my_coef_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_coef_controller)); cinfo->coef = &coef->pub; coef->pub.start_pass = start_pass_coef; coef->pub.compress_data = compress_output; /* Save pointer to virtual arrays */ coef->whole_image = coef_arrays; /* Allocate and pre-zero space for dummy DCT blocks. */ buffer = (JBLOCKROW) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); FMEMZERO((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) { coef->dummy_buffer[i] = buffer + i; } } ================================================ FILE: tess-two/jni/libjpeg/jdapimin.c ================================================ /* * jdapimin.c * * Copyright (C) 1994-1998, Thomas G. Lane. * Modified 2009-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains application interface code for the decompression half * of the JPEG library. These are the "minimum" API routines that may be * needed in either the normal full-decompression case or the * transcoding-only case. * * Most of the routines intended to be called directly by an application * are in this file or in jdapistd.c. But also see jcomapi.c for routines * shared by compression and decompression, and jdtrans.c for the transcoding * case. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * Initialization of a JPEG decompression object. * The error manager must already be set up (in case memory manager fails). */ GLOBAL(void) jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize) { int i; /* Guard against version mismatches between library and caller. */ cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */ if (version != JPEG_LIB_VERSION) ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version); if (structsize != SIZEOF(struct jpeg_decompress_struct)) ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize); /* For debugging purposes, we zero the whole master structure. * But the application has already set the err pointer, and may have set * client_data, so we have to save and restore those fields. * Note: if application hasn't set client_data, tools like Purify may * complain here. */ { struct jpeg_error_mgr * err = cinfo->err; void * client_data = cinfo->client_data; /* ignore Purify complaint here */ MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct)); cinfo->err = err; cinfo->client_data = client_data; } cinfo->is_decompressor = TRUE; /* Initialize a memory manager instance for this object */ jinit_memory_mgr((j_common_ptr) cinfo); /* Zero out pointers to permanent structures. */ cinfo->progress = NULL; cinfo->src = NULL; for (i = 0; i < NUM_QUANT_TBLS; i++) cinfo->quant_tbl_ptrs[i] = NULL; for (i = 0; i < NUM_HUFF_TBLS; i++) { cinfo->dc_huff_tbl_ptrs[i] = NULL; cinfo->ac_huff_tbl_ptrs[i] = NULL; } /* Initialize marker processor so application can override methods * for COM, APPn markers before calling jpeg_read_header. */ cinfo->marker_list = NULL; jinit_marker_reader(cinfo); /* And initialize the overall input controller. */ jinit_input_controller(cinfo); /* OK, I'm ready */ cinfo->global_state = DSTATE_START; } /* * Destruction of a JPEG decompression object */ GLOBAL(void) jpeg_destroy_decompress (j_decompress_ptr cinfo) { jpeg_destroy((j_common_ptr) cinfo); /* use common routine */ } /* * Abort processing of a JPEG decompression operation, * but don't destroy the object itself. */ GLOBAL(void) jpeg_abort_decompress (j_decompress_ptr cinfo) { jpeg_abort((j_common_ptr) cinfo); /* use common routine */ } /* * Set default decompression parameters. */ LOCAL(void) default_decompress_parms (j_decompress_ptr cinfo) { int cid0, cid1, cid2; /* Guess the input colorspace, and set output colorspace accordingly. */ /* Note application may override our guesses. */ switch (cinfo->num_components) { case 1: cinfo->jpeg_color_space = JCS_GRAYSCALE; cinfo->out_color_space = JCS_GRAYSCALE; break; case 3: cid0 = cinfo->comp_info[0].component_id; cid1 = cinfo->comp_info[1].component_id; cid2 = cinfo->comp_info[2].component_id; /* First try to guess from the component IDs */ if (cid0 == 0x01 && cid1 == 0x02 && cid2 == 0x03) cinfo->jpeg_color_space = JCS_YCbCr; else if (cid0 == 0x01 && cid1 == 0x22 && cid2 == 0x23) cinfo->jpeg_color_space = JCS_BG_YCC; else if (cid0 == 0x52 && cid1 == 0x47 && cid2 == 0x42) cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */ else if (cid0 == 0x72 && cid1 == 0x67 && cid2 == 0x62) cinfo->jpeg_color_space = JCS_BG_RGB; /* ASCII 'r', 'g', 'b' */ else if (cinfo->saw_JFIF_marker) cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ else if (cinfo->saw_Adobe_marker) { switch (cinfo->Adobe_transform) { case 0: cinfo->jpeg_color_space = JCS_RGB; break; case 1: cinfo->jpeg_color_space = JCS_YCbCr; break; default: WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform); cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ break; } } else { TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2); cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ } /* Always guess RGB is proper output colorspace. */ cinfo->out_color_space = JCS_RGB; break; case 4: if (cinfo->saw_Adobe_marker) { switch (cinfo->Adobe_transform) { case 0: cinfo->jpeg_color_space = JCS_CMYK; break; case 2: cinfo->jpeg_color_space = JCS_YCCK; break; default: WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform); cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */ break; } } else { /* No special markers, assume straight CMYK. */ cinfo->jpeg_color_space = JCS_CMYK; } cinfo->out_color_space = JCS_CMYK; break; default: cinfo->jpeg_color_space = JCS_UNKNOWN; cinfo->out_color_space = JCS_UNKNOWN; break; } /* Set defaults for other decompression parameters. */ cinfo->scale_num = cinfo->block_size; /* 1:1 scaling */ cinfo->scale_denom = cinfo->block_size; cinfo->output_gamma = 1.0; cinfo->buffered_image = FALSE; cinfo->raw_data_out = FALSE; cinfo->dct_method = JDCT_DEFAULT; cinfo->do_fancy_upsampling = TRUE; cinfo->do_block_smoothing = TRUE; cinfo->quantize_colors = FALSE; /* We set these in case application only sets quantize_colors. */ cinfo->dither_mode = JDITHER_FS; #ifdef QUANT_2PASS_SUPPORTED cinfo->two_pass_quantize = TRUE; #else cinfo->two_pass_quantize = FALSE; #endif cinfo->desired_number_of_colors = 256; cinfo->colormap = NULL; /* Initialize for no mode change in buffered-image mode. */ cinfo->enable_1pass_quant = FALSE; cinfo->enable_external_quant = FALSE; cinfo->enable_2pass_quant = FALSE; } /* * Decompression startup: read start of JPEG datastream to see what's there. * Need only initialize JPEG object and supply a data source before calling. * * This routine will read as far as the first SOS marker (ie, actual start of * compressed data), and will save all tables and parameters in the JPEG * object. It will also initialize the decompression parameters to default * values, and finally return JPEG_HEADER_OK. On return, the application may * adjust the decompression parameters and then call jpeg_start_decompress. * (Or, if the application only wanted to determine the image parameters, * the data need not be decompressed. In that case, call jpeg_abort or * jpeg_destroy to release any temporary space.) * If an abbreviated (tables only) datastream is presented, the routine will * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then * re-use the JPEG object to read the abbreviated image datastream(s). * It is unnecessary (but OK) to call jpeg_abort in this case. * The JPEG_SUSPENDED return code only occurs if the data source module * requests suspension of the decompressor. In this case the application * should load more source data and then re-call jpeg_read_header to resume * processing. * If a non-suspending data source is used and require_image is TRUE, then the * return code need not be inspected since only JPEG_HEADER_OK is possible. * * This routine is now just a front end to jpeg_consume_input, with some * extra error checking. */ GLOBAL(int) jpeg_read_header (j_decompress_ptr cinfo, boolean require_image) { int retcode; if (cinfo->global_state != DSTATE_START && cinfo->global_state != DSTATE_INHEADER) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); retcode = jpeg_consume_input(cinfo); switch (retcode) { case JPEG_REACHED_SOS: retcode = JPEG_HEADER_OK; break; case JPEG_REACHED_EOI: if (require_image) /* Complain if application wanted an image */ ERREXIT(cinfo, JERR_NO_IMAGE); /* Reset to start state; it would be safer to require the application to * call jpeg_abort, but we can't change it now for compatibility reasons. * A side effect is to free any temporary memory (there shouldn't be any). */ jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */ retcode = JPEG_HEADER_TABLES_ONLY; break; case JPEG_SUSPENDED: /* no work */ break; } return retcode; } /* * Consume data in advance of what the decompressor requires. * This can be called at any time once the decompressor object has * been created and a data source has been set up. * * This routine is essentially a state machine that handles a couple * of critical state-transition actions, namely initial setup and * transition from header scanning to ready-for-start_decompress. * All the actual input is done via the input controller's consume_input * method. */ GLOBAL(int) jpeg_consume_input (j_decompress_ptr cinfo) { int retcode = JPEG_SUSPENDED; /* NB: every possible DSTATE value should be listed in this switch */ switch (cinfo->global_state) { case DSTATE_START: /* Start-of-datastream actions: reset appropriate modules */ (*cinfo->inputctl->reset_input_controller) (cinfo); /* Initialize application's data source module */ (*cinfo->src->init_source) (cinfo); cinfo->global_state = DSTATE_INHEADER; /*FALLTHROUGH*/ case DSTATE_INHEADER: retcode = (*cinfo->inputctl->consume_input) (cinfo); if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */ /* Set up default parameters based on header data */ default_decompress_parms(cinfo); /* Set global state: ready for start_decompress */ cinfo->global_state = DSTATE_READY; } break; case DSTATE_READY: /* Can't advance past first SOS until start_decompress is called */ retcode = JPEG_REACHED_SOS; break; case DSTATE_PRELOAD: case DSTATE_PRESCAN: case DSTATE_SCANNING: case DSTATE_RAW_OK: case DSTATE_BUFIMAGE: case DSTATE_BUFPOST: case DSTATE_STOPPING: retcode = (*cinfo->inputctl->consume_input) (cinfo); break; default: ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); } return retcode; } /* * Have we finished reading the input file? */ GLOBAL(boolean) jpeg_input_complete (j_decompress_ptr cinfo) { /* Check for valid jpeg object */ if (cinfo->global_state < DSTATE_START || cinfo->global_state > DSTATE_STOPPING) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); return cinfo->inputctl->eoi_reached; } /* * Is there more than one scan? */ GLOBAL(boolean) jpeg_has_multiple_scans (j_decompress_ptr cinfo) { /* Only valid after jpeg_read_header completes */ if (cinfo->global_state < DSTATE_READY || cinfo->global_state > DSTATE_STOPPING) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); return cinfo->inputctl->has_multiple_scans; } /* * Finish JPEG decompression. * * This will normally just verify the file trailer and release temp storage. * * Returns FALSE if suspended. The return value need be inspected only if * a suspending data source is used. */ GLOBAL(boolean) jpeg_finish_decompress (j_decompress_ptr cinfo) { if ((cinfo->global_state == DSTATE_SCANNING || cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) { /* Terminate final pass of non-buffered mode */ if (cinfo->output_scanline < cinfo->output_height) ERREXIT(cinfo, JERR_TOO_LITTLE_DATA); (*cinfo->master->finish_output_pass) (cinfo); cinfo->global_state = DSTATE_STOPPING; } else if (cinfo->global_state == DSTATE_BUFIMAGE) { /* Finishing after a buffered-image operation */ cinfo->global_state = DSTATE_STOPPING; } else if (cinfo->global_state != DSTATE_STOPPING) { /* STOPPING = repeat call after a suspension, anything else is error */ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); } /* Read until EOI */ while (! cinfo->inputctl->eoi_reached) { if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED) return FALSE; /* Suspend, come back later */ } /* Do final cleanup */ (*cinfo->src->term_source) (cinfo); /* We can use jpeg_abort to release memory and reset global_state */ jpeg_abort((j_common_ptr) cinfo); return TRUE; } ================================================ FILE: tess-two/jni/libjpeg/jdapistd.c ================================================ /* * jdapistd.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2002-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains application interface code for the decompression half * of the JPEG library. These are the "standard" API routines that are * used in the normal full-decompression case. They are not used by a * transcoding-only application. Note that if an application links in * jpeg_start_decompress, it will end up linking in the entire decompressor. * We thus must separate this file from jdapimin.c to avoid linking the * whole decompression library into a transcoder. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Forward declarations */ LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo)); /* * Decompression initialization. * jpeg_read_header must be completed before calling this. * * If a multipass operating mode was selected, this will do all but the * last pass, and thus may take a great deal of time. * * Returns FALSE if suspended. The return value need be inspected only if * a suspending data source is used. */ GLOBAL(boolean) jpeg_start_decompress (j_decompress_ptr cinfo) { if (cinfo->global_state == DSTATE_READY) { /* First call: initialize master control, select active modules */ jinit_master_decompress(cinfo); if (cinfo->buffered_image) { /* No more work here; expecting jpeg_start_output next */ cinfo->global_state = DSTATE_BUFIMAGE; return TRUE; } cinfo->global_state = DSTATE_PRELOAD; } if (cinfo->global_state == DSTATE_PRELOAD) { /* If file has multiple scans, absorb them all into the coef buffer */ if (cinfo->inputctl->has_multiple_scans) { #ifdef D_MULTISCAN_FILES_SUPPORTED for (;;) { int retcode; /* Call progress monitor hook if present */ if (cinfo->progress != NULL) (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); /* Absorb some more input */ retcode = (*cinfo->inputctl->consume_input) (cinfo); if (retcode == JPEG_SUSPENDED) return FALSE; if (retcode == JPEG_REACHED_EOI) break; /* Advance progress counter if appropriate */ if (cinfo->progress != NULL && (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) { /* jdmaster underestimated number of scans; ratchet up one scan */ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; } } } #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif /* D_MULTISCAN_FILES_SUPPORTED */ } cinfo->output_scan_number = cinfo->input_scan_number; } else if (cinfo->global_state != DSTATE_PRESCAN) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Perform any dummy output passes, and set up for the final pass */ return output_pass_setup(cinfo); } /* * Set up for an output pass, and perform any dummy pass(es) needed. * Common subroutine for jpeg_start_decompress and jpeg_start_output. * Entry: global_state = DSTATE_PRESCAN only if previously suspended. * Exit: If done, returns TRUE and sets global_state for proper output mode. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN. */ LOCAL(boolean) output_pass_setup (j_decompress_ptr cinfo) { if (cinfo->global_state != DSTATE_PRESCAN) { /* First call: do pass setup */ (*cinfo->master->prepare_for_output_pass) (cinfo); cinfo->output_scanline = 0; cinfo->global_state = DSTATE_PRESCAN; } /* Loop over any required dummy passes */ while (cinfo->master->is_dummy_pass) { #ifdef QUANT_2PASS_SUPPORTED /* Crank through the dummy pass */ while (cinfo->output_scanline < cinfo->output_height) { JDIMENSION last_scanline; /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->output_scanline; cinfo->progress->pass_limit = (long) cinfo->output_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Process some data */ last_scanline = cinfo->output_scanline; (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL, &cinfo->output_scanline, (JDIMENSION) 0); if (cinfo->output_scanline == last_scanline) return FALSE; /* No progress made, must suspend */ } /* Finish up dummy pass, and set up for another one */ (*cinfo->master->finish_output_pass) (cinfo); (*cinfo->master->prepare_for_output_pass) (cinfo); cinfo->output_scanline = 0; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif /* QUANT_2PASS_SUPPORTED */ } /* Ready for application to drive output pass through * jpeg_read_scanlines or jpeg_read_raw_data. */ cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING; return TRUE; } /* * Read some scanlines of data from the JPEG decompressor. * * The return value will be the number of lines actually read. * This may be less than the number requested in several cases, * including bottom of image, data source suspension, and operating * modes that emit multiple scanlines at a time. * * Note: we warn about excess calls to jpeg_read_scanlines() since * this likely signals an application programmer error. However, * an oversize buffer (max_lines > scanlines remaining) is not an error. */ GLOBAL(JDIMENSION) jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines) { JDIMENSION row_ctr; if (cinfo->global_state != DSTATE_SCANNING) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (cinfo->output_scanline >= cinfo->output_height) { WARNMS(cinfo, JWRN_TOO_MUCH_DATA); return 0; } /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->output_scanline; cinfo->progress->pass_limit = (long) cinfo->output_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Process some data */ row_ctr = 0; (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines); cinfo->output_scanline += row_ctr; return row_ctr; } /* * Alternate entry point to read raw data. * Processes exactly one iMCU row per call, unless suspended. */ GLOBAL(JDIMENSION) jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data, JDIMENSION max_lines) { JDIMENSION lines_per_iMCU_row; if (cinfo->global_state != DSTATE_RAW_OK) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (cinfo->output_scanline >= cinfo->output_height) { WARNMS(cinfo, JWRN_TOO_MUCH_DATA); return 0; } /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->output_scanline; cinfo->progress->pass_limit = (long) cinfo->output_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Verify that at least one iMCU row can be returned. */ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_v_scaled_size; if (max_lines < lines_per_iMCU_row) ERREXIT(cinfo, JERR_BUFFER_SIZE); /* Decompress directly into user's buffer. */ if (! (*cinfo->coef->decompress_data) (cinfo, data)) return 0; /* suspension forced, can do nothing more */ /* OK, we processed one iMCU row. */ cinfo->output_scanline += lines_per_iMCU_row; return lines_per_iMCU_row; } /* Additional entry points for buffered-image mode. */ #ifdef D_MULTISCAN_FILES_SUPPORTED /* * Initialize for an output pass in buffered-image mode. */ GLOBAL(boolean) jpeg_start_output (j_decompress_ptr cinfo, int scan_number) { if (cinfo->global_state != DSTATE_BUFIMAGE && cinfo->global_state != DSTATE_PRESCAN) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Limit scan number to valid range */ if (scan_number <= 0) scan_number = 1; if (cinfo->inputctl->eoi_reached && scan_number > cinfo->input_scan_number) scan_number = cinfo->input_scan_number; cinfo->output_scan_number = scan_number; /* Perform any dummy output passes, and set up for the real pass */ return output_pass_setup(cinfo); } /* * Finish up after an output pass in buffered-image mode. * * Returns FALSE if suspended. The return value need be inspected only if * a suspending data source is used. */ GLOBAL(boolean) jpeg_finish_output (j_decompress_ptr cinfo) { if ((cinfo->global_state == DSTATE_SCANNING || cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) { /* Terminate this pass. */ /* We do not require the whole pass to have been completed. */ (*cinfo->master->finish_output_pass) (cinfo); cinfo->global_state = DSTATE_BUFPOST; } else if (cinfo->global_state != DSTATE_BUFPOST) { /* BUFPOST = repeat call after a suspension, anything else is error */ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); } /* Read markers looking for SOS or EOI */ while (cinfo->input_scan_number <= cinfo->output_scan_number && ! cinfo->inputctl->eoi_reached) { if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED) return FALSE; /* Suspend, come back later */ } cinfo->global_state = DSTATE_BUFIMAGE; return TRUE; } #endif /* D_MULTISCAN_FILES_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jdarith.c ================================================ /* * jdarith.c * * Developed 1997-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains portable arithmetic entropy decoding routines for JPEG * (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81). * * Both sequential and progressive modes are supported in this single module. * * Suspension is not currently supported in this module. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Expanded entropy decoder object for arithmetic decoding. */ typedef struct { struct jpeg_entropy_decoder pub; /* public fields */ INT32 c; /* C register, base of coding interval + input bit buffer */ INT32 a; /* A register, normalized size of coding interval */ int ct; /* bit shift counter, # of bits left in bit buffer part of C */ /* init: ct = -16 */ /* run: ct = 0..7 */ /* error: ct = -1 */ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */ unsigned int restarts_to_go; /* MCUs left in this restart interval */ /* Pointers to statistics areas (these workspaces have image lifespan) */ unsigned char * dc_stats[NUM_ARITH_TBLS]; unsigned char * ac_stats[NUM_ARITH_TBLS]; /* Statistics bin for coding with fixed probability 0.5 */ unsigned char fixed_bin[4]; } arith_entropy_decoder; typedef arith_entropy_decoder * arith_entropy_ptr; /* The following two definitions specify the allocation chunk size * for the statistics area. * According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least * 49 statistics bins for DC, and 245 statistics bins for AC coding. * * We use a compact representation with 1 byte per statistics bin, * thus the numbers directly represent byte sizes. * This 1 byte per statistics bin contains the meaning of the MPS * (more probable symbol) in the highest bit (mask 0x80), and the * index into the probability estimation state machine table * in the lower bits (mask 0x7F). */ #define DC_STAT_BINS 64 #define AC_STAT_BINS 256 LOCAL(int) get_byte (j_decompress_ptr cinfo) /* Read next input byte; we do not support suspension in this module. */ { struct jpeg_source_mgr * src = cinfo->src; if (src->bytes_in_buffer == 0) if (! (*src->fill_input_buffer) (cinfo)) ERREXIT(cinfo, JERR_CANT_SUSPEND); src->bytes_in_buffer--; return GETJOCTET(*src->next_input_byte++); } /* * The core arithmetic decoding routine (common in JPEG and JBIG). * This needs to go as fast as possible. * Machine-dependent optimization facilities * are not utilized in this portable implementation. * However, this code should be fairly efficient and * may be a good base for further optimizations anyway. * * Return value is 0 or 1 (binary decision). * * Note: I've changed the handling of the code base & bit * buffer register C compared to other implementations * based on the standards layout & procedures. * While it also contains both the actual base of the * coding interval (16 bits) and the next-bits buffer, * the cut-point between these two parts is floating * (instead of fixed) with the bit shift counter CT. * Thus, we also need only one (variable instead of * fixed size) shift for the LPS/MPS decision, and * we can do away with any renormalization update * of C (except for new data insertion, of course). * * I've also introduced a new scheme for accessing * the probability estimation state machine table, * derived from Markus Kuhn's JBIG implementation. */ LOCAL(int) arith_decode (j_decompress_ptr cinfo, unsigned char *st) { register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy; register unsigned char nl, nm; register INT32 qe, temp; register int sv, data; /* Renormalization & data input per section D.2.6 */ while (e->a < 0x8000L) { if (--e->ct < 0) { /* Need to fetch next data byte */ if (cinfo->unread_marker) data = 0; /* stuff zero data */ else { data = get_byte(cinfo); /* read next input byte */ if (data == 0xFF) { /* zero stuff or marker code */ do data = get_byte(cinfo); while (data == 0xFF); /* swallow extra 0xFF bytes */ if (data == 0) data = 0xFF; /* discard stuffed zero byte */ else { /* Note: Different from the Huffman decoder, hitting * a marker while processing the compressed data * segment is legal in arithmetic coding. * The convention is to supply zero data * then until decoding is complete. */ cinfo->unread_marker = data; data = 0; } } } e->c = (e->c << 8) | data; /* insert data into C register */ if ((e->ct += 8) < 0) /* update bit shift counter */ /* Need more initial bytes */ if (++e->ct == 0) /* Got 2 initial bytes -> re-init A and exit loop */ e->a = 0x8000L; /* => e->a = 0x10000L after loop exit */ } e->a <<= 1; } /* Fetch values from our compact representation of Table D.3(D.2): * Qe values and probability estimation state machine */ sv = *st; qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */ nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */ nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */ /* Decode & estimation procedures per sections D.2.4 & D.2.5 */ temp = e->a - qe; e->a = temp; temp <<= e->ct; if (e->c >= temp) { e->c -= temp; /* Conditional LPS (less probable symbol) exchange */ if (e->a < qe) { e->a = qe; *st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */ } else { e->a = qe; *st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */ sv ^= 0x80; /* Exchange LPS/MPS */ } } else if (e->a < 0x8000L) { /* Conditional MPS (more probable symbol) exchange */ if (e->a < qe) { *st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */ sv ^= 0x80; /* Exchange LPS/MPS */ } else { *st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */ } } return sv >> 7; } /* * Check for a restart marker & resynchronize decoder. */ LOCAL(void) process_restart (j_decompress_ptr cinfo) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; int ci; jpeg_component_info * compptr; /* Advance past the RSTn marker */ if (! (*cinfo->marker->read_restart_marker) (cinfo)) ERREXIT(cinfo, JERR_CANT_SUSPEND); /* Re-initialize statistics areas */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) { MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS); /* Reset DC predictions to 0 */ entropy->last_dc_val[ci] = 0; entropy->dc_context[ci] = 0; } if ((! cinfo->progressive_mode && cinfo->lim_Se) || (cinfo->progressive_mode && cinfo->Ss)) { MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS); } } /* Reset arithmetic decoding variables */ entropy->c = 0; entropy->a = 0; entropy->ct = -16; /* force reading 2 initial bytes to fill C */ /* Reset restart counter */ entropy->restarts_to_go = cinfo->restart_interval; } /* * Arithmetic MCU decoding. * Each of these routines decodes and returns one MCU's worth of * arithmetic-compressed coefficients. * The coefficients are reordered from zigzag order into natural array order, * but are not dequantized. * * The i'th block of the MCU is stored into the block pointed to by * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER. */ /* * MCU decoding for DC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; JBLOCKROW block; unsigned char *st; int blkn, ci, tbl, sign; int v, m; /* Process restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) process_restart(cinfo); entropy->restarts_to_go--; } if (entropy->ct == -1) return TRUE; /* if error do nothing */ /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { block = MCU_data[blkn]; ci = cinfo->MCU_membership[blkn]; tbl = cinfo->cur_comp_info[ci]->dc_tbl_no; /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */ /* Table F.4: Point to statistics bin S0 for DC coefficient coding */ st = entropy->dc_stats[tbl] + entropy->dc_context[ci]; /* Figure F.19: Decode_DC_DIFF */ if (arith_decode(cinfo, st) == 0) entropy->dc_context[ci] = 0; else { /* Figure F.21: Decoding nonzero value v */ /* Figure F.22: Decoding the sign of v */ sign = arith_decode(cinfo, st + 1); st += 2; st += sign; /* Figure F.23: Decoding the magnitude category of v */ if ((m = arith_decode(cinfo, st)) != 0) { st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */ while (arith_decode(cinfo, st)) { if ((m <<= 1) == 0x8000) { WARNMS(cinfo, JWRN_ARITH_BAD_CODE); entropy->ct = -1; /* magnitude overflow */ return TRUE; } st += 1; } } /* Section F.1.4.4.1.2: Establish dc_context conditioning category */ if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1)) entropy->dc_context[ci] = 0; /* zero diff category */ else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1)) entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */ else entropy->dc_context[ci] = 4 + (sign * 4); /* small diff category */ v = m; /* Figure F.24: Decoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) if (arith_decode(cinfo, st)) v |= m; v += 1; if (sign) v = -v; entropy->last_dc_val[ci] += v; } /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */ (*block)[0] = (JCOEF) (entropy->last_dc_val[ci] << cinfo->Al); } return TRUE; } /* * MCU decoding for AC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; JBLOCKROW block; unsigned char *st; int tbl, sign, k; int v, m; const int * natural_order; /* Process restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) process_restart(cinfo); entropy->restarts_to_go--; } if (entropy->ct == -1) return TRUE; /* if error do nothing */ natural_order = cinfo->natural_order; /* There is always only one block per MCU */ block = MCU_data[0]; tbl = cinfo->cur_comp_info[0]->ac_tbl_no; /* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */ /* Figure F.20: Decode_AC_coefficients */ k = cinfo->Ss - 1; do { st = entropy->ac_stats[tbl] + 3 * k; if (arith_decode(cinfo, st)) break; /* EOB flag */ for (;;) { k++; if (arith_decode(cinfo, st + 1)) break; st += 3; if (k >= cinfo->Se) { WARNMS(cinfo, JWRN_ARITH_BAD_CODE); entropy->ct = -1; /* spectral overflow */ return TRUE; } } /* Figure F.21: Decoding nonzero value v */ /* Figure F.22: Decoding the sign of v */ sign = arith_decode(cinfo, entropy->fixed_bin); st += 2; /* Figure F.23: Decoding the magnitude category of v */ if ((m = arith_decode(cinfo, st)) != 0) { if (arith_decode(cinfo, st)) { m <<= 1; st = entropy->ac_stats[tbl] + (k <= cinfo->arith_ac_K[tbl] ? 189 : 217); while (arith_decode(cinfo, st)) { if ((m <<= 1) == 0x8000) { WARNMS(cinfo, JWRN_ARITH_BAD_CODE); entropy->ct = -1; /* magnitude overflow */ return TRUE; } st += 1; } } } v = m; /* Figure F.24: Decoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) if (arith_decode(cinfo, st)) v |= m; v += 1; if (sign) v = -v; /* Scale and output coefficient in natural (dezigzagged) order */ (*block)[natural_order[k]] = (JCOEF) (v << cinfo->Al); } while (k < cinfo->Se); return TRUE; } /* * MCU decoding for DC successive approximation refinement scan. * Note: we assume such scans can be multi-component, * although the spec is not very clear on the point. */ METHODDEF(boolean) decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; unsigned char *st; int p1, blkn; /* Process restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) process_restart(cinfo); entropy->restarts_to_go--; } st = entropy->fixed_bin; /* use fixed probability estimation */ p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */ /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { /* Encoded data is simply the next bit of the two's-complement DC value */ if (arith_decode(cinfo, st)) MCU_data[blkn][0][0] |= p1; } return TRUE; } /* * MCU decoding for AC successive approximation refinement scan. */ METHODDEF(boolean) decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; JBLOCKROW block; JCOEFPTR thiscoef; unsigned char *st; int tbl, k, kex; int p1, m1; const int * natural_order; /* Process restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) process_restart(cinfo); entropy->restarts_to_go--; } if (entropy->ct == -1) return TRUE; /* if error do nothing */ natural_order = cinfo->natural_order; /* There is always only one block per MCU */ block = MCU_data[0]; tbl = cinfo->cur_comp_info[0]->ac_tbl_no; p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */ m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */ /* Establish EOBx (previous stage end-of-block) index */ kex = cinfo->Se; do { if ((*block)[natural_order[kex]]) break; } while (--kex); k = cinfo->Ss - 1; do { st = entropy->ac_stats[tbl] + 3 * k; if (k >= kex) if (arith_decode(cinfo, st)) break; /* EOB flag */ for (;;) { thiscoef = *block + natural_order[++k]; if (*thiscoef) { /* previously nonzero coef */ if (arith_decode(cinfo, st + 2)) { if (*thiscoef < 0) *thiscoef += m1; else *thiscoef += p1; } break; } if (arith_decode(cinfo, st + 1)) { /* newly nonzero coef */ if (arith_decode(cinfo, entropy->fixed_bin)) *thiscoef = m1; else *thiscoef = p1; break; } st += 3; if (k >= cinfo->Se) { WARNMS(cinfo, JWRN_ARITH_BAD_CODE); entropy->ct = -1; /* spectral overflow */ return TRUE; } } } while (k < cinfo->Se); return TRUE; } /* * Decode one MCU's worth of arithmetic-compressed coefficients. */ METHODDEF(boolean) decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; jpeg_component_info * compptr; JBLOCKROW block; unsigned char *st; int blkn, ci, tbl, sign, k; int v, m; const int * natural_order; /* Process restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) process_restart(cinfo); entropy->restarts_to_go--; } if (entropy->ct == -1) return TRUE; /* if error do nothing */ natural_order = cinfo->natural_order; /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { block = MCU_data[blkn]; ci = cinfo->MCU_membership[blkn]; compptr = cinfo->cur_comp_info[ci]; /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */ tbl = compptr->dc_tbl_no; /* Table F.4: Point to statistics bin S0 for DC coefficient coding */ st = entropy->dc_stats[tbl] + entropy->dc_context[ci]; /* Figure F.19: Decode_DC_DIFF */ if (arith_decode(cinfo, st) == 0) entropy->dc_context[ci] = 0; else { /* Figure F.21: Decoding nonzero value v */ /* Figure F.22: Decoding the sign of v */ sign = arith_decode(cinfo, st + 1); st += 2; st += sign; /* Figure F.23: Decoding the magnitude category of v */ if ((m = arith_decode(cinfo, st)) != 0) { st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */ while (arith_decode(cinfo, st)) { if ((m <<= 1) == 0x8000) { WARNMS(cinfo, JWRN_ARITH_BAD_CODE); entropy->ct = -1; /* magnitude overflow */ return TRUE; } st += 1; } } /* Section F.1.4.4.1.2: Establish dc_context conditioning category */ if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1)) entropy->dc_context[ci] = 0; /* zero diff category */ else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1)) entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */ else entropy->dc_context[ci] = 4 + (sign * 4); /* small diff category */ v = m; /* Figure F.24: Decoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) if (arith_decode(cinfo, st)) v |= m; v += 1; if (sign) v = -v; entropy->last_dc_val[ci] += v; } (*block)[0] = (JCOEF) entropy->last_dc_val[ci]; /* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */ if (cinfo->lim_Se == 0) continue; tbl = compptr->ac_tbl_no; k = 0; /* Figure F.20: Decode_AC_coefficients */ do { st = entropy->ac_stats[tbl] + 3 * k; if (arith_decode(cinfo, st)) break; /* EOB flag */ for (;;) { k++; if (arith_decode(cinfo, st + 1)) break; st += 3; if (k >= cinfo->lim_Se) { WARNMS(cinfo, JWRN_ARITH_BAD_CODE); entropy->ct = -1; /* spectral overflow */ return TRUE; } } /* Figure F.21: Decoding nonzero value v */ /* Figure F.22: Decoding the sign of v */ sign = arith_decode(cinfo, entropy->fixed_bin); st += 2; /* Figure F.23: Decoding the magnitude category of v */ if ((m = arith_decode(cinfo, st)) != 0) { if (arith_decode(cinfo, st)) { m <<= 1; st = entropy->ac_stats[tbl] + (k <= cinfo->arith_ac_K[tbl] ? 189 : 217); while (arith_decode(cinfo, st)) { if ((m <<= 1) == 0x8000) { WARNMS(cinfo, JWRN_ARITH_BAD_CODE); entropy->ct = -1; /* magnitude overflow */ return TRUE; } st += 1; } } } v = m; /* Figure F.24: Decoding the magnitude bit pattern of v */ st += 14; while (m >>= 1) if (arith_decode(cinfo, st)) v |= m; v += 1; if (sign) v = -v; (*block)[natural_order[k]] = (JCOEF) v; } while (k < cinfo->lim_Se); } return TRUE; } /* * Initialize for an arithmetic-compressed scan. */ METHODDEF(void) start_pass (j_decompress_ptr cinfo) { arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy; int ci, tbl; jpeg_component_info * compptr; if (cinfo->progressive_mode) { /* Validate progressive scan parameters */ if (cinfo->Ss == 0) { if (cinfo->Se != 0) goto bad; } else { /* need not check Ss/Se < 0 since they came from unsigned bytes */ if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se) goto bad; /* AC scans may have only one component */ if (cinfo->comps_in_scan != 1) goto bad; } if (cinfo->Ah != 0) { /* Successive approximation refinement scan: must have Al = Ah-1. */ if (cinfo->Ah-1 != cinfo->Al) goto bad; } if (cinfo->Al > 13) { /* need not check for < 0 */ bad: ERREXIT4(cinfo, JERR_BAD_PROGRESSION, cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al); } /* Update progression status, and verify that scan order is legal. * Note that inter-scan inconsistencies are treated as warnings * not fatal errors ... not clear if this is right way to behave. */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { int coefi, cindex = cinfo->cur_comp_info[ci]->component_index; int *coef_bit_ptr = & cinfo->coef_bits[cindex][0]; if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */ WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0); for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) { int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi]; if (cinfo->Ah != expected) WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi); coef_bit_ptr[coefi] = cinfo->Al; } } /* Select MCU decoding routine */ if (cinfo->Ah == 0) { if (cinfo->Ss == 0) entropy->pub.decode_mcu = decode_mcu_DC_first; else entropy->pub.decode_mcu = decode_mcu_AC_first; } else { if (cinfo->Ss == 0) entropy->pub.decode_mcu = decode_mcu_DC_refine; else entropy->pub.decode_mcu = decode_mcu_AC_refine; } } else { /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG. * This ought to be an error condition, but we make it a warning. */ if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 || (cinfo->Se < DCTSIZE2 && cinfo->Se != cinfo->lim_Se)) WARNMS(cinfo, JWRN_NOT_SEQUENTIAL); /* Select MCU decoding routine */ entropy->pub.decode_mcu = decode_mcu; } /* Allocate & initialize requested statistics areas */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) { tbl = compptr->dc_tbl_no; if (tbl < 0 || tbl >= NUM_ARITH_TBLS) ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl); if (entropy->dc_stats[tbl] == NULL) entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS); MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS); /* Initialize DC predictions to 0 */ entropy->last_dc_val[ci] = 0; entropy->dc_context[ci] = 0; } if ((! cinfo->progressive_mode && cinfo->lim_Se) || (cinfo->progressive_mode && cinfo->Ss)) { tbl = compptr->ac_tbl_no; if (tbl < 0 || tbl >= NUM_ARITH_TBLS) ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl); if (entropy->ac_stats[tbl] == NULL) entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS); MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS); } } /* Initialize arithmetic decoding variables */ entropy->c = 0; entropy->a = 0; entropy->ct = -16; /* force reading 2 initial bytes to fill C */ /* Initialize restart counter */ entropy->restarts_to_go = cinfo->restart_interval; } /* * Finish up at the end of an arithmetic-compressed scan. */ METHODDEF(void) finish_pass (j_decompress_ptr cinfo) { /* no work necessary here */ } /* * Module initialization routine for arithmetic entropy decoding. */ GLOBAL(void) jinit_arith_decoder (j_decompress_ptr cinfo) { arith_entropy_ptr entropy; int i; entropy = (arith_entropy_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(arith_entropy_decoder)); cinfo->entropy = &entropy->pub; entropy->pub.start_pass = start_pass; entropy->pub.finish_pass = finish_pass; /* Mark tables unallocated */ for (i = 0; i < NUM_ARITH_TBLS; i++) { entropy->dc_stats[i] = NULL; entropy->ac_stats[i] = NULL; } /* Initialize index for fixed probability estimation */ entropy->fixed_bin[0] = 113; if (cinfo->progressive_mode) { /* Create progression status table */ int *coef_bit_ptr, ci; cinfo->coef_bits = (int (*)[DCTSIZE2]) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->num_components*DCTSIZE2*SIZEOF(int)); coef_bit_ptr = & cinfo->coef_bits[0][0]; for (ci = 0; ci < cinfo->num_components; ci++) for (i = 0; i < DCTSIZE2; i++) *coef_bit_ptr++ = -1; } } ================================================ FILE: tess-two/jni/libjpeg/jdatadst.c ================================================ /* * jdatadst.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2009-2012 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains compression data destination routines for the case of * emitting JPEG data to memory or to a file (or any stdio stream). * While these routines are sufficient for most applications, * some will want to use a different destination manager. * IMPORTANT: we assume that fwrite() will correctly transcribe an array of * JOCTETs into 8-bit-wide elements on external storage. If char is wider * than 8 bits on your machine, you may need to do some tweaking. */ /* this is not a core library module, so it doesn't define JPEG_INTERNALS */ #include "jinclude.h" #include "jpeglib.h" #include "jerror.h" #ifndef HAVE_STDLIB_H /* should declare malloc(),free() */ extern void * malloc JPP((size_t size)); extern void free JPP((void *ptr)); #endif /* Expanded data destination object for stdio output */ typedef struct { struct jpeg_destination_mgr pub; /* public fields */ FILE * outfile; /* target stream */ JOCTET * buffer; /* start of buffer */ } my_destination_mgr; typedef my_destination_mgr * my_dest_ptr; #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ /* Expanded data destination object for memory output */ typedef struct { struct jpeg_destination_mgr pub; /* public fields */ unsigned char ** outbuffer; /* target buffer */ unsigned long * outsize; unsigned char * newbuffer; /* newly allocated buffer */ JOCTET * buffer; /* start of buffer */ size_t bufsize; } my_mem_destination_mgr; typedef my_mem_destination_mgr * my_mem_dest_ptr; /* * Initialize destination --- called by jpeg_start_compress * before any data is actually written. */ METHODDEF(void) init_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; /* Allocate the output buffer --- it will be released when done with image */ dest->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * SIZEOF(JOCTET)); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; } METHODDEF(void) init_mem_destination (j_compress_ptr cinfo) { /* no work necessary here */ } /* * Empty the output buffer --- called whenever buffer fills up. * * In typical applications, this should write the entire output buffer * (ignoring the current state of next_output_byte & free_in_buffer), * reset the pointer & count to the start of the buffer, and return TRUE * indicating that the buffer has been dumped. * * In applications that need to be able to suspend compression due to output * overrun, a FALSE return indicates that the buffer cannot be emptied now. * In this situation, the compressor will return to its caller (possibly with * an indication that it has not accepted all the supplied scanlines). The * application should resume compression after it has made more room in the * output buffer. Note that there are substantial restrictions on the use of * suspension --- see the documentation. * * When suspending, the compressor will back up to a convenient restart point * (typically the start of the current MCU). next_output_byte & free_in_buffer * indicate where the restart point will be if the current call returns FALSE. * Data beyond this point will be regenerated after resumption, so do not * write it out when emptying the buffer externally. */ METHODDEF(boolean) empty_output_buffer (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) != (size_t) OUTPUT_BUF_SIZE) ERREXIT(cinfo, JERR_FILE_WRITE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; return TRUE; } METHODDEF(boolean) empty_mem_output_buffer (j_compress_ptr cinfo) { size_t nextsize; JOCTET * nextbuffer; my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; /* Try to allocate new buffer with double size */ nextsize = dest->bufsize * 2; nextbuffer = (JOCTET *) malloc(nextsize); if (nextbuffer == NULL) ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10); MEMCOPY(nextbuffer, dest->buffer, dest->bufsize); if (dest->newbuffer != NULL) free(dest->newbuffer); dest->newbuffer = nextbuffer; dest->pub.next_output_byte = nextbuffer + dest->bufsize; dest->pub.free_in_buffer = dest->bufsize; dest->buffer = nextbuffer; dest->bufsize = nextsize; return TRUE; } /* * Terminate destination --- called by jpeg_finish_compress * after all data has been written. Usually needs to flush buffer. * * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding * application must deal with any cleanup that should happen even * for error exit. */ METHODDEF(void) term_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; /* Write any data remaining in the buffer */ if (datacount > 0) { if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount) ERREXIT(cinfo, JERR_FILE_WRITE); } fflush(dest->outfile); /* Make sure we wrote the output file OK */ if (ferror(dest->outfile)) ERREXIT(cinfo, JERR_FILE_WRITE); } METHODDEF(void) term_mem_destination (j_compress_ptr cinfo) { my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; *dest->outbuffer = dest->buffer; *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; } /* * Prepare for output to a stdio stream. * The caller must have already opened the stream, and is responsible * for closing it after finishing compression. */ GLOBAL(void) jpeg_stdio_dest (j_compress_ptr cinfo, FILE * outfile) { my_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images * can be written to the same file without re-executing jpeg_stdio_dest. * This makes it dangerous to use this manager and a different destination * manager serially with the same JPEG object, because their private object * sizes may be different. Caveat programmer. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_destination_mgr)); } dest = (my_dest_ptr) cinfo->dest; dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; dest->outfile = outfile; } /* * Prepare for output to a memory buffer. * The caller may supply an own initial buffer with appropriate size. * Otherwise, or when the actual data output exceeds the given size, * the library adapts the buffer size as necessary. * The standard library functions malloc/free are used for allocating * larger memory, so the buffer is available to the application after * finishing compression, and then the application is responsible for * freeing the requested memory. * Note: An initial buffer supplied by the caller is expected to be * managed by the application. The library does not free such buffer * when allocating a larger buffer. */ GLOBAL(void) jpeg_mem_dest (j_compress_ptr cinfo, unsigned char ** outbuffer, unsigned long * outsize) { my_mem_dest_ptr dest; if (outbuffer == NULL || outsize == NULL) /* sanity check */ ERREXIT(cinfo, JERR_BUFFER_SIZE); /* The destination object is made permanent so that multiple JPEG images * can be written to the same buffer without re-executing jpeg_mem_dest. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_mem_destination_mgr)); } dest = (my_mem_dest_ptr) cinfo->dest; dest->pub.init_destination = init_mem_destination; dest->pub.empty_output_buffer = empty_mem_output_buffer; dest->pub.term_destination = term_mem_destination; dest->outbuffer = outbuffer; dest->outsize = outsize; dest->newbuffer = NULL; if (*outbuffer == NULL || *outsize == 0) { /* Allocate initial buffer */ dest->newbuffer = *outbuffer = (unsigned char *) malloc(OUTPUT_BUF_SIZE); if (dest->newbuffer == NULL) ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10); *outsize = OUTPUT_BUF_SIZE; } dest->pub.next_output_byte = dest->buffer = *outbuffer; dest->pub.free_in_buffer = dest->bufsize = *outsize; } ================================================ FILE: tess-two/jni/libjpeg/jdatasrc.c ================================================ /* * jdatasrc.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2009-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains decompression data source routines for the case of * reading JPEG data from memory or from a file (or any stdio stream). * While these routines are sufficient for most applications, * some will want to use a different source manager. * IMPORTANT: we assume that fread() will correctly transcribe an array of * JOCTETs from 8-bit-wide elements on external storage. If char is wider * than 8 bits on your machine, you may need to do some tweaking. */ /* this is not a core library module, so it doesn't define JPEG_INTERNALS */ #include "jinclude.h" #include "jpeglib.h" #include "jerror.h" /* Expanded data source object for stdio input */ typedef struct { struct jpeg_source_mgr pub; /* public fields */ FILE * infile; /* source stream */ JOCTET * buffer; /* start of buffer */ boolean start_of_file; /* have we gotten any data yet? */ } my_source_mgr; typedef my_source_mgr * my_src_ptr; #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ /* * Initialize source --- called by jpeg_read_header * before any data is actually read. */ METHODDEF(void) init_source (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; /* We reset the empty-input-file flag for each image, * but we don't clear the input buffer. * This is correct behavior for reading a series of images from one source. */ src->start_of_file = TRUE; } METHODDEF(void) init_mem_source (j_decompress_ptr cinfo) { /* no work necessary here */ } /* * Fill the input buffer --- called whenever buffer is emptied. * * In typical applications, this should read fresh data into the buffer * (ignoring the current state of next_input_byte & bytes_in_buffer), * reset the pointer & count to the start of the buffer, and return TRUE * indicating that the buffer has been reloaded. It is not necessary to * fill the buffer entirely, only to obtain at least one more byte. * * There is no such thing as an EOF return. If the end of the file has been * reached, the routine has a choice of ERREXIT() or inserting fake data into * the buffer. In most cases, generating a warning message and inserting a * fake EOI marker is the best course of action --- this will allow the * decompressor to output however much of the image is there. However, * the resulting error message is misleading if the real problem is an empty * input file, so we handle that case specially. * * In applications that need to be able to suspend compression due to input * not being available yet, a FALSE return indicates that no more data can be * obtained right now, but more may be forthcoming later. In this situation, * the decompressor will return to its caller (with an indication of the * number of scanlines it has read, if any). The application should resume * decompression after it has loaded more data into the input buffer. Note * that there are substantial restrictions on the use of suspension --- see * the documentation. * * When suspending, the decompressor will back up to a convenient restart point * (typically the start of the current MCU). next_input_byte & bytes_in_buffer * indicate where the restart point will be if the current call returns FALSE. * Data beyond this point must be rescanned after resumption, so move it to * the front of the buffer rather than discarding it. */ METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; size_t nbytes; nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE); if (nbytes <= 0) { if (src->start_of_file) /* Treat empty input file as fatal error */ ERREXIT(cinfo, JERR_INPUT_EMPTY); WARNMS(cinfo, JWRN_JPEG_EOF); /* Insert a fake EOI marker */ src->buffer[0] = (JOCTET) 0xFF; src->buffer[1] = (JOCTET) JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; src->start_of_file = FALSE; return TRUE; } METHODDEF(boolean) fill_mem_input_buffer (j_decompress_ptr cinfo) { static const JOCTET mybuffer[4] = { (JOCTET) 0xFF, (JOCTET) JPEG_EOI, 0, 0 }; /* The whole JPEG data is expected to reside in the supplied memory * buffer, so any request for more data beyond the given buffer size * is treated as an error. */ WARNMS(cinfo, JWRN_JPEG_EOF); /* Insert a fake EOI marker */ cinfo->src->next_input_byte = mybuffer; cinfo->src->bytes_in_buffer = 2; return TRUE; } /* * Skip data --- used to skip over a potentially large amount of * uninteresting data (such as an APPn marker). * * Writers of suspendable-input applications must note that skip_input_data * is not granted the right to give a suspension return. If the skip extends * beyond the data currently in the buffer, the buffer can be marked empty so * that the next read will cause a fill_input_buffer call that can suspend. * Arranging for additional bytes to be discarded before reloading the input * buffer is the application writer's problem. */ METHODDEF(void) skip_input_data (j_decompress_ptr cinfo, long num_bytes) { struct jpeg_source_mgr * src = cinfo->src; /* Just a dumb implementation for now. Could use fseek() except * it doesn't work on pipes. Not clear that being smart is worth * any trouble anyway --- large skips are infrequent. */ if (num_bytes > 0) { while (num_bytes > (long) src->bytes_in_buffer) { num_bytes -= (long) src->bytes_in_buffer; (void) (*src->fill_input_buffer) (cinfo); /* note we assume that fill_input_buffer will never return FALSE, * so suspension need not be handled. */ } src->next_input_byte += (size_t) num_bytes; src->bytes_in_buffer -= (size_t) num_bytes; } } /* * An additional method that can be provided by data source modules is the * resync_to_restart method for error recovery in the presence of RST markers. * For the moment, this source module just uses the default resync method * provided by the JPEG library. That method assumes that no backtracking * is possible. */ /* * Terminate source --- called by jpeg_finish_decompress * after all data has been read. Often a no-op. * * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding * application must deal with any cleanup that should happen even * for error exit. */ METHODDEF(void) term_source (j_decompress_ptr cinfo) { /* no work necessary here */ } /* * Prepare for input from a stdio stream. * The caller must have already opened the stream, and is responsible * for closing it after finishing decompression. */ GLOBAL(void) jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile) { my_src_ptr src; /* The source object and input buffer are made permanent so that a series * of JPEG images can be read from the same file by calling jpeg_stdio_src * only before the first one. (If we discarded the buffer at the end of * one image, we'd likely lose the start of the next one.) * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_source_mgr)); src = (my_src_ptr) cinfo->src; src->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * SIZEOF(JOCTET)); } src = (my_src_ptr) cinfo->src; src->pub.init_source = init_source; src->pub.fill_input_buffer = fill_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->pub.term_source = term_source; src->infile = infile; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } /* * Prepare for input from a supplied memory buffer. * The buffer must contain the whole JPEG data. */ GLOBAL(void) jpeg_mem_src (j_decompress_ptr cinfo, const unsigned char * inbuffer, unsigned long insize) { struct jpeg_source_mgr * src; if (inbuffer == NULL || insize == 0) /* Treat empty input as fatal error */ ERREXIT(cinfo, JERR_INPUT_EMPTY); /* The source object is made permanent so that a series of JPEG images * can be read from the same buffer by calling jpeg_mem_src only before * the first one. */ if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(struct jpeg_source_mgr)); } src = cinfo->src; src->init_source = init_mem_source; src->fill_input_buffer = fill_mem_input_buffer; src->skip_input_data = skip_input_data; src->resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->term_source = term_source; src->bytes_in_buffer = (size_t) insize; src->next_input_byte = (const JOCTET *) inbuffer; } ================================================ FILE: tess-two/jni/libjpeg/jdcoefct.c ================================================ /* * jdcoefct.c * * Copyright (C) 1994-1997, Thomas G. Lane. * Modified 2002-2011 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the coefficient buffer controller for decompression. * This controller is the top level of the JPEG decompressor proper. * The coefficient buffer lies between entropy decoding and inverse-DCT steps. * * In buffered-image mode, this controller is the interface between * input-oriented processing and output-oriented processing. * Also, the input side (only) is used when reading a file for transcoding. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Block smoothing is only applicable for progressive JPEG, so: */ #ifndef D_PROGRESSIVE_SUPPORTED #undef BLOCK_SMOOTHING_SUPPORTED #endif /* Private buffer controller object */ typedef struct { struct jpeg_d_coef_controller pub; /* public fields */ /* These variables keep track of the current location of the input side. */ /* cinfo->input_iMCU_row is also used for this. */ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */ int MCU_vert_offset; /* counts MCU rows within iMCU row */ int MCU_rows_per_iMCU_row; /* number of such rows needed */ /* The output side's location is represented by cinfo->output_iMCU_row. */ /* In single-pass modes, it's sufficient to buffer just one MCU. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks, * and let the entropy decoder write into that workspace each time. * (On 80x86, the workspace is FAR even though it's not really very big; * this is to keep the module interfaces unchanged when a large coefficient * buffer is necessary.) * In multi-pass modes, this array points to the current MCU's blocks * within the virtual arrays; it is used only by the input side. */ JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU]; #ifdef D_MULTISCAN_FILES_SUPPORTED /* In multi-pass modes, we need a virtual block array for each component. */ jvirt_barray_ptr whole_image[MAX_COMPONENTS]; #endif #ifdef BLOCK_SMOOTHING_SUPPORTED /* When doing block smoothing, we latch coefficient Al values here */ int * coef_bits_latch; #define SAVED_COEFS 6 /* we save coef_bits[0..5] */ #endif } my_coef_controller; typedef my_coef_controller * my_coef_ptr; /* Forward declarations */ METHODDEF(int) decompress_onepass JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); #ifdef D_MULTISCAN_FILES_SUPPORTED METHODDEF(int) decompress_data JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); #endif #ifdef BLOCK_SMOOTHING_SUPPORTED LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo)); METHODDEF(int) decompress_smooth_data JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); #endif LOCAL(void) start_iMCU_row (j_decompress_ptr cinfo) /* Reset within-iMCU-row counters for a new row (input side) */ { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; /* In an interleaved scan, an MCU row is the same as an iMCU row. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. * But at the bottom of the image, process only what's left. */ if (cinfo->comps_in_scan > 1) { coef->MCU_rows_per_iMCU_row = 1; } else { if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1)) coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; else coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; } coef->MCU_ctr = 0; coef->MCU_vert_offset = 0; } /* * Initialize for an input processing pass. */ METHODDEF(void) start_input_pass (j_decompress_ptr cinfo) { cinfo->input_iMCU_row = 0; start_iMCU_row(cinfo); } /* * Initialize for an output processing pass. */ METHODDEF(void) start_output_pass (j_decompress_ptr cinfo) { #ifdef BLOCK_SMOOTHING_SUPPORTED my_coef_ptr coef = (my_coef_ptr) cinfo->coef; /* If multipass, check to see whether to use block smoothing on this pass */ if (coef->pub.coef_arrays != NULL) { if (cinfo->do_block_smoothing && smoothing_ok(cinfo)) coef->pub.decompress_data = decompress_smooth_data; else coef->pub.decompress_data = decompress_data; } #endif cinfo->output_iMCU_row = 0; } /* * Decompress and return some data in the single-pass case. * Always attempts to emit one fully interleaved MCU row ("iMCU" row). * Input and output must run in lockstep since we have only a one-MCU buffer. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. * * NB: output_buf contains a plane for each component in image, * which we index according to the component's SOF position. */ METHODDEF(int) decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; int blkn, ci, xindex, yindex, yoffset, useful_width; JSAMPARRAY output_ptr; JDIMENSION start_col, output_col; jpeg_component_info *compptr; inverse_DCT_method_ptr inverse_DCT; /* Loop to process as much as one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) { /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */ if (cinfo->lim_Se) /* can bypass in DC only case */ FMEMZERO((void FAR *) coef->MCU_buffer[0], (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK))); if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->MCU_ctr = MCU_col_num; return JPEG_SUSPENDED; } /* Determine where data should go in output_buf and do the IDCT thing. * We skip dummy blocks at the right and bottom edges (but blkn gets * incremented past them!). Note the inner loop relies on having * allocated the MCU_buffer[] blocks sequentially. */ blkn = 0; /* index of current DCT block within MCU */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Don't bother to IDCT an uninteresting component. */ if (! compptr->component_needed) { blkn += compptr->MCU_blocks; continue; } inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index]; useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width : compptr->last_col_width; output_ptr = output_buf[compptr->component_index] + yoffset * compptr->DCT_v_scaled_size; start_col = MCU_col_num * compptr->MCU_sample_width; for (yindex = 0; yindex < compptr->MCU_height; yindex++) { if (cinfo->input_iMCU_row < last_iMCU_row || yoffset+yindex < compptr->last_row_height) { output_col = start_col; for (xindex = 0; xindex < useful_width; xindex++) { (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) coef->MCU_buffer[blkn+xindex], output_ptr, output_col); output_col += compptr->DCT_h_scaled_size; } } blkn += compptr->MCU_width; output_ptr += compptr->DCT_v_scaled_size; } } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->MCU_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ cinfo->output_iMCU_row++; if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) { start_iMCU_row(cinfo); return JPEG_ROW_COMPLETED; } /* Completed the scan */ (*cinfo->inputctl->finish_input_pass) (cinfo); return JPEG_SCAN_COMPLETED; } /* * Dummy consume-input routine for single-pass operation. */ METHODDEF(int) dummy_consume_data (j_decompress_ptr cinfo) { return JPEG_SUSPENDED; /* Always indicate nothing was done */ } #ifdef D_MULTISCAN_FILES_SUPPORTED /* * Consume input data and store it in the full-image coefficient buffer. * We read as much as one fully interleaved MCU row ("iMCU" row) per call, * ie, v_samp_factor block rows for each component in the scan. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. */ METHODDEF(int) consume_data (j_decompress_ptr cinfo) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ int blkn, ci, xindex, yindex, yoffset; JDIMENSION start_col; JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; JBLOCKROW buffer_ptr; jpeg_component_info *compptr; /* Align the virtual buffers for the components used in this scan. */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; buffer[ci] = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], cinfo->input_iMCU_row * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, TRUE); /* Note: entropy decoder expects buffer to be zeroed, * but this is handled automatically by the memory manager * because we requested a pre-zeroed array. */ } /* Loop to process one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row; MCU_col_num++) { /* Construct list of pointers to DCT blocks belonging to this MCU */ blkn = 0; /* index of current DCT block within MCU */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; start_col = MCU_col_num * compptr->MCU_width; for (yindex = 0; yindex < compptr->MCU_height; yindex++) { buffer_ptr = buffer[ci][yindex+yoffset] + start_col; for (xindex = 0; xindex < compptr->MCU_width; xindex++) { coef->MCU_buffer[blkn++] = buffer_ptr++; } } } /* Try to fetch the MCU. */ if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->MCU_ctr = MCU_col_num; return JPEG_SUSPENDED; } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->MCU_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) { start_iMCU_row(cinfo); return JPEG_ROW_COMPLETED; } /* Completed the scan */ (*cinfo->inputctl->finish_input_pass) (cinfo); return JPEG_SCAN_COMPLETED; } /* * Decompress and return some data in the multi-pass case. * Always attempts to emit one fully interleaved MCU row ("iMCU" row). * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. * * NB: output_buf contains a plane for each component in image. */ METHODDEF(int) decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; JDIMENSION block_num; int ci, block_row, block_rows; JBLOCKARRAY buffer; JBLOCKROW buffer_ptr; JSAMPARRAY output_ptr; JDIMENSION output_col; jpeg_component_info *compptr; inverse_DCT_method_ptr inverse_DCT; /* Force some input to be done if we are getting ahead of the input. */ while (cinfo->input_scan_number < cinfo->output_scan_number || (cinfo->input_scan_number == cinfo->output_scan_number && cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) { if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED) return JPEG_SUSPENDED; } /* OK, output from the virtual arrays. */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Don't bother to IDCT an uninteresting component. */ if (! compptr->component_needed) continue; /* Align the virtual buffer for this component. */ buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], cinfo->output_iMCU_row * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, FALSE); /* Count non-dummy DCT block rows in this iMCU row. */ if (cinfo->output_iMCU_row < last_iMCU_row) block_rows = compptr->v_samp_factor; else { /* NB: can't use last_row_height here; it is input-side-dependent! */ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (block_rows == 0) block_rows = compptr->v_samp_factor; } inverse_DCT = cinfo->idct->inverse_DCT[ci]; output_ptr = output_buf[ci]; /* Loop over all DCT blocks to be processed. */ for (block_row = 0; block_row < block_rows; block_row++) { buffer_ptr = buffer[block_row]; output_col = 0; for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) { (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr, output_ptr, output_col); buffer_ptr++; output_col += compptr->DCT_h_scaled_size; } output_ptr += compptr->DCT_v_scaled_size; } } if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows) return JPEG_ROW_COMPLETED; return JPEG_SCAN_COMPLETED; } #endif /* D_MULTISCAN_FILES_SUPPORTED */ #ifdef BLOCK_SMOOTHING_SUPPORTED /* * This code applies interblock smoothing as described by section K.8 * of the JPEG standard: the first 5 AC coefficients are estimated from * the DC values of a DCT block and its 8 neighboring blocks. * We apply smoothing only for progressive JPEG decoding, and only if * the coefficients it can estimate are not yet known to full precision. */ /* Natural-order array positions of the first 5 zigzag-order coefficients */ #define Q01_POS 1 #define Q10_POS 8 #define Q20_POS 16 #define Q11_POS 9 #define Q02_POS 2 /* * Determine whether block smoothing is applicable and safe. * We also latch the current states of the coef_bits[] entries for the * AC coefficients; otherwise, if the input side of the decompressor * advances into a new scan, we might think the coefficients are known * more accurately than they really are. */ LOCAL(boolean) smoothing_ok (j_decompress_ptr cinfo) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; boolean smoothing_useful = FALSE; int ci, coefi; jpeg_component_info *compptr; JQUANT_TBL * qtable; int * coef_bits; int * coef_bits_latch; if (! cinfo->progressive_mode || cinfo->coef_bits == NULL) return FALSE; /* Allocate latch area if not already done */ if (coef->coef_bits_latch == NULL) coef->coef_bits_latch = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->num_components * (SAVED_COEFS * SIZEOF(int))); coef_bits_latch = coef->coef_bits_latch; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* All components' quantization values must already be latched. */ if ((qtable = compptr->quant_table) == NULL) return FALSE; /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */ if (qtable->quantval[0] == 0 || qtable->quantval[Q01_POS] == 0 || qtable->quantval[Q10_POS] == 0 || qtable->quantval[Q20_POS] == 0 || qtable->quantval[Q11_POS] == 0 || qtable->quantval[Q02_POS] == 0) return FALSE; /* DC values must be at least partly known for all components. */ coef_bits = cinfo->coef_bits[ci]; if (coef_bits[0] < 0) return FALSE; /* Block smoothing is helpful if some AC coefficients remain inaccurate. */ for (coefi = 1; coefi <= 5; coefi++) { coef_bits_latch[coefi] = coef_bits[coefi]; if (coef_bits[coefi] != 0) smoothing_useful = TRUE; } coef_bits_latch += SAVED_COEFS; } return smoothing_useful; } /* * Variant of decompress_data for use when doing block smoothing. */ METHODDEF(int) decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; JDIMENSION block_num, last_block_column; int ci, block_row, block_rows, access_rows; JBLOCKARRAY buffer; JBLOCKROW buffer_ptr, prev_block_row, next_block_row; JSAMPARRAY output_ptr; JDIMENSION output_col; jpeg_component_info *compptr; inverse_DCT_method_ptr inverse_DCT; boolean first_row, last_row; JBLOCK workspace; int *coef_bits; JQUANT_TBL *quanttbl; INT32 Q00,Q01,Q02,Q10,Q11,Q20, num; int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9; int Al, pred; /* Force some input to be done if we are getting ahead of the input. */ while (cinfo->input_scan_number <= cinfo->output_scan_number && ! cinfo->inputctl->eoi_reached) { if (cinfo->input_scan_number == cinfo->output_scan_number) { /* If input is working on current scan, we ordinarily want it to * have completed the current row. But if input scan is DC, * we want it to keep one row ahead so that next block row's DC * values are up to date. */ JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0; if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta) break; } if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED) return JPEG_SUSPENDED; } /* OK, output from the virtual arrays. */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Don't bother to IDCT an uninteresting component. */ if (! compptr->component_needed) continue; /* Count non-dummy DCT block rows in this iMCU row. */ if (cinfo->output_iMCU_row < last_iMCU_row) { block_rows = compptr->v_samp_factor; access_rows = block_rows * 2; /* this and next iMCU row */ last_row = FALSE; } else { /* NB: can't use last_row_height here; it is input-side-dependent! */ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (block_rows == 0) block_rows = compptr->v_samp_factor; access_rows = block_rows; /* this iMCU row only */ last_row = TRUE; } /* Align the virtual buffer for this component. */ if (cinfo->output_iMCU_row > 0) { access_rows += compptr->v_samp_factor; /* prior iMCU row too */ buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor, (JDIMENSION) access_rows, FALSE); buffer += compptr->v_samp_factor; /* point to current iMCU row */ first_row = FALSE; } else { buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE); first_row = TRUE; } /* Fetch component-dependent info */ coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS); quanttbl = compptr->quant_table; Q00 = quanttbl->quantval[0]; Q01 = quanttbl->quantval[Q01_POS]; Q10 = quanttbl->quantval[Q10_POS]; Q20 = quanttbl->quantval[Q20_POS]; Q11 = quanttbl->quantval[Q11_POS]; Q02 = quanttbl->quantval[Q02_POS]; inverse_DCT = cinfo->idct->inverse_DCT[ci]; output_ptr = output_buf[ci]; /* Loop over all DCT blocks to be processed. */ for (block_row = 0; block_row < block_rows; block_row++) { buffer_ptr = buffer[block_row]; if (first_row && block_row == 0) prev_block_row = buffer_ptr; else prev_block_row = buffer[block_row-1]; if (last_row && block_row == block_rows-1) next_block_row = buffer_ptr; else next_block_row = buffer[block_row+1]; /* We fetch the surrounding DC values using a sliding-register approach. * Initialize all nine here so as to do the right thing on narrow pics. */ DC1 = DC2 = DC3 = (int) prev_block_row[0][0]; DC4 = DC5 = DC6 = (int) buffer_ptr[0][0]; DC7 = DC8 = DC9 = (int) next_block_row[0][0]; output_col = 0; last_block_column = compptr->width_in_blocks - 1; for (block_num = 0; block_num <= last_block_column; block_num++) { /* Fetch current DCT block into workspace so we can modify it. */ jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1); /* Update DC values */ if (block_num < last_block_column) { DC3 = (int) prev_block_row[1][0]; DC6 = (int) buffer_ptr[1][0]; DC9 = (int) next_block_row[1][0]; } /* Compute coefficient estimates per K.8. * An estimate is applied only if coefficient is still zero, * and is not known to be fully accurate. */ /* AC01 */ if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) { num = 36 * Q00 * (DC4 - DC6); if (num >= 0) { pred = (int) (((Q01<<7) + num) / (Q01<<8)); if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { pred = (int) (((Q10<<7) + num) / (Q10<<8)); if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { pred = (int) (((Q20<<7) + num) / (Q20<<8)); if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { pred = (int) (((Q11<<7) + num) / (Q11<<8)); if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { pred = (int) (((Q02<<7) + num) / (Q02<<8)); if (Al > 0 && pred >= (1< 0 && pred >= (1<DCT_h_scaled_size; } output_ptr += compptr->DCT_v_scaled_size; } } if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows) return JPEG_ROW_COMPLETED; return JPEG_SCAN_COMPLETED; } #endif /* BLOCK_SMOOTHING_SUPPORTED */ /* * Initialize coefficient buffer controller. */ GLOBAL(void) jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer) { my_coef_ptr coef; coef = (my_coef_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_coef_controller)); cinfo->coef = (struct jpeg_d_coef_controller *) coef; coef->pub.start_input_pass = start_input_pass; coef->pub.start_output_pass = start_output_pass; #ifdef BLOCK_SMOOTHING_SUPPORTED coef->coef_bits_latch = NULL; #endif /* Create the coefficient buffer. */ if (need_full_buffer) { #ifdef D_MULTISCAN_FILES_SUPPORTED /* Allocate a full-image virtual array for each component, */ /* padded to a multiple of samp_factor DCT blocks in each direction. */ /* Note we ask for a pre-zeroed array. */ int ci, access_rows; jpeg_component_info *compptr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { access_rows = compptr->v_samp_factor; #ifdef BLOCK_SMOOTHING_SUPPORTED /* If block smoothing could be used, need a bigger window */ if (cinfo->progressive_mode) access_rows *= 3; #endif coef->whole_image[ci] = (*cinfo->mem->request_virt_barray) ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE, (JDIMENSION) jround_up((long) compptr->width_in_blocks, (long) compptr->h_samp_factor), (JDIMENSION) jround_up((long) compptr->height_in_blocks, (long) compptr->v_samp_factor), (JDIMENSION) access_rows); } coef->pub.consume_data = consume_data; coef->pub.decompress_data = decompress_data; coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */ #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { /* We only need a single-MCU buffer. */ JBLOCKROW buffer; int i; buffer = (JBLOCKROW) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) { coef->MCU_buffer[i] = buffer + i; } if (cinfo->lim_Se == 0) /* DC only case: want to bypass later */ FMEMZERO((void FAR *) buffer, (size_t) (D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK))); coef->pub.consume_data = dummy_consume_data; coef->pub.decompress_data = decompress_onepass; coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */ } } ================================================ FILE: tess-two/jni/libjpeg/jdcolor.c ================================================ /* * jdcolor.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2011-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains output colorspace conversion routines. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Private subobject */ typedef struct { struct jpeg_color_deconverter pub; /* public fields */ /* Private state for YCbCr->RGB and BG_YCC->RGB conversion */ int * Cr_r_tab; /* => table for Cr to R conversion */ int * Cb_b_tab; /* => table for Cb to B conversion */ INT32 * Cr_g_tab; /* => table for Cr to G conversion */ INT32 * Cb_g_tab; /* => table for Cb to G conversion */ /* Private state for RGB->Y conversion */ INT32 * rgb_y_tab; /* => table for RGB to Y conversion */ } my_color_deconverter; typedef my_color_deconverter * my_cconvert_ptr; /*************** YCbCr -> RGB conversion: most common case **************/ /*************** BG_YCC -> RGB conversion: less common case **************/ /*************** RGB -> Y conversion: less common case **************/ /* * YCbCr is defined per Recommendation ITU-R BT.601-7 (03/2011), * previously known as Recommendation CCIR 601-1, except that Cb and Cr * are normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. * sRGB (standard RGB color space) is defined per IEC 61966-2-1:1999. * sYCC (standard luma-chroma-chroma color space with extended gamut) * is defined per IEC 61966-2-1:1999 Amendment A1:2003 Annex F. * bg-sRGB and bg-sYCC (big gamut standard color spaces) * are defined per IEC 61966-2-1:1999 Amendment A1:2003 Annex G. * Note that the derived conversion coefficients given in some of these * documents are imprecise. The general conversion equations are * * R = Y + K * (1 - Kr) * Cr * G = Y - K * (Kb * (1 - Kb) * Cb + Kr * (1 - Kr) * Cr) / (1 - Kr - Kb) * B = Y + K * (1 - Kb) * Cb * * Y = Kr * R + (1 - Kr - Kb) * G + Kb * B * * With Kr = 0.299 and Kb = 0.114 (derived according to SMPTE RP 177-1993 * from the 1953 FCC NTSC primaries and CIE Illuminant C), K = 2 for sYCC, * the conversion equations to be implemented are therefore * * R = Y + 1.402 * Cr * G = Y - 0.344136286 * Cb - 0.714136286 * Cr * B = Y + 1.772 * Cb * * Y = 0.299 * R + 0.587 * G + 0.114 * B * * where Cb and Cr represent the incoming values less CENTERJSAMPLE. * For bg-sYCC, with K = 4, the equations are * * R = Y + 2.804 * Cr * G = Y - 0.688272572 * Cb - 1.428272572 * Cr * B = Y + 3.544 * Cb * * To avoid floating-point arithmetic, we represent the fractional constants * as integers scaled up by 2^16 (about 4 digits precision); we have to divide * the products by 2^16, with appropriate rounding, to get the correct answer. * Notice that Y, being an integral input, does not contribute any fraction * so it need not participate in the rounding. * * For even more speed, we avoid doing any multiplications in the inner loop * by precalculating the constants times Cb and Cr for all possible values. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); * for 9-bit to 12-bit samples it is still acceptable. It's not very * reasonable for 16-bit samples, but if you want lossless storage you * shouldn't be changing colorspace anyway. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the * values for the G calculation are left scaled up, since we must add them * together before rounding. */ #define SCALEBITS 16 /* speediest right-shift on some machines */ #define ONE_HALF ((INT32) 1 << (SCALEBITS-1)) #define FIX(x) ((INT32) ((x) * (1L<Y conversion and divide it up into * three parts, instead of doing three alloc_small requests. This lets us * use a single table base address, which can be held in a register in the * inner loops on many machines (more than can hold all three addresses, * anyway). */ #define R_Y_OFF 0 /* offset to R => Y section */ #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */ #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */ #define TABLE_SIZE (3*(MAXJSAMPLE+1)) /* * Initialize tables for YCbCr->RGB and BG_YCC->RGB colorspace conversion. */ LOCAL(void) build_ycc_rgb_table (j_decompress_ptr cinfo) /* Normal case, sYCC */ { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; int i; INT32 x; SHIFT_TEMPS cconvert->Cr_r_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); cconvert->Cb_b_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); cconvert->Cr_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); cconvert->Cb_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ /* Cr=>R value is nearest int to 1.402 * x */ cconvert->Cr_r_tab[i] = (int) RIGHT_SHIFT(FIX(1.402) * x + ONE_HALF, SCALEBITS); /* Cb=>B value is nearest int to 1.772 * x */ cconvert->Cb_b_tab[i] = (int) RIGHT_SHIFT(FIX(1.772) * x + ONE_HALF, SCALEBITS); /* Cr=>G value is scaled-up -0.714136286 * x */ cconvert->Cr_g_tab[i] = (- FIX(0.714136286)) * x; /* Cb=>G value is scaled-up -0.344136286 * x */ /* We also add in ONE_HALF so that need not do it in inner loop */ cconvert->Cb_g_tab[i] = (- FIX(0.344136286)) * x + ONE_HALF; } } LOCAL(void) build_bg_ycc_rgb_table (j_decompress_ptr cinfo) /* Wide gamut case, bg-sYCC */ { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; int i; INT32 x; SHIFT_TEMPS cconvert->Cr_r_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); cconvert->Cb_b_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); cconvert->Cr_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); cconvert->Cb_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ /* Cr=>R value is nearest int to 2.804 * x */ cconvert->Cr_r_tab[i] = (int) RIGHT_SHIFT(FIX(2.804) * x + ONE_HALF, SCALEBITS); /* Cb=>B value is nearest int to 3.544 * x */ cconvert->Cb_b_tab[i] = (int) RIGHT_SHIFT(FIX(3.544) * x + ONE_HALF, SCALEBITS); /* Cr=>G value is scaled-up -1.428272572 * x */ cconvert->Cr_g_tab[i] = (- FIX(1.428272572)) * x; /* Cb=>G value is scaled-up -0.688272572 * x */ /* We also add in ONE_HALF so that need not do it in inner loop */ cconvert->Cb_g_tab[i] = (- FIX(0.688272572)) * x + ONE_HALF; } } /* * Convert some rows of samples to the output colorspace. * * Note that we change from noninterleaved, one-plane-per-component format * to interleaved-pixel format. The output buffer is therefore three times * as wide as the input buffer. * A starting row offset is provided only for the input buffer. The caller * can easily adjust the passed output_buf value to accommodate any row * offset required on that side. */ METHODDEF(void) ycc_rgb_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register int y, cb, cr; register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; /* copy these pointers into registers if possible */ register JSAMPLE * range_limit = cinfo->sample_range_limit; register int * Crrtab = cconvert->Cr_r_tab; register int * Cbbtab = cconvert->Cb_b_tab; register INT32 * Crgtab = cconvert->Cr_g_tab; register INT32 * Cbgtab = cconvert->Cb_g_tab; SHIFT_TEMPS while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { y = GETJSAMPLE(inptr0[col]); cb = GETJSAMPLE(inptr1[col]); cr = GETJSAMPLE(inptr2[col]); /* Range-limiting is essential due to noise introduced by DCT losses, * for extended gamut (sYCC) and wide gamut (bg-sYCC) encodings. */ outptr[RGB_RED] = range_limit[y + Crrtab[cr]]; outptr[RGB_GREEN] = range_limit[y + ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS))]; outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]]; outptr += RGB_PIXELSIZE; } } } /**************** Cases other than YCC -> RGB ****************/ /* * Initialize for RGB->grayscale colorspace conversion. */ LOCAL(void) build_rgb_y_table (j_decompress_ptr cinfo) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; INT32 * rgb_y_tab; INT32 i; /* Allocate and fill in the conversion tables. */ cconvert->rgb_y_tab = rgb_y_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (TABLE_SIZE * SIZEOF(INT32))); for (i = 0; i <= MAXJSAMPLE; i++) { rgb_y_tab[i+R_Y_OFF] = FIX(0.299) * i; rgb_y_tab[i+G_Y_OFF] = FIX(0.587) * i; rgb_y_tab[i+B_Y_OFF] = FIX(0.114) * i + ONE_HALF; } } /* * Convert RGB to grayscale. */ METHODDEF(void) rgb_gray_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register INT32 * ctab = cconvert->rgb_y_tab; register int r, g, b; register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { r = GETJSAMPLE(inptr0[col]); g = GETJSAMPLE(inptr1[col]); b = GETJSAMPLE(inptr2[col]); /* Y */ outptr[col] = (JSAMPLE) ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) >> SCALEBITS); } } } /* * [R-G,G,B-G] to [R,G,B] conversion with modulo calculation * (inverse color transform). * This can be seen as an adaption of the general YCbCr->RGB * conversion equation with Kr = Kb = 0, while replacing the * normalization by modulo calculation. */ METHODDEF(void) rgb1_rgb_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { register int r, g, b; register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { r = GETJSAMPLE(inptr0[col]); g = GETJSAMPLE(inptr1[col]); b = GETJSAMPLE(inptr2[col]); /* Assume that MAXJSAMPLE+1 is a power of 2, so that the MOD * (modulo) operator is equivalent to the bitmask operator AND. */ outptr[RGB_RED] = (JSAMPLE) ((r + g - CENTERJSAMPLE) & MAXJSAMPLE); outptr[RGB_GREEN] = (JSAMPLE) g; outptr[RGB_BLUE] = (JSAMPLE) ((b + g - CENTERJSAMPLE) & MAXJSAMPLE); outptr += RGB_PIXELSIZE; } } } /* * [R-G,G,B-G] to grayscale conversion with modulo calculation * (inverse color transform). */ METHODDEF(void) rgb1_gray_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register INT32 * ctab = cconvert->rgb_y_tab; register int r, g, b; register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { r = GETJSAMPLE(inptr0[col]); g = GETJSAMPLE(inptr1[col]); b = GETJSAMPLE(inptr2[col]); /* Assume that MAXJSAMPLE+1 is a power of 2, so that the MOD * (modulo) operator is equivalent to the bitmask operator AND. */ r = (r + g - CENTERJSAMPLE) & MAXJSAMPLE; b = (b + g - CENTERJSAMPLE) & MAXJSAMPLE; /* Y */ outptr[col] = (JSAMPLE) ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) >> SCALEBITS); } } } /* * No colorspace change, but conversion from separate-planes * to interleaved representation. */ METHODDEF(void) rgb_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { /* We can dispense with GETJSAMPLE() here */ outptr[RGB_RED] = inptr0[col]; outptr[RGB_GREEN] = inptr1[col]; outptr[RGB_BLUE] = inptr2[col]; outptr += RGB_PIXELSIZE; } } } /* * Color conversion for no colorspace change: just copy the data, * converting from separate-planes to interleaved representation. */ METHODDEF(void) null_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { int ci; register int nc = cinfo->num_components; register JSAMPROW outptr; register JSAMPROW inptr; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; while (--num_rows >= 0) { for (ci = 0; ci < nc; ci++) { inptr = input_buf[ci][input_row]; outptr = output_buf[0] + ci; for (col = 0; col < num_cols; col++) { *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */ outptr += nc; } } input_row++; output_buf++; } } /* * Color conversion for grayscale: just copy the data. * This also works for YCC -> grayscale conversion, in which * we just copy the Y (luminance) component and ignore chrominance. */ METHODDEF(void) grayscale_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0, num_rows, cinfo->output_width); } /* * Convert grayscale to RGB: just duplicate the graylevel three times. * This is provided to support applications that don't want to cope * with grayscale as a separate case. */ METHODDEF(void) gray_rgb_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { register JSAMPROW outptr; register JSAMPROW inptr; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; while (--num_rows >= 0) { inptr = input_buf[0][input_row++]; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { /* We can dispense with GETJSAMPLE() here */ outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col]; outptr += RGB_PIXELSIZE; } } } /* * Adobe-style YCCK->CMYK conversion. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same * conversion as above, while passing K (black) unchanged. * We assume build_ycc_rgb_table has been called. */ METHODDEF(void) ycck_cmyk_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register int y, cb, cr; register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2, inptr3; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; /* copy these pointers into registers if possible */ register JSAMPLE * range_limit = cinfo->sample_range_limit; register int * Crrtab = cconvert->Cr_r_tab; register int * Cbbtab = cconvert->Cb_b_tab; register INT32 * Crgtab = cconvert->Cr_g_tab; register INT32 * Cbgtab = cconvert->Cb_g_tab; SHIFT_TEMPS while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; inptr3 = input_buf[3][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { y = GETJSAMPLE(inptr0[col]); cb = GETJSAMPLE(inptr1[col]); cr = GETJSAMPLE(inptr2[col]); /* Range-limiting is essential due to noise introduced by DCT losses, * and for extended gamut encodings (sYCC). */ outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */ outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS)))]; outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */ /* K passes through unchanged */ outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */ outptr += 4; } } } /* * Empty method for start_pass. */ METHODDEF(void) start_pass_dcolor (j_decompress_ptr cinfo) { /* no work needed */ } /* * Module initialization routine for output colorspace conversion. */ GLOBAL(void) jinit_color_deconverter (j_decompress_ptr cinfo) { my_cconvert_ptr cconvert; int ci; cconvert = (my_cconvert_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_color_deconverter)); cinfo->cconvert = &cconvert->pub; cconvert->pub.start_pass = start_pass_dcolor; /* Make sure num_components agrees with jpeg_color_space */ switch (cinfo->jpeg_color_space) { case JCS_GRAYSCALE: if (cinfo->num_components != 1) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; case JCS_RGB: case JCS_YCbCr: case JCS_BG_RGB: case JCS_BG_YCC: if (cinfo->num_components != 3) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; case JCS_CMYK: case JCS_YCCK: if (cinfo->num_components != 4) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; default: /* JCS_UNKNOWN can be anything */ if (cinfo->num_components < 1) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; } /* Support color transform only for RGB colorspaces */ if (cinfo->color_transform && cinfo->jpeg_color_space != JCS_RGB && cinfo->jpeg_color_space != JCS_BG_RGB) ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); /* Set out_color_components and conversion method based on requested space. * Also clear the component_needed flags for any unused components, * so that earlier pipeline stages can avoid useless computation. */ switch (cinfo->out_color_space) { case JCS_GRAYSCALE: cinfo->out_color_components = 1; switch (cinfo->jpeg_color_space) { case JCS_GRAYSCALE: case JCS_YCbCr: case JCS_BG_YCC: cconvert->pub.color_convert = grayscale_convert; /* For color->grayscale conversion, only the Y (0) component is needed */ for (ci = 1; ci < cinfo->num_components; ci++) cinfo->comp_info[ci].component_needed = FALSE; break; case JCS_RGB: switch (cinfo->color_transform) { case JCT_NONE: cconvert->pub.color_convert = rgb_gray_convert; break; case JCT_SUBTRACT_GREEN: cconvert->pub.color_convert = rgb1_gray_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } build_rgb_y_table(cinfo); break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; case JCS_RGB: cinfo->out_color_components = RGB_PIXELSIZE; switch (cinfo->jpeg_color_space) { case JCS_GRAYSCALE: cconvert->pub.color_convert = gray_rgb_convert; break; case JCS_YCbCr: cconvert->pub.color_convert = ycc_rgb_convert; build_ycc_rgb_table(cinfo); break; case JCS_BG_YCC: cconvert->pub.color_convert = ycc_rgb_convert; build_bg_ycc_rgb_table(cinfo); break; case JCS_RGB: switch (cinfo->color_transform) { case JCT_NONE: cconvert->pub.color_convert = rgb_convert; break; case JCT_SUBTRACT_GREEN: cconvert->pub.color_convert = rgb1_rgb_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; case JCS_BG_RGB: cinfo->out_color_components = RGB_PIXELSIZE; if (cinfo->jpeg_color_space == JCS_BG_RGB) { switch (cinfo->color_transform) { case JCT_NONE: cconvert->pub.color_convert = rgb_convert; break; case JCT_SUBTRACT_GREEN: cconvert->pub.color_convert = rgb1_rgb_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } } else ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; case JCS_CMYK: cinfo->out_color_components = 4; switch (cinfo->jpeg_color_space) { case JCS_YCCK: cconvert->pub.color_convert = ycck_cmyk_convert; build_ycc_rgb_table(cinfo); break; case JCS_CMYK: cconvert->pub.color_convert = null_convert; break; default: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } break; default: /* Permit null conversion to same output space */ if (cinfo->out_color_space == cinfo->jpeg_color_space) { cinfo->out_color_components = cinfo->num_components; cconvert->pub.color_convert = null_convert; } else /* unsupported non-null conversion */ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; } if (cinfo->quantize_colors) cinfo->output_components = 1; /* single colormapped output component */ else cinfo->output_components = cinfo->out_color_components; } ================================================ FILE: tess-two/jni/libjpeg/jdct.h ================================================ /* * jdct.h * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2002-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This include file contains common declarations for the forward and * inverse DCT modules. These declarations are private to the DCT managers * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms. * The individual DCT algorithms are kept in separate files to ease * machine-dependent tuning (e.g., assembly coding). */ /* * A forward DCT routine is given a pointer to an input sample array and * a pointer to a work area of type DCTELEM[]; the DCT is to be performed * in-place in that buffer. Type DCTELEM is int for 8-bit samples, INT32 * for 12-bit samples. (NOTE: Floating-point DCT implementations use an * array of type FAST_FLOAT, instead.) * The input data is to be fetched from the sample array starting at a * specified column. (Any row offset needed will be applied to the array * pointer before it is passed to the FDCT code.) * Note that the number of samples fetched by the FDCT routine is * DCT_h_scaled_size * DCT_v_scaled_size. * The DCT outputs are returned scaled up by a factor of 8; they therefore * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This * convention improves accuracy in integer implementations and saves some * work in floating-point ones. * Quantization of the output coefficients is done by jcdctmgr.c. */ #if BITS_IN_JSAMPLE == 8 typedef int DCTELEM; /* 16 or 32 bits is fine */ #else typedef INT32 DCTELEM; /* must have 32 bits */ #endif typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data, JSAMPARRAY sample_data, JDIMENSION start_col)); /* * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer * to an output sample array. The routine must dequantize the input data as * well as perform the IDCT; for dequantization, it uses the multiplier table * pointed to by compptr->dct_table. The output data is to be placed into the * sample array starting at a specified column. (Any row offset needed will * be applied to the array pointer before it is passed to the IDCT code.) * Note that the number of samples emitted by the IDCT routine is * DCT_h_scaled_size * DCT_v_scaled_size. */ /* typedef inverse_DCT_method_ptr is declared in jpegint.h */ /* * Each IDCT routine has its own ideas about the best dct_table element type. */ typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */ #if BITS_IN_JSAMPLE == 8 typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */ #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */ #else typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */ #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */ #endif typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */ /* * Each IDCT routine is responsible for range-limiting its results and * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could * be quite far out of range if the input data is corrupt, so a bulletproof * range-limiting step is required. We use a mask-and-table-lookup method * to do the combined operations quickly, assuming that MAXJSAMPLE+1 * is a power of 2. See the comments with prepare_range_limit_table * (in jdmaster.c) for more info. */ #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */ #define RANGE_CENTER (MAXJSAMPLE * 2 + 2) #define RANGE_SUBSET (RANGE_CENTER - CENTERJSAMPLE) #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit - RANGE_SUBSET) /* Short forms of external names for systems with brain-damaged linkers. */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jpeg_fdct_islow jFDislow #define jpeg_fdct_ifast jFDifast #define jpeg_fdct_float jFDfloat #define jpeg_fdct_7x7 jFD7x7 #define jpeg_fdct_6x6 jFD6x6 #define jpeg_fdct_5x5 jFD5x5 #define jpeg_fdct_4x4 jFD4x4 #define jpeg_fdct_3x3 jFD3x3 #define jpeg_fdct_2x2 jFD2x2 #define jpeg_fdct_1x1 jFD1x1 #define jpeg_fdct_9x9 jFD9x9 #define jpeg_fdct_10x10 jFD10x10 #define jpeg_fdct_11x11 jFD11x11 #define jpeg_fdct_12x12 jFD12x12 #define jpeg_fdct_13x13 jFD13x13 #define jpeg_fdct_14x14 jFD14x14 #define jpeg_fdct_15x15 jFD15x15 #define jpeg_fdct_16x16 jFD16x16 #define jpeg_fdct_16x8 jFD16x8 #define jpeg_fdct_14x7 jFD14x7 #define jpeg_fdct_12x6 jFD12x6 #define jpeg_fdct_10x5 jFD10x5 #define jpeg_fdct_8x4 jFD8x4 #define jpeg_fdct_6x3 jFD6x3 #define jpeg_fdct_4x2 jFD4x2 #define jpeg_fdct_2x1 jFD2x1 #define jpeg_fdct_8x16 jFD8x16 #define jpeg_fdct_7x14 jFD7x14 #define jpeg_fdct_6x12 jFD6x12 #define jpeg_fdct_5x10 jFD5x10 #define jpeg_fdct_4x8 jFD4x8 #define jpeg_fdct_3x6 jFD3x6 #define jpeg_fdct_2x4 jFD2x4 #define jpeg_fdct_1x2 jFD1x2 #define jpeg_idct_islow jRDislow #define jpeg_idct_ifast jRDifast #define jpeg_idct_float jRDfloat #define jpeg_idct_7x7 jRD7x7 #define jpeg_idct_6x6 jRD6x6 #define jpeg_idct_5x5 jRD5x5 #define jpeg_idct_4x4 jRD4x4 #define jpeg_idct_3x3 jRD3x3 #define jpeg_idct_2x2 jRD2x2 #define jpeg_idct_1x1 jRD1x1 #define jpeg_idct_9x9 jRD9x9 #define jpeg_idct_10x10 jRD10x10 #define jpeg_idct_11x11 jRD11x11 #define jpeg_idct_12x12 jRD12x12 #define jpeg_idct_13x13 jRD13x13 #define jpeg_idct_14x14 jRD14x14 #define jpeg_idct_15x15 jRD15x15 #define jpeg_idct_16x16 jRD16x16 #define jpeg_idct_16x8 jRD16x8 #define jpeg_idct_14x7 jRD14x7 #define jpeg_idct_12x6 jRD12x6 #define jpeg_idct_10x5 jRD10x5 #define jpeg_idct_8x4 jRD8x4 #define jpeg_idct_6x3 jRD6x3 #define jpeg_idct_4x2 jRD4x2 #define jpeg_idct_2x1 jRD2x1 #define jpeg_idct_8x16 jRD8x16 #define jpeg_idct_7x14 jRD7x14 #define jpeg_idct_6x12 jRD6x12 #define jpeg_idct_5x10 jRD5x10 #define jpeg_idct_4x8 jRD4x8 #define jpeg_idct_3x6 jRD3x8 #define jpeg_idct_2x4 jRD2x4 #define jpeg_idct_1x2 jRD1x2 #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* Extern declarations for the forward and inverse DCT routines. */ EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_7x7 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_6x6 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_5x5 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_4x4 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_3x3 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_2x2 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_1x1 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_9x9 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_10x10 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_11x11 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_12x12 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_13x13 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_14x14 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_15x15 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_16x16 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_16x8 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_14x7 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_12x6 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_10x5 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_8x4 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_6x3 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_4x2 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_2x1 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_8x16 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_7x14 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_6x12 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_5x10 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_4x8 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_3x6 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_2x4 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_fdct_1x2 JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col)); EXTERN(void) jpeg_idct_islow JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_ifast JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_float JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_7x7 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_6x6 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_5x5 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_4x4 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_3x3 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_2x2 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_1x1 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_9x9 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_10x10 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_11x11 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_12x12 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_13x13 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_14x14 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_15x15 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_16x16 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_16x8 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_14x7 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_12x6 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_10x5 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_8x4 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_6x3 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_4x2 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_2x1 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_8x16 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_7x14 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_6x12 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_5x10 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_4x8 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_3x6 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_2x4 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); EXTERN(void) jpeg_idct_1x2 JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); /* * Macros for handling fixed-point arithmetic; these are used by many * but not all of the DCT/IDCT modules. * * All values are expected to be of type INT32. * Fractional constants are scaled left by CONST_BITS bits. * CONST_BITS is defined within each module using these macros, * and may differ from one module to the next. */ #define ONE ((INT32) 1) #define CONST_SCALE (ONE << CONST_BITS) /* Convert a positive real constant to an integer scaled by CONST_SCALE. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time, * thus causing a lot of useless floating-point operations at run time. */ #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5)) /* Descale and correctly round an INT32 value that's scaled by N bits. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding * the fudge factor is correct for either sign of X. */ #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. * This macro is used only when the two inputs will actually be no more than * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a * full 32x32 multiply. This provides a useful speedup on many machines. * Unfortunately there is no way to specify a 16x16->32 multiply portably * in C, but some C compilers will do the right thing if you provide the * correct combination of casts. */ #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */ #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const))) #endif #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */ #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const))) #endif #ifndef MULTIPLY16C16 /* default definition */ #define MULTIPLY16C16(var,const) ((var) * (const)) #endif /* Same except both inputs are variables. */ #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */ #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2))) #endif #ifndef MULTIPLY16V16 /* default definition */ #define MULTIPLY16V16(var1,var2) ((var1) * (var2)) #endif /* Like RIGHT_SHIFT, but applies to a DCTELEM. * We assume that int right shift is unsigned if INT32 right shift is. */ #ifdef RIGHT_SHIFT_IS_UNSIGNED #define ISHIFT_TEMPS DCTELEM ishift_temp; #if BITS_IN_JSAMPLE == 8 #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */ #else #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */ #endif #define IRIGHT_SHIFT(x,shft) \ ((ishift_temp = (x)) < 0 ? \ (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \ (ishift_temp >> (shft))) #else #define ISHIFT_TEMPS #define IRIGHT_SHIFT(x,shft) ((x) >> (shft)) #endif ================================================ FILE: tess-two/jni/libjpeg/jddctmgr.c ================================================ /* * jddctmgr.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2002-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the inverse-DCT management logic. * This code selects a particular IDCT implementation to be used, * and it performs related housekeeping chores. No code in this file * is executed per IDCT step, only during output pass setup. * * Note that the IDCT routines are responsible for performing coefficient * dequantization as well as the IDCT proper. This module sets up the * dequantization multiplier table needed by the IDCT routine. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ /* * The decompressor input side (jdinput.c) saves away the appropriate * quantization table for each component at the start of the first scan * involving that component. (This is necessary in order to correctly * decode files that reuse Q-table slots.) * When we are ready to make an output pass, the saved Q-table is converted * to a multiplier table that will actually be used by the IDCT routine. * The multiplier table contents are IDCT-method-dependent. To support * application changes in IDCT method between scans, we can remake the * multiplier tables if necessary. * In buffered-image mode, the first output pass may occur before any data * has been seen for some components, and thus before their Q-tables have * been saved away. To handle this case, multiplier tables are preset * to zeroes; the result of the IDCT will be a neutral gray level. */ /* Private subobject for this module */ typedef struct { struct jpeg_inverse_dct pub; /* public fields */ /* This array contains the IDCT method code that each multiplier table * is currently set up for, or -1 if it's not yet set up. * The actual multiplier tables are pointed to by dct_table in the * per-component comp_info structures. */ int cur_method[MAX_COMPONENTS]; } my_idct_controller; typedef my_idct_controller * my_idct_ptr; /* Allocated multiplier tables: big enough for any supported variant */ typedef union { ISLOW_MULT_TYPE islow_array[DCTSIZE2]; #ifdef DCT_IFAST_SUPPORTED IFAST_MULT_TYPE ifast_array[DCTSIZE2]; #endif #ifdef DCT_FLOAT_SUPPORTED FLOAT_MULT_TYPE float_array[DCTSIZE2]; #endif } multiplier_table; /* The current scaled-IDCT routines require ISLOW-style multiplier tables, * so be sure to compile that code if either ISLOW or SCALING is requested. */ #ifdef DCT_ISLOW_SUPPORTED #define PROVIDE_ISLOW_TABLES #else #ifdef IDCT_SCALING_SUPPORTED #define PROVIDE_ISLOW_TABLES #endif #endif /* * Prepare for an output pass. * Here we select the proper IDCT routine for each component and build * a matching multiplier table. */ METHODDEF(void) start_pass (j_decompress_ptr cinfo) { my_idct_ptr idct = (my_idct_ptr) cinfo->idct; int ci, i; jpeg_component_info *compptr; int method = 0; inverse_DCT_method_ptr method_ptr = NULL; JQUANT_TBL * qtbl; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Select the proper IDCT routine for this component's scaling */ switch ((compptr->DCT_h_scaled_size << 8) + compptr->DCT_v_scaled_size) { #ifdef IDCT_SCALING_SUPPORTED case ((1 << 8) + 1): method_ptr = jpeg_idct_1x1; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((2 << 8) + 2): method_ptr = jpeg_idct_2x2; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((3 << 8) + 3): method_ptr = jpeg_idct_3x3; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((4 << 8) + 4): method_ptr = jpeg_idct_4x4; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((5 << 8) + 5): method_ptr = jpeg_idct_5x5; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((6 << 8) + 6): method_ptr = jpeg_idct_6x6; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((7 << 8) + 7): method_ptr = jpeg_idct_7x7; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((9 << 8) + 9): method_ptr = jpeg_idct_9x9; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((10 << 8) + 10): method_ptr = jpeg_idct_10x10; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((11 << 8) + 11): method_ptr = jpeg_idct_11x11; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((12 << 8) + 12): method_ptr = jpeg_idct_12x12; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((13 << 8) + 13): method_ptr = jpeg_idct_13x13; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((14 << 8) + 14): method_ptr = jpeg_idct_14x14; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((15 << 8) + 15): method_ptr = jpeg_idct_15x15; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((16 << 8) + 16): method_ptr = jpeg_idct_16x16; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((16 << 8) + 8): method_ptr = jpeg_idct_16x8; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((14 << 8) + 7): method_ptr = jpeg_idct_14x7; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((12 << 8) + 6): method_ptr = jpeg_idct_12x6; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((10 << 8) + 5): method_ptr = jpeg_idct_10x5; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((8 << 8) + 4): method_ptr = jpeg_idct_8x4; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((6 << 8) + 3): method_ptr = jpeg_idct_6x3; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((4 << 8) + 2): method_ptr = jpeg_idct_4x2; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((2 << 8) + 1): method_ptr = jpeg_idct_2x1; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((8 << 8) + 16): method_ptr = jpeg_idct_8x16; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((7 << 8) + 14): method_ptr = jpeg_idct_7x14; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((6 << 8) + 12): method_ptr = jpeg_idct_6x12; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((5 << 8) + 10): method_ptr = jpeg_idct_5x10; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((4 << 8) + 8): method_ptr = jpeg_idct_4x8; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((3 << 8) + 6): method_ptr = jpeg_idct_3x6; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((2 << 8) + 4): method_ptr = jpeg_idct_2x4; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; case ((1 << 8) + 2): method_ptr = jpeg_idct_1x2; method = JDCT_ISLOW; /* jidctint uses islow-style table */ break; #endif case ((DCTSIZE << 8) + DCTSIZE): switch (cinfo->dct_method) { #ifdef DCT_ISLOW_SUPPORTED case JDCT_ISLOW: method_ptr = jpeg_idct_islow; method = JDCT_ISLOW; break; #endif #ifdef DCT_IFAST_SUPPORTED case JDCT_IFAST: method_ptr = jpeg_idct_ifast; method = JDCT_IFAST; break; #endif #ifdef DCT_FLOAT_SUPPORTED case JDCT_FLOAT: method_ptr = jpeg_idct_float; method = JDCT_FLOAT; break; #endif default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } break; default: ERREXIT2(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_h_scaled_size, compptr->DCT_v_scaled_size); break; } idct->pub.inverse_DCT[ci] = method_ptr; /* Create multiplier table from quant table. * However, we can skip this if the component is uninteresting * or if we already built the table. Also, if no quant table * has yet been saved for the component, we leave the * multiplier table all-zero; we'll be reading zeroes from the * coefficient controller's buffer anyway. */ if (! compptr->component_needed || idct->cur_method[ci] == method) continue; qtbl = compptr->quant_table; if (qtbl == NULL) /* happens if no data yet for component */ continue; idct->cur_method[ci] = method; switch (method) { #ifdef PROVIDE_ISLOW_TABLES case JDCT_ISLOW: { /* For LL&M IDCT method, multipliers are equal to raw quantization * coefficients, but are stored as ints to ensure access efficiency. */ ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table; for (i = 0; i < DCTSIZE2; i++) { ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i]; } } break; #endif #ifdef DCT_IFAST_SUPPORTED case JDCT_IFAST: { /* For AA&N IDCT method, multipliers are equal to quantization * coefficients scaled by scalefactor[row]*scalefactor[col], where * scalefactor[0] = 1 * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 * For integer operation, the multiplier table is to be scaled by * IFAST_SCALE_BITS. */ IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table; #define CONST_BITS 14 static const INT16 aanscales[DCTSIZE2] = { /* precomputed values scaled up by 14 bits */ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 }; SHIFT_TEMPS for (i = 0; i < DCTSIZE2; i++) { ifmtbl[i] = (IFAST_MULT_TYPE) DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i], (INT32) aanscales[i]), CONST_BITS-IFAST_SCALE_BITS); } } break; #endif #ifdef DCT_FLOAT_SUPPORTED case JDCT_FLOAT: { /* For float AA&N IDCT method, multipliers are equal to quantization * coefficients scaled by scalefactor[row]*scalefactor[col], where * scalefactor[0] = 1 * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 * We apply a further scale factor of 1/8. */ FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table; int row, col; static const double aanscalefactor[DCTSIZE] = { 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 }; i = 0; for (row = 0; row < DCTSIZE; row++) { for (col = 0; col < DCTSIZE; col++) { fmtbl[i] = (FLOAT_MULT_TYPE) ((double) qtbl->quantval[i] * aanscalefactor[row] * aanscalefactor[col] * 0.125); i++; } } } break; #endif default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } } } /* * Initialize IDCT manager. */ GLOBAL(void) jinit_inverse_dct (j_decompress_ptr cinfo) { my_idct_ptr idct; int ci; jpeg_component_info *compptr; idct = (my_idct_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_idct_controller)); cinfo->idct = &idct->pub; idct->pub.start_pass = start_pass; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Allocate and pre-zero a multiplier table for each component */ compptr->dct_table = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(multiplier_table)); MEMZERO(compptr->dct_table, SIZEOF(multiplier_table)); /* Mark multiplier table not yet set up for any method */ idct->cur_method[ci] = -1; } } ================================================ FILE: tess-two/jni/libjpeg/jdhuff.c ================================================ /* * jdhuff.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2006-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains Huffman entropy decoding routines. * Both sequential and progressive modes are supported in this single module. * * Much of the complexity here has to do with supporting input suspension. * If the data source module demands suspension, we want to be able to back * up to the start of the current MCU. To do this, we copy state variables * into local working storage, and update them back to the permanent * storage only upon successful completion of an MCU. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Derived data constructed for each Huffman table */ #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */ typedef struct { /* Basic tables: (element [0] of each array is unused) */ INT32 maxcode[18]; /* largest code of length k (-1 if none) */ /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */ INT32 valoffset[17]; /* huffval[] offset for codes of length k */ /* valoffset[k] = huffval[] index of 1st symbol of code length k, less * the smallest code of length k; so given a code of length k, the * corresponding symbol is huffval[code + valoffset[k]] */ /* Link to public Huffman table (needed only in jpeg_huff_decode) */ JHUFF_TBL *pub; /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of * the input data stream. If the next Huffman code is no more * than HUFF_LOOKAHEAD bits long, we can obtain its length and * the corresponding symbol directly from these tables. */ int look_nbits[1< 32 bits on your machine, and shifting/masking longs is * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE * appropriately should be a win. Unfortunately we can't define the size * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8) * because not all machines measure sizeof in 8-bit bytes. */ typedef struct { /* Bitreading state saved across MCUs */ bit_buf_type get_buffer; /* current bit-extraction buffer */ int bits_left; /* # of unused bits in it */ } bitread_perm_state; typedef struct { /* Bitreading working state within an MCU */ /* Current data source location */ /* We need a copy, rather than munging the original, in case of suspension */ const JOCTET * next_input_byte; /* => next byte to read from source */ size_t bytes_in_buffer; /* # of bytes remaining in source buffer */ /* Bit input buffer --- note these values are kept in register variables, * not in this struct, inside the inner loops. */ bit_buf_type get_buffer; /* current bit-extraction buffer */ int bits_left; /* # of unused bits in it */ /* Pointer needed by jpeg_fill_bit_buffer. */ j_decompress_ptr cinfo; /* back link to decompress master record */ } bitread_working_state; /* Macros to declare and load/save bitread local variables. */ #define BITREAD_STATE_VARS \ register bit_buf_type get_buffer; \ register int bits_left; \ bitread_working_state br_state #define BITREAD_LOAD_STATE(cinfop,permstate) \ br_state.cinfo = cinfop; \ br_state.next_input_byte = cinfop->src->next_input_byte; \ br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \ get_buffer = permstate.get_buffer; \ bits_left = permstate.bits_left; #define BITREAD_SAVE_STATE(cinfop,permstate) \ cinfop->src->next_input_byte = br_state.next_input_byte; \ cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \ permstate.get_buffer = get_buffer; \ permstate.bits_left = bits_left /* * These macros provide the in-line portion of bit fetching. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer * before using GET_BITS, PEEK_BITS, or DROP_BITS. * The variables get_buffer and bits_left are assumed to be locals, * but the state struct might not be (jpeg_huff_decode needs this). * CHECK_BIT_BUFFER(state,n,action); * Ensure there are N bits in get_buffer; if suspend, take action. * val = GET_BITS(n); * Fetch next N bits. * val = PEEK_BITS(n); * Fetch next N bits without removing them from the buffer. * DROP_BITS(n); * Discard next N bits. * The value N should be a simple variable, not an expression, because it * is evaluated multiple times. */ #define CHECK_BIT_BUFFER(state,nbits,action) \ { if (bits_left < (nbits)) { \ if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \ { action; } \ get_buffer = (state).get_buffer; bits_left = (state).bits_left; } } #define GET_BITS(nbits) \ (((int) (get_buffer >> (bits_left -= (nbits)))) & BIT_MASK(nbits)) #define PEEK_BITS(nbits) \ (((int) (get_buffer >> (bits_left - (nbits)))) & BIT_MASK(nbits)) #define DROP_BITS(nbits) \ (bits_left -= (nbits)) /* * Code for extracting next Huffman-coded symbol from input bit stream. * Again, this is time-critical and we make the main paths be macros. * * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits * without looping. Usually, more than 95% of the Huffman codes will be 8 * or fewer bits long. The few overlength codes are handled with a loop, * which need not be inline code. * * Notes about the HUFF_DECODE macro: * 1. Near the end of the data segment, we may fail to get enough bits * for a lookahead. In that case, we do it the hard way. * 2. If the lookahead table contains no entry, the next code must be * more than HUFF_LOOKAHEAD bits long. * 3. jpeg_huff_decode returns -1 if forced to suspend. */ #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \ { register int nb, look; \ if (bits_left < HUFF_LOOKAHEAD) { \ if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \ get_buffer = state.get_buffer; bits_left = state.bits_left; \ if (bits_left < HUFF_LOOKAHEAD) { \ nb = 1; goto slowlabel; \ } \ } \ look = PEEK_BITS(HUFF_LOOKAHEAD); \ if ((nb = htbl->look_nbits[look]) != 0) { \ DROP_BITS(nb); \ result = htbl->look_sym[look]; \ } else { \ nb = HUFF_LOOKAHEAD+1; \ slowlabel: \ if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \ { failaction; } \ get_buffer = state.get_buffer; bits_left = state.bits_left; \ } \ } /* * Expanded entropy decoder object for Huffman decoding. * * The savable_state subrecord contains fields that change within an MCU, * but must not be updated permanently until we complete the MCU. */ typedef struct { unsigned int EOBRUN; /* remaining EOBs in EOBRUN */ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ } savable_state; /* This macro is to work around compilers with missing or broken * structure assignment. You'll need to fix this code if you have * such a compiler and you change MAX_COMPS_IN_SCAN. */ #ifndef NO_STRUCT_ASSIGN #define ASSIGN_STATE(dest,src) ((dest) = (src)) #else #if MAX_COMPS_IN_SCAN == 4 #define ASSIGN_STATE(dest,src) \ ((dest).EOBRUN = (src).EOBRUN, \ (dest).last_dc_val[0] = (src).last_dc_val[0], \ (dest).last_dc_val[1] = (src).last_dc_val[1], \ (dest).last_dc_val[2] = (src).last_dc_val[2], \ (dest).last_dc_val[3] = (src).last_dc_val[3]) #endif #endif typedef struct { struct jpeg_entropy_decoder pub; /* public fields */ /* These fields are loaded into local variables at start of each MCU. * In case of suspension, we exit WITHOUT updating them. */ bitread_perm_state bitstate; /* Bit buffer at start of MCU */ savable_state saved; /* Other state at start of MCU */ /* These fields are NOT loaded into local working state. */ boolean insufficient_data; /* set TRUE after emitting warning */ unsigned int restarts_to_go; /* MCUs left in this restart interval */ /* Following two fields used only in progressive mode */ /* Pointers to derived tables (these workspaces have image lifespan) */ d_derived_tbl * derived_tbls[NUM_HUFF_TBLS]; d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */ /* Following fields used only in sequential mode */ /* Pointers to derived tables (these workspaces have image lifespan) */ d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; /* Precalculated info set up by start_pass for use in decode_mcu: */ /* Pointers to derived tables to be used for each block within an MCU */ d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU]; d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU]; /* Whether we care about the DC and AC coefficient values for each block */ int coef_limit[D_MAX_BLOCKS_IN_MCU]; } huff_entropy_decoder; typedef huff_entropy_decoder * huff_entropy_ptr; static const int jpeg_zigzag_order[8][8] = { { 0, 1, 5, 6, 14, 15, 27, 28 }, { 2, 4, 7, 13, 16, 26, 29, 42 }, { 3, 8, 12, 17, 25, 30, 41, 43 }, { 9, 11, 18, 24, 31, 40, 44, 53 }, { 10, 19, 23, 32, 39, 45, 52, 54 }, { 20, 22, 33, 38, 46, 51, 55, 60 }, { 21, 34, 37, 47, 50, 56, 59, 61 }, { 35, 36, 48, 49, 57, 58, 62, 63 } }; static const int jpeg_zigzag_order7[7][7] = { { 0, 1, 5, 6, 14, 15, 27 }, { 2, 4, 7, 13, 16, 26, 28 }, { 3, 8, 12, 17, 25, 29, 38 }, { 9, 11, 18, 24, 30, 37, 39 }, { 10, 19, 23, 31, 36, 40, 45 }, { 20, 22, 32, 35, 41, 44, 46 }, { 21, 33, 34, 42, 43, 47, 48 } }; static const int jpeg_zigzag_order6[6][6] = { { 0, 1, 5, 6, 14, 15 }, { 2, 4, 7, 13, 16, 25 }, { 3, 8, 12, 17, 24, 26 }, { 9, 11, 18, 23, 27, 32 }, { 10, 19, 22, 28, 31, 33 }, { 20, 21, 29, 30, 34, 35 } }; static const int jpeg_zigzag_order5[5][5] = { { 0, 1, 5, 6, 14 }, { 2, 4, 7, 13, 15 }, { 3, 8, 12, 16, 21 }, { 9, 11, 17, 20, 22 }, { 10, 18, 19, 23, 24 } }; static const int jpeg_zigzag_order4[4][4] = { { 0, 1, 5, 6 }, { 2, 4, 7, 12 }, { 3, 8, 11, 13 }, { 9, 10, 14, 15 } }; static const int jpeg_zigzag_order3[3][3] = { { 0, 1, 5 }, { 2, 4, 6 }, { 3, 7, 8 } }; static const int jpeg_zigzag_order2[2][2] = { { 0, 1 }, { 2, 3 } }; /* * Compute the derived values for a Huffman table. * This routine also performs some validation checks on the table. */ LOCAL(void) jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno, d_derived_tbl ** pdtbl) { JHUFF_TBL *htbl; d_derived_tbl *dtbl; int p, i, l, si, numsymbols; int lookbits, ctr; char huffsize[257]; unsigned int huffcode[257]; unsigned int code; /* Note that huffsize[] and huffcode[] are filled in code-length order, * paralleling the order of the symbols themselves in htbl->huffval[]. */ /* Find the input Huffman table */ if (tblno < 0 || tblno >= NUM_HUFF_TBLS) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); htbl = isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno]; if (htbl == NULL) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); /* Allocate a workspace if we haven't already done so. */ if (*pdtbl == NULL) *pdtbl = (d_derived_tbl *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(d_derived_tbl)); dtbl = *pdtbl; dtbl->pub = htbl; /* fill in back link */ /* Figure C.1: make table of Huffman code length for each symbol */ p = 0; for (l = 1; l <= 16; l++) { i = (int) htbl->bits[l]; if (i < 0 || p + i > 256) /* protect against table overrun */ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); while (i--) huffsize[p++] = (char) l; } huffsize[p] = 0; numsymbols = p; /* Figure C.2: generate the codes themselves */ /* We also validate that the counts represent a legal Huffman code tree. */ code = 0; si = huffsize[0]; p = 0; while (huffsize[p]) { while (((int) huffsize[p]) == si) { huffcode[p++] = code; code++; } /* code is now 1 more than the last code used for codelength si; but * it must still fit in si bits, since no code is allowed to be all ones. */ if (((INT32) code) >= (((INT32) 1) << si)) ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); code <<= 1; si++; } /* Figure F.15: generate decoding tables for bit-sequential decoding */ p = 0; for (l = 1; l <= 16; l++) { if (htbl->bits[l]) { /* valoffset[l] = huffval[] index of 1st symbol of code length l, * minus the minimum code of length l */ dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p]; p += htbl->bits[l]; dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */ } else { dtbl->maxcode[l] = -1; /* -1 if no codes of this length */ } } dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */ /* Compute lookahead tables to speed up decoding. * First we set all the table entries to 0, indicating "too long"; * then we iterate through the Huffman codes that are short enough and * fill in all the entries that correspond to bit sequences starting * with that code. */ MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits)); p = 0; for (l = 1; l <= HUFF_LOOKAHEAD; l++) { for (i = 1; i <= (int) htbl->bits[l]; i++, p++) { /* l = current code's length, p = its index in huffcode[] & huffval[]. */ /* Generate left-justified code followed by all possible bit sequences */ lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l); for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) { dtbl->look_nbits[lookbits] = l; dtbl->look_sym[lookbits] = htbl->huffval[p]; lookbits++; } } } /* Validate symbols as being reasonable. * For AC tables, we make no check, but accept all byte values 0..255. * For DC tables, we require the symbols to be in range 0..15. * (Tighter bounds could be applied depending on the data depth and mode, * but this is sufficient to ensure safe decoding.) */ if (isDC) { for (i = 0; i < numsymbols; i++) { int sym = htbl->huffval[i]; if (sym < 0 || sym > 15) ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); } } } /* * Out-of-line code for bit fetching. * Note: current values of get_buffer and bits_left are passed as parameters, * but are returned in the corresponding fields of the state struct. * * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width * of get_buffer to be used. (On machines with wider words, an even larger * buffer could be used.) However, on some machines 32-bit shifts are * quite slow and take time proportional to the number of places shifted. * (This is true with most PC compilers, for instance.) In this case it may * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the * average shift distance at the cost of more calls to jpeg_fill_bit_buffer. */ #ifdef SLOW_SHIFT_32 #define MIN_GET_BITS 15 /* minimum allowable value */ #else #define MIN_GET_BITS (BIT_BUF_SIZE-7) #endif LOCAL(boolean) jpeg_fill_bit_buffer (bitread_working_state * state, register bit_buf_type get_buffer, register int bits_left, int nbits) /* Load up the bit buffer to a depth of at least nbits */ { /* Copy heavily used state fields into locals (hopefully registers) */ register const JOCTET * next_input_byte = state->next_input_byte; register size_t bytes_in_buffer = state->bytes_in_buffer; j_decompress_ptr cinfo = state->cinfo; /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */ /* (It is assumed that no request will be for more than that many bits.) */ /* We fail to do so only if we hit a marker or are forced to suspend. */ if (cinfo->unread_marker == 0) { /* cannot advance past a marker */ while (bits_left < MIN_GET_BITS) { register int c; /* Attempt to read a byte */ if (bytes_in_buffer == 0) { if (! (*cinfo->src->fill_input_buffer) (cinfo)) return FALSE; next_input_byte = cinfo->src->next_input_byte; bytes_in_buffer = cinfo->src->bytes_in_buffer; } bytes_in_buffer--; c = GETJOCTET(*next_input_byte++); /* If it's 0xFF, check and discard stuffed zero byte */ if (c == 0xFF) { /* Loop here to discard any padding FF's on terminating marker, * so that we can save a valid unread_marker value. NOTE: we will * accept multiple FF's followed by a 0 as meaning a single FF data * byte. This data pattern is not valid according to the standard. */ do { if (bytes_in_buffer == 0) { if (! (*cinfo->src->fill_input_buffer) (cinfo)) return FALSE; next_input_byte = cinfo->src->next_input_byte; bytes_in_buffer = cinfo->src->bytes_in_buffer; } bytes_in_buffer--; c = GETJOCTET(*next_input_byte++); } while (c == 0xFF); if (c == 0) { /* Found FF/00, which represents an FF data byte */ c = 0xFF; } else { /* Oops, it's actually a marker indicating end of compressed data. * Save the marker code for later use. * Fine point: it might appear that we should save the marker into * bitread working state, not straight into permanent state. But * once we have hit a marker, we cannot need to suspend within the * current MCU, because we will read no more bytes from the data * source. So it is OK to update permanent state right away. */ cinfo->unread_marker = c; /* See if we need to insert some fake zero bits. */ goto no_more_bytes; } } /* OK, load c into get_buffer */ get_buffer = (get_buffer << 8) | c; bits_left += 8; } /* end while */ } else { no_more_bytes: /* We get here if we've read the marker that terminates the compressed * data segment. There should be enough bits in the buffer register * to satisfy the request; if so, no problem. */ if (nbits > bits_left) { /* Uh-oh. Report corrupted data to user and stuff zeroes into * the data stream, so that we can produce some kind of image. * We use a nonvolatile flag to ensure that only one warning message * appears per data segment. */ if (! ((huff_entropy_ptr) cinfo->entropy)->insufficient_data) { WARNMS(cinfo, JWRN_HIT_MARKER); ((huff_entropy_ptr) cinfo->entropy)->insufficient_data = TRUE; } /* Fill the buffer with zero bits */ get_buffer <<= MIN_GET_BITS - bits_left; bits_left = MIN_GET_BITS; } } /* Unload the local registers */ state->next_input_byte = next_input_byte; state->bytes_in_buffer = bytes_in_buffer; state->get_buffer = get_buffer; state->bits_left = bits_left; return TRUE; } /* * Figure F.12: extend sign bit. * On some machines, a shift and sub will be faster than a table lookup. */ #ifdef AVOID_TABLES #define BIT_MASK(nbits) ((1<<(nbits))-1) #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x)) #else #define BIT_MASK(nbits) bmask[nbits] #define HUFF_EXTEND(x,s) ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x)) static const int bmask[16] = /* bmask[n] is mask for n rightmost bits */ { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF }; #endif /* AVOID_TABLES */ /* * Out-of-line code for Huffman code decoding. */ LOCAL(int) jpeg_huff_decode (bitread_working_state * state, register bit_buf_type get_buffer, register int bits_left, d_derived_tbl * htbl, int min_bits) { register int l = min_bits; register INT32 code; /* HUFF_DECODE has determined that the code is at least min_bits */ /* bits long, so fetch that many bits in one swoop. */ CHECK_BIT_BUFFER(*state, l, return -1); code = GET_BITS(l); /* Collect the rest of the Huffman code one bit at a time. */ /* This is per Figure F.16 in the JPEG spec. */ while (code > htbl->maxcode[l]) { code <<= 1; CHECK_BIT_BUFFER(*state, 1, return -1); code |= GET_BITS(1); l++; } /* Unload the local registers */ state->get_buffer = get_buffer; state->bits_left = bits_left; /* With garbage input we may reach the sentinel value l = 17. */ if (l > 16) { WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE); return 0; /* fake a zero as the safest result */ } return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ]; } /* * Finish up at the end of a Huffman-compressed scan. */ METHODDEF(void) finish_pass_huff (j_decompress_ptr cinfo) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; /* Throw away any unused bits remaining in bit buffer; */ /* include any full bytes in next_marker's count of discarded bytes */ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8; entropy->bitstate.bits_left = 0; } /* * Check for a restart marker & resynchronize decoder. * Returns FALSE if must suspend. */ LOCAL(boolean) process_restart (j_decompress_ptr cinfo) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int ci; finish_pass_huff(cinfo); /* Advance past the RSTn marker */ if (! (*cinfo->marker->read_restart_marker) (cinfo)) return FALSE; /* Re-initialize DC predictions to 0 */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) entropy->saved.last_dc_val[ci] = 0; /* Re-init EOB run count, too */ entropy->saved.EOBRUN = 0; /* Reset restart counter */ entropy->restarts_to_go = cinfo->restart_interval; /* Reset out-of-data flag, unless read_restart_marker left us smack up * against a marker. In that case we will end up treating the next data * segment as empty, and we can avoid producing bogus output pixels by * leaving the flag set. */ if (cinfo->unread_marker == 0) entropy->insufficient_data = FALSE; return TRUE; } /* * Huffman MCU decoding. * Each of these routines decodes and returns one MCU's worth of * Huffman-compressed coefficients. * The coefficients are reordered from zigzag order into natural array order, * but are not dequantized. * * The i'th block of the MCU is stored into the block pointed to by * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER. * (Wholesale zeroing is usually a little faster than retail...) * * We return FALSE if data source requested suspension. In that case no * changes have been made to permanent state. (Exception: some output * coefficients may already have been assigned. This is harmless for * spectral selection, since we'll just re-assign them on the next call. * Successive approximation AC refinement has to be more careful, however.) */ /* * MCU decoding for DC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int Al = cinfo->Al; register int s, r; int blkn, ci; JBLOCKROW block; BITREAD_STATE_VARS; savable_state state; d_derived_tbl * tbl; jpeg_component_info * compptr; /* Process restart marker if needed; may have to suspend */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! process_restart(cinfo)) return FALSE; } /* If we've run out of data, just leave the MCU set to zeroes. * This way, we return uniform gray for the remainder of the segment. */ if (! entropy->insufficient_data) { /* Load up working state */ BITREAD_LOAD_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(state, entropy->saved); /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { block = MCU_data[blkn]; ci = cinfo->MCU_membership[blkn]; compptr = cinfo->cur_comp_info[ci]; tbl = entropy->derived_tbls[compptr->dc_tbl_no]; /* Decode a single block's worth of coefficients */ /* Section F.2.2.1: decode the DC coefficient difference */ HUFF_DECODE(s, br_state, tbl, return FALSE, label1); if (s) { CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); } /* Convert DC difference to actual value, update last_dc_val */ s += state.last_dc_val[ci]; state.last_dc_val[ci] = s; /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */ (*block)[0] = (JCOEF) (s << Al); } /* Completed MCU, so update state */ BITREAD_SAVE_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(entropy->saved, state); } /* Account for restart interval (no-op if not using restarts) */ entropy->restarts_to_go--; return TRUE; } /* * MCU decoding for AC initial scan (either spectral selection, * or first pass of successive approximation). */ METHODDEF(boolean) decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; register int s, k, r; unsigned int EOBRUN; int Se, Al; const int * natural_order; JBLOCKROW block; BITREAD_STATE_VARS; d_derived_tbl * tbl; /* Process restart marker if needed; may have to suspend */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! process_restart(cinfo)) return FALSE; } /* If we've run out of data, just leave the MCU set to zeroes. * This way, we return uniform gray for the remainder of the segment. */ if (! entropy->insufficient_data) { Se = cinfo->Se; Al = cinfo->Al; natural_order = cinfo->natural_order; /* Load up working state. * We can avoid loading/saving bitread state if in an EOB run. */ EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */ /* There is always only one block per MCU */ if (EOBRUN) /* if it's a band of zeroes... */ EOBRUN--; /* ...process it now (we do nothing) */ else { BITREAD_LOAD_STATE(cinfo,entropy->bitstate); block = MCU_data[0]; tbl = entropy->ac_derived_tbl; for (k = cinfo->Ss; k <= Se; k++) { HUFF_DECODE(s, br_state, tbl, return FALSE, label2); r = s >> 4; s &= 15; if (s) { k += r; CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); /* Scale and output coefficient in natural (dezigzagged) order */ (*block)[natural_order[k]] = (JCOEF) (s << Al); } else { if (r != 15) { /* EOBr, run length is 2^r + appended bits */ if (r) { /* EOBr, r > 0 */ EOBRUN = 1 << r; CHECK_BIT_BUFFER(br_state, r, return FALSE); r = GET_BITS(r); EOBRUN += r; EOBRUN--; /* this band is processed at this moment */ } break; /* force end-of-band */ } k += 15; /* ZRL: skip 15 zeroes in band */ } } BITREAD_SAVE_STATE(cinfo,entropy->bitstate); } /* Completed MCU, so update state */ entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */ } /* Account for restart interval (no-op if not using restarts) */ entropy->restarts_to_go--; return TRUE; } /* * MCU decoding for DC successive approximation refinement scan. * Note: we assume such scans can be multi-component, * although the spec is not very clear on the point. */ METHODDEF(boolean) decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int p1, blkn; BITREAD_STATE_VARS; /* Process restart marker if needed; may have to suspend */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! process_restart(cinfo)) return FALSE; } /* Not worth the cycles to check insufficient_data here, * since we will not change the data anyway if we read zeroes. */ /* Load up working state */ BITREAD_LOAD_STATE(cinfo,entropy->bitstate); p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */ /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { /* Encoded data is simply the next bit of the two's-complement DC value */ CHECK_BIT_BUFFER(br_state, 1, return FALSE); if (GET_BITS(1)) MCU_data[blkn][0][0] |= p1; /* Note: since we use |=, repeating the assignment later is safe */ } /* Completed MCU, so update state */ BITREAD_SAVE_STATE(cinfo,entropy->bitstate); /* Account for restart interval (no-op if not using restarts) */ entropy->restarts_to_go--; return TRUE; } /* * MCU decoding for AC successive approximation refinement scan. */ METHODDEF(boolean) decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; register int s, k, r; unsigned int EOBRUN; int Se, p1, m1; const int * natural_order; JBLOCKROW block; JCOEFPTR thiscoef; BITREAD_STATE_VARS; d_derived_tbl * tbl; int num_newnz; int newnz_pos[DCTSIZE2]; /* Process restart marker if needed; may have to suspend */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! process_restart(cinfo)) return FALSE; } /* If we've run out of data, don't modify the MCU. */ if (! entropy->insufficient_data) { Se = cinfo->Se; p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */ m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */ natural_order = cinfo->natural_order; /* Load up working state */ BITREAD_LOAD_STATE(cinfo,entropy->bitstate); EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */ /* There is always only one block per MCU */ block = MCU_data[0]; tbl = entropy->ac_derived_tbl; /* If we are forced to suspend, we must undo the assignments to any newly * nonzero coefficients in the block, because otherwise we'd get confused * next time about which coefficients were already nonzero. * But we need not undo addition of bits to already-nonzero coefficients; * instead, we can test the current bit to see if we already did it. */ num_newnz = 0; /* initialize coefficient loop counter to start of band */ k = cinfo->Ss; if (EOBRUN == 0) { do { HUFF_DECODE(s, br_state, tbl, goto undoit, label3); r = s >> 4; s &= 15; if (s) { if (s != 1) /* size of new coef should always be 1 */ WARNMS(cinfo, JWRN_HUFF_BAD_CODE); CHECK_BIT_BUFFER(br_state, 1, goto undoit); if (GET_BITS(1)) s = p1; /* newly nonzero coef is positive */ else s = m1; /* newly nonzero coef is negative */ } else { if (r != 15) { EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */ if (r) { CHECK_BIT_BUFFER(br_state, r, goto undoit); r = GET_BITS(r); EOBRUN += r; } break; /* rest of block is handled by EOB logic */ } /* note s = 0 for processing ZRL */ } /* Advance over already-nonzero coefs and r still-zero coefs, * appending correction bits to the nonzeroes. A correction bit is 1 * if the absolute value of the coefficient must be increased. */ do { thiscoef = *block + natural_order[k]; if (*thiscoef) { CHECK_BIT_BUFFER(br_state, 1, goto undoit); if (GET_BITS(1)) { if ((*thiscoef & p1) == 0) { /* do nothing if already set it */ if (*thiscoef >= 0) *thiscoef += p1; else *thiscoef += m1; } } } else { if (--r < 0) break; /* reached target zero coefficient */ } k++; } while (k <= Se); if (s) { int pos = natural_order[k]; /* Output newly nonzero coefficient */ (*block)[pos] = (JCOEF) s; /* Remember its position in case we have to suspend */ newnz_pos[num_newnz++] = pos; } k++; } while (k <= Se); } if (EOBRUN) { /* Scan any remaining coefficient positions after the end-of-band * (the last newly nonzero coefficient, if any). Append a correction * bit to each already-nonzero coefficient. A correction bit is 1 * if the absolute value of the coefficient must be increased. */ do { thiscoef = *block + natural_order[k]; if (*thiscoef) { CHECK_BIT_BUFFER(br_state, 1, goto undoit); if (GET_BITS(1)) { if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */ if (*thiscoef >= 0) *thiscoef += p1; else *thiscoef += m1; } } } k++; } while (k <= Se); /* Count one block completed in EOB run */ EOBRUN--; } /* Completed MCU, so update state */ BITREAD_SAVE_STATE(cinfo,entropy->bitstate); entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */ } /* Account for restart interval (no-op if not using restarts) */ entropy->restarts_to_go--; return TRUE; undoit: /* Re-zero any output coefficients that we made newly nonzero */ while (num_newnz) (*block)[newnz_pos[--num_newnz]] = 0; return FALSE; } /* * Decode one MCU's worth of Huffman-compressed coefficients, * partial blocks. */ METHODDEF(boolean) decode_mcu_sub (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; const int * natural_order; int Se, blkn; BITREAD_STATE_VARS; savable_state state; /* Process restart marker if needed; may have to suspend */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! process_restart(cinfo)) return FALSE; } /* If we've run out of data, just leave the MCU set to zeroes. * This way, we return uniform gray for the remainder of the segment. */ if (! entropy->insufficient_data) { natural_order = cinfo->natural_order; Se = cinfo->lim_Se; /* Load up working state */ BITREAD_LOAD_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(state, entropy->saved); /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { JBLOCKROW block = MCU_data[blkn]; d_derived_tbl * htbl; register int s, k, r; int coef_limit, ci; /* Decode a single block's worth of coefficients */ /* Section F.2.2.1: decode the DC coefficient difference */ htbl = entropy->dc_cur_tbls[blkn]; HUFF_DECODE(s, br_state, htbl, return FALSE, label1); htbl = entropy->ac_cur_tbls[blkn]; k = 1; coef_limit = entropy->coef_limit[blkn]; if (coef_limit) { /* Convert DC difference to actual value, update last_dc_val */ if (s) { CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); } ci = cinfo->MCU_membership[blkn]; s += state.last_dc_val[ci]; state.last_dc_val[ci] = s; /* Output the DC coefficient */ (*block)[0] = (JCOEF) s; /* Section F.2.2.2: decode the AC coefficients */ /* Since zeroes are skipped, output area must be cleared beforehand */ for (; k < coef_limit; k++) { HUFF_DECODE(s, br_state, htbl, return FALSE, label2); r = s >> 4; s &= 15; if (s) { k += r; CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); /* Output coefficient in natural (dezigzagged) order. * Note: the extra entries in natural_order[] will save us * if k > Se, which could happen if the data is corrupted. */ (*block)[natural_order[k]] = (JCOEF) s; } else { if (r != 15) goto EndOfBlock; k += 15; } } } else { if (s) { CHECK_BIT_BUFFER(br_state, s, return FALSE); DROP_BITS(s); } } /* Section F.2.2.2: decode the AC coefficients */ /* In this path we just discard the values */ for (; k <= Se; k++) { HUFF_DECODE(s, br_state, htbl, return FALSE, label3); r = s >> 4; s &= 15; if (s) { k += r; CHECK_BIT_BUFFER(br_state, s, return FALSE); DROP_BITS(s); } else { if (r != 15) break; k += 15; } } EndOfBlock: ; } /* Completed MCU, so update state */ BITREAD_SAVE_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(entropy->saved, state); } /* Account for restart interval (no-op if not using restarts) */ entropy->restarts_to_go--; return TRUE; } /* * Decode one MCU's worth of Huffman-compressed coefficients, * full-size blocks. */ METHODDEF(boolean) decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int blkn; BITREAD_STATE_VARS; savable_state state; /* Process restart marker if needed; may have to suspend */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! process_restart(cinfo)) return FALSE; } /* If we've run out of data, just leave the MCU set to zeroes. * This way, we return uniform gray for the remainder of the segment. */ if (! entropy->insufficient_data) { /* Load up working state */ BITREAD_LOAD_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(state, entropy->saved); /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { JBLOCKROW block = MCU_data[blkn]; d_derived_tbl * htbl; register int s, k, r; int coef_limit, ci; /* Decode a single block's worth of coefficients */ /* Section F.2.2.1: decode the DC coefficient difference */ htbl = entropy->dc_cur_tbls[blkn]; HUFF_DECODE(s, br_state, htbl, return FALSE, label1); htbl = entropy->ac_cur_tbls[blkn]; k = 1; coef_limit = entropy->coef_limit[blkn]; if (coef_limit) { /* Convert DC difference to actual value, update last_dc_val */ if (s) { CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); } ci = cinfo->MCU_membership[blkn]; s += state.last_dc_val[ci]; state.last_dc_val[ci] = s; /* Output the DC coefficient */ (*block)[0] = (JCOEF) s; /* Section F.2.2.2: decode the AC coefficients */ /* Since zeroes are skipped, output area must be cleared beforehand */ for (; k < coef_limit; k++) { HUFF_DECODE(s, br_state, htbl, return FALSE, label2); r = s >> 4; s &= 15; if (s) { k += r; CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); /* Output coefficient in natural (dezigzagged) order. * Note: the extra entries in jpeg_natural_order[] will save us * if k >= DCTSIZE2, which could happen if the data is corrupted. */ (*block)[jpeg_natural_order[k]] = (JCOEF) s; } else { if (r != 15) goto EndOfBlock; k += 15; } } } else { if (s) { CHECK_BIT_BUFFER(br_state, s, return FALSE); DROP_BITS(s); } } /* Section F.2.2.2: decode the AC coefficients */ /* In this path we just discard the values */ for (; k < DCTSIZE2; k++) { HUFF_DECODE(s, br_state, htbl, return FALSE, label3); r = s >> 4; s &= 15; if (s) { k += r; CHECK_BIT_BUFFER(br_state, s, return FALSE); DROP_BITS(s); } else { if (r != 15) break; k += 15; } } EndOfBlock: ; } /* Completed MCU, so update state */ BITREAD_SAVE_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(entropy->saved, state); } /* Account for restart interval (no-op if not using restarts) */ entropy->restarts_to_go--; return TRUE; } /* * Initialize for a Huffman-compressed scan. */ METHODDEF(void) start_pass_huff_decoder (j_decompress_ptr cinfo) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int ci, blkn, tbl, i; jpeg_component_info * compptr; if (cinfo->progressive_mode) { /* Validate progressive scan parameters */ if (cinfo->Ss == 0) { if (cinfo->Se != 0) goto bad; } else { /* need not check Ss/Se < 0 since they came from unsigned bytes */ if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se) goto bad; /* AC scans may have only one component */ if (cinfo->comps_in_scan != 1) goto bad; } if (cinfo->Ah != 0) { /* Successive approximation refinement scan: must have Al = Ah-1. */ if (cinfo->Ah-1 != cinfo->Al) goto bad; } if (cinfo->Al > 13) { /* need not check for < 0 */ /* Arguably the maximum Al value should be less than 13 for 8-bit precision, * but the spec doesn't say so, and we try to be liberal about what we * accept. Note: large Al values could result in out-of-range DC * coefficients during early scans, leading to bizarre displays due to * overflows in the IDCT math. But we won't crash. */ bad: ERREXIT4(cinfo, JERR_BAD_PROGRESSION, cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al); } /* Update progression status, and verify that scan order is legal. * Note that inter-scan inconsistencies are treated as warnings * not fatal errors ... not clear if this is right way to behave. */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { int coefi, cindex = cinfo->cur_comp_info[ci]->component_index; int *coef_bit_ptr = & cinfo->coef_bits[cindex][0]; if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */ WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0); for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) { int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi]; if (cinfo->Ah != expected) WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi); coef_bit_ptr[coefi] = cinfo->Al; } } /* Select MCU decoding routine */ if (cinfo->Ah == 0) { if (cinfo->Ss == 0) entropy->pub.decode_mcu = decode_mcu_DC_first; else entropy->pub.decode_mcu = decode_mcu_AC_first; } else { if (cinfo->Ss == 0) entropy->pub.decode_mcu = decode_mcu_DC_refine; else entropy->pub.decode_mcu = decode_mcu_AC_refine; } for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Make sure requested tables are present, and compute derived tables. * We may build same derived table more than once, but it's not expensive. */ if (cinfo->Ss == 0) { if (cinfo->Ah == 0) { /* DC refinement needs no table */ tbl = compptr->dc_tbl_no; jpeg_make_d_derived_tbl(cinfo, TRUE, tbl, & entropy->derived_tbls[tbl]); } } else { tbl = compptr->ac_tbl_no; jpeg_make_d_derived_tbl(cinfo, FALSE, tbl, & entropy->derived_tbls[tbl]); /* remember the single active table */ entropy->ac_derived_tbl = entropy->derived_tbls[tbl]; } /* Initialize DC predictions to 0 */ entropy->saved.last_dc_val[ci] = 0; } /* Initialize private state variables */ entropy->saved.EOBRUN = 0; } else { /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG. * This ought to be an error condition, but we make it a warning because * there are some baseline files out there with all zeroes in these bytes. */ if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 || ((cinfo->is_baseline || cinfo->Se < DCTSIZE2) && cinfo->Se != cinfo->lim_Se)) WARNMS(cinfo, JWRN_NOT_SEQUENTIAL); /* Select MCU decoding routine */ /* We retain the hard-coded case for full-size blocks. * This is not necessary, but it appears that this version is slightly * more performant in the given implementation. * With an improved implementation we would prefer a single optimized * function. */ if (cinfo->lim_Se != DCTSIZE2-1) entropy->pub.decode_mcu = decode_mcu_sub; else entropy->pub.decode_mcu = decode_mcu; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Compute derived values for Huffman tables */ /* We may do this more than once for a table, but it's not expensive */ tbl = compptr->dc_tbl_no; jpeg_make_d_derived_tbl(cinfo, TRUE, tbl, & entropy->dc_derived_tbls[tbl]); if (cinfo->lim_Se) { /* AC needs no table when not present */ tbl = compptr->ac_tbl_no; jpeg_make_d_derived_tbl(cinfo, FALSE, tbl, & entropy->ac_derived_tbls[tbl]); } /* Initialize DC predictions to 0 */ entropy->saved.last_dc_val[ci] = 0; } /* Precalculate decoding info for each block in an MCU of this scan */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { ci = cinfo->MCU_membership[blkn]; compptr = cinfo->cur_comp_info[ci]; /* Precalculate which table to use for each block */ entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no]; entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no]; /* Decide whether we really care about the coefficient values */ if (compptr->component_needed) { ci = compptr->DCT_v_scaled_size; i = compptr->DCT_h_scaled_size; switch (cinfo->lim_Se) { case (1*1-1): entropy->coef_limit[blkn] = 1; break; case (2*2-1): if (ci <= 0 || ci > 2) ci = 2; if (i <= 0 || i > 2) i = 2; entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order2[ci - 1][i - 1]; break; case (3*3-1): if (ci <= 0 || ci > 3) ci = 3; if (i <= 0 || i > 3) i = 3; entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order3[ci - 1][i - 1]; break; case (4*4-1): if (ci <= 0 || ci > 4) ci = 4; if (i <= 0 || i > 4) i = 4; entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order4[ci - 1][i - 1]; break; case (5*5-1): if (ci <= 0 || ci > 5) ci = 5; if (i <= 0 || i > 5) i = 5; entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order5[ci - 1][i - 1]; break; case (6*6-1): if (ci <= 0 || ci > 6) ci = 6; if (i <= 0 || i > 6) i = 6; entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order6[ci - 1][i - 1]; break; case (7*7-1): if (ci <= 0 || ci > 7) ci = 7; if (i <= 0 || i > 7) i = 7; entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order7[ci - 1][i - 1]; break; default: if (ci <= 0 || ci > 8) ci = 8; if (i <= 0 || i > 8) i = 8; entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1]; break; } } else { entropy->coef_limit[blkn] = 0; } } } /* Initialize bitread state variables */ entropy->bitstate.bits_left = 0; entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ entropy->insufficient_data = FALSE; /* Initialize restart counter */ entropy->restarts_to_go = cinfo->restart_interval; } /* * Module initialization routine for Huffman entropy decoding. */ GLOBAL(void) jinit_huff_decoder (j_decompress_ptr cinfo) { huff_entropy_ptr entropy; int i; entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_decoder)); cinfo->entropy = &entropy->pub; entropy->pub.start_pass = start_pass_huff_decoder; entropy->pub.finish_pass = finish_pass_huff; if (cinfo->progressive_mode) { /* Create progression status table */ int *coef_bit_ptr, ci; cinfo->coef_bits = (int (*)[DCTSIZE2]) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->num_components*DCTSIZE2*SIZEOF(int)); coef_bit_ptr = & cinfo->coef_bits[0][0]; for (ci = 0; ci < cinfo->num_components; ci++) for (i = 0; i < DCTSIZE2; i++) *coef_bit_ptr++ = -1; /* Mark derived tables unallocated */ for (i = 0; i < NUM_HUFF_TBLS; i++) { entropy->derived_tbls[i] = NULL; } } else { /* Mark tables unallocated */ for (i = 0; i < NUM_HUFF_TBLS; i++) { entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; } } } ================================================ FILE: tess-two/jni/libjpeg/jdinput.c ================================================ /* * jdinput.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2002-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains input control logic for the JPEG decompressor. * These routines are concerned with controlling the decompressor's input * processing (marker reading and coefficient decoding). The actual input * reading is done in jdmarker.c, jdhuff.c, and jdarith.c. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Private state */ typedef struct { struct jpeg_input_controller pub; /* public fields */ int inheaders; /* Nonzero until first SOS is reached */ } my_input_controller; typedef my_input_controller * my_inputctl_ptr; /* Forward declarations */ METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo)); /* * Routines to calculate various quantities related to the size of the image. */ /* * Compute output image dimensions and related values. * NOTE: this is exported for possible use by application. * Hence it mustn't do anything that can't be done twice. */ GLOBAL(void) jpeg_core_output_dimensions (j_decompress_ptr cinfo) /* Do computations that are needed before master selection phase. * This function is used for transcoding and full decompression. */ { #ifdef IDCT_SCALING_SUPPORTED int ci; jpeg_component_info *compptr; /* Compute actual output image dimensions and DCT scaling choices. */ if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom) { /* Provide 1/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 1; cinfo->min_DCT_v_scaled_size = 1; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 2) { /* Provide 2/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 2L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 2L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 2; cinfo->min_DCT_v_scaled_size = 2; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 3) { /* Provide 3/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 3L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 3L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 3; cinfo->min_DCT_v_scaled_size = 3; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 4) { /* Provide 4/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 4L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 4L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 4; cinfo->min_DCT_v_scaled_size = 4; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 5) { /* Provide 5/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 5L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 5L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 5; cinfo->min_DCT_v_scaled_size = 5; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 6) { /* Provide 6/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 6L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 6L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 6; cinfo->min_DCT_v_scaled_size = 6; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 7) { /* Provide 7/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 7L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 7L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 7; cinfo->min_DCT_v_scaled_size = 7; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 8) { /* Provide 8/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 8L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 8L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 8; cinfo->min_DCT_v_scaled_size = 8; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 9) { /* Provide 9/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 9L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 9L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 9; cinfo->min_DCT_v_scaled_size = 9; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 10) { /* Provide 10/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 10L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 10L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 10; cinfo->min_DCT_v_scaled_size = 10; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 11) { /* Provide 11/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 11L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 11L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 11; cinfo->min_DCT_v_scaled_size = 11; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 12) { /* Provide 12/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 12L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 12L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 12; cinfo->min_DCT_v_scaled_size = 12; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 13) { /* Provide 13/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 13L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 13L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 13; cinfo->min_DCT_v_scaled_size = 13; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 14) { /* Provide 14/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 14L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 14L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 14; cinfo->min_DCT_v_scaled_size = 14; } else if (cinfo->scale_num * cinfo->block_size <= cinfo->scale_denom * 15) { /* Provide 15/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 15L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 15L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 15; cinfo->min_DCT_v_scaled_size = 15; } else { /* Provide 16/block_size scaling */ cinfo->output_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * 16L, (long) cinfo->block_size); cinfo->output_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * 16L, (long) cinfo->block_size); cinfo->min_DCT_h_scaled_size = 16; cinfo->min_DCT_v_scaled_size = 16; } /* Recompute dimensions of components */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { compptr->DCT_h_scaled_size = cinfo->min_DCT_h_scaled_size; compptr->DCT_v_scaled_size = cinfo->min_DCT_v_scaled_size; } #else /* !IDCT_SCALING_SUPPORTED */ /* Hardwire it to "no scaling" */ cinfo->output_width = cinfo->image_width; cinfo->output_height = cinfo->image_height; /* initial_setup has already initialized DCT_scaled_size, * and has computed unscaled downsampled_width and downsampled_height. */ #endif /* IDCT_SCALING_SUPPORTED */ } LOCAL(void) initial_setup (j_decompress_ptr cinfo) /* Called once, when first SOS marker is reached */ { int ci; jpeg_component_info *compptr; /* Make sure image isn't bigger than I can handle */ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION || (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION) ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); /* Only 8 to 12 bits data precision are supported for DCT based JPEG */ if (cinfo->data_precision < 8 || cinfo->data_precision > 12) ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); /* Check that number of components won't exceed internal array sizes */ if (cinfo->num_components > MAX_COMPONENTS) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPONENTS); /* Compute maximum sampling factors; check factor validity */ cinfo->max_h_samp_factor = 1; cinfo->max_v_samp_factor = 1; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR || compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR) ERREXIT(cinfo, JERR_BAD_SAMPLING); cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor, compptr->h_samp_factor); cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor, compptr->v_samp_factor); } /* Derive block_size, natural_order, and lim_Se */ if (cinfo->is_baseline || (cinfo->progressive_mode && cinfo->comps_in_scan)) { /* no pseudo SOS marker */ cinfo->block_size = DCTSIZE; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; } else switch (cinfo->Se) { case (1*1-1): cinfo->block_size = 1; cinfo->natural_order = jpeg_natural_order; /* not needed */ cinfo->lim_Se = cinfo->Se; break; case (2*2-1): cinfo->block_size = 2; cinfo->natural_order = jpeg_natural_order2; cinfo->lim_Se = cinfo->Se; break; case (3*3-1): cinfo->block_size = 3; cinfo->natural_order = jpeg_natural_order3; cinfo->lim_Se = cinfo->Se; break; case (4*4-1): cinfo->block_size = 4; cinfo->natural_order = jpeg_natural_order4; cinfo->lim_Se = cinfo->Se; break; case (5*5-1): cinfo->block_size = 5; cinfo->natural_order = jpeg_natural_order5; cinfo->lim_Se = cinfo->Se; break; case (6*6-1): cinfo->block_size = 6; cinfo->natural_order = jpeg_natural_order6; cinfo->lim_Se = cinfo->Se; break; case (7*7-1): cinfo->block_size = 7; cinfo->natural_order = jpeg_natural_order7; cinfo->lim_Se = cinfo->Se; break; case (8*8-1): cinfo->block_size = 8; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (9*9-1): cinfo->block_size = 9; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (10*10-1): cinfo->block_size = 10; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (11*11-1): cinfo->block_size = 11; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (12*12-1): cinfo->block_size = 12; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (13*13-1): cinfo->block_size = 13; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (14*14-1): cinfo->block_size = 14; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (15*15-1): cinfo->block_size = 15; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; case (16*16-1): cinfo->block_size = 16; cinfo->natural_order = jpeg_natural_order; cinfo->lim_Se = DCTSIZE2-1; break; default: ERREXIT4(cinfo, JERR_BAD_PROGRESSION, cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al); break; } /* We initialize DCT_scaled_size and min_DCT_scaled_size to block_size. * In the full decompressor, * this will be overridden by jpeg_calc_output_dimensions in jdmaster.c; * but in the transcoder, * jpeg_calc_output_dimensions is not used, so we must do it here. */ cinfo->min_DCT_h_scaled_size = cinfo->block_size; cinfo->min_DCT_v_scaled_size = cinfo->block_size; /* Compute dimensions of components */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { compptr->DCT_h_scaled_size = cinfo->block_size; compptr->DCT_v_scaled_size = cinfo->block_size; /* Size in DCT blocks */ compptr->width_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, (long) (cinfo->max_h_samp_factor * cinfo->block_size)); compptr->height_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, (long) (cinfo->max_v_samp_factor * cinfo->block_size)); /* downsampled_width and downsampled_height will also be overridden by * jdmaster.c if we are doing full decompression. The transcoder library * doesn't use these values, but the calling application might. */ /* Size in samples */ compptr->downsampled_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, (long) cinfo->max_h_samp_factor); compptr->downsampled_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, (long) cinfo->max_v_samp_factor); /* Mark component needed, until color conversion says otherwise */ compptr->component_needed = TRUE; /* Mark no quantization table yet saved for component */ compptr->quant_table = NULL; } /* Compute number of fully interleaved MCU rows. */ cinfo->total_iMCU_rows = (JDIMENSION) jdiv_round_up((long) cinfo->image_height, (long) (cinfo->max_v_samp_factor * cinfo->block_size)); /* Decide whether file contains multiple scans */ if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode) cinfo->inputctl->has_multiple_scans = TRUE; else cinfo->inputctl->has_multiple_scans = FALSE; } LOCAL(void) per_scan_setup (j_decompress_ptr cinfo) /* Do computations that are needed before processing a JPEG scan */ /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */ { int ci, mcublks, tmp; jpeg_component_info *compptr; if (cinfo->comps_in_scan == 1) { /* Noninterleaved (single-component) scan */ compptr = cinfo->cur_comp_info[0]; /* Overall image size in MCUs */ cinfo->MCUs_per_row = compptr->width_in_blocks; cinfo->MCU_rows_in_scan = compptr->height_in_blocks; /* For noninterleaved scan, always one block per MCU */ compptr->MCU_width = 1; compptr->MCU_height = 1; compptr->MCU_blocks = 1; compptr->MCU_sample_width = compptr->DCT_h_scaled_size; compptr->last_col_width = 1; /* For noninterleaved scans, it is convenient to define last_row_height * as the number of block rows present in the last iMCU row. */ tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (tmp == 0) tmp = compptr->v_samp_factor; compptr->last_row_height = tmp; /* Prepare array describing MCU composition */ cinfo->blocks_in_MCU = 1; cinfo->MCU_membership[0] = 0; } else { /* Interleaved (multi-component) scan */ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan, MAX_COMPS_IN_SCAN); /* Overall image size in MCUs */ cinfo->MCUs_per_row = (JDIMENSION) jdiv_round_up((long) cinfo->image_width, (long) (cinfo->max_h_samp_factor * cinfo->block_size)); cinfo->MCU_rows_in_scan = (JDIMENSION) jdiv_round_up((long) cinfo->image_height, (long) (cinfo->max_v_samp_factor * cinfo->block_size)); cinfo->blocks_in_MCU = 0; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Sampling factors give # of blocks of component in each MCU */ compptr->MCU_width = compptr->h_samp_factor; compptr->MCU_height = compptr->v_samp_factor; compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height; compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_h_scaled_size; /* Figure number of non-dummy blocks in last MCU column & row */ tmp = (int) (compptr->width_in_blocks % compptr->MCU_width); if (tmp == 0) tmp = compptr->MCU_width; compptr->last_col_width = tmp; tmp = (int) (compptr->height_in_blocks % compptr->MCU_height); if (tmp == 0) tmp = compptr->MCU_height; compptr->last_row_height = tmp; /* Prepare array describing MCU composition */ mcublks = compptr->MCU_blocks; if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU) ERREXIT(cinfo, JERR_BAD_MCU_SIZE); while (mcublks-- > 0) { cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci; } } } } /* * Save away a copy of the Q-table referenced by each component present * in the current scan, unless already saved during a prior scan. * * In a multiple-scan JPEG file, the encoder could assign different components * the same Q-table slot number, but change table definitions between scans * so that each component uses a different Q-table. (The IJG encoder is not * currently capable of doing this, but other encoders might.) Since we want * to be able to dequantize all the components at the end of the file, this * means that we have to save away the table actually used for each component. * We do this by copying the table at the start of the first scan containing * the component. * The JPEG spec prohibits the encoder from changing the contents of a Q-table * slot between scans of a component using that slot. If the encoder does so * anyway, this decoder will simply use the Q-table values that were current * at the start of the first scan for the component. * * The decompressor output side looks only at the saved quant tables, * not at the current Q-table slots. */ LOCAL(void) latch_quant_tables (j_decompress_ptr cinfo) { int ci, qtblno; jpeg_component_info *compptr; JQUANT_TBL * qtbl; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* No work if we already saved Q-table for this component */ if (compptr->quant_table != NULL) continue; /* Make sure specified quantization table is present */ qtblno = compptr->quant_tbl_no; if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || cinfo->quant_tbl_ptrs[qtblno] == NULL) ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno); /* OK, save away the quantization table */ qtbl = (JQUANT_TBL *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(JQUANT_TBL)); MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL)); compptr->quant_table = qtbl; } } /* * Initialize the input modules to read a scan of compressed data. * The first call to this is done by jdmaster.c after initializing * the entire decompressor (during jpeg_start_decompress). * Subsequent calls come from consume_markers, below. */ METHODDEF(void) start_input_pass (j_decompress_ptr cinfo) { per_scan_setup(cinfo); latch_quant_tables(cinfo); (*cinfo->entropy->start_pass) (cinfo); (*cinfo->coef->start_input_pass) (cinfo); cinfo->inputctl->consume_input = cinfo->coef->consume_data; } /* * Finish up after inputting a compressed-data scan. * This is called by the coefficient controller after it's read all * the expected data of the scan. */ METHODDEF(void) finish_input_pass (j_decompress_ptr cinfo) { (*cinfo->entropy->finish_pass) (cinfo); cinfo->inputctl->consume_input = consume_markers; } /* * Read JPEG markers before, between, or after compressed-data scans. * Change state as necessary when a new scan is reached. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. * * The consume_input method pointer points either here or to the * coefficient controller's consume_data routine, depending on whether * we are reading a compressed data segment or inter-segment markers. * * Note: This function should NOT return a pseudo SOS marker (with zero * component number) to the caller. A pseudo marker received by * read_markers is processed and then skipped for other markers. */ METHODDEF(int) consume_markers (j_decompress_ptr cinfo) { my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl; int val; if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */ return JPEG_REACHED_EOI; for (;;) { /* Loop to pass pseudo SOS marker */ val = (*cinfo->marker->read_markers) (cinfo); switch (val) { case JPEG_REACHED_SOS: /* Found SOS */ if (inputctl->inheaders) { /* 1st SOS */ if (inputctl->inheaders == 1) initial_setup(cinfo); if (cinfo->comps_in_scan == 0) { /* pseudo SOS marker */ inputctl->inheaders = 2; break; } inputctl->inheaders = 0; /* Note: start_input_pass must be called by jdmaster.c * before any more input can be consumed. jdapimin.c is * responsible for enforcing this sequencing. */ } else { /* 2nd or later SOS marker */ if (! inputctl->pub.has_multiple_scans) ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */ if (cinfo->comps_in_scan == 0) /* unexpected pseudo SOS marker */ break; start_input_pass(cinfo); } return val; case JPEG_REACHED_EOI: /* Found EOI */ inputctl->pub.eoi_reached = TRUE; if (inputctl->inheaders) { /* Tables-only datastream, apparently */ if (cinfo->marker->saw_SOF) ERREXIT(cinfo, JERR_SOF_NO_SOS); } else { /* Prevent infinite loop in coef ctlr's decompress_data routine * if user set output_scan_number larger than number of scans. */ if (cinfo->output_scan_number > cinfo->input_scan_number) cinfo->output_scan_number = cinfo->input_scan_number; } return val; case JPEG_SUSPENDED: return val; default: return val; } } } /* * Reset state to begin a fresh datastream. */ METHODDEF(void) reset_input_controller (j_decompress_ptr cinfo) { my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl; inputctl->pub.consume_input = consume_markers; inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */ inputctl->pub.eoi_reached = FALSE; inputctl->inheaders = 1; /* Reset other modules */ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo); (*cinfo->marker->reset_marker_reader) (cinfo); /* Reset progression state -- would be cleaner if entropy decoder did this */ cinfo->coef_bits = NULL; } /* * Initialize the input controller module. * This is called only once, when the decompression object is created. */ GLOBAL(void) jinit_input_controller (j_decompress_ptr cinfo) { my_inputctl_ptr inputctl; /* Create subobject in permanent pool */ inputctl = (my_inputctl_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_input_controller)); cinfo->inputctl = &inputctl->pub; /* Initialize method pointers */ inputctl->pub.consume_input = consume_markers; inputctl->pub.reset_input_controller = reset_input_controller; inputctl->pub.start_input_pass = start_input_pass; inputctl->pub.finish_input_pass = finish_input_pass; /* Initialize state: can't use reset_input_controller since we don't * want to try to reset other modules yet. */ inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */ inputctl->pub.eoi_reached = FALSE; inputctl->inheaders = 1; } ================================================ FILE: tess-two/jni/libjpeg/jdmainct.c ================================================ /* * jdmainct.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2002-2012 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the main buffer controller for decompression. * The main buffer lies between the JPEG decompressor proper and the * post-processor; it holds downsampled data in the JPEG colorspace. * * Note that this code is bypassed in raw-data mode, since the application * supplies the equivalent of the main buffer in that case. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * In the current system design, the main buffer need never be a full-image * buffer; any full-height buffers will be found inside the coefficient or * postprocessing controllers. Nonetheless, the main controller is not * trivial. Its responsibility is to provide context rows for upsampling/ * rescaling, and doing this in an efficient fashion is a bit tricky. * * Postprocessor input data is counted in "row groups". A row group * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size) * sample rows of each component. (We require DCT_scaled_size values to be * chosen such that these numbers are integers. In practice DCT_scaled_size * values will likely be powers of two, so we actually have the stronger * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.) * Upsampling will typically produce max_v_samp_factor pixel rows from each * row group (times any additional scale factor that the upsampler is * applying). * * The coefficient controller will deliver data to us one iMCU row at a time; * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or * exactly min_DCT_scaled_size row groups. (This amount of data corresponds * to one row of MCUs when the image is fully interleaved.) Note that the * number of sample rows varies across components, but the number of row * groups does not. Some garbage sample rows may be included in the last iMCU * row at the bottom of the image. * * Depending on the vertical scaling algorithm used, the upsampler may need * access to the sample row(s) above and below its current input row group. * The upsampler is required to set need_context_rows TRUE at global selection * time if so. When need_context_rows is FALSE, this controller can simply * obtain one iMCU row at a time from the coefficient controller and dole it * out as row groups to the postprocessor. * * When need_context_rows is TRUE, this controller guarantees that the buffer * passed to postprocessing contains at least one row group's worth of samples * above and below the row group(s) being processed. Note that the context * rows "above" the first passed row group appear at negative row offsets in * the passed buffer. At the top and bottom of the image, the required * context rows are manufactured by duplicating the first or last real sample * row; this avoids having special cases in the upsampling inner loops. * * The amount of context is fixed at one row group just because that's a * convenient number for this controller to work with. The existing * upsamplers really only need one sample row of context. An upsampler * supporting arbitrary output rescaling might wish for more than one row * group of context when shrinking the image; tough, we don't handle that. * (This is justified by the assumption that downsizing will be handled mostly * by adjusting the DCT_scaled_size values, so that the actual scale factor at * the upsample step needn't be much less than one.) * * To provide the desired context, we have to retain the last two row groups * of one iMCU row while reading in the next iMCU row. (The last row group * can't be processed until we have another row group for its below-context, * and so we have to save the next-to-last group too for its above-context.) * We could do this most simply by copying data around in our buffer, but * that'd be very slow. We can avoid copying any data by creating a rather * strange pointer structure. Here's how it works. We allocate a workspace * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number * of row groups per iMCU row). We create two sets of redundant pointers to * the workspace. Labeling the physical row groups 0 to M+1, the synthesized * pointer lists look like this: * M+1 M-1 * master pointer --> 0 master pointer --> 0 * 1 1 * ... ... * M-3 M-3 * M-2 M * M-1 M+1 * M M-2 * M+1 M-1 * 0 0 * We read alternate iMCU rows using each master pointer; thus the last two * row groups of the previous iMCU row remain un-overwritten in the workspace. * The pointer lists are set up so that the required context rows appear to * be adjacent to the proper places when we pass the pointer lists to the * upsampler. * * The above pictures describe the normal state of the pointer lists. * At top and bottom of the image, we diddle the pointer lists to duplicate * the first or last sample row as necessary (this is cheaper than copying * sample rows around). * * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that * situation each iMCU row provides only one row group so the buffering logic * must be different (eg, we must read two iMCU rows before we can emit the * first row group). For now, we simply do not support providing context * rows when min_DCT_scaled_size is 1. That combination seems unlikely to * be worth providing --- if someone wants a 1/8th-size preview, they probably * want it quick and dirty, so a context-free upsampler is sufficient. */ /* Private buffer controller object */ typedef struct { struct jpeg_d_main_controller pub; /* public fields */ /* Pointer to allocated workspace (M or M+2 row groups). */ JSAMPARRAY buffer[MAX_COMPONENTS]; boolean buffer_full; /* Have we gotten an iMCU row from decoder? */ JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */ /* Remaining fields are only used in the context case. */ /* These are the master pointers to the funny-order pointer lists. */ JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */ int whichptr; /* indicates which pointer set is now in use */ int context_state; /* process_data state machine status */ JDIMENSION rowgroups_avail; /* row groups available to postprocessor */ JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */ } my_main_controller; typedef my_main_controller * my_main_ptr; /* context_state values: */ #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */ #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */ #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */ /* Forward declarations */ METHODDEF(void) process_data_simple_main JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); METHODDEF(void) process_data_context_main JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); #ifdef QUANT_2PASS_SUPPORTED METHODDEF(void) process_data_crank_post JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); #endif LOCAL(void) alloc_funny_pointers (j_decompress_ptr cinfo) /* Allocate space for the funny pointer lists. * This is done only once, not once per pass. */ { my_main_ptr mainp = (my_main_ptr) cinfo->main; int ci, rgroup; int M = cinfo->min_DCT_v_scaled_size; jpeg_component_info *compptr; JSAMPARRAY xbuf; /* Get top-level space for component array pointers. * We alloc both arrays with one call to save a few cycles. */ mainp->xbuffer[0] = (JSAMPIMAGE) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->num_components * 2 * SIZEOF(JSAMPARRAY)); mainp->xbuffer[1] = mainp->xbuffer[0] + cinfo->num_components; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { rgroup = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) / cinfo->min_DCT_v_scaled_size; /* height of a row group of component */ /* Get space for pointer lists --- M+4 row groups in each list. * We alloc both pointer lists with one call to save a few cycles. */ xbuf = (JSAMPARRAY) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW)); xbuf += rgroup; /* want one row group at negative offsets */ mainp->xbuffer[0][ci] = xbuf; xbuf += rgroup * (M + 4); mainp->xbuffer[1][ci] = xbuf; } } LOCAL(void) make_funny_pointers (j_decompress_ptr cinfo) /* Create the funny pointer lists discussed in the comments above. * The actual workspace is already allocated (in main->buffer), * and the space for the pointer lists is allocated too. * This routine just fills in the curiously ordered lists. * This will be repeated at the beginning of each pass. */ { my_main_ptr mainp = (my_main_ptr) cinfo->main; int ci, i, rgroup; int M = cinfo->min_DCT_v_scaled_size; jpeg_component_info *compptr; JSAMPARRAY buf, xbuf0, xbuf1; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { rgroup = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) / cinfo->min_DCT_v_scaled_size; /* height of a row group of component */ xbuf0 = mainp->xbuffer[0][ci]; xbuf1 = mainp->xbuffer[1][ci]; /* First copy the workspace pointers as-is */ buf = mainp->buffer[ci]; for (i = 0; i < rgroup * (M + 2); i++) { xbuf0[i] = xbuf1[i] = buf[i]; } /* In the second list, put the last four row groups in swapped order */ for (i = 0; i < rgroup * 2; i++) { xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i]; xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i]; } /* The wraparound pointers at top and bottom will be filled later * (see set_wraparound_pointers, below). Initially we want the "above" * pointers to duplicate the first actual data line. This only needs * to happen in xbuffer[0]. */ for (i = 0; i < rgroup; i++) { xbuf0[i - rgroup] = xbuf0[0]; } } } LOCAL(void) set_wraparound_pointers (j_decompress_ptr cinfo) /* Set up the "wraparound" pointers at top and bottom of the pointer lists. * This changes the pointer list state from top-of-image to the normal state. */ { my_main_ptr mainp = (my_main_ptr) cinfo->main; int ci, i, rgroup; int M = cinfo->min_DCT_v_scaled_size; jpeg_component_info *compptr; JSAMPARRAY xbuf0, xbuf1; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { rgroup = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) / cinfo->min_DCT_v_scaled_size; /* height of a row group of component */ xbuf0 = mainp->xbuffer[0][ci]; xbuf1 = mainp->xbuffer[1][ci]; for (i = 0; i < rgroup; i++) { xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i]; xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i]; xbuf0[rgroup*(M+2) + i] = xbuf0[i]; xbuf1[rgroup*(M+2) + i] = xbuf1[i]; } } } LOCAL(void) set_bottom_pointers (j_decompress_ptr cinfo) /* Change the pointer lists to duplicate the last sample row at the bottom * of the image. whichptr indicates which xbuffer holds the final iMCU row. * Also sets rowgroups_avail to indicate number of nondummy row groups in row. */ { my_main_ptr mainp = (my_main_ptr) cinfo->main; int ci, i, rgroup, iMCUheight, rows_left; jpeg_component_info *compptr; JSAMPARRAY xbuf; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Count sample rows in one iMCU row and in one row group */ iMCUheight = compptr->v_samp_factor * compptr->DCT_v_scaled_size; rgroup = iMCUheight / cinfo->min_DCT_v_scaled_size; /* Count nondummy sample rows remaining for this component */ rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight); if (rows_left == 0) rows_left = iMCUheight; /* Count nondummy row groups. Should get same answer for each component, * so we need only do it once. */ if (ci == 0) { mainp->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1); } /* Duplicate the last real sample row rgroup*2 times; this pads out the * last partial rowgroup and ensures at least one full rowgroup of context. */ xbuf = mainp->xbuffer[mainp->whichptr][ci]; for (i = 0; i < rgroup * 2; i++) { xbuf[rows_left + i] = xbuf[rows_left-1]; } } } /* * Initialize for a processing pass. */ METHODDEF(void) start_pass_main (j_decompress_ptr cinfo, J_BUF_MODE pass_mode) { my_main_ptr mainp = (my_main_ptr) cinfo->main; switch (pass_mode) { case JBUF_PASS_THRU: if (cinfo->upsample->need_context_rows) { mainp->pub.process_data = process_data_context_main; make_funny_pointers(cinfo); /* Create the xbuffer[] lists */ mainp->whichptr = 0; /* Read first iMCU row into xbuffer[0] */ mainp->context_state = CTX_PREPARE_FOR_IMCU; mainp->iMCU_row_ctr = 0; } else { /* Simple case with no context needed */ mainp->pub.process_data = process_data_simple_main; } mainp->buffer_full = FALSE; /* Mark buffer empty */ mainp->rowgroup_ctr = 0; break; #ifdef QUANT_2PASS_SUPPORTED case JBUF_CRANK_DEST: /* For last pass of 2-pass quantization, just crank the postprocessor */ mainp->pub.process_data = process_data_crank_post; break; #endif default: ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); break; } } /* * Process some data. * This handles the simple case where no context is required. */ METHODDEF(void) process_data_simple_main (j_decompress_ptr cinfo, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_main_ptr mainp = (my_main_ptr) cinfo->main; JDIMENSION rowgroups_avail; /* Read input data if we haven't filled the main buffer yet */ if (! mainp->buffer_full) { if (! (*cinfo->coef->decompress_data) (cinfo, mainp->buffer)) return; /* suspension forced, can do nothing more */ mainp->buffer_full = TRUE; /* OK, we have an iMCU row to work with */ } /* There are always min_DCT_scaled_size row groups in an iMCU row. */ rowgroups_avail = (JDIMENSION) cinfo->min_DCT_v_scaled_size; /* Note: at the bottom of the image, we may pass extra garbage row groups * to the postprocessor. The postprocessor has to check for bottom * of image anyway (at row resolution), so no point in us doing it too. */ /* Feed the postprocessor */ (*cinfo->post->post_process_data) (cinfo, mainp->buffer, &mainp->rowgroup_ctr, rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); /* Has postprocessor consumed all the data yet? If so, mark buffer empty */ if (mainp->rowgroup_ctr >= rowgroups_avail) { mainp->buffer_full = FALSE; mainp->rowgroup_ctr = 0; } } /* * Process some data. * This handles the case where context rows must be provided. */ METHODDEF(void) process_data_context_main (j_decompress_ptr cinfo, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_main_ptr mainp = (my_main_ptr) cinfo->main; /* Read input data if we haven't filled the main buffer yet */ if (! mainp->buffer_full) { if (! (*cinfo->coef->decompress_data) (cinfo, mainp->xbuffer[mainp->whichptr])) return; /* suspension forced, can do nothing more */ mainp->buffer_full = TRUE; /* OK, we have an iMCU row to work with */ mainp->iMCU_row_ctr++; /* count rows received */ } /* Postprocessor typically will not swallow all the input data it is handed * in one call (due to filling the output buffer first). Must be prepared * to exit and restart. This switch lets us keep track of how far we got. * Note that each case falls through to the next on successful completion. */ switch (mainp->context_state) { case CTX_POSTPONED_ROW: /* Call postprocessor using previously set pointers for postponed row */ (*cinfo->post->post_process_data) (cinfo, mainp->xbuffer[mainp->whichptr], &mainp->rowgroup_ctr, mainp->rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); if (mainp->rowgroup_ctr < mainp->rowgroups_avail) return; /* Need to suspend */ mainp->context_state = CTX_PREPARE_FOR_IMCU; if (*out_row_ctr >= out_rows_avail) return; /* Postprocessor exactly filled output buf */ /*FALLTHROUGH*/ case CTX_PREPARE_FOR_IMCU: /* Prepare to process first M-1 row groups of this iMCU row */ mainp->rowgroup_ctr = 0; mainp->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_v_scaled_size - 1); /* Check for bottom of image: if so, tweak pointers to "duplicate" * the last sample row, and adjust rowgroups_avail to ignore padding rows. */ if (mainp->iMCU_row_ctr == cinfo->total_iMCU_rows) set_bottom_pointers(cinfo); mainp->context_state = CTX_PROCESS_IMCU; /*FALLTHROUGH*/ case CTX_PROCESS_IMCU: /* Call postprocessor using previously set pointers */ (*cinfo->post->post_process_data) (cinfo, mainp->xbuffer[mainp->whichptr], &mainp->rowgroup_ctr, mainp->rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); if (mainp->rowgroup_ctr < mainp->rowgroups_avail) return; /* Need to suspend */ /* After the first iMCU, change wraparound pointers to normal state */ if (mainp->iMCU_row_ctr == 1) set_wraparound_pointers(cinfo); /* Prepare to load new iMCU row using other xbuffer list */ mainp->whichptr ^= 1; /* 0=>1 or 1=>0 */ mainp->buffer_full = FALSE; /* Still need to process last row group of this iMCU row, */ /* which is saved at index M+1 of the other xbuffer */ mainp->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_v_scaled_size + 1); mainp->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_v_scaled_size + 2); mainp->context_state = CTX_POSTPONED_ROW; } } /* * Process some data. * Final pass of two-pass quantization: just call the postprocessor. * Source data will be the postprocessor controller's internal buffer. */ #ifdef QUANT_2PASS_SUPPORTED METHODDEF(void) process_data_crank_post (j_decompress_ptr cinfo, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL, (JDIMENSION *) NULL, (JDIMENSION) 0, output_buf, out_row_ctr, out_rows_avail); } #endif /* QUANT_2PASS_SUPPORTED */ /* * Initialize main buffer controller. */ GLOBAL(void) jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer) { my_main_ptr mainp; int ci, rgroup, ngroups; jpeg_component_info *compptr; mainp = (my_main_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_main_controller)); cinfo->main = &mainp->pub; mainp->pub.start_pass = start_pass_main; if (need_full_buffer) /* shouldn't happen */ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); /* Allocate the workspace. * ngroups is the number of row groups we need. */ if (cinfo->upsample->need_context_rows) { if (cinfo->min_DCT_v_scaled_size < 2) /* unsupported, see comments above */ ERREXIT(cinfo, JERR_NOTIMPL); alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */ ngroups = cinfo->min_DCT_v_scaled_size + 2; } else { ngroups = cinfo->min_DCT_v_scaled_size; } for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { rgroup = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) / cinfo->min_DCT_v_scaled_size; /* height of a row group of component */ mainp->buffer[ci] = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, compptr->width_in_blocks * ((JDIMENSION) compptr->DCT_h_scaled_size), (JDIMENSION) (rgroup * ngroups)); } } ================================================ FILE: tess-two/jni/libjpeg/jdmarker.c ================================================ /* * jdmarker.c * * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2009-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to decode JPEG datastream markers. * Most of the complexity arises from our desire to support input * suspension: if not all of the data for a marker is available, * we must exit back to the application. On resumption, we reprocess * the marker. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" typedef enum { /* JPEG marker codes */ M_SOF0 = 0xc0, M_SOF1 = 0xc1, M_SOF2 = 0xc2, M_SOF3 = 0xc3, M_SOF5 = 0xc5, M_SOF6 = 0xc6, M_SOF7 = 0xc7, M_JPG = 0xc8, M_SOF9 = 0xc9, M_SOF10 = 0xca, M_SOF11 = 0xcb, M_SOF13 = 0xcd, M_SOF14 = 0xce, M_SOF15 = 0xcf, M_DHT = 0xc4, M_DAC = 0xcc, M_RST0 = 0xd0, M_RST1 = 0xd1, M_RST2 = 0xd2, M_RST3 = 0xd3, M_RST4 = 0xd4, M_RST5 = 0xd5, M_RST6 = 0xd6, M_RST7 = 0xd7, M_SOI = 0xd8, M_EOI = 0xd9, M_SOS = 0xda, M_DQT = 0xdb, M_DNL = 0xdc, M_DRI = 0xdd, M_DHP = 0xde, M_EXP = 0xdf, M_APP0 = 0xe0, M_APP1 = 0xe1, M_APP2 = 0xe2, M_APP3 = 0xe3, M_APP4 = 0xe4, M_APP5 = 0xe5, M_APP6 = 0xe6, M_APP7 = 0xe7, M_APP8 = 0xe8, M_APP9 = 0xe9, M_APP10 = 0xea, M_APP11 = 0xeb, M_APP12 = 0xec, M_APP13 = 0xed, M_APP14 = 0xee, M_APP15 = 0xef, M_JPG0 = 0xf0, M_JPG8 = 0xf8, M_JPG13 = 0xfd, M_COM = 0xfe, M_TEM = 0x01, M_ERROR = 0x100 } JPEG_MARKER; /* Private state */ typedef struct { struct jpeg_marker_reader pub; /* public fields */ /* Application-overridable marker processing methods */ jpeg_marker_parser_method process_COM; jpeg_marker_parser_method process_APPn[16]; /* Limit on marker data length to save for each marker type */ unsigned int length_limit_COM; unsigned int length_limit_APPn[16]; /* Status of COM/APPn marker saving */ jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */ unsigned int bytes_read; /* data bytes read so far in marker */ /* Note: cur_marker is not linked into marker_list until it's all read. */ } my_marker_reader; typedef my_marker_reader * my_marker_ptr; /* * Macros for fetching data from the data source module. * * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect * the current restart point; we update them only when we have reached a * suitable place to restart if a suspension occurs. */ /* Declare and initialize local copies of input pointer/count */ #define INPUT_VARS(cinfo) \ struct jpeg_source_mgr * datasrc = (cinfo)->src; \ const JOCTET * next_input_byte = datasrc->next_input_byte; \ size_t bytes_in_buffer = datasrc->bytes_in_buffer /* Unload the local copies --- do this only at a restart boundary */ #define INPUT_SYNC(cinfo) \ ( datasrc->next_input_byte = next_input_byte, \ datasrc->bytes_in_buffer = bytes_in_buffer ) /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */ #define INPUT_RELOAD(cinfo) \ ( next_input_byte = datasrc->next_input_byte, \ bytes_in_buffer = datasrc->bytes_in_buffer ) /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer, * but we must reload the local copies after a successful fill. */ #define MAKE_BYTE_AVAIL(cinfo,action) \ if (bytes_in_buffer == 0) { \ if (! (*datasrc->fill_input_buffer) (cinfo)) \ { action; } \ INPUT_RELOAD(cinfo); \ } /* Read a byte into variable V. * If must suspend, take the specified action (typically "return FALSE"). */ #define INPUT_BYTE(cinfo,V,action) \ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \ bytes_in_buffer--; \ V = GETJOCTET(*next_input_byte++); ) /* As above, but read two bytes interpreted as an unsigned 16-bit integer. * V should be declared unsigned int or perhaps INT32. */ #define INPUT_2BYTES(cinfo,V,action) \ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \ bytes_in_buffer--; \ V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \ MAKE_BYTE_AVAIL(cinfo,action); \ bytes_in_buffer--; \ V += GETJOCTET(*next_input_byte++); ) /* * Routines to process JPEG markers. * * Entry condition: JPEG marker itself has been read and its code saved * in cinfo->unread_marker; input restart point is just after the marker. * * Exit: if return TRUE, have read and processed any parameters, and have * updated the restart point to point after the parameters. * If return FALSE, was forced to suspend before reaching end of * marker parameters; restart point has not been moved. Same routine * will be called again after application supplies more input data. * * This approach to suspension assumes that all of a marker's parameters * can fit into a single input bufferload. This should hold for "normal" * markers. Some COM/APPn markers might have large parameter segments * that might not fit. If we are simply dropping such a marker, we use * skip_input_data to get past it, and thereby put the problem on the * source manager's shoulders. If we are saving the marker's contents * into memory, we use a slightly different convention: when forced to * suspend, the marker processor updates the restart point to the end of * what it's consumed (ie, the end of the buffer) before returning FALSE. * On resumption, cinfo->unread_marker still contains the marker code, * but the data source will point to the next chunk of marker data. * The marker processor must retain internal state to deal with this. * * Note that we don't bother to avoid duplicate trace messages if a * suspension occurs within marker parameters. Other side effects * require more care. */ LOCAL(boolean) get_soi (j_decompress_ptr cinfo) /* Process an SOI marker */ { int i; TRACEMS(cinfo, 1, JTRC_SOI); if (cinfo->marker->saw_SOI) ERREXIT(cinfo, JERR_SOI_DUPLICATE); /* Reset all parameters that are defined to be reset by SOI */ for (i = 0; i < NUM_ARITH_TBLS; i++) { cinfo->arith_dc_L[i] = 0; cinfo->arith_dc_U[i] = 1; cinfo->arith_ac_K[i] = 5; } cinfo->restart_interval = 0; /* Set initial assumptions for colorspace etc */ cinfo->jpeg_color_space = JCS_UNKNOWN; cinfo->color_transform = JCT_NONE; cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */ cinfo->saw_JFIF_marker = FALSE; cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */ cinfo->JFIF_minor_version = 1; cinfo->density_unit = 0; cinfo->X_density = 1; cinfo->Y_density = 1; cinfo->saw_Adobe_marker = FALSE; cinfo->Adobe_transform = 0; cinfo->marker->saw_SOI = TRUE; return TRUE; } LOCAL(boolean) get_sof (j_decompress_ptr cinfo, boolean is_baseline, boolean is_prog, boolean is_arith) /* Process a SOFn marker */ { INT32 length; int c, ci, i; jpeg_component_info * compptr; INPUT_VARS(cinfo); cinfo->is_baseline = is_baseline; cinfo->progressive_mode = is_prog; cinfo->arith_code = is_arith; INPUT_2BYTES(cinfo, length, return FALSE); INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE); INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE); INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE); INPUT_BYTE(cinfo, cinfo->num_components, return FALSE); length -= 8; TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker, (int) cinfo->image_width, (int) cinfo->image_height, cinfo->num_components); if (cinfo->marker->saw_SOF) ERREXIT(cinfo, JERR_SOF_DUPLICATE); /* We don't support files in which the image height is initially specified */ /* as 0 and is later redefined by DNL. As long as we have to check that, */ /* might as well have a general sanity check. */ if (cinfo->image_height <= 0 || cinfo->image_width <= 0 || cinfo->num_components <= 0) ERREXIT(cinfo, JERR_EMPTY_IMAGE); if (length != (cinfo->num_components * 3)) ERREXIT(cinfo, JERR_BAD_LENGTH); if (cinfo->comp_info == NULL) /* do only once, even if suspend */ cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->num_components * SIZEOF(jpeg_component_info)); for (ci = 0; ci < cinfo->num_components; ci++) { INPUT_BYTE(cinfo, c, return FALSE); /* Check to see whether component id has already been seen */ /* (in violation of the spec, but unfortunately seen in some */ /* files). If so, create "fake" component id equal to the */ /* max id seen so far + 1. */ for (i = 0, compptr = cinfo->comp_info; i < ci; i++, compptr++) { if (c == compptr->component_id) { compptr = cinfo->comp_info; c = compptr->component_id; compptr++; for (i = 1; i < ci; i++, compptr++) { if (compptr->component_id > c) c = compptr->component_id; } c++; break; } } compptr->component_id = c; compptr->component_index = ci; INPUT_BYTE(cinfo, c, return FALSE); compptr->h_samp_factor = (c >> 4) & 15; compptr->v_samp_factor = (c ) & 15; INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE); TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT, compptr->component_id, compptr->h_samp_factor, compptr->v_samp_factor, compptr->quant_tbl_no); } cinfo->marker->saw_SOF = TRUE; INPUT_SYNC(cinfo); return TRUE; } LOCAL(boolean) get_sos (j_decompress_ptr cinfo) /* Process a SOS marker */ { INT32 length; int c, ci, i, n; jpeg_component_info * compptr; INPUT_VARS(cinfo); if (! cinfo->marker->saw_SOF) ERREXITS(cinfo, JERR_SOF_BEFORE, "SOS"); INPUT_2BYTES(cinfo, length, return FALSE); INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */ TRACEMS1(cinfo, 1, JTRC_SOS, n); if (length != (n * 2 + 6) || n > MAX_COMPS_IN_SCAN || (n == 0 && !cinfo->progressive_mode)) /* pseudo SOS marker only allowed in progressive mode */ ERREXIT(cinfo, JERR_BAD_LENGTH); cinfo->comps_in_scan = n; /* Collect the component-spec parameters */ for (i = 0; i < n; i++) { INPUT_BYTE(cinfo, c, return FALSE); /* Detect the case where component id's are not unique, and, if so, */ /* create a fake component id using the same logic as in get_sof. */ /* Note: This also ensures that all of the SOF components are */ /* referenced in the single scan case, which prevents access to */ /* uninitialized memory in later decoding stages. */ for (ci = 0; ci < i; ci++) { if (c == cinfo->cur_comp_info[ci]->component_id) { c = cinfo->cur_comp_info[0]->component_id; for (ci = 1; ci < i; ci++) { compptr = cinfo->cur_comp_info[ci]; if (compptr->component_id > c) c = compptr->component_id; } c++; break; } } for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (c == compptr->component_id) goto id_found; } ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, c); id_found: cinfo->cur_comp_info[i] = compptr; INPUT_BYTE(cinfo, c, return FALSE); compptr->dc_tbl_no = (c >> 4) & 15; compptr->ac_tbl_no = (c ) & 15; TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, compptr->component_id, compptr->dc_tbl_no, compptr->ac_tbl_no); } /* Collect the additional scan parameters Ss, Se, Ah/Al. */ INPUT_BYTE(cinfo, c, return FALSE); cinfo->Ss = c; INPUT_BYTE(cinfo, c, return FALSE); cinfo->Se = c; INPUT_BYTE(cinfo, c, return FALSE); cinfo->Ah = (c >> 4) & 15; cinfo->Al = (c ) & 15; TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al); /* Prepare to scan data & restart markers */ cinfo->marker->next_restart_num = 0; /* Count another (non-pseudo) SOS marker */ if (n) cinfo->input_scan_number++; INPUT_SYNC(cinfo); return TRUE; } #ifdef D_ARITH_CODING_SUPPORTED LOCAL(boolean) get_dac (j_decompress_ptr cinfo) /* Process a DAC marker */ { INT32 length; int index, val; INPUT_VARS(cinfo); INPUT_2BYTES(cinfo, length, return FALSE); length -= 2; while (length > 0) { INPUT_BYTE(cinfo, index, return FALSE); INPUT_BYTE(cinfo, val, return FALSE); length -= 2; TRACEMS2(cinfo, 1, JTRC_DAC, index, val); if (index < 0 || index >= (2*NUM_ARITH_TBLS)) ERREXIT1(cinfo, JERR_DAC_INDEX, index); if (index >= NUM_ARITH_TBLS) { /* define AC table */ cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val; } else { /* define DC table */ cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F); cinfo->arith_dc_U[index] = (UINT8) (val >> 4); if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index]) ERREXIT1(cinfo, JERR_DAC_VALUE, val); } } if (length != 0) ERREXIT(cinfo, JERR_BAD_LENGTH); INPUT_SYNC(cinfo); return TRUE; } #else /* ! D_ARITH_CODING_SUPPORTED */ #define get_dac(cinfo) skip_variable(cinfo) #endif /* D_ARITH_CODING_SUPPORTED */ LOCAL(boolean) get_dht (j_decompress_ptr cinfo) /* Process a DHT marker */ { INT32 length; UINT8 bits[17]; UINT8 huffval[256]; int i, index, count; JHUFF_TBL **htblptr; INPUT_VARS(cinfo); INPUT_2BYTES(cinfo, length, return FALSE); length -= 2; while (length > 16) { INPUT_BYTE(cinfo, index, return FALSE); TRACEMS1(cinfo, 1, JTRC_DHT, index); bits[0] = 0; count = 0; for (i = 1; i <= 16; i++) { INPUT_BYTE(cinfo, bits[i], return FALSE); count += bits[i]; } length -= 1 + 16; TRACEMS8(cinfo, 2, JTRC_HUFFBITS, bits[1], bits[2], bits[3], bits[4], bits[5], bits[6], bits[7], bits[8]); TRACEMS8(cinfo, 2, JTRC_HUFFBITS, bits[9], bits[10], bits[11], bits[12], bits[13], bits[14], bits[15], bits[16]); /* Here we just do minimal validation of the counts to avoid walking * off the end of our table space. jdhuff.c will check more carefully. */ if (count > 256 || ((INT32) count) > length) ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); MEMZERO(huffval, SIZEOF(huffval)); /* pre-zero array for later copy */ for (i = 0; i < count; i++) INPUT_BYTE(cinfo, huffval[i], return FALSE); length -= count; if (index & 0x10) { /* AC table definition */ index -= 0x10; htblptr = &cinfo->ac_huff_tbl_ptrs[index]; } else { /* DC table definition */ htblptr = &cinfo->dc_huff_tbl_ptrs[index]; } if (index < 0 || index >= NUM_HUFF_TBLS) ERREXIT1(cinfo, JERR_DHT_INDEX, index); if (*htblptr == NULL) *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits)); MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval)); } if (length != 0) ERREXIT(cinfo, JERR_BAD_LENGTH); INPUT_SYNC(cinfo); return TRUE; } LOCAL(boolean) get_dqt (j_decompress_ptr cinfo) /* Process a DQT marker */ { INT32 length, count, i; int n, prec; unsigned int tmp; JQUANT_TBL *quant_ptr; const int *natural_order; INPUT_VARS(cinfo); INPUT_2BYTES(cinfo, length, return FALSE); length -= 2; while (length > 0) { length--; INPUT_BYTE(cinfo, n, return FALSE); prec = n >> 4; n &= 0x0F; TRACEMS2(cinfo, 1, JTRC_DQT, n, prec); if (n >= NUM_QUANT_TBLS) ERREXIT1(cinfo, JERR_DQT_INDEX, n); if (cinfo->quant_tbl_ptrs[n] == NULL) cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo); quant_ptr = cinfo->quant_tbl_ptrs[n]; if (prec) { if (length < DCTSIZE2 * 2) { /* Initialize full table for safety. */ for (i = 0; i < DCTSIZE2; i++) { quant_ptr->quantval[i] = 1; } count = length >> 1; } else count = DCTSIZE2; } else { if (length < DCTSIZE2) { /* Initialize full table for safety. */ for (i = 0; i < DCTSIZE2; i++) { quant_ptr->quantval[i] = 1; } count = length; } else count = DCTSIZE2; } switch (count) { case (2*2): natural_order = jpeg_natural_order2; break; case (3*3): natural_order = jpeg_natural_order3; break; case (4*4): natural_order = jpeg_natural_order4; break; case (5*5): natural_order = jpeg_natural_order5; break; case (6*6): natural_order = jpeg_natural_order6; break; case (7*7): natural_order = jpeg_natural_order7; break; default: natural_order = jpeg_natural_order; break; } for (i = 0; i < count; i++) { if (prec) INPUT_2BYTES(cinfo, tmp, return FALSE); else INPUT_BYTE(cinfo, tmp, return FALSE); /* We convert the zigzag-order table to natural array order. */ quant_ptr->quantval[natural_order[i]] = (UINT16) tmp; } if (cinfo->err->trace_level >= 2) { for (i = 0; i < DCTSIZE2; i += 8) { TRACEMS8(cinfo, 2, JTRC_QUANTVALS, quant_ptr->quantval[i], quant_ptr->quantval[i+1], quant_ptr->quantval[i+2], quant_ptr->quantval[i+3], quant_ptr->quantval[i+4], quant_ptr->quantval[i+5], quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]); } } length -= count; if (prec) length -= count; } if (length != 0) ERREXIT(cinfo, JERR_BAD_LENGTH); INPUT_SYNC(cinfo); return TRUE; } LOCAL(boolean) get_dri (j_decompress_ptr cinfo) /* Process a DRI marker */ { INT32 length; unsigned int tmp; INPUT_VARS(cinfo); INPUT_2BYTES(cinfo, length, return FALSE); if (length != 4) ERREXIT(cinfo, JERR_BAD_LENGTH); INPUT_2BYTES(cinfo, tmp, return FALSE); TRACEMS1(cinfo, 1, JTRC_DRI, tmp); cinfo->restart_interval = tmp; INPUT_SYNC(cinfo); return TRUE; } LOCAL(boolean) get_lse (j_decompress_ptr cinfo) /* Process an LSE marker */ { INT32 length; unsigned int tmp; int cid; INPUT_VARS(cinfo); if (! cinfo->marker->saw_SOF) ERREXITS(cinfo, JERR_SOF_BEFORE, "LSE"); if (cinfo->num_components < 3) goto bad; INPUT_2BYTES(cinfo, length, return FALSE); if (length != 24) ERREXIT(cinfo, JERR_BAD_LENGTH); INPUT_BYTE(cinfo, tmp, return FALSE); if (tmp != 0x0D) /* ID inverse transform specification */ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker); INPUT_2BYTES(cinfo, tmp, return FALSE); if (tmp != MAXJSAMPLE) goto bad; /* MAXTRANS */ INPUT_BYTE(cinfo, tmp, return FALSE); if (tmp != 3) goto bad; /* Nt=3 */ INPUT_BYTE(cinfo, cid, return FALSE); if (cid != cinfo->comp_info[1].component_id) goto bad; INPUT_BYTE(cinfo, cid, return FALSE); if (cid != cinfo->comp_info[0].component_id) goto bad; INPUT_BYTE(cinfo, cid, return FALSE); if (cid != cinfo->comp_info[2].component_id) goto bad; INPUT_BYTE(cinfo, tmp, return FALSE); if (tmp != 0x80) goto bad; /* F1: CENTER1=1, NORM1=0 */ INPUT_2BYTES(cinfo, tmp, return FALSE); if (tmp != 0) goto bad; /* A(1,1)=0 */ INPUT_2BYTES(cinfo, tmp, return FALSE); if (tmp != 0) goto bad; /* A(1,2)=0 */ INPUT_BYTE(cinfo, tmp, return FALSE); if (tmp != 0) goto bad; /* F2: CENTER2=0, NORM2=0 */ INPUT_2BYTES(cinfo, tmp, return FALSE); if (tmp != 1) goto bad; /* A(2,1)=1 */ INPUT_2BYTES(cinfo, tmp, return FALSE); if (tmp != 0) goto bad; /* A(2,2)=0 */ INPUT_BYTE(cinfo, tmp, return FALSE); if (tmp != 0) goto bad; /* F3: CENTER3=0, NORM3=0 */ INPUT_2BYTES(cinfo, tmp, return FALSE); if (tmp != 1) goto bad; /* A(3,1)=1 */ INPUT_2BYTES(cinfo, tmp, return FALSE); if (tmp != 0) { /* A(3,2)=0 */ bad: ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); } /* OK, valid transform that we can handle. */ cinfo->color_transform = JCT_SUBTRACT_GREEN; INPUT_SYNC(cinfo); return TRUE; } /* * Routines for processing APPn and COM markers. * These are either saved in memory or discarded, per application request. * APP0 and APP14 are specially checked to see if they are * JFIF and Adobe markers, respectively. */ #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */ #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */ #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */ LOCAL(void) examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data, unsigned int datalen, INT32 remaining) /* Examine first few bytes from an APP0. * Take appropriate action if it is a JFIF marker. * datalen is # of bytes at data[], remaining is length of rest of marker data. */ { INT32 totallen = (INT32) datalen + remaining; if (datalen >= APP0_DATA_LEN && GETJOCTET(data[0]) == 0x4A && GETJOCTET(data[1]) == 0x46 && GETJOCTET(data[2]) == 0x49 && GETJOCTET(data[3]) == 0x46 && GETJOCTET(data[4]) == 0) { /* Found JFIF APP0 marker: save info */ cinfo->saw_JFIF_marker = TRUE; cinfo->JFIF_major_version = GETJOCTET(data[5]); cinfo->JFIF_minor_version = GETJOCTET(data[6]); cinfo->density_unit = GETJOCTET(data[7]); cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]); cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]); /* Check version. * Major version must be 1 or 2, anything else signals an incompatible * change. * (We used to treat this as an error, but now it's a nonfatal warning, * because some bozo at Hijaak couldn't read the spec.) * Minor version should be 0..2, but process anyway if newer. */ if (cinfo->JFIF_major_version != 1 && cinfo->JFIF_major_version != 2) WARNMS2(cinfo, JWRN_JFIF_MAJOR, cinfo->JFIF_major_version, cinfo->JFIF_minor_version); /* Generate trace messages */ TRACEMS5(cinfo, 1, JTRC_JFIF, cinfo->JFIF_major_version, cinfo->JFIF_minor_version, cinfo->X_density, cinfo->Y_density, cinfo->density_unit); /* Validate thumbnail dimensions and issue appropriate messages */ if (GETJOCTET(data[12]) | GETJOCTET(data[13])) TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, GETJOCTET(data[12]), GETJOCTET(data[13])); totallen -= APP0_DATA_LEN; if (totallen != ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3)) TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen); } else if (datalen >= 6 && GETJOCTET(data[0]) == 0x4A && GETJOCTET(data[1]) == 0x46 && GETJOCTET(data[2]) == 0x58 && GETJOCTET(data[3]) == 0x58 && GETJOCTET(data[4]) == 0) { /* Found JFIF "JFXX" extension APP0 marker */ /* The library doesn't actually do anything with these, * but we try to produce a helpful trace message. */ switch (GETJOCTET(data[5])) { case 0x10: TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen); break; case 0x11: TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen); break; case 0x13: TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen); break; default: TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION, GETJOCTET(data[5]), (int) totallen); break; } } else { /* Start of APP0 does not match "JFIF" or "JFXX", or too short */ TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen); } } LOCAL(void) examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data, unsigned int datalen, INT32 remaining) /* Examine first few bytes from an APP14. * Take appropriate action if it is an Adobe marker. * datalen is # of bytes at data[], remaining is length of rest of marker data. */ { unsigned int version, flags0, flags1, transform; if (datalen >= APP14_DATA_LEN && GETJOCTET(data[0]) == 0x41 && GETJOCTET(data[1]) == 0x64 && GETJOCTET(data[2]) == 0x6F && GETJOCTET(data[3]) == 0x62 && GETJOCTET(data[4]) == 0x65) { /* Found Adobe APP14 marker */ version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]); flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]); flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]); transform = GETJOCTET(data[11]); TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform); cinfo->saw_Adobe_marker = TRUE; cinfo->Adobe_transform = (UINT8) transform; } else { /* Start of APP14 does not match "Adobe", or too short */ TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining)); } } METHODDEF(boolean) get_interesting_appn (j_decompress_ptr cinfo) /* Process an APP0 or APP14 marker without saving it */ { INT32 length; JOCTET b[APPN_DATA_LEN]; unsigned int i, numtoread; INPUT_VARS(cinfo); INPUT_2BYTES(cinfo, length, return FALSE); length -= 2; /* get the interesting part of the marker data */ if (length >= APPN_DATA_LEN) numtoread = APPN_DATA_LEN; else if (length > 0) numtoread = (unsigned int) length; else numtoread = 0; for (i = 0; i < numtoread; i++) INPUT_BYTE(cinfo, b[i], return FALSE); length -= numtoread; /* process it */ switch (cinfo->unread_marker) { case M_APP0: examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length); break; case M_APP14: examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length); break; default: /* can't get here unless jpeg_save_markers chooses wrong processor */ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker); break; } /* skip any remaining data -- could be lots */ INPUT_SYNC(cinfo); if (length > 0) (*cinfo->src->skip_input_data) (cinfo, (long) length); return TRUE; } #ifdef SAVE_MARKERS_SUPPORTED METHODDEF(boolean) save_marker (j_decompress_ptr cinfo) /* Save an APPn or COM marker into the marker list */ { my_marker_ptr marker = (my_marker_ptr) cinfo->marker; jpeg_saved_marker_ptr cur_marker = marker->cur_marker; unsigned int bytes_read, data_length; JOCTET FAR * data; INT32 length = 0; INPUT_VARS(cinfo); if (cur_marker == NULL) { /* begin reading a marker */ INPUT_2BYTES(cinfo, length, return FALSE); length -= 2; if (length >= 0) { /* watch out for bogus length word */ /* figure out how much we want to save */ unsigned int limit; if (cinfo->unread_marker == (int) M_COM) limit = marker->length_limit_COM; else limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0]; if ((unsigned int) length < limit) limit = (unsigned int) length; /* allocate and initialize the marker item */ cur_marker = (jpeg_saved_marker_ptr) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(struct jpeg_marker_struct) + limit); cur_marker->next = NULL; cur_marker->marker = (UINT8) cinfo->unread_marker; cur_marker->original_length = (unsigned int) length; cur_marker->data_length = limit; /* data area is just beyond the jpeg_marker_struct */ data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1); marker->cur_marker = cur_marker; marker->bytes_read = 0; bytes_read = 0; data_length = limit; } else { /* deal with bogus length word */ bytes_read = data_length = 0; data = NULL; } } else { /* resume reading a marker */ bytes_read = marker->bytes_read; data_length = cur_marker->data_length; data = cur_marker->data + bytes_read; } while (bytes_read < data_length) { INPUT_SYNC(cinfo); /* move the restart point to here */ marker->bytes_read = bytes_read; /* If there's not at least one byte in buffer, suspend */ MAKE_BYTE_AVAIL(cinfo, return FALSE); /* Copy bytes with reasonable rapidity */ while (bytes_read < data_length && bytes_in_buffer > 0) { *data++ = *next_input_byte++; bytes_in_buffer--; bytes_read++; } } /* Done reading what we want to read */ if (cur_marker != NULL) { /* will be NULL if bogus length word */ /* Add new marker to end of list */ if (cinfo->marker_list == NULL) { cinfo->marker_list = cur_marker; } else { jpeg_saved_marker_ptr prev = cinfo->marker_list; while (prev->next != NULL) prev = prev->next; prev->next = cur_marker; } /* Reset pointer & calc remaining data length */ data = cur_marker->data; length = cur_marker->original_length - data_length; } /* Reset to initial state for next marker */ marker->cur_marker = NULL; /* Process the marker if interesting; else just make a generic trace msg */ switch (cinfo->unread_marker) { case M_APP0: examine_app0(cinfo, data, data_length, length); break; case M_APP14: examine_app14(cinfo, data, data_length, length); break; default: TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) (data_length + length)); break; } /* skip any remaining data -- could be lots */ INPUT_SYNC(cinfo); /* do before skip_input_data */ if (length > 0) (*cinfo->src->skip_input_data) (cinfo, (long) length); return TRUE; } #endif /* SAVE_MARKERS_SUPPORTED */ METHODDEF(boolean) skip_variable (j_decompress_ptr cinfo) /* Skip over an unknown or uninteresting variable-length marker */ { INT32 length; INPUT_VARS(cinfo); INPUT_2BYTES(cinfo, length, return FALSE); length -= 2; TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length); INPUT_SYNC(cinfo); /* do before skip_input_data */ if (length > 0) (*cinfo->src->skip_input_data) (cinfo, (long) length); return TRUE; } /* * Find the next JPEG marker, save it in cinfo->unread_marker. * Returns FALSE if had to suspend before reaching a marker; * in that case cinfo->unread_marker is unchanged. * * Note that the result might not be a valid marker code, * but it will never be 0 or FF. */ LOCAL(boolean) next_marker (j_decompress_ptr cinfo) { int c; INPUT_VARS(cinfo); for (;;) { INPUT_BYTE(cinfo, c, return FALSE); /* Skip any non-FF bytes. * This may look a bit inefficient, but it will not occur in a valid file. * We sync after each discarded byte so that a suspending data source * can discard the byte from its buffer. */ while (c != 0xFF) { cinfo->marker->discarded_bytes++; INPUT_SYNC(cinfo); INPUT_BYTE(cinfo, c, return FALSE); } /* This loop swallows any duplicate FF bytes. Extra FFs are legal as * pad bytes, so don't count them in discarded_bytes. We assume there * will not be so many consecutive FF bytes as to overflow a suspending * data source's input buffer. */ do { INPUT_BYTE(cinfo, c, return FALSE); } while (c == 0xFF); if (c != 0) break; /* found a valid marker, exit loop */ /* Reach here if we found a stuffed-zero data sequence (FF/00). * Discard it and loop back to try again. */ cinfo->marker->discarded_bytes += 2; INPUT_SYNC(cinfo); } if (cinfo->marker->discarded_bytes != 0) { WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c); cinfo->marker->discarded_bytes = 0; } cinfo->unread_marker = c; INPUT_SYNC(cinfo); return TRUE; } LOCAL(boolean) first_marker (j_decompress_ptr cinfo) /* Like next_marker, but used to obtain the initial SOI marker. */ /* For this marker, we do not allow preceding garbage or fill; otherwise, * we might well scan an entire input file before realizing it ain't JPEG. * If an application wants to process non-JFIF files, it must seek to the * SOI before calling the JPEG library. */ { int c, c2; INPUT_VARS(cinfo); INPUT_BYTE(cinfo, c, return FALSE); INPUT_BYTE(cinfo, c2, return FALSE); if (c != 0xFF || c2 != (int) M_SOI) ERREXIT2(cinfo, JERR_NO_SOI, c, c2); cinfo->unread_marker = c2; INPUT_SYNC(cinfo); return TRUE; } /* * Read markers until SOS or EOI. * * Returns same codes as are defined for jpeg_consume_input: * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. * * Note: This function may return a pseudo SOS marker (with zero * component number) for treat by input controller's consume_input. * consume_input itself should filter out (skip) the pseudo marker * after processing for the caller. */ METHODDEF(int) read_markers (j_decompress_ptr cinfo) { /* Outer loop repeats once for each marker. */ for (;;) { /* Collect the marker proper, unless we already did. */ /* NB: first_marker() enforces the requirement that SOI appear first. */ if (cinfo->unread_marker == 0) { if (! cinfo->marker->saw_SOI) { if (! first_marker(cinfo)) return JPEG_SUSPENDED; } else { if (! next_marker(cinfo)) return JPEG_SUSPENDED; } } /* At this point cinfo->unread_marker contains the marker code and the * input point is just past the marker proper, but before any parameters. * A suspension will cause us to return with this state still true. */ switch (cinfo->unread_marker) { case M_SOI: if (! get_soi(cinfo)) return JPEG_SUSPENDED; break; case M_SOF0: /* Baseline */ if (! get_sof(cinfo, TRUE, FALSE, FALSE)) return JPEG_SUSPENDED; break; case M_SOF1: /* Extended sequential, Huffman */ if (! get_sof(cinfo, FALSE, FALSE, FALSE)) return JPEG_SUSPENDED; break; case M_SOF2: /* Progressive, Huffman */ if (! get_sof(cinfo, FALSE, TRUE, FALSE)) return JPEG_SUSPENDED; break; case M_SOF9: /* Extended sequential, arithmetic */ if (! get_sof(cinfo, FALSE, FALSE, TRUE)) return JPEG_SUSPENDED; break; case M_SOF10: /* Progressive, arithmetic */ if (! get_sof(cinfo, FALSE, TRUE, TRUE)) return JPEG_SUSPENDED; break; /* Currently unsupported SOFn types */ case M_SOF3: /* Lossless, Huffman */ case M_SOF5: /* Differential sequential, Huffman */ case M_SOF6: /* Differential progressive, Huffman */ case M_SOF7: /* Differential lossless, Huffman */ case M_JPG: /* Reserved for JPEG extensions */ case M_SOF11: /* Lossless, arithmetic */ case M_SOF13: /* Differential sequential, arithmetic */ case M_SOF14: /* Differential progressive, arithmetic */ case M_SOF15: /* Differential lossless, arithmetic */ ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker); break; case M_SOS: if (! get_sos(cinfo)) return JPEG_SUSPENDED; cinfo->unread_marker = 0; /* processed the marker */ return JPEG_REACHED_SOS; case M_EOI: TRACEMS(cinfo, 1, JTRC_EOI); cinfo->unread_marker = 0; /* processed the marker */ return JPEG_REACHED_EOI; case M_DAC: if (! get_dac(cinfo)) return JPEG_SUSPENDED; break; case M_DHT: if (! get_dht(cinfo)) return JPEG_SUSPENDED; break; case M_DQT: if (! get_dqt(cinfo)) return JPEG_SUSPENDED; break; case M_DRI: if (! get_dri(cinfo)) return JPEG_SUSPENDED; break; case M_JPG8: if (! get_lse(cinfo)) return JPEG_SUSPENDED; break; case M_APP0: case M_APP1: case M_APP2: case M_APP3: case M_APP4: case M_APP5: case M_APP6: case M_APP7: case M_APP8: case M_APP9: case M_APP10: case M_APP11: case M_APP12: case M_APP13: case M_APP14: case M_APP15: if (! (*((my_marker_ptr) cinfo->marker)->process_APPn[ cinfo->unread_marker - (int) M_APP0]) (cinfo)) return JPEG_SUSPENDED; break; case M_COM: if (! (*((my_marker_ptr) cinfo->marker)->process_COM) (cinfo)) return JPEG_SUSPENDED; break; case M_RST0: /* these are all parameterless */ case M_RST1: case M_RST2: case M_RST3: case M_RST4: case M_RST5: case M_RST6: case M_RST7: case M_TEM: TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker); break; case M_DNL: /* Ignore DNL ... perhaps the wrong thing */ if (! skip_variable(cinfo)) return JPEG_SUSPENDED; break; default: /* must be DHP, EXP, JPGn, or RESn */ /* For now, we treat the reserved markers as fatal errors since they are * likely to be used to signal incompatible JPEG Part 3 extensions. * Once the JPEG 3 version-number marker is well defined, this code * ought to change! */ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker); break; } /* Successfully processed marker, so reset state variable */ cinfo->unread_marker = 0; } /* end loop */ } /* * Read a restart marker, which is expected to appear next in the datastream; * if the marker is not there, take appropriate recovery action. * Returns FALSE if suspension is required. * * This is called by the entropy decoder after it has read an appropriate * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder * has already read a marker from the data source. Under normal conditions * cinfo->unread_marker will be reset to 0 before returning; if not reset, * it holds a marker which the decoder will be unable to read past. */ METHODDEF(boolean) read_restart_marker (j_decompress_ptr cinfo) { /* Obtain a marker unless we already did. */ /* Note that next_marker will complain if it skips any data. */ if (cinfo->unread_marker == 0) { if (! next_marker(cinfo)) return FALSE; } if (cinfo->unread_marker == ((int) M_RST0 + cinfo->marker->next_restart_num)) { /* Normal case --- swallow the marker and let entropy decoder continue */ TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num); cinfo->unread_marker = 0; } else { /* Uh-oh, the restart markers have been messed up. */ /* Let the data source manager determine how to resync. */ if (! (*cinfo->src->resync_to_restart) (cinfo, cinfo->marker->next_restart_num)) return FALSE; } /* Update next-restart state */ cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7; return TRUE; } /* * This is the default resync_to_restart method for data source managers * to use if they don't have any better approach. Some data source managers * may be able to back up, or may have additional knowledge about the data * which permits a more intelligent recovery strategy; such managers would * presumably supply their own resync method. * * read_restart_marker calls resync_to_restart if it finds a marker other than * the restart marker it was expecting. (This code is *not* used unless * a nonzero restart interval has been declared.) cinfo->unread_marker is * the marker code actually found (might be anything, except 0 or FF). * The desired restart marker number (0..7) is passed as a parameter. * This routine is supposed to apply whatever error recovery strategy seems * appropriate in order to position the input stream to the next data segment. * Note that cinfo->unread_marker is treated as a marker appearing before * the current data-source input point; usually it should be reset to zero * before returning. * Returns FALSE if suspension is required. * * This implementation is substantially constrained by wanting to treat the * input as a data stream; this means we can't back up. Therefore, we have * only the following actions to work with: * 1. Simply discard the marker and let the entropy decoder resume at next * byte of file. * 2. Read forward until we find another marker, discarding intervening * data. (In theory we could look ahead within the current bufferload, * without having to discard data if we don't find the desired marker. * This idea is not implemented here, in part because it makes behavior * dependent on buffer size and chance buffer-boundary positions.) * 3. Leave the marker unread (by failing to zero cinfo->unread_marker). * This will cause the entropy decoder to process an empty data segment, * inserting dummy zeroes, and then we will reprocess the marker. * * #2 is appropriate if we think the desired marker lies ahead, while #3 is * appropriate if the found marker is a future restart marker (indicating * that we have missed the desired restart marker, probably because it got * corrupted). * We apply #2 or #3 if the found marker is a restart marker no more than * two counts behind or ahead of the expected one. We also apply #2 if the * found marker is not a legal JPEG marker code (it's certainly bogus data). * If the found marker is a restart marker more than 2 counts away, we do #1 * (too much risk that the marker is erroneous; with luck we will be able to * resync at some future point). * For any valid non-restart JPEG marker, we apply #3. This keeps us from * overrunning the end of a scan. An implementation limited to single-scan * files might find it better to apply #2 for markers other than EOI, since * any other marker would have to be bogus data in that case. */ GLOBAL(boolean) jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired) { int marker = cinfo->unread_marker; int action = 1; /* Always put up a warning. */ WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired); /* Outer loop handles repeated decision after scanning forward. */ for (;;) { if (marker < (int) M_SOF0) action = 2; /* invalid marker */ else if (marker < (int) M_RST0 || marker > (int) M_RST7) action = 3; /* valid non-restart marker */ else { if (marker == ((int) M_RST0 + ((desired+1) & 7)) || marker == ((int) M_RST0 + ((desired+2) & 7))) action = 3; /* one of the next two expected restarts */ else if (marker == ((int) M_RST0 + ((desired-1) & 7)) || marker == ((int) M_RST0 + ((desired-2) & 7))) action = 2; /* a prior restart, so advance */ else action = 1; /* desired restart or too far away */ } TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action); switch (action) { case 1: /* Discard marker and let entropy decoder resume processing. */ cinfo->unread_marker = 0; return TRUE; case 2: /* Scan to the next marker, and repeat the decision loop. */ if (! next_marker(cinfo)) return FALSE; marker = cinfo->unread_marker; break; case 3: /* Return without advancing past this marker. */ /* Entropy decoder will be forced to process an empty segment. */ return TRUE; } } /* end loop */ } /* * Reset marker processing state to begin a fresh datastream. */ METHODDEF(void) reset_marker_reader (j_decompress_ptr cinfo) { my_marker_ptr marker = (my_marker_ptr) cinfo->marker; cinfo->comp_info = NULL; /* until allocated by get_sof */ cinfo->input_scan_number = 0; /* no SOS seen yet */ cinfo->unread_marker = 0; /* no pending marker */ marker->pub.saw_SOI = FALSE; /* set internal state too */ marker->pub.saw_SOF = FALSE; marker->pub.discarded_bytes = 0; marker->cur_marker = NULL; } /* * Initialize the marker reader module. * This is called only once, when the decompression object is created. */ GLOBAL(void) jinit_marker_reader (j_decompress_ptr cinfo) { my_marker_ptr marker; int i; /* Create subobject in permanent pool */ marker = (my_marker_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_marker_reader)); cinfo->marker = &marker->pub; /* Initialize public method pointers */ marker->pub.reset_marker_reader = reset_marker_reader; marker->pub.read_markers = read_markers; marker->pub.read_restart_marker = read_restart_marker; /* Initialize COM/APPn processing. * By default, we examine and then discard APP0 and APP14, * but simply discard COM and all other APPn. */ marker->process_COM = skip_variable; marker->length_limit_COM = 0; for (i = 0; i < 16; i++) { marker->process_APPn[i] = skip_variable; marker->length_limit_APPn[i] = 0; } marker->process_APPn[0] = get_interesting_appn; marker->process_APPn[14] = get_interesting_appn; /* Reset marker processing state */ reset_marker_reader(cinfo); } /* * Control saving of COM and APPn markers into marker_list. */ #ifdef SAVE_MARKERS_SUPPORTED GLOBAL(void) jpeg_save_markers (j_decompress_ptr cinfo, int marker_code, unsigned int length_limit) { my_marker_ptr marker = (my_marker_ptr) cinfo->marker; long maxlength; jpeg_marker_parser_method processor; /* Length limit mustn't be larger than what we can allocate * (should only be a concern in a 16-bit environment). */ maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct); if (((long) length_limit) > maxlength) length_limit = (unsigned int) maxlength; /* Choose processor routine to use. * APP0/APP14 have special requirements. */ if (length_limit) { processor = save_marker; /* If saving APP0/APP14, save at least enough for our internal use. */ if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN) length_limit = APP0_DATA_LEN; else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN) length_limit = APP14_DATA_LEN; } else { processor = skip_variable; /* If discarding APP0/APP14, use our regular on-the-fly processor. */ if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14) processor = get_interesting_appn; } if (marker_code == (int) M_COM) { marker->process_COM = processor; marker->length_limit_COM = length_limit; } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) { marker->process_APPn[marker_code - (int) M_APP0] = processor; marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit; } else ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code); } #endif /* SAVE_MARKERS_SUPPORTED */ /* * Install a special processing method for COM or APPn markers. */ GLOBAL(void) jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code, jpeg_marker_parser_method routine) { my_marker_ptr marker = (my_marker_ptr) cinfo->marker; if (marker_code == (int) M_COM) marker->process_COM = routine; else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) marker->process_APPn[marker_code - (int) M_APP0] = routine; else ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code); } ================================================ FILE: tess-two/jni/libjpeg/jdmaster.c ================================================ /* * jdmaster.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2002-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains master control logic for the JPEG decompressor. * These routines are concerned with selecting the modules to be executed * and with determining the number of passes and the work to be done in each * pass. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Private state */ typedef struct { struct jpeg_decomp_master pub; /* public fields */ int pass_number; /* # of passes completed */ boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */ /* Saved references to initialized quantizer modules, * in case we need to switch modes. */ struct jpeg_color_quantizer * quantizer_1pass; struct jpeg_color_quantizer * quantizer_2pass; } my_decomp_master; typedef my_decomp_master * my_master_ptr; /* * Determine whether merged upsample/color conversion should be used. * CRUCIAL: this must match the actual capabilities of jdmerge.c! */ LOCAL(boolean) use_merged_upsample (j_decompress_ptr cinfo) { #ifdef UPSAMPLE_MERGING_SUPPORTED /* Merging is the equivalent of plain box-filter upsampling. */ /* The following condition is only needed if fancy shall select * a different upsampling method. In our current implementation * fancy only affects the DCT scaling, thus we can use fancy * upsampling and merged upsample simultaneously, in particular * with scaled DCT sizes larger than the default DCTSIZE. */ #if 0 if (cinfo->do_fancy_upsampling) return FALSE; #endif if (cinfo->CCIR601_sampling) return FALSE; /* jdmerge.c only supports YCC=>RGB color conversion */ if ((cinfo->jpeg_color_space != JCS_YCbCr && cinfo->jpeg_color_space != JCS_BG_YCC) || cinfo->num_components != 3 || cinfo->out_color_space != JCS_RGB || cinfo->out_color_components != RGB_PIXELSIZE || cinfo->color_transform) return FALSE; /* and it only handles 2h1v or 2h2v sampling ratios */ if (cinfo->comp_info[0].h_samp_factor != 2 || cinfo->comp_info[1].h_samp_factor != 1 || cinfo->comp_info[2].h_samp_factor != 1 || cinfo->comp_info[0].v_samp_factor > 2 || cinfo->comp_info[1].v_samp_factor != 1 || cinfo->comp_info[2].v_samp_factor != 1) return FALSE; /* furthermore, it doesn't work if we've scaled the IDCTs differently */ if (cinfo->comp_info[0].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size || cinfo->comp_info[1].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size || cinfo->comp_info[2].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size || cinfo->comp_info[0].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size || cinfo->comp_info[1].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size || cinfo->comp_info[2].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size) return FALSE; /* ??? also need to test for upsample-time rescaling, when & if supported */ return TRUE; /* by golly, it'll work... */ #else return FALSE; #endif } /* * Compute output image dimensions and related values. * NOTE: this is exported for possible use by application. * Hence it mustn't do anything that can't be done twice. * Also note that it may be called before the master module is initialized! */ GLOBAL(void) jpeg_calc_output_dimensions (j_decompress_ptr cinfo) /* Do computations that are needed before master selection phase. * This function is used for full decompression. */ { #ifdef IDCT_SCALING_SUPPORTED int ci; jpeg_component_info *compptr; #endif /* Prevent application from calling me at wrong times */ if (cinfo->global_state != DSTATE_READY) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Compute core output image dimensions and DCT scaling choices. */ jpeg_core_output_dimensions(cinfo); #ifdef IDCT_SCALING_SUPPORTED /* In selecting the actual DCT scaling for each component, we try to * scale up the chroma components via IDCT scaling rather than upsampling. * This saves time if the upsampler gets to use 1:1 scaling. * Note this code adapts subsampling ratios which are powers of 2. */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { int ssize = 1; while (cinfo->min_DCT_h_scaled_size * ssize <= (cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) && (cinfo->max_h_samp_factor % (compptr->h_samp_factor * ssize * 2)) == 0) { ssize = ssize * 2; } compptr->DCT_h_scaled_size = cinfo->min_DCT_h_scaled_size * ssize; ssize = 1; while (cinfo->min_DCT_v_scaled_size * ssize <= (cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) && (cinfo->max_v_samp_factor % (compptr->v_samp_factor * ssize * 2)) == 0) { ssize = ssize * 2; } compptr->DCT_v_scaled_size = cinfo->min_DCT_v_scaled_size * ssize; /* We don't support IDCT ratios larger than 2. */ if (compptr->DCT_h_scaled_size > compptr->DCT_v_scaled_size * 2) compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size * 2; else if (compptr->DCT_v_scaled_size > compptr->DCT_h_scaled_size * 2) compptr->DCT_v_scaled_size = compptr->DCT_h_scaled_size * 2; } /* Recompute downsampled dimensions of components; * application needs to know these if using raw downsampled data. */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Size in samples, after IDCT scaling */ compptr->downsampled_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * (long) (compptr->h_samp_factor * compptr->DCT_h_scaled_size), (long) (cinfo->max_h_samp_factor * cinfo->block_size)); compptr->downsampled_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * (long) (compptr->v_samp_factor * compptr->DCT_v_scaled_size), (long) (cinfo->max_v_samp_factor * cinfo->block_size)); } #endif /* IDCT_SCALING_SUPPORTED */ /* Report number of components in selected colorspace. */ /* Probably this should be in the color conversion module... */ switch (cinfo->out_color_space) { case JCS_GRAYSCALE: cinfo->out_color_components = 1; break; case JCS_RGB: case JCS_BG_RGB: cinfo->out_color_components = RGB_PIXELSIZE; break; case JCS_YCbCr: case JCS_BG_YCC: cinfo->out_color_components = 3; break; case JCS_CMYK: case JCS_YCCK: cinfo->out_color_components = 4; break; default: /* else must be same colorspace as in file */ cinfo->out_color_components = cinfo->num_components; break; } cinfo->output_components = (cinfo->quantize_colors ? 1 : cinfo->out_color_components); /* See if upsampler will want to emit more than one row at a time */ if (use_merged_upsample(cinfo)) cinfo->rec_outbuf_height = cinfo->max_v_samp_factor; else cinfo->rec_outbuf_height = 1; } /* * Several decompression processes need to range-limit values to the range * 0..MAXJSAMPLE; the input value may fall somewhat outside this range * due to noise introduced by quantization, roundoff error, etc. These * processes are inner loops and need to be as fast as possible. On most * machines, particularly CPUs with pipelines or instruction prefetch, * a (subscript-check-less) C table lookup * x = sample_range_limit[x]; * is faster than explicit tests * if (x < 0) x = 0; * else if (x > MAXJSAMPLE) x = MAXJSAMPLE; * These processes all use a common table prepared by the routine below. * * For most steps we can mathematically guarantee that the initial value * of x is within 2*(MAXJSAMPLE+1) of the legal range, so a table running * from -2*(MAXJSAMPLE+1) to 3*MAXJSAMPLE+2 is sufficient. But for the * initial limiting step (just after the IDCT), a wildly out-of-range value * is possible if the input data is corrupt. To avoid any chance of indexing * off the end of memory and getting a bad-pointer trap, we perform the * post-IDCT limiting thus: * x = (sample_range_limit - SUBSET)[(x + CENTER) & MASK]; * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit * samples. Under normal circumstances this is more than enough range and * a correct output will be generated; with bogus input data the mask will * cause wraparound, and we will safely generate a bogus-but-in-range output. * For the post-IDCT step, we want to convert the data from signed to unsigned * representation by adding CENTERJSAMPLE at the same time that we limit it. * This is accomplished with SUBSET = CENTER - CENTERJSAMPLE. * * Note that the table is allocated in near data space on PCs; it's small * enough and used often enough to justify this. */ LOCAL(void) prepare_range_limit_table (j_decompress_ptr cinfo) /* Allocate and fill in the sample_range_limit table */ { JSAMPLE * table; int i; table = (JSAMPLE *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 5 * (MAXJSAMPLE+1) * SIZEOF(JSAMPLE)); /* First segment of range limit table: limit[x] = 0 for x < 0 */ MEMZERO(table, 2 * (MAXJSAMPLE+1) * SIZEOF(JSAMPLE)); table += 2 * (MAXJSAMPLE+1); /* allow negative subscripts of table */ cinfo->sample_range_limit = table; /* Main part of range limit table: limit[x] = x */ for (i = 0; i <= MAXJSAMPLE; i++) table[i] = (JSAMPLE) i; /* End of range limit table: limit[x] = MAXJSAMPLE for x > MAXJSAMPLE */ for (; i < 3 * (MAXJSAMPLE+1); i++) table[i] = MAXJSAMPLE; } /* * Master selection of decompression modules. * This is done once at jpeg_start_decompress time. We determine * which modules will be used and give them appropriate initialization calls. * We also initialize the decompressor input side to begin consuming data. * * Since jpeg_read_header has finished, we know what is in the SOF * and (first) SOS markers. We also have all the application parameter * settings. */ LOCAL(void) master_selection (j_decompress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; boolean use_c_buffer; long samplesperrow; JDIMENSION jd_samplesperrow; /* For now, precision must match compiled-in value... */ if (cinfo->data_precision != BITS_IN_JSAMPLE) ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); /* Initialize dimensions and other stuff */ jpeg_calc_output_dimensions(cinfo); prepare_range_limit_table(cinfo); /* Sanity check on image dimensions */ if (cinfo->output_height <= 0 || cinfo->output_width <= 0 || cinfo->out_color_components <= 0) ERREXIT(cinfo, JERR_EMPTY_IMAGE); /* Width of an output scanline must be representable as JDIMENSION. */ samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components; jd_samplesperrow = (JDIMENSION) samplesperrow; if ((long) jd_samplesperrow != samplesperrow) ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); /* Initialize my private state */ master->pass_number = 0; master->using_merged_upsample = use_merged_upsample(cinfo); /* Color quantizer selection */ master->quantizer_1pass = NULL; master->quantizer_2pass = NULL; /* No mode changes if not using buffered-image mode. */ if (! cinfo->quantize_colors || ! cinfo->buffered_image) { cinfo->enable_1pass_quant = FALSE; cinfo->enable_external_quant = FALSE; cinfo->enable_2pass_quant = FALSE; } if (cinfo->quantize_colors) { if (cinfo->raw_data_out) ERREXIT(cinfo, JERR_NOTIMPL); /* 2-pass quantizer only works in 3-component color space. */ if (cinfo->out_color_components != 3) { cinfo->enable_1pass_quant = TRUE; cinfo->enable_external_quant = FALSE; cinfo->enable_2pass_quant = FALSE; cinfo->colormap = NULL; } else if (cinfo->colormap != NULL) { cinfo->enable_external_quant = TRUE; } else if (cinfo->two_pass_quantize) { cinfo->enable_2pass_quant = TRUE; } else { cinfo->enable_1pass_quant = TRUE; } if (cinfo->enable_1pass_quant) { #ifdef QUANT_1PASS_SUPPORTED jinit_1pass_quantizer(cinfo); master->quantizer_1pass = cinfo->cquantize; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } /* We use the 2-pass code to map to external colormaps. */ if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) { #ifdef QUANT_2PASS_SUPPORTED jinit_2pass_quantizer(cinfo); master->quantizer_2pass = cinfo->cquantize; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } /* If both quantizers are initialized, the 2-pass one is left active; * this is necessary for starting with quantization to an external map. */ } /* Post-processing: in particular, color conversion first */ if (! cinfo->raw_data_out) { if (master->using_merged_upsample) { #ifdef UPSAMPLE_MERGING_SUPPORTED jinit_merged_upsampler(cinfo); /* does color conversion too */ #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { jinit_color_deconverter(cinfo); jinit_upsampler(cinfo); } jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant); } /* Inverse DCT */ jinit_inverse_dct(cinfo); /* Entropy decoding: either Huffman or arithmetic coding. */ if (cinfo->arith_code) jinit_arith_decoder(cinfo); else { jinit_huff_decoder(cinfo); } /* Initialize principal buffer controllers. */ use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image; jinit_d_coef_controller(cinfo, use_c_buffer); if (! cinfo->raw_data_out) jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */); /* We can now tell the memory manager to allocate virtual arrays. */ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); /* Initialize input side of decompressor to consume first scan. */ (*cinfo->inputctl->start_input_pass) (cinfo); #ifdef D_MULTISCAN_FILES_SUPPORTED /* If jpeg_start_decompress will read the whole file, initialize * progress monitoring appropriately. The input step is counted * as one pass. */ if (cinfo->progress != NULL && ! cinfo->buffered_image && cinfo->inputctl->has_multiple_scans) { int nscans; /* Estimate number of scans to set pass_limit. */ if (cinfo->progressive_mode) { /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ nscans = 2 + 3 * cinfo->num_components; } else { /* For a nonprogressive multiscan file, estimate 1 scan per component. */ nscans = cinfo->num_components; } cinfo->progress->pass_counter = 0L; cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans; cinfo->progress->completed_passes = 0; cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2); /* Count the input pass as done */ master->pass_number++; } #endif /* D_MULTISCAN_FILES_SUPPORTED */ } /* * Per-pass setup. * This is called at the beginning of each output pass. We determine which * modules will be active during this pass and give them appropriate * start_pass calls. We also set is_dummy_pass to indicate whether this * is a "real" output pass or a dummy pass for color quantization. * (In the latter case, jdapistd.c will crank the pass to completion.) */ METHODDEF(void) prepare_for_output_pass (j_decompress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; if (master->pub.is_dummy_pass) { #ifdef QUANT_2PASS_SUPPORTED /* Final pass of 2-pass quantization */ master->pub.is_dummy_pass = FALSE; (*cinfo->cquantize->start_pass) (cinfo, FALSE); (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST); (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST); #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif /* QUANT_2PASS_SUPPORTED */ } else { if (cinfo->quantize_colors && cinfo->colormap == NULL) { /* Select new quantization method */ if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) { cinfo->cquantize = master->quantizer_2pass; master->pub.is_dummy_pass = TRUE; } else if (cinfo->enable_1pass_quant) { cinfo->cquantize = master->quantizer_1pass; } else { ERREXIT(cinfo, JERR_MODE_CHANGE); } } (*cinfo->idct->start_pass) (cinfo); (*cinfo->coef->start_output_pass) (cinfo); if (! cinfo->raw_data_out) { if (! master->using_merged_upsample) (*cinfo->cconvert->start_pass) (cinfo); (*cinfo->upsample->start_pass) (cinfo); if (cinfo->quantize_colors) (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass); (*cinfo->post->start_pass) (cinfo, (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU)); (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU); } } /* Set up progress monitor's pass info if present */ if (cinfo->progress != NULL) { cinfo->progress->completed_passes = master->pass_number; cinfo->progress->total_passes = master->pass_number + (master->pub.is_dummy_pass ? 2 : 1); /* In buffered-image mode, we assume one more output pass if EOI not * yet reached, but no more passes if EOI has been reached. */ if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) { cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1); } } } /* * Finish up at end of an output pass. */ METHODDEF(void) finish_output_pass (j_decompress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; if (cinfo->quantize_colors) (*cinfo->cquantize->finish_pass) (cinfo); master->pass_number++; } #ifdef D_MULTISCAN_FILES_SUPPORTED /* * Switch to a new external colormap between output passes. */ GLOBAL(void) jpeg_new_colormap (j_decompress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; /* Prevent application from calling me at wrong times */ if (cinfo->global_state != DSTATE_BUFIMAGE) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (cinfo->quantize_colors && cinfo->enable_external_quant && cinfo->colormap != NULL) { /* Select 2-pass quantizer for external colormap use */ cinfo->cquantize = master->quantizer_2pass; /* Notify quantizer of colormap change */ (*cinfo->cquantize->new_color_map) (cinfo); master->pub.is_dummy_pass = FALSE; /* just in case */ } else ERREXIT(cinfo, JERR_MODE_CHANGE); } #endif /* D_MULTISCAN_FILES_SUPPORTED */ /* * Initialize master decompression control and select active modules. * This is performed at the start of jpeg_start_decompress. */ GLOBAL(void) jinit_master_decompress (j_decompress_ptr cinfo) { my_master_ptr master; master = (my_master_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_decomp_master)); cinfo->master = &master->pub; master->pub.prepare_for_output_pass = prepare_for_output_pass; master->pub.finish_output_pass = finish_output_pass; master->pub.is_dummy_pass = FALSE; master_selection(cinfo); } ================================================ FILE: tess-two/jni/libjpeg/jdmerge.c ================================================ /* * jdmerge.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2013-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains code for merged upsampling/color conversion. * * This file combines functions from jdsample.c and jdcolor.c; * read those files first to understand what's going on. * * When the chroma components are to be upsampled by simple replication * (ie, box filtering), we can save some work in color conversion by * calculating all the output pixels corresponding to a pair of chroma * samples at one time. In the conversion equations * R = Y + K1 * Cr * G = Y + K2 * Cb + K3 * Cr * B = Y + K4 * Cb * only the Y term varies among the group of pixels corresponding to a pair * of chroma samples, so the rest of the terms can be calculated just once. * At typical sampling ratios, this eliminates half or three-quarters of the * multiplications needed for color conversion. * * This file currently provides implementations for the following cases: * YCC => RGB color conversion only (YCbCr or BG_YCC). * Sampling ratios of 2h1v or 2h2v. * No scaling needed at upsample time. * Corner-aligned (non-CCIR601) sampling alignment. * Other special cases could be added, but in most applications these are * the only common cases. (For uncommon cases we fall back on the more * general code in jdsample.c and jdcolor.c.) */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #ifdef UPSAMPLE_MERGING_SUPPORTED /* Private subobject */ typedef struct { struct jpeg_upsampler pub; /* public fields */ /* Pointer to routine to do actual upsampling/conversion of one row group */ JMETHOD(void, upmethod, (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr, JSAMPARRAY output_buf)); /* Private state for YCC->RGB conversion */ int * Cr_r_tab; /* => table for Cr to R conversion */ int * Cb_b_tab; /* => table for Cb to B conversion */ INT32 * Cr_g_tab; /* => table for Cr to G conversion */ INT32 * Cb_g_tab; /* => table for Cb to G conversion */ /* For 2:1 vertical sampling, we produce two output rows at a time. * We need a "spare" row buffer to hold the second output row if the * application provides just a one-row buffer; we also use the spare * to discard the dummy last row if the image height is odd. */ JSAMPROW spare_row; boolean spare_full; /* T if spare buffer is occupied */ JDIMENSION out_row_width; /* samples per output row */ JDIMENSION rows_to_go; /* counts rows remaining in image */ } my_upsampler; typedef my_upsampler * my_upsample_ptr; #define SCALEBITS 16 /* speediest right-shift on some machines */ #define ONE_HALF ((INT32) 1 << (SCALEBITS-1)) #define FIX(x) ((INT32) ((x) * (1L<RGB and BG_YCC->RGB colorspace conversion. * This is taken directly from jdcolor.c; see that file for more info. */ LOCAL(void) build_ycc_rgb_table (j_decompress_ptr cinfo) /* Normal case, sYCC */ { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; int i; INT32 x; SHIFT_TEMPS upsample->Cr_r_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); upsample->Cb_b_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); upsample->Cr_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); upsample->Cb_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ /* Cr=>R value is nearest int to 1.402 * x */ upsample->Cr_r_tab[i] = (int) RIGHT_SHIFT(FIX(1.402) * x + ONE_HALF, SCALEBITS); /* Cb=>B value is nearest int to 1.772 * x */ upsample->Cb_b_tab[i] = (int) RIGHT_SHIFT(FIX(1.772) * x + ONE_HALF, SCALEBITS); /* Cr=>G value is scaled-up -0.714136286 * x */ upsample->Cr_g_tab[i] = (- FIX(0.714136286)) * x; /* Cb=>G value is scaled-up -0.344136286 * x */ /* We also add in ONE_HALF so that need not do it in inner loop */ upsample->Cb_g_tab[i] = (- FIX(0.344136286)) * x + ONE_HALF; } } LOCAL(void) build_bg_ycc_rgb_table (j_decompress_ptr cinfo) /* Wide gamut case, bg-sYCC */ { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; int i; INT32 x; SHIFT_TEMPS upsample->Cr_r_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); upsample->Cb_b_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); upsample->Cr_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); upsample->Cb_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ /* Cr=>R value is nearest int to 2.804 * x */ upsample->Cr_r_tab[i] = (int) RIGHT_SHIFT(FIX(2.804) * x + ONE_HALF, SCALEBITS); /* Cb=>B value is nearest int to 3.544 * x */ upsample->Cb_b_tab[i] = (int) RIGHT_SHIFT(FIX(3.544) * x + ONE_HALF, SCALEBITS); /* Cr=>G value is scaled-up -1.428272572 * x */ upsample->Cr_g_tab[i] = (- FIX(1.428272572)) * x; /* Cb=>G value is scaled-up -0.688272572 * x */ /* We also add in ONE_HALF so that need not do it in inner loop */ upsample->Cb_g_tab[i] = (- FIX(0.688272572)) * x + ONE_HALF; } } /* * Initialize for an upsampling pass. */ METHODDEF(void) start_pass_merged_upsample (j_decompress_ptr cinfo) { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; /* Mark the spare buffer empty */ upsample->spare_full = FALSE; /* Initialize total-height counter for detecting bottom of image */ upsample->rows_to_go = cinfo->output_height; } /* * Control routine to do upsampling (and color conversion). * * The control routine just handles the row buffering considerations. */ METHODDEF(void) merged_2v_upsample (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) /* 2:1 vertical sampling case: may need a spare row. */ { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; JSAMPROW work_ptrs[2]; JDIMENSION num_rows; /* number of rows returned to caller */ if (upsample->spare_full) { /* If we have a spare row saved from a previous cycle, just return it. */ jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0, 1, upsample->out_row_width); num_rows = 1; upsample->spare_full = FALSE; } else { /* Figure number of rows to return to caller. */ num_rows = 2; /* Not more than the distance to the end of the image. */ if (num_rows > upsample->rows_to_go) num_rows = upsample->rows_to_go; /* And not more than what the client can accept: */ out_rows_avail -= *out_row_ctr; if (num_rows > out_rows_avail) num_rows = out_rows_avail; /* Create output pointer array for upsampler. */ work_ptrs[0] = output_buf[*out_row_ctr]; if (num_rows > 1) { work_ptrs[1] = output_buf[*out_row_ctr + 1]; } else { work_ptrs[1] = upsample->spare_row; upsample->spare_full = TRUE; } /* Now do the upsampling. */ (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs); } /* Adjust counts */ *out_row_ctr += num_rows; upsample->rows_to_go -= num_rows; /* When the buffer is emptied, declare this input row group consumed */ if (! upsample->spare_full) (*in_row_group_ctr)++; } METHODDEF(void) merged_1v_upsample (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) /* 1:1 vertical sampling case: much easier, never need a spare row. */ { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; /* Just do the upsampling. */ (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, output_buf + *out_row_ctr); /* Adjust counts */ (*out_row_ctr)++; (*in_row_group_ctr)++; } /* * These are the routines invoked by the control routines to do * the actual upsampling/conversion. One row group is processed per call. * * Note: since we may be writing directly into application-supplied buffers, * we have to be honest about the output width; we can't assume the buffer * has been rounded up to an even width. */ /* * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical. */ METHODDEF(void) h2v1_merged_upsample (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr, JSAMPARRAY output_buf) { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; register int y, cred, cgreen, cblue; int cb, cr; register JSAMPROW outptr; JSAMPROW inptr0, inptr1, inptr2; JDIMENSION col; /* copy these pointers into registers if possible */ register JSAMPLE * range_limit = cinfo->sample_range_limit; int * Crrtab = upsample->Cr_r_tab; int * Cbbtab = upsample->Cb_b_tab; INT32 * Crgtab = upsample->Cr_g_tab; INT32 * Cbgtab = upsample->Cb_g_tab; SHIFT_TEMPS inptr0 = input_buf[0][in_row_group_ctr]; inptr1 = input_buf[1][in_row_group_ctr]; inptr2 = input_buf[2][in_row_group_ctr]; outptr = output_buf[0]; /* Loop for each pair of output pixels */ for (col = cinfo->output_width >> 1; col > 0; col--) { /* Do the chroma part of the calculation */ cb = GETJSAMPLE(*inptr1++); cr = GETJSAMPLE(*inptr2++); cred = Crrtab[cr]; cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); cblue = Cbbtab[cb]; /* Fetch 2 Y values and emit 2 pixels */ y = GETJSAMPLE(*inptr0++); outptr[RGB_RED] = range_limit[y + cred]; outptr[RGB_GREEN] = range_limit[y + cgreen]; outptr[RGB_BLUE] = range_limit[y + cblue]; outptr += RGB_PIXELSIZE; y = GETJSAMPLE(*inptr0++); outptr[RGB_RED] = range_limit[y + cred]; outptr[RGB_GREEN] = range_limit[y + cgreen]; outptr[RGB_BLUE] = range_limit[y + cblue]; outptr += RGB_PIXELSIZE; } /* If image width is odd, do the last output column separately */ if (cinfo->output_width & 1) { cb = GETJSAMPLE(*inptr1); cr = GETJSAMPLE(*inptr2); cred = Crrtab[cr]; cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); cblue = Cbbtab[cb]; y = GETJSAMPLE(*inptr0); outptr[RGB_RED] = range_limit[y + cred]; outptr[RGB_GREEN] = range_limit[y + cgreen]; outptr[RGB_BLUE] = range_limit[y + cblue]; } } /* * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical. */ METHODDEF(void) h2v2_merged_upsample (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr, JSAMPARRAY output_buf) { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; register int y, cred, cgreen, cblue; int cb, cr; register JSAMPROW outptr0, outptr1; JSAMPROW inptr00, inptr01, inptr1, inptr2; JDIMENSION col; /* copy these pointers into registers if possible */ register JSAMPLE * range_limit = cinfo->sample_range_limit; int * Crrtab = upsample->Cr_r_tab; int * Cbbtab = upsample->Cb_b_tab; INT32 * Crgtab = upsample->Cr_g_tab; INT32 * Cbgtab = upsample->Cb_g_tab; SHIFT_TEMPS inptr00 = input_buf[0][in_row_group_ctr*2]; inptr01 = input_buf[0][in_row_group_ctr*2 + 1]; inptr1 = input_buf[1][in_row_group_ctr]; inptr2 = input_buf[2][in_row_group_ctr]; outptr0 = output_buf[0]; outptr1 = output_buf[1]; /* Loop for each group of output pixels */ for (col = cinfo->output_width >> 1; col > 0; col--) { /* Do the chroma part of the calculation */ cb = GETJSAMPLE(*inptr1++); cr = GETJSAMPLE(*inptr2++); cred = Crrtab[cr]; cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); cblue = Cbbtab[cb]; /* Fetch 4 Y values and emit 4 pixels */ y = GETJSAMPLE(*inptr00++); outptr0[RGB_RED] = range_limit[y + cred]; outptr0[RGB_GREEN] = range_limit[y + cgreen]; outptr0[RGB_BLUE] = range_limit[y + cblue]; outptr0 += RGB_PIXELSIZE; y = GETJSAMPLE(*inptr00++); outptr0[RGB_RED] = range_limit[y + cred]; outptr0[RGB_GREEN] = range_limit[y + cgreen]; outptr0[RGB_BLUE] = range_limit[y + cblue]; outptr0 += RGB_PIXELSIZE; y = GETJSAMPLE(*inptr01++); outptr1[RGB_RED] = range_limit[y + cred]; outptr1[RGB_GREEN] = range_limit[y + cgreen]; outptr1[RGB_BLUE] = range_limit[y + cblue]; outptr1 += RGB_PIXELSIZE; y = GETJSAMPLE(*inptr01++); outptr1[RGB_RED] = range_limit[y + cred]; outptr1[RGB_GREEN] = range_limit[y + cgreen]; outptr1[RGB_BLUE] = range_limit[y + cblue]; outptr1 += RGB_PIXELSIZE; } /* If image width is odd, do the last output column separately */ if (cinfo->output_width & 1) { cb = GETJSAMPLE(*inptr1); cr = GETJSAMPLE(*inptr2); cred = Crrtab[cr]; cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS); cblue = Cbbtab[cb]; y = GETJSAMPLE(*inptr00); outptr0[RGB_RED] = range_limit[y + cred]; outptr0[RGB_GREEN] = range_limit[y + cgreen]; outptr0[RGB_BLUE] = range_limit[y + cblue]; y = GETJSAMPLE(*inptr01); outptr1[RGB_RED] = range_limit[y + cred]; outptr1[RGB_GREEN] = range_limit[y + cgreen]; outptr1[RGB_BLUE] = range_limit[y + cblue]; } } /* * Module initialization routine for merged upsampling/color conversion. * * NB: this is called under the conditions determined by use_merged_upsample() * in jdmaster.c. That routine MUST correspond to the actual capabilities * of this module; no safety checks are made here. */ GLOBAL(void) jinit_merged_upsampler (j_decompress_ptr cinfo) { my_upsample_ptr upsample; upsample = (my_upsample_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_upsampler)); cinfo->upsample = &upsample->pub; upsample->pub.start_pass = start_pass_merged_upsample; upsample->pub.need_context_rows = FALSE; upsample->out_row_width = cinfo->output_width * cinfo->out_color_components; if (cinfo->max_v_samp_factor == 2) { upsample->pub.upsample = merged_2v_upsample; upsample->upmethod = h2v2_merged_upsample; /* Allocate a spare row buffer */ upsample->spare_row = (JSAMPROW) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE))); } else { upsample->pub.upsample = merged_1v_upsample; upsample->upmethod = h2v1_merged_upsample; /* No spare row needed */ upsample->spare_row = NULL; } if (cinfo->jpeg_color_space == JCS_BG_YCC) build_bg_ycc_rgb_table(cinfo); else build_ycc_rgb_table(cinfo); } #endif /* UPSAMPLE_MERGING_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jdpostct.c ================================================ /* * jdpostct.c * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the decompression postprocessing controller. * This controller manages the upsampling, color conversion, and color * quantization/reduction steps; specifically, it controls the buffering * between upsample/color conversion and color quantization/reduction. * * If no color quantization/reduction is required, then this module has no * work to do, and it just hands off to the upsample/color conversion code. * An integrated upsample/convert/quantize process would replace this module * entirely. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Private buffer controller object */ typedef struct { struct jpeg_d_post_controller pub; /* public fields */ /* Color quantization source buffer: this holds output data from * the upsample/color conversion step to be passed to the quantizer. * For two-pass color quantization, we need a full-image buffer; * for one-pass operation, a strip buffer is sufficient. */ jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */ JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */ JDIMENSION strip_height; /* buffer size in rows */ /* for two-pass mode only: */ JDIMENSION starting_row; /* row # of first row in current strip */ JDIMENSION next_row; /* index of next row to fill/empty in strip */ } my_post_controller; typedef my_post_controller * my_post_ptr; /* Forward declarations */ METHODDEF(void) post_process_1pass JPP((j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); #ifdef QUANT_2PASS_SUPPORTED METHODDEF(void) post_process_prepass JPP((j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); METHODDEF(void) post_process_2pass JPP((j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); #endif /* * Initialize for a processing pass. */ METHODDEF(void) start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode) { my_post_ptr post = (my_post_ptr) cinfo->post; switch (pass_mode) { case JBUF_PASS_THRU: if (cinfo->quantize_colors) { /* Single-pass processing with color quantization. */ post->pub.post_process_data = post_process_1pass; /* We could be doing buffered-image output before starting a 2-pass * color quantization; in that case, jinit_d_post_controller did not * allocate a strip buffer. Use the virtual-array buffer as workspace. */ if (post->buffer == NULL) { post->buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, post->whole_image, (JDIMENSION) 0, post->strip_height, TRUE); } } else { /* For single-pass processing without color quantization, * I have no work to do; just call the upsampler directly. */ post->pub.post_process_data = cinfo->upsample->upsample; } break; #ifdef QUANT_2PASS_SUPPORTED case JBUF_SAVE_AND_PASS: /* First pass of 2-pass quantization */ if (post->whole_image == NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); post->pub.post_process_data = post_process_prepass; break; case JBUF_CRANK_DEST: /* Second pass of 2-pass quantization */ if (post->whole_image == NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); post->pub.post_process_data = post_process_2pass; break; #endif /* QUANT_2PASS_SUPPORTED */ default: ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); break; } post->starting_row = post->next_row = 0; } /* * Process some data in the one-pass (strip buffer) case. * This is used for color precision reduction as well as one-pass quantization. */ METHODDEF(void) post_process_1pass (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_post_ptr post = (my_post_ptr) cinfo->post; JDIMENSION num_rows, max_rows; /* Fill the buffer, but not more than what we can dump out in one go. */ /* Note we rely on the upsampler to detect bottom of image. */ max_rows = out_rows_avail - *out_row_ctr; if (max_rows > post->strip_height) max_rows = post->strip_height; num_rows = 0; (*cinfo->upsample->upsample) (cinfo, input_buf, in_row_group_ctr, in_row_groups_avail, post->buffer, &num_rows, max_rows); /* Quantize and emit data. */ (*cinfo->cquantize->color_quantize) (cinfo, post->buffer, output_buf + *out_row_ctr, (int) num_rows); *out_row_ctr += num_rows; } #ifdef QUANT_2PASS_SUPPORTED /* * Process some data in the first pass of 2-pass quantization. */ METHODDEF(void) post_process_prepass (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_post_ptr post = (my_post_ptr) cinfo->post; JDIMENSION old_next_row, num_rows; /* Reposition virtual buffer if at start of strip. */ if (post->next_row == 0) { post->buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, post->whole_image, post->starting_row, post->strip_height, TRUE); } /* Upsample some data (up to a strip height's worth). */ old_next_row = post->next_row; (*cinfo->upsample->upsample) (cinfo, input_buf, in_row_group_ctr, in_row_groups_avail, post->buffer, &post->next_row, post->strip_height); /* Allow quantizer to scan new data. No data is emitted, */ /* but we advance out_row_ctr so outer loop can tell when we're done. */ if (post->next_row > old_next_row) { num_rows = post->next_row - old_next_row; (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row, (JSAMPARRAY) NULL, (int) num_rows); *out_row_ctr += num_rows; } /* Advance if we filled the strip. */ if (post->next_row >= post->strip_height) { post->starting_row += post->strip_height; post->next_row = 0; } } /* * Process some data in the second pass of 2-pass quantization. */ METHODDEF(void) post_process_2pass (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_post_ptr post = (my_post_ptr) cinfo->post; JDIMENSION num_rows, max_rows; /* Reposition virtual buffer if at start of strip. */ if (post->next_row == 0) { post->buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, post->whole_image, post->starting_row, post->strip_height, FALSE); } /* Determine number of rows to emit. */ num_rows = post->strip_height - post->next_row; /* available in strip */ max_rows = out_rows_avail - *out_row_ctr; /* available in output area */ if (num_rows > max_rows) num_rows = max_rows; /* We have to check bottom of image here, can't depend on upsampler. */ max_rows = cinfo->output_height - post->starting_row; if (num_rows > max_rows) num_rows = max_rows; /* Quantize and emit data. */ (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + post->next_row, output_buf + *out_row_ctr, (int) num_rows); *out_row_ctr += num_rows; /* Advance if we filled the strip. */ post->next_row += num_rows; if (post->next_row >= post->strip_height) { post->starting_row += post->strip_height; post->next_row = 0; } } #endif /* QUANT_2PASS_SUPPORTED */ /* * Initialize postprocessing controller. */ GLOBAL(void) jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer) { my_post_ptr post; post = (my_post_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_post_controller)); cinfo->post = (struct jpeg_d_post_controller *) post; post->pub.start_pass = start_pass_dpost; post->whole_image = NULL; /* flag for no virtual arrays */ post->buffer = NULL; /* flag for no strip buffer */ /* Create the quantization buffer, if needed */ if (cinfo->quantize_colors) { /* The buffer strip height is max_v_samp_factor, which is typically * an efficient number of rows for upsampling to return. * (In the presence of output rescaling, we might want to be smarter?) */ post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor; if (need_full_buffer) { /* Two-pass color quantization: need full-image storage. */ /* We round up the number of rows to a multiple of the strip height. */ #ifdef QUANT_2PASS_SUPPORTED post->whole_image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, cinfo->output_width * cinfo->out_color_components, (JDIMENSION) jround_up((long) cinfo->output_height, (long) post->strip_height), post->strip_height); #else ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); #endif /* QUANT_2PASS_SUPPORTED */ } else { /* One-pass color quantization: just make a strip buffer. */ post->buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width * cinfo->out_color_components, post->strip_height); } } } ================================================ FILE: tess-two/jni/libjpeg/jdsample.c ================================================ /* * jdsample.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2002-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains upsampling routines. * * Upsampling input data is counted in "row groups". A row group * is defined to be (v_samp_factor * DCT_v_scaled_size / min_DCT_v_scaled_size) * sample rows of each component. Upsampling will normally produce * max_v_samp_factor pixel rows from each row group (but this could vary * if the upsampler is applying a scale factor of its own). * * An excellent reference for image resampling is * Digital Image Warping, George Wolberg, 1990. * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Pointer to routine to upsample a single component */ typedef JMETHOD(void, upsample1_ptr, (j_decompress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)); /* Private subobject */ typedef struct { struct jpeg_upsampler pub; /* public fields */ /* Color conversion buffer. When using separate upsampling and color * conversion steps, this buffer holds one upsampled row group until it * has been color converted and output. * Note: we do not allocate any storage for component(s) which are full-size, * ie do not need rescaling. The corresponding entry of color_buf[] is * simply set to point to the input data array, thereby avoiding copying. */ JSAMPARRAY color_buf[MAX_COMPONENTS]; /* Per-component upsampling method pointers */ upsample1_ptr methods[MAX_COMPONENTS]; int next_row_out; /* counts rows emitted from color_buf */ JDIMENSION rows_to_go; /* counts rows remaining in image */ /* Height of an input row group for each component. */ int rowgroup_height[MAX_COMPONENTS]; /* These arrays save pixel expansion factors so that int_expand need not * recompute them each time. They are unused for other upsampling methods. */ UINT8 h_expand[MAX_COMPONENTS]; UINT8 v_expand[MAX_COMPONENTS]; } my_upsampler; typedef my_upsampler * my_upsample_ptr; /* * Initialize for an upsampling pass. */ METHODDEF(void) start_pass_upsample (j_decompress_ptr cinfo) { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; /* Mark the conversion buffer empty */ upsample->next_row_out = cinfo->max_v_samp_factor; /* Initialize total-height counter for detecting bottom of image */ upsample->rows_to_go = cinfo->output_height; } /* * Control routine to do upsampling (and color conversion). * * In this version we upsample each component independently. * We upsample one row group into the conversion buffer, then apply * color conversion a row at a time. */ METHODDEF(void) sep_upsample (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; int ci; jpeg_component_info * compptr; JDIMENSION num_rows; /* Fill the conversion buffer, if it's empty */ if (upsample->next_row_out >= cinfo->max_v_samp_factor) { for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Invoke per-component upsample method. Notice we pass a POINTER * to color_buf[ci], so that fullsize_upsample can change it. */ (*upsample->methods[ci]) (cinfo, compptr, input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]), upsample->color_buf + ci); } upsample->next_row_out = 0; } /* Color-convert and emit rows */ /* How many we have in the buffer: */ num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out); /* Not more than the distance to the end of the image. Need this test * in case the image height is not a multiple of max_v_samp_factor: */ if (num_rows > upsample->rows_to_go) num_rows = upsample->rows_to_go; /* And not more than what the client can accept: */ out_rows_avail -= *out_row_ctr; if (num_rows > out_rows_avail) num_rows = out_rows_avail; (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf, (JDIMENSION) upsample->next_row_out, output_buf + *out_row_ctr, (int) num_rows); /* Adjust counts */ *out_row_ctr += num_rows; upsample->rows_to_go -= num_rows; upsample->next_row_out += num_rows; /* When the buffer is emptied, declare this input row group consumed */ if (upsample->next_row_out >= cinfo->max_v_samp_factor) (*in_row_group_ctr)++; } /* * These are the routines invoked by sep_upsample to upsample pixel values * of a single component. One row group is processed per call. */ /* * For full-size components, we just make color_buf[ci] point at the * input buffer, and thus avoid copying any data. Note that this is * safe only because sep_upsample doesn't declare the input row group * "consumed" until we are done color converting and emitting it. */ METHODDEF(void) fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) { *output_data_ptr = input_data; } /* * This is a no-op version used for "uninteresting" components. * These components will not be referenced by color conversion. */ METHODDEF(void) noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) { *output_data_ptr = NULL; /* safety check */ } /* * This version handles any integral sampling ratios. * This is not used for typical JPEG files, so it need not be fast. * Nor, for that matter, is it particularly accurate: the algorithm is * simple replication of the input pixel onto the corresponding output * pixels. The hi-falutin sampling literature refers to this as a * "box filter". A box filter tends to introduce visible artifacts, * so if you are actually going to use 3:1 or 4:1 sampling ratios * you would be well advised to improve this code. */ METHODDEF(void) int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) { my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; JSAMPARRAY output_data = *output_data_ptr; register JSAMPROW inptr, outptr; register JSAMPLE invalue; register int h; JSAMPROW outend; int h_expand, v_expand; int inrow, outrow; h_expand = upsample->h_expand[compptr->component_index]; v_expand = upsample->v_expand[compptr->component_index]; inrow = outrow = 0; while (outrow < cinfo->max_v_samp_factor) { /* Generate one output row with proper horizontal expansion */ inptr = input_data[inrow]; outptr = output_data[outrow]; outend = outptr + cinfo->output_width; while (outptr < outend) { invalue = *inptr++; /* don't need GETJSAMPLE() here */ for (h = h_expand; h > 0; h--) { *outptr++ = invalue; } } /* Generate any additional output rows by duplicating the first one */ if (v_expand > 1) { jcopy_sample_rows(output_data, outrow, output_data, outrow+1, v_expand-1, cinfo->output_width); } inrow++; outrow += v_expand; } } /* * Fast processing for the common case of 2:1 horizontal and 1:1 vertical. * It's still a box filter. */ METHODDEF(void) h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) { JSAMPARRAY output_data = *output_data_ptr; register JSAMPROW inptr, outptr; register JSAMPLE invalue; JSAMPROW outend; int outrow; for (outrow = 0; outrow < cinfo->max_v_samp_factor; outrow++) { inptr = input_data[outrow]; outptr = output_data[outrow]; outend = outptr + cinfo->output_width; while (outptr < outend) { invalue = *inptr++; /* don't need GETJSAMPLE() here */ *outptr++ = invalue; *outptr++ = invalue; } } } /* * Fast processing for the common case of 2:1 horizontal and 2:1 vertical. * It's still a box filter. */ METHODDEF(void) h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr) { JSAMPARRAY output_data = *output_data_ptr; register JSAMPROW inptr, outptr; register JSAMPLE invalue; JSAMPROW outend; int inrow, outrow; inrow = outrow = 0; while (outrow < cinfo->max_v_samp_factor) { inptr = input_data[inrow]; outptr = output_data[outrow]; outend = outptr + cinfo->output_width; while (outptr < outend) { invalue = *inptr++; /* don't need GETJSAMPLE() here */ *outptr++ = invalue; *outptr++ = invalue; } jcopy_sample_rows(output_data, outrow, output_data, outrow+1, 1, cinfo->output_width); inrow++; outrow += 2; } } /* * Module initialization routine for upsampling. */ GLOBAL(void) jinit_upsampler (j_decompress_ptr cinfo) { my_upsample_ptr upsample; int ci; jpeg_component_info * compptr; int h_in_group, v_in_group, h_out_group, v_out_group; upsample = (my_upsample_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_upsampler)); cinfo->upsample = &upsample->pub; upsample->pub.start_pass = start_pass_upsample; upsample->pub.upsample = sep_upsample; upsample->pub.need_context_rows = FALSE; /* until we find out differently */ if (cinfo->CCIR601_sampling) /* this isn't supported */ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); /* Verify we can handle the sampling factors, select per-component methods, * and create storage as needed. */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Compute size of an "input group" after IDCT scaling. This many samples * are to be converted to max_h_samp_factor * max_v_samp_factor pixels. */ h_in_group = (compptr->h_samp_factor * compptr->DCT_h_scaled_size) / cinfo->min_DCT_h_scaled_size; v_in_group = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) / cinfo->min_DCT_v_scaled_size; h_out_group = cinfo->max_h_samp_factor; v_out_group = cinfo->max_v_samp_factor; upsample->rowgroup_height[ci] = v_in_group; /* save for use later */ if (! compptr->component_needed) { /* Don't bother to upsample an uninteresting component. */ upsample->methods[ci] = noop_upsample; continue; /* don't need to allocate buffer */ } if (h_in_group == h_out_group && v_in_group == v_out_group) { /* Fullsize components can be processed without any work. */ upsample->methods[ci] = fullsize_upsample; continue; /* don't need to allocate buffer */ } if (h_in_group * 2 == h_out_group && v_in_group == v_out_group) { /* Special case for 2h1v upsampling */ upsample->methods[ci] = h2v1_upsample; } else if (h_in_group * 2 == h_out_group && v_in_group * 2 == v_out_group) { /* Special case for 2h2v upsampling */ upsample->methods[ci] = h2v2_upsample; } else if ((h_out_group % h_in_group) == 0 && (v_out_group % v_in_group) == 0) { /* Generic integral-factors upsampling method */ upsample->methods[ci] = int_upsample; upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group); upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group); } else ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) jround_up((long) cinfo->output_width, (long) cinfo->max_h_samp_factor), (JDIMENSION) cinfo->max_v_samp_factor); } } ================================================ FILE: tess-two/jni/libjpeg/jdtrans.c ================================================ /* * jdtrans.c * * Copyright (C) 1995-1997, Thomas G. Lane. * Modified 2000-2009 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains library routines for transcoding decompression, * that is, reading raw DCT coefficient arrays from an input JPEG file. * The routines in jdapimin.c will also be needed by a transcoder. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Forward declarations */ LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo)); /* * Read the coefficient arrays from a JPEG file. * jpeg_read_header must be completed before calling this. * * The entire image is read into a set of virtual coefficient-block arrays, * one per component. The return value is a pointer to the array of * virtual-array descriptors. These can be manipulated directly via the * JPEG memory manager, or handed off to jpeg_write_coefficients(). * To release the memory occupied by the virtual arrays, call * jpeg_finish_decompress() when done with the data. * * An alternative usage is to simply obtain access to the coefficient arrays * during a buffered-image-mode decompression operation. This is allowed * after any jpeg_finish_output() call. The arrays can be accessed until * jpeg_finish_decompress() is called. (Note that any call to the library * may reposition the arrays, so don't rely on access_virt_barray() results * to stay valid across library calls.) * * Returns NULL if suspended. This case need be checked only if * a suspending data source is used. */ GLOBAL(jvirt_barray_ptr *) jpeg_read_coefficients (j_decompress_ptr cinfo) { if (cinfo->global_state == DSTATE_READY) { /* First call: initialize active modules */ transdecode_master_selection(cinfo); cinfo->global_state = DSTATE_RDCOEFS; } if (cinfo->global_state == DSTATE_RDCOEFS) { /* Absorb whole file into the coef buffer */ for (;;) { int retcode; /* Call progress monitor hook if present */ if (cinfo->progress != NULL) (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); /* Absorb some more input */ retcode = (*cinfo->inputctl->consume_input) (cinfo); if (retcode == JPEG_SUSPENDED) return NULL; if (retcode == JPEG_REACHED_EOI) break; /* Advance progress counter if appropriate */ if (cinfo->progress != NULL && (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) { /* startup underestimated number of scans; ratchet up one scan */ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; } } } /* Set state so that jpeg_finish_decompress does the right thing */ cinfo->global_state = DSTATE_STOPPING; } /* At this point we should be in state DSTATE_STOPPING if being used * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access * to the coefficients during a full buffered-image-mode decompression. */ if ((cinfo->global_state == DSTATE_STOPPING || cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) { return cinfo->coef->coef_arrays; } /* Oops, improper usage */ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); return NULL; /* keep compiler happy */ } /* * Master selection of decompression modules for transcoding. * This substitutes for jdmaster.c's initialization of the full decompressor. */ LOCAL(void) transdecode_master_selection (j_decompress_ptr cinfo) { /* This is effectively a buffered-image operation. */ cinfo->buffered_image = TRUE; /* Compute output image dimensions and related values. */ jpeg_core_output_dimensions(cinfo); /* Entropy decoding: either Huffman or arithmetic coding. */ if (cinfo->arith_code) jinit_arith_decoder(cinfo); else { jinit_huff_decoder(cinfo); } /* Always get a full-image coefficient buffer. */ jinit_d_coef_controller(cinfo, TRUE); /* We can now tell the memory manager to allocate virtual arrays. */ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); /* Initialize input side of decompressor to consume first scan. */ (*cinfo->inputctl->start_input_pass) (cinfo); /* Initialize progress monitoring. */ if (cinfo->progress != NULL) { int nscans; /* Estimate number of scans to set pass_limit. */ if (cinfo->progressive_mode) { /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ nscans = 2 + 3 * cinfo->num_components; } else if (cinfo->inputctl->has_multiple_scans) { /* For a nonprogressive multiscan file, estimate 1 scan per component. */ nscans = cinfo->num_components; } else { nscans = 1; } cinfo->progress->pass_counter = 0L; cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans; cinfo->progress->completed_passes = 0; cinfo->progress->total_passes = 1; } } ================================================ FILE: tess-two/jni/libjpeg/jerror.c ================================================ /* * jerror.c * * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2012-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains simple error-reporting and trace-message routines. * These are suitable for Unix-like systems and others where writing to * stderr is the right thing to do. Many applications will want to replace * some or all of these routines. * * If you define USE_WINDOWS_MESSAGEBOX in jconfig.h or in the makefile, * you get a Windows-specific hack to display error messages in a dialog box. * It ain't much, but it beats dropping error messages into the bit bucket, * which is what happens to output to stderr under most Windows C compilers. * * These routines are used by both the compression and decompression code. */ #ifdef USE_WINDOWS_MESSAGEBOX #include #endif /* this is not a core library module, so it doesn't define JPEG_INTERNALS */ #include "jinclude.h" #include "jpeglib.h" #include "jversion.h" #include "jerror.h" #ifndef EXIT_FAILURE /* define exit() codes if not provided */ #define EXIT_FAILURE 1 #endif /* * Create the message string table. * We do this from the master message list in jerror.h by re-reading * jerror.h with a suitable definition for macro JMESSAGE. * The message table is made an external symbol just in case any applications * want to refer to it directly. */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jpeg_std_message_table jMsgTable #endif #define JMESSAGE(code,string) string , const char * const jpeg_std_message_table[] = { #include "jerror.h" NULL }; /* * Error exit handler: must not return to caller. * * Applications may override this if they want to get control back after * an error. Typically one would longjmp somewhere instead of exiting. * The setjmp buffer can be made a private field within an expanded error * handler object. Note that the info needed to generate an error message * is stored in the error object, so you can generate the message now or * later, at your convenience. * You should make sure that the JPEG object is cleaned up (with jpeg_abort * or jpeg_destroy) at some point. */ METHODDEF(noreturn_t) error_exit (j_common_ptr cinfo) { /* Always display the message */ (*cinfo->err->output_message) (cinfo); /* Let the memory manager delete any temp files before we die */ jpeg_destroy(cinfo); exit(EXIT_FAILURE); } /* * Actual output of an error or trace message. * Applications may override this method to send JPEG messages somewhere * other than stderr. * * On Windows, printing to stderr is generally completely useless, * so we provide optional code to produce an error-dialog popup. * Most Windows applications will still prefer to override this routine, * but if they don't, it'll do something at least marginally useful. * * NOTE: to use the library in an environment that doesn't support the * C stdio library, you may have to delete the call to fprintf() entirely, * not just not use this routine. */ METHODDEF(void) output_message (j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; /* Create the message */ (*cinfo->err->format_message) (cinfo, buffer); #ifdef USE_WINDOWS_MESSAGEBOX /* Display it in a message dialog box */ MessageBox(GetActiveWindow(), buffer, "JPEG Library Error", MB_OK | MB_ICONERROR); #else /* Send it to stderr, adding a newline */ fprintf(stderr, "%s\n", buffer); #endif } /* * Decide whether to emit a trace or warning message. * msg_level is one of: * -1: recoverable corrupt-data warning, may want to abort. * 0: important advisory messages (always display to user). * 1: first level of tracing detail. * 2,3,...: successively more detailed tracing messages. * An application might override this method if it wanted to abort on warnings * or change the policy about which messages to display. */ METHODDEF(void) emit_message (j_common_ptr cinfo, int msg_level) { struct jpeg_error_mgr * err = cinfo->err; if (msg_level < 0) { /* It's a warning message. Since corrupt files may generate many warnings, * the policy implemented here is to show only the first warning, * unless trace_level >= 3. */ if (err->num_warnings == 0 || err->trace_level >= 3) (*err->output_message) (cinfo); /* Always count warnings in num_warnings. */ err->num_warnings++; } else { /* It's a trace message. Show it if trace_level >= msg_level. */ if (err->trace_level >= msg_level) (*err->output_message) (cinfo); } } /* * Format a message string for the most recent JPEG error or message. * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX * characters. Note that no '\n' character is added to the string. * Few applications should need to override this method. */ METHODDEF(void) format_message (j_common_ptr cinfo, char * buffer) { struct jpeg_error_mgr * err = cinfo->err; int msg_code = err->msg_code; const char * msgtext = NULL; const char * msgptr; char ch; boolean isstring; /* Look up message string in proper table */ if (msg_code > 0 && msg_code <= err->last_jpeg_message) { msgtext = err->jpeg_message_table[msg_code]; } else if (err->addon_message_table != NULL && msg_code >= err->first_addon_message && msg_code <= err->last_addon_message) { msgtext = err->addon_message_table[msg_code - err->first_addon_message]; } /* Defend against bogus message number */ if (msgtext == NULL) { err->msg_parm.i[0] = msg_code; msgtext = err->jpeg_message_table[0]; } /* Check for string parameter, as indicated by %s in the message text */ isstring = FALSE; msgptr = msgtext; while ((ch = *msgptr++) != '\0') { if (ch == '%') { if (*msgptr == 's') isstring = TRUE; break; } } /* Format the message into the passed buffer */ if (isstring) sprintf(buffer, msgtext, err->msg_parm.s); else sprintf(buffer, msgtext, err->msg_parm.i[0], err->msg_parm.i[1], err->msg_parm.i[2], err->msg_parm.i[3], err->msg_parm.i[4], err->msg_parm.i[5], err->msg_parm.i[6], err->msg_parm.i[7]); } /* * Reset error state variables at start of a new image. * This is called during compression startup to reset trace/error * processing to default state, without losing any application-specific * method pointers. An application might possibly want to override * this method if it has additional error processing state. */ METHODDEF(void) reset_error_mgr (j_common_ptr cinfo) { cinfo->err->num_warnings = 0; /* trace_level is not reset since it is an application-supplied parameter */ cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */ } /* * Fill in the standard error-handling methods in a jpeg_error_mgr object. * Typical call is: * struct jpeg_compress_struct cinfo; * struct jpeg_error_mgr err; * * cinfo.err = jpeg_std_error(&err); * after which the application may override some of the methods. */ GLOBAL(struct jpeg_error_mgr *) jpeg_std_error (struct jpeg_error_mgr * err) { err->error_exit = error_exit; err->emit_message = emit_message; err->output_message = output_message; err->format_message = format_message; err->reset_error_mgr = reset_error_mgr; err->trace_level = 0; /* default = no tracing */ err->num_warnings = 0; /* no warnings emitted yet */ err->msg_code = 0; /* may be useful as a flag for "no error" */ /* Initialize message table pointers */ err->jpeg_message_table = jpeg_std_message_table; err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1; err->addon_message_table = NULL; err->first_addon_message = 0; /* for safety */ err->last_addon_message = 0; return err; } ================================================ FILE: tess-two/jni/libjpeg/jerror.h ================================================ /* * jerror.h * * Copyright (C) 1994-1997, Thomas G. Lane. * Modified 1997-2012 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file defines the error and message codes for the JPEG library. * Edit this file to add new codes, or to translate the message strings to * some other language. * A set of error-reporting macros are defined too. Some applications using * the JPEG library may wish to include this file to get the error codes * and/or the macros. */ /* * To define the enum list of message codes, include this file without * defining macro JMESSAGE. To create a message string table, include it * again with a suitable JMESSAGE definition (see jerror.c for an example). */ #ifndef JMESSAGE #ifndef JERROR_H /* First time through, define the enum list */ #define JMAKE_ENUM_LIST #else /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */ #define JMESSAGE(code,string) #endif /* JERROR_H */ #endif /* JMESSAGE */ #ifdef JMAKE_ENUM_LIST typedef enum { #define JMESSAGE(code,string) code , #endif /* JMAKE_ENUM_LIST */ JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */ /* For maintenance convenience, list is alphabetical by message code name */ JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix") JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix") JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode") JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS") JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request") JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range") JMESSAGE(JERR_BAD_DCTSIZE, "DCT scaled block size %dx%d not supported") JMESSAGE(JERR_BAD_DROP_SAMPLING, "Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c") JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition") JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace") JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace") JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length") JMESSAGE(JERR_BAD_LIB_VERSION, "Wrong JPEG library version: library is %d, caller expects %d") JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan") JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d") JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d") JMESSAGE(JERR_BAD_PROGRESSION, "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d") JMESSAGE(JERR_BAD_PROG_SCRIPT, "Invalid progressive parameters at scan script entry %d") JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors") JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d") JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d") JMESSAGE(JERR_BAD_STRUCT_SIZE, "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u") JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access") JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small") JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here") JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet") JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d") JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request") JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d") JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x") JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d") JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d") JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)") JMESSAGE(JERR_EMS_READ, "Read from EMS failed") JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed") JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan") JMESSAGE(JERR_FILE_READ, "Input file read error") JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?") JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet") JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow") JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry") JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels") JMESSAGE(JERR_INPUT_EMPTY, "Empty input file") JMESSAGE(JERR_INPUT_EOF, "Premature end of input file") JMESSAGE(JERR_MISMATCHED_QUANT_TABLE, "Cannot transcode due to multiple use of quantization table %d") JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data") JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change") JMESSAGE(JERR_NOTIMPL, "Not implemented yet") JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time") JMESSAGE(JERR_NO_ARITH_TABLE, "Arithmetic table 0x%02x was not defined") JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported") JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined") JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image") JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined") JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x") JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)") JMESSAGE(JERR_QUANT_COMPONENTS, "Cannot quantize more than %d color components") JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors") JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors") JMESSAGE(JERR_SOF_BEFORE, "Invalid JPEG file structure: %s before SOF") JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers") JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker") JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x") JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers") JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s") JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file") JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file") JMESSAGE(JERR_TFILE_WRITE, "Write failed on temporary file --- out of disk space?") JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines") JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x") JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up") JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation") JMESSAGE(JERR_XMS_READ, "Read from XMS failed") JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed") JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT) JMESSAGE(JMSG_VERSION, JVERSION) JMESSAGE(JTRC_16BIT_TABLES, "Caution: quantization tables are too coarse for baseline JPEG") JMESSAGE(JTRC_ADOBE, "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d") JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u") JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u") JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x") JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x") JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d") JMESSAGE(JTRC_DRI, "Define Restart Interval %u") JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u") JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u") JMESSAGE(JTRC_EOI, "End Of Image") JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d") JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d") JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE, "Warning: thumbnail image size does not match data length %u") JMESSAGE(JTRC_JFIF_EXTENSION, "JFIF extension marker: type 0x%02x, length %u") JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image") JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u") JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x") JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u") JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors") JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors") JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization") JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d") JMESSAGE(JTRC_RST, "RST%d") JMESSAGE(JTRC_SMOOTH_NOTIMPL, "Smoothing not supported with nonstandard sampling ratios") JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d") JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d") JMESSAGE(JTRC_SOI, "Start of Image") JMESSAGE(JTRC_SOS, "Start Of Scan: %d components") JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d") JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d") JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s") JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s") JMESSAGE(JTRC_THUMB_JPEG, "JFIF extension marker: JPEG-compressed thumbnail image, length %u") JMESSAGE(JTRC_THUMB_PALETTE, "JFIF extension marker: palette thumbnail image, length %u") JMESSAGE(JTRC_THUMB_RGB, "JFIF extension marker: RGB thumbnail image, length %u") JMESSAGE(JTRC_UNKNOWN_IDS, "Unrecognized component IDs %d %d %d, assuming YCbCr") JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u") JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u") JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d") JMESSAGE(JWRN_ARITH_BAD_CODE, "Corrupt JPEG data: bad arithmetic code") JMESSAGE(JWRN_BOGUS_PROGRESSION, "Inconsistent progression sequence for component %d coefficient %d") JMESSAGE(JWRN_EXTRANEOUS_DATA, "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x") JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment") JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code") JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d") JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file") JMESSAGE(JWRN_MUST_RESYNC, "Corrupt JPEG data: found marker 0x%02x instead of RST%d") JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG") JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines") #ifdef JMAKE_ENUM_LIST JMSG_LASTMSGCODE } J_MESSAGE_CODE; #undef JMAKE_ENUM_LIST #endif /* JMAKE_ENUM_LIST */ /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */ #undef JMESSAGE #ifndef JERROR_H #define JERROR_H /* Macros to simplify using the error and trace message stuff */ /* The first parameter is either type of cinfo pointer */ /* Fatal errors (print message and exit) */ #define ERREXIT(cinfo,code) \ ((cinfo)->err->msg_code = (code), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT1(cinfo,code,p1) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT2(cinfo,code,p1,p2) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT3(cinfo,code,p1,p2,p3) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (cinfo)->err->msg_parm.i[2] = (p3), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (cinfo)->err->msg_parm.i[2] = (p3), \ (cinfo)->err->msg_parm.i[3] = (p4), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT6(cinfo,code,p1,p2,p3,p4,p5,p6) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (cinfo)->err->msg_parm.i[2] = (p3), \ (cinfo)->err->msg_parm.i[3] = (p4), \ (cinfo)->err->msg_parm.i[4] = (p5), \ (cinfo)->err->msg_parm.i[5] = (p6), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXITS(cinfo,code,str) \ ((cinfo)->err->msg_code = (code), \ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define MAKESTMT(stuff) do { stuff } while (0) /* Nonfatal errors (we can keep going, but the data is probably corrupt) */ #define WARNMS(cinfo,code) \ ((cinfo)->err->msg_code = (code), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) #define WARNMS1(cinfo,code,p1) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) #define WARNMS2(cinfo,code,p1,p2) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) /* Informational/debugging messages */ #define TRACEMS(cinfo,lvl,code) \ ((cinfo)->err->msg_code = (code), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #define TRACEMS1(cinfo,lvl,code,p1) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #define TRACEMS2(cinfo,lvl,code,p1,p2) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \ (cinfo)->err->msg_code = (code); \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ (cinfo)->err->msg_code = (code); \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ _mp[4] = (p5); \ (cinfo)->err->msg_code = (code); \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \ (cinfo)->err->msg_code = (code); \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) #define TRACEMSS(cinfo,lvl,code,str) \ ((cinfo)->err->msg_code = (code), \ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #endif /* JERROR_H */ ================================================ FILE: tess-two/jni/libjpeg/jfdctflt.c ================================================ /* * jfdctflt.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2003-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a floating-point implementation of the * forward DCT (Discrete Cosine Transform). * * This implementation should be more accurate than either of the integer * DCT implementations. However, it may not give the same results on all * machines because of differences in roundoff behavior. Speed will depend * on the hardware's floating point capacity. * * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT * on each column. Direct algorithms are also available, but they are * much more complex and seem not to be any faster when reduced to code. * * This implementation is based on Arai, Agui, and Nakajima's algorithm for * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in * Japanese, but the algorithm is described in the Pennebaker & Mitchell * JPEG textbook (see REFERENCES section in file README). The following code * is based directly on figure 4-8 in P&M. * While an 8-point DCT cannot be done in less than 11 multiplies, it is * possible to arrange the computation so that many of the multiplies are * simple scalings of the final outputs. These multiplies can then be * folded into the multiplications or divisions by the JPEG quantization * table entries. The AA&N method leaves only 5 multiplies and 29 adds * to be done in the DCT itself. * The primary disadvantage of this method is that with a fixed-point * implementation, accuracy is lost due to imprecise representation of the * scaled quantization values. However, that problem does not arise if * we use floating point arithmetic. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ #ifdef DCT_FLOAT_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ #endif /* * Perform the forward DCT on one block of samples. * * cK represents cos(K*pi/16). */ GLOBAL(void) jpeg_fdct_float (FAST_FLOAT * data, JSAMPARRAY sample_data, JDIMENSION start_col) { FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; FAST_FLOAT tmp10, tmp11, tmp12, tmp13; FAST_FLOAT z1, z2, z3, z4, z5, z11, z13; FAST_FLOAT *dataptr; JSAMPROW elemptr; int ctr; /* Pass 1: process rows. */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Load data into workspace */ tmp0 = (FAST_FLOAT) (GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7])); tmp7 = (FAST_FLOAT) (GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7])); tmp1 = (FAST_FLOAT) (GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6])); tmp6 = (FAST_FLOAT) (GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6])); tmp2 = (FAST_FLOAT) (GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5])); tmp5 = (FAST_FLOAT) (GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5])); tmp3 = (FAST_FLOAT) (GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4])); tmp4 = (FAST_FLOAT) (GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4])); /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; /* Apply unsigned->signed conversion. */ dataptr[0] = tmp10 + tmp11 - 8 * CENTERJSAMPLE; /* phase 3 */ dataptr[4] = tmp10 - tmp11; z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */ dataptr[2] = tmp13 + z1; /* phase 5 */ dataptr[6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[5] = z13 + z2; /* phase 6 */ dataptr[3] = z13 - z2; dataptr[1] = z11 + z4; dataptr[7] = z11 - z4; dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */ dataptr[DCTSIZE*4] = tmp10 - tmp11; z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */ dataptr[DCTSIZE*6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */ dataptr[DCTSIZE*3] = z13 - z2; dataptr[DCTSIZE*1] = z11 + z4; dataptr[DCTSIZE*7] = z11 - z4; dataptr++; /* advance pointer to next column */ } } #endif /* DCT_FLOAT_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jfdctfst.c ================================================ /* * jfdctfst.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2003-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a fast, not so accurate integer implementation of the * forward DCT (Discrete Cosine Transform). * * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT * on each column. Direct algorithms are also available, but they are * much more complex and seem not to be any faster when reduced to code. * * This implementation is based on Arai, Agui, and Nakajima's algorithm for * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in * Japanese, but the algorithm is described in the Pennebaker & Mitchell * JPEG textbook (see REFERENCES section in file README). The following code * is based directly on figure 4-8 in P&M. * While an 8-point DCT cannot be done in less than 11 multiplies, it is * possible to arrange the computation so that many of the multiplies are * simple scalings of the final outputs. These multiplies can then be * folded into the multiplications or divisions by the JPEG quantization * table entries. The AA&N method leaves only 5 multiplies and 29 adds * to be done in the DCT itself. * The primary disadvantage of this method is that with fixed-point math, * accuracy is lost due to imprecise representation of the scaled * quantization values. The smaller the quantization table entry, the less * precise the scaled value, so this implementation does worse with high- * quality-setting files than with low-quality ones. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ #ifdef DCT_IFAST_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ #endif /* Scaling decisions are generally the same as in the LL&M algorithm; * see jfdctint.c for more details. However, we choose to descale * (right shift) multiplication products as soon as they are formed, * rather than carrying additional fractional bits into subsequent additions. * This compromises accuracy slightly, but it lets us save a few shifts. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples) * everywhere except in the multiplications proper; this saves a good deal * of work on 16-bit-int machines. * * Again to save a few shifts, the intermediate results between pass 1 and * pass 2 are not upscaled, but are represented only to integral precision. * * A final compromise is to represent the multiplicative constants to only * 8 fractional bits, rather than 13. This saves some shifting work on some * machines, and may also reduce the cost of multiplication (since there * are fewer one-bits in the constants). */ #define CONST_BITS 8 /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 8 #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */ #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */ #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */ #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */ #else #define FIX_0_382683433 FIX(0.382683433) #define FIX_0_541196100 FIX(0.541196100) #define FIX_0_707106781 FIX(0.707106781) #define FIX_1_306562965 FIX(1.306562965) #endif /* We can gain a little more speed, with a further compromise in accuracy, * by omitting the addition in a descaling shift. This yields an incorrectly * rounded result half the time... */ #ifndef USE_ACCURATE_ROUNDING #undef DESCALE #define DESCALE(x,n) RIGHT_SHIFT(x, n) #endif /* Multiply a DCTELEM variable by an INT32 constant, and immediately * descale to yield a DCTELEM result. */ #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS)) /* * Perform the forward DCT on one block of samples. * * cK represents cos(K*pi/16). */ GLOBAL(void) jpeg_fdct_ifast (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; DCTELEM tmp10, tmp11, tmp12, tmp13; DCTELEM z1, z2, z3, z4, z5, z11, z13; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Load data into workspace */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp7 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp6 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp5 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp4 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; /* Apply unsigned->signed conversion. */ dataptr[0] = tmp10 + tmp11 - 8 * CENTERJSAMPLE; /* phase 3 */ dataptr[4] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ dataptr[2] = tmp13 + z1; /* phase 5 */ dataptr[6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[5] = z13 + z2; /* phase 6 */ dataptr[3] = z13 - z2; dataptr[1] = z11 + z4; dataptr[7] = z11 - z4; dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */ dataptr[DCTSIZE*4] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */ dataptr[DCTSIZE*6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */ dataptr[DCTSIZE*3] = z13 - z2; dataptr[DCTSIZE*1] = z11 + z4; dataptr[DCTSIZE*7] = z11 - z4; dataptr++; /* advance pointer to next column */ } } #endif /* DCT_IFAST_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jfdctint.c ================================================ /* * jfdctint.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modification developed 2003-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a slow-but-accurate integer implementation of the * forward DCT (Discrete Cosine Transform). * * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT * on each column. Direct algorithms are also available, but they are * much more complex and seem not to be any faster when reduced to code. * * This implementation is based on an algorithm described in * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. * The primary algorithm described there uses 11 multiplies and 29 adds. * We use their alternate method with 12 multiplies and 32 adds. * The advantage of this method is that no data path contains more than one * multiplication; this allows a very simple and accurate implementation in * scaled fixed-point arithmetic, with a minimal number of shifts. * * We also provide FDCT routines with various input sample block sizes for * direct resolution reduction or enlargement and for direct resolving the * common 2x1 and 1x2 subsampling cases without additional resampling: NxN * (N=1...16), 2NxN, and Nx2N (N=1...8) pixels for one 8x8 output DCT block. * * For N<8 we fill the remaining block coefficients with zero. * For N>8 we apply a partial N-point FDCT on the input samples, computing * just the lower 8 frequency coefficients and discarding the rest. * * We must scale the output coefficients of the N-point FDCT appropriately * to the standard 8-point FDCT level by 8/N per 1-D pass. This scaling * is folded into the constant multipliers (pass 2) and/or final/initial * shifting. * * CAUTION: We rely on the FIX() macro except for the N=1,2,4,8 cases * since there would be too many additional constants to pre-calculate. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ #ifdef DCT_ISLOW_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCT blocks. /* deliberate syntax err */ #endif /* * The poop on this scaling stuff is as follows: * * Each 1-D DCT step produces outputs which are a factor of sqrt(N) * larger than the true DCT outputs. The final outputs are therefore * a factor of N larger than desired; since N=8 this can be cured by * a simple right shift at the end of the algorithm. The advantage of * this arrangement is that we save two multiplications per 1-D DCT, * because the y0 and y4 outputs need not be divided by sqrt(N). * In the IJG code, this factor of 8 is removed by the quantization step * (in jcdctmgr.c), NOT in this module. * * We have to do addition and subtraction of the integer inputs, which * is no problem, and multiplication by fractional constants, which is * a problem to do in integer arithmetic. We multiply all the constants * by CONST_SCALE and convert them to integer constants (thus retaining * CONST_BITS bits of precision in the constants). After doing a * multiplication we have to divide the product by CONST_SCALE, with proper * rounding, to produce the correct output. This division can be done * cheaply as a right shift of CONST_BITS bits. We postpone shifting * as long as possible so that partial sums can be added together with * full fractional precision. * * The outputs of the first pass are scaled up by PASS1_BITS bits so that * they are represented to better-than-integral precision. These outputs * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word * with the recommended scaling. (For 12-bit sample data, the intermediate * array is INT32 anyway.) * * To avoid overflow of the 32-bit intermediate results in pass 2, we must * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis * shows that the values given below are the most effective. */ #if BITS_IN_JSAMPLE == 8 #define CONST_BITS 13 #define PASS1_BITS 2 #else #define CONST_BITS 13 #define PASS1_BITS 1 /* lose a little precision to avoid overflow */ #endif /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 13 #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */ #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */ #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */ #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */ #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */ #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */ #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */ #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */ #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */ #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */ #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */ #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */ #else #define FIX_0_298631336 FIX(0.298631336) #define FIX_0_390180644 FIX(0.390180644) #define FIX_0_541196100 FIX(0.541196100) #define FIX_0_765366865 FIX(0.765366865) #define FIX_0_899976223 FIX(0.899976223) #define FIX_1_175875602 FIX(1.175875602) #define FIX_1_501321110 FIX(1.501321110) #define FIX_1_847759065 FIX(1.847759065) #define FIX_1_961570560 FIX(1.961570560) #define FIX_2_053119869 FIX(2.053119869) #define FIX_2_562915447 FIX(2.562915447) #define FIX_3_072711026 FIX(3.072711026) #endif /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. * For 8-bit samples with the recommended scaling, all the variable * and constant values involved are no more than 16 bits wide, so a * 16x16->32 bit multiply can be used instead of a full 32x32 multiply. * For 12-bit samples, a full 32-bit multiplication will be needed. */ #if BITS_IN_JSAMPLE == 8 #define MULTIPLY(var,const) MULTIPLY16C16(var,const) #else #define MULTIPLY(var,const) ((var) * (const)) #endif /* * Perform the forward DCT on one block of samples. */ GLOBAL(void) jpeg_fdct_islow (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "c1" should be "c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); dataptr[2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* -c3+c5 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp0 += z1 + tmp12; tmp3 += z1 + tmp13; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp1 += z1 + tmp13; tmp2 += z1 + tmp12; dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0, CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp1, CONST_BITS-PASS1_BITS); dataptr[5] = (DCTELEM) RIGHT_SHIFT(tmp2, CONST_BITS-PASS1_BITS); dataptr[7] = (DCTELEM) RIGHT_SHIFT(tmp3, CONST_BITS-PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "c1" should be "c6". */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; /* Add fudge factor here for final descale. */ tmp10 = tmp0 + tmp3 + (ONE << (PASS1_BITS-1)); tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; dataptr[DCTSIZE*0] = (DCTELEM) RIGHT_SHIFT(tmp10 + tmp11, PASS1_BITS); dataptr[DCTSIZE*4] = (DCTELEM) RIGHT_SHIFT(tmp10 - tmp11, PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS+PASS1_BITS-1); dataptr[DCTSIZE*2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), /* c2-c6 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), /* c2+c6 */ CONST_BITS+PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS+PASS1_BITS-1); tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* -c3+c5 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp0 += z1 + tmp12; tmp3 += z1 + tmp13; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp1 += z1 + tmp13; tmp2 += z1 + tmp12; dataptr[DCTSIZE*1] = (DCTELEM) RIGHT_SHIFT(tmp0, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) RIGHT_SHIFT(tmp1, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*5] = (DCTELEM) RIGHT_SHIFT(tmp2, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*7] = (DCTELEM) RIGHT_SHIFT(tmp3, CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } #ifdef DCT_SCALING_SUPPORTED /* * Perform the forward DCT on a 7x7 sample block. */ GLOBAL(void) jpeg_fdct_7x7 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12; INT32 z1, z2, z3; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * cK represents sqrt(2) * cos(K*pi/14). */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[6]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[5]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[4]); tmp3 = GETJSAMPLE(elemptr[3]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[6]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[5]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[4]); z1 = tmp0 + tmp2; /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((z1 + tmp1 + tmp3 - 7 * CENTERJSAMPLE) << PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.353553391)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(0.920609002)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.314692123)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS-PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(0.881747734)); /* c4 */ dataptr[4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.707106781)), /* c2+c6-c4 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS-PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.613604268)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(1.870828693)); /* c3+c1-c5 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS-PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS-PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/7)**2 = 64/49, which we fold * into the constant multipliers: * cK now represents sqrt(2) * cos(K*pi/14) * 64/49. */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*6]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*5]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*4]; tmp3 = dataptr[DCTSIZE*3]; tmp10 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*6]; tmp11 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*5]; tmp12 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*4]; z1 = tmp0 + tmp2; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(z1 + tmp1 + tmp3, FIX(1.306122449)), /* 64/49 */ CONST_BITS+PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.461784020)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(1.202428084)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.411026446)); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS+PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(1.151670509)); /* c4 */ dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.923568041)), /* c2+c6-c4 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS+PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.221765677)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.222383464)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.800824523)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.801442310)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(2.443531355)); /* c3+c1-c5 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp0, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp1, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp2, CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x6 sample block. */ GLOBAL(void) jpeg_fdct_6x6 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS-PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS-PASS1_BITS); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS-PASS1_BITS); dataptr[1] = (DCTELEM) (tmp10 + ((tmp0 + tmp1) << PASS1_BITS)); dataptr[3] = (DCTELEM) ((tmp0 - tmp1 - tmp2) << PASS1_BITS); dataptr[5] = (DCTELEM) (tmp10 + ((tmp2 - tmp1) << PASS1_BITS)); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)**2 = 16/9, which we fold * into the constant multipliers: * cK now represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*5]; tmp11 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*5]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*3]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS+PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 5x5 sample block. */ GLOBAL(void) jpeg_fdct_5x5 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We scale the results further by 2 as part of output adaption * scaling for different DCT size. * cK represents sqrt(2) * cos(K*pi/10). */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[3]); tmp2 = GETJSAMPLE(elemptr[2]); tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp2 - 5 * CENTERJSAMPLE) << (PASS1_BITS+1)); tmp11 = MULTIPLY(tmp11, FIX(0.790569415)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.353553391)); /* (c2-c4)/2 */ dataptr[2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS-PASS1_BITS-1); dataptr[4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS-PASS1_BITS-1); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(0.831253876)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.513743148)), /* c1-c3 */ CONST_BITS-PASS1_BITS-1); dataptr[3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.176250899)), /* c1+c3 */ CONST_BITS-PASS1_BITS-1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/5)**2 = 64/25, which we partially * fold into the constant multipliers (other part was done in pass 1): * cK now represents sqrt(2) * cos(K*pi/10) * 32/25. */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*4]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*3]; tmp2 = dataptr[DCTSIZE*2]; tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*4]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*3]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS+PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(1.011928851)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.452548340)); /* (c2-c4)/2 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS+PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(1.064004961)); /* c3 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.657591230)), /* c1-c3 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.785601151)), /* c1+c3 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x4 sample block. */ GLOBAL(void) jpeg_fdct_4x4 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We must also scale the output by (8/4)**2 = 2**2, which we add here. * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS+2)); dataptr[2] = (DCTELEM) ((tmp0 - tmp1) << (PASS1_BITS+2)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-3); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS-2); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS-2); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*3] + (ONE << (PASS1_BITS-1)); tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*2]; tmp10 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*3]; tmp11 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*2]; dataptr[DCTSIZE*0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); dataptr[DCTSIZE*2] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS+PASS1_BITS-1); dataptr[DCTSIZE*1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 3x3 sample block. */ GLOBAL(void) jpeg_fdct_3x3 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We scale the results further by 2**2 as part of output adaption * scaling for different DCT size. * cK represents sqrt(2) * cos(K*pi/6). */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[2]); tmp1 = GETJSAMPLE(elemptr[1]); tmp2 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 3 * CENTERJSAMPLE) << (PASS1_BITS+2)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(0.707106781)), /* c2 */ CONST_BITS-PASS1_BITS-2); /* Odd part */ dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(1.224744871)), /* c1 */ CONST_BITS-PASS1_BITS-2); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/3)**2 = 64/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * cK now represents sqrt(2) * cos(K*pi/6) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*2]; tmp1 = dataptr[DCTSIZE*1]; tmp2 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*2]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(1.257078722)), /* c2 */ CONST_BITS+PASS1_BITS); /* Odd part */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(2.177324216)), /* c1 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x2 sample block. */ GLOBAL(void) jpeg_fdct_2x2 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { DCTELEM tmp0, tmp1, tmp2, tmp3; JSAMPROW elemptr; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT. */ /* Row 0 */ elemptr = sample_data[0] + start_col; tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[1]); tmp1 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[1]); /* Row 1 */ elemptr = sample_data[1] + start_col; tmp2 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[1]); tmp3 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[1]); /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/2)**2 = 2**4. */ /* Column 0 */ /* Apply unsigned->signed conversion. */ data[DCTSIZE*0] = (tmp0 + tmp2 - 4 * CENTERJSAMPLE) << 4; data[DCTSIZE*1] = (tmp0 - tmp2) << 4; /* Column 1 */ data[DCTSIZE*0+1] = (tmp1 + tmp3) << 4; data[DCTSIZE*1+1] = (tmp1 - tmp3) << 4; } /* * Perform the forward DCT on a 1x1 sample block. */ GLOBAL(void) jpeg_fdct_1x1 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { DCTELEM dcval; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); dcval = GETJSAMPLE(sample_data[0][start_col]); /* We leave the result scaled up by an overall factor of 8. */ /* We must also scale the output by (8/1)**2 = 2**6. */ /* Apply unsigned->signed conversion. */ data[0] = (dcval - CENTERJSAMPLE) << 6; } /* * Perform the forward DCT on a 9x9 sample block. */ GLOBAL(void) jpeg_fdct_9x9 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1, z2; DCTELEM workspace[8]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * we scale the results further by 2 as part of output adaption * scaling for different DCT size. * cK represents sqrt(2) * cos(K*pi/18). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[8]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[7]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[6]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[5]); tmp4 = GETJSAMPLE(elemptr[4]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[8]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[7]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[6]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[5]); z1 = tmp0 + tmp2 + tmp3; z2 = tmp1 + tmp4; /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((z1 + z2 - 9 * CENTERJSAMPLE) << 1); dataptr[6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z2 - z2, FIX(0.707106781)), /* c6 */ CONST_BITS-1); z1 = MULTIPLY(tmp0 - tmp2, FIX(1.328926049)); /* c2 */ z2 = MULTIPLY(tmp1 - tmp4 - tmp4, FIX(0.707106781)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp2 - tmp3, FIX(1.083350441)) /* c4 */ + z1 + z2, CONST_BITS-1); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp3 - tmp0, FIX(0.245575608)) /* c8 */ + z1 - z2, CONST_BITS-1); /* Odd part */ dataptr[3] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12 - tmp13, FIX(1.224744871)), /* c3 */ CONST_BITS-1); tmp11 = MULTIPLY(tmp11, FIX(1.224744871)); /* c3 */ tmp0 = MULTIPLY(tmp10 + tmp12, FIX(0.909038955)); /* c5 */ tmp1 = MULTIPLY(tmp10 + tmp13, FIX(0.483689525)); /* c7 */ dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp0 + tmp1, CONST_BITS-1); tmp2 = MULTIPLY(tmp12 - tmp13, FIX(1.392728481)); /* c1 */ dataptr[5] = (DCTELEM) DESCALE(tmp0 - tmp11 - tmp2, CONST_BITS-1); dataptr[7] = (DCTELEM) DESCALE(tmp1 - tmp11 + tmp2, CONST_BITS-1); ctr++; if (ctr != DCTSIZE) { if (ctr == 9) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/9)**2 = 64/81, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/18) * 128/81. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*0]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*7]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*6]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*5]; tmp4 = dataptr[DCTSIZE*4]; tmp10 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*0]; tmp11 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*7]; tmp12 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*6]; tmp13 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*5]; z1 = tmp0 + tmp2 + tmp3; z2 = tmp1 + tmp4; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(z1 + z2, FIX(1.580246914)), /* 128/81 */ CONST_BITS+2); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z2 - z2, FIX(1.117403309)), /* c6 */ CONST_BITS+2); z1 = MULTIPLY(tmp0 - tmp2, FIX(2.100031287)); /* c2 */ z2 = MULTIPLY(tmp1 - tmp4 - tmp4, FIX(1.117403309)); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp2 - tmp3, FIX(1.711961190)) /* c4 */ + z1 + z2, CONST_BITS+2); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp3 - tmp0, FIX(0.388070096)) /* c8 */ + z1 - z2, CONST_BITS+2); /* Odd part */ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12 - tmp13, FIX(1.935399303)), /* c3 */ CONST_BITS+2); tmp11 = MULTIPLY(tmp11, FIX(1.935399303)); /* c3 */ tmp0 = MULTIPLY(tmp10 + tmp12, FIX(1.436506004)); /* c5 */ tmp1 = MULTIPLY(tmp10 + tmp13, FIX(0.764348879)); /* c7 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp11 + tmp0 + tmp1, CONST_BITS+2); tmp2 = MULTIPLY(tmp12 - tmp13, FIX(2.200854883)); /* c1 */ dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp0 - tmp11 - tmp2, CONST_BITS+2); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp1 - tmp11 + tmp2, CONST_BITS+2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 10x10 sample block. */ GLOBAL(void) jpeg_fdct_10x10 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM workspace[8*2]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * we scale the results further by 2 as part of output adaption * scaling for different DCT size. * cK represents sqrt(2) * cos(K*pi/20). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[8]); tmp12 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[5]); tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[8]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[5]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 10 * CENTERJSAMPLE) << 1); tmp12 += tmp12; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.144122806)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.437016024)), /* c8 */ CONST_BITS-1); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(0.831253876)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.513743148)), /* c2-c6 */ CONST_BITS-1); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.176250899)), /* c2+c6 */ CONST_BITS-1); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[5] = (DCTELEM) ((tmp10 - tmp11 - tmp2) << 1); tmp2 <<= CONST_BITS; dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.396802247)) + /* c1 */ MULTIPLY(tmp1, FIX(1.260073511)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.642039522)) + /* c7 */ MULTIPLY(tmp4, FIX(0.221231742)), /* c9 */ CONST_BITS-1); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(0.951056516)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.587785252)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.309016994)) + /* (c3-c7)/2 */ (tmp11 << (CONST_BITS - 1)) - tmp2; dataptr[3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS-1); dataptr[7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS-1); ctr++; if (ctr != DCTSIZE) { if (ctr == 10) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/10)**2 = 16/25, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/20) * 32/25. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*1]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*0]; tmp12 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*7]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*6]; tmp4 = dataptr[DCTSIZE*4] + dataptr[DCTSIZE*5]; tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*1]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*0]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*7]; tmp3 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*6]; tmp4 = dataptr[DCTSIZE*4] - dataptr[DCTSIZE*5]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(1.28)), /* 32/25 */ CONST_BITS+2); tmp12 += tmp12; dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.464477191)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.559380511)), /* c8 */ CONST_BITS+2); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(1.064004961)); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.657591230)), /* c2-c6 */ CONST_BITS+2); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.785601151)), /* c2+c6 */ CONST_BITS+2); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS+2); tmp2 = MULTIPLY(tmp2, FIX(1.28)); /* 32/25 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.787906876)) + /* c1 */ MULTIPLY(tmp1, FIX(1.612894094)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.821810588)) + /* c7 */ MULTIPLY(tmp4, FIX(0.283176630)), /* c9 */ CONST_BITS+2); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(1.217352341)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.752365123)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.395541753)) + /* (c3-c7)/2 */ MULTIPLY(tmp11, FIX(0.64)) - tmp2; /* 16/25 */ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS+2); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS+2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on an 11x11 sample block. */ GLOBAL(void) jpeg_fdct_11x11 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; INT32 z1, z2, z3; DCTELEM workspace[8*3]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * we scale the results further by 2 as part of output adaption * scaling for different DCT size. * cK represents sqrt(2) * cos(K*pi/22). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[10]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[9]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[8]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[7]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[6]); tmp5 = GETJSAMPLE(elemptr[5]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[10]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[9]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[8]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[7]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 - 11 * CENTERJSAMPLE) << 1); tmp5 += tmp5; tmp0 -= tmp5; tmp1 -= tmp5; tmp2 -= tmp5; tmp3 -= tmp5; tmp4 -= tmp5; z1 = MULTIPLY(tmp0 + tmp3, FIX(1.356927976)) + /* c2 */ MULTIPLY(tmp2 + tmp4, FIX(0.201263574)); /* c10 */ z2 = MULTIPLY(tmp1 - tmp3, FIX(0.926112931)); /* c6 */ z3 = MULTIPLY(tmp0 - tmp1, FIX(1.189712156)); /* c4 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 - MULTIPLY(tmp3, FIX(1.018300590)) /* c2+c8-c6 */ - MULTIPLY(tmp4, FIX(1.390975730)), /* c4+c10 */ CONST_BITS-1); dataptr[4] = (DCTELEM) DESCALE(z2 + z3 + MULTIPLY(tmp1, FIX(0.062335650)) /* c4-c6-c10 */ - MULTIPLY(tmp2, FIX(1.356927976)) /* c2 */ + MULTIPLY(tmp4, FIX(0.587485545)), /* c8 */ CONST_BITS-1); dataptr[6] = (DCTELEM) DESCALE(z1 + z3 - MULTIPLY(tmp0, FIX(1.620527200)) /* c2+c4-c6 */ - MULTIPLY(tmp2, FIX(0.788749120)), /* c8+c10 */ CONST_BITS-1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.286413905)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.068791298)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.764581576)); /* c7 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.719967871)) /* c7+c5+c3-c1 */ + MULTIPLY(tmp14, FIX(0.398430003)); /* c9 */ tmp4 = MULTIPLY(tmp11 + tmp12, - FIX(0.764581576)); /* -c7 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.399818907)); /* -c1 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(1.276416582)) /* c9+c7+c1-c3 */ - MULTIPLY(tmp14, FIX(1.068791298)); /* c5 */ tmp10 = MULTIPLY(tmp12 + tmp13, FIX(0.398430003)); /* c9 */ tmp2 += tmp4 + tmp10 - MULTIPLY(tmp12, FIX(1.989053629)) /* c9+c5+c3-c7 */ + MULTIPLY(tmp14, FIX(1.399818907)); /* c1 */ tmp3 += tmp5 + tmp10 + MULTIPLY(tmp13, FIX(1.305598626)) /* c1+c5-c9-c7 */ - MULTIPLY(tmp14, FIX(1.286413905)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS-1); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS-1); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS-1); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS-1); ctr++; if (ctr != DCTSIZE) { if (ctr == 11) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/11)**2 = 64/121, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/22) * 128/121. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*2]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*1]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*0]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*7]; tmp4 = dataptr[DCTSIZE*4] + dataptr[DCTSIZE*6]; tmp5 = dataptr[DCTSIZE*5]; tmp10 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*2]; tmp11 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*1]; tmp12 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*0]; tmp13 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*7]; tmp14 = dataptr[DCTSIZE*4] - dataptr[DCTSIZE*6]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5, FIX(1.057851240)), /* 128/121 */ CONST_BITS+2); tmp5 += tmp5; tmp0 -= tmp5; tmp1 -= tmp5; tmp2 -= tmp5; tmp3 -= tmp5; tmp4 -= tmp5; z1 = MULTIPLY(tmp0 + tmp3, FIX(1.435427942)) + /* c2 */ MULTIPLY(tmp2 + tmp4, FIX(0.212906922)); /* c10 */ z2 = MULTIPLY(tmp1 - tmp3, FIX(0.979689713)); /* c6 */ z3 = MULTIPLY(tmp0 - tmp1, FIX(1.258538479)); /* c4 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + z2 - MULTIPLY(tmp3, FIX(1.077210542)) /* c2+c8-c6 */ - MULTIPLY(tmp4, FIX(1.471445400)), /* c4+c10 */ CONST_BITS+2); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(z2 + z3 + MULTIPLY(tmp1, FIX(0.065941844)) /* c4-c6-c10 */ - MULTIPLY(tmp2, FIX(1.435427942)) /* c2 */ + MULTIPLY(tmp4, FIX(0.621472312)), /* c8 */ CONST_BITS+2); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + z3 - MULTIPLY(tmp0, FIX(1.714276708)) /* c2+c4-c6 */ - MULTIPLY(tmp2, FIX(0.834379234)), /* c8+c10 */ CONST_BITS+2); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.360834544)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.130622199)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.808813568)); /* c7 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.819470145)) /* c7+c5+c3-c1 */ + MULTIPLY(tmp14, FIX(0.421479672)); /* c9 */ tmp4 = MULTIPLY(tmp11 + tmp12, - FIX(0.808813568)); /* -c7 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.480800167)); /* -c1 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(1.350258864)) /* c9+c7+c1-c3 */ - MULTIPLY(tmp14, FIX(1.130622199)); /* c5 */ tmp10 = MULTIPLY(tmp12 + tmp13, FIX(0.421479672)); /* c9 */ tmp2 += tmp4 + tmp10 - MULTIPLY(tmp12, FIX(2.104122847)) /* c9+c5+c3-c7 */ + MULTIPLY(tmp14, FIX(1.480800167)); /* c1 */ tmp3 += tmp5 + tmp10 + MULTIPLY(tmp13, FIX(1.381129125)) /* c1+c5-c9-c7 */ - MULTIPLY(tmp14, FIX(1.360834544)); /* c3 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp0, CONST_BITS+2); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp1, CONST_BITS+2); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp2, CONST_BITS+2); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp3, CONST_BITS+2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 12x12 sample block. */ GLOBAL(void) jpeg_fdct_12x12 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM workspace[8*4]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT. * cK represents sqrt(2) * cos(K*pi/24). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[6]); tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) (tmp10 + tmp11 + tmp12 - 12 * CENTERJSAMPLE); dataptr[6] = (DCTELEM) (tmp13 - tmp14 - tmp15); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.224744871)), /* c4 */ CONST_BITS); dataptr[2] = (DCTELEM) DESCALE(tmp14 - tmp15 + MULTIPLY(tmp13 + tmp15, FIX(1.366025404)), /* c2 */ CONST_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX_0_541196100); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX_0_765366865); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX_1_847759065); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.121971054)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.860918669)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.580774953)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.184591911)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.184591911)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.339493912)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.860918669)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.725788011)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(1.121971054)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.306562965)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX_0_541196100); /* c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 12) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/12)**2 = 4/9, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/24) * 8/9. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*3]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*2]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*1]; tmp3 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*0]; tmp4 = dataptr[DCTSIZE*4] + dataptr[DCTSIZE*7]; tmp5 = dataptr[DCTSIZE*5] + dataptr[DCTSIZE*6]; tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*3]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*2]; tmp2 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*1]; tmp3 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*0]; tmp4 = dataptr[DCTSIZE*4] - dataptr[DCTSIZE*7]; tmp5 = dataptr[DCTSIZE*5] - dataptr[DCTSIZE*6]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(0.888888889)), /* 8/9 */ CONST_BITS+1); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(MULTIPLY(tmp13 - tmp14 - tmp15, FIX(0.888888889)), /* 8/9 */ CONST_BITS+1); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.088662108)), /* c4 */ CONST_BITS+1); dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp14 - tmp15, FIX(0.888888889)) + /* 8/9 */ MULTIPLY(tmp13 + tmp15, FIX(1.214244803)), /* c2 */ CONST_BITS+1); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX(0.481063200)); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX(0.680326102)); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX(1.642452502)); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(0.997307603)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.765261039)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.516244403)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.164081699)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.164081699)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.079550144)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.765261039)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.645144899)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(0.997307603)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.161389302)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX(0.481063200)); /* c9 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10, CONST_BITS+1); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp11, CONST_BITS+1); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp12, CONST_BITS+1); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp13, CONST_BITS+1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 13x13 sample block. */ GLOBAL(void) jpeg_fdct_13x13 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; INT32 z1, z2; DCTELEM workspace[8*5]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT. * cK represents sqrt(2) * cos(K*pi/26). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[12]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[11]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[10]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[9]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[8]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[7]); tmp6 = GETJSAMPLE(elemptr[6]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[12]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[11]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[10]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[9]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[8]); tmp15 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) (tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 + tmp6 - 13 * CENTERJSAMPLE); tmp6 += tmp6; tmp0 -= tmp6; tmp1 -= tmp6; tmp2 -= tmp6; tmp3 -= tmp6; tmp4 -= tmp6; tmp5 -= tmp6; dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.373119086)) + /* c2 */ MULTIPLY(tmp1, FIX(1.058554052)) + /* c6 */ MULTIPLY(tmp2, FIX(0.501487041)) - /* c10 */ MULTIPLY(tmp3, FIX(0.170464608)) - /* c12 */ MULTIPLY(tmp4, FIX(0.803364869)) - /* c8 */ MULTIPLY(tmp5, FIX(1.252223920)), /* c4 */ CONST_BITS); z1 = MULTIPLY(tmp0 - tmp2, FIX(1.155388986)) - /* (c4+c6)/2 */ MULTIPLY(tmp3 - tmp4, FIX(0.435816023)) - /* (c2-c10)/2 */ MULTIPLY(tmp1 - tmp5, FIX(0.316450131)); /* (c8-c12)/2 */ z2 = MULTIPLY(tmp0 + tmp2, FIX(0.096834934)) - /* (c4-c6)/2 */ MULTIPLY(tmp3 + tmp4, FIX(0.937303064)) + /* (c2+c10)/2 */ MULTIPLY(tmp1 + tmp5, FIX(0.486914739)); /* (c8+c12)/2 */ dataptr[4] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 - z2, CONST_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.322312651)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.163874945)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.937797057)) + /* c7 */ MULTIPLY(tmp14 + tmp15, FIX(0.338443458)); /* c11 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(2.020082300)) + /* c3+c5+c7-c1 */ MULTIPLY(tmp14, FIX(0.318774355)); /* c9-c11 */ tmp4 = MULTIPLY(tmp14 - tmp15, FIX(0.937797057)) - /* c7 */ MULTIPLY(tmp11 + tmp12, FIX(0.338443458)); /* c11 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.163874945)); /* -c5 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(0.837223564)) - /* c5+c9+c11-c3 */ MULTIPLY(tmp14, FIX(2.341699410)); /* c1+c7 */ tmp6 = MULTIPLY(tmp12 + tmp13, - FIX(0.657217813)); /* -c9 */ tmp2 += tmp4 + tmp6 - MULTIPLY(tmp12, FIX(1.572116027)) + /* c1+c5-c9-c11 */ MULTIPLY(tmp15, FIX(2.260109708)); /* c3+c7 */ tmp3 += tmp5 + tmp6 + MULTIPLY(tmp13, FIX(2.205608352)) - /* c3+c5+c9-c7 */ MULTIPLY(tmp15, FIX(1.742345811)); /* c1+c11 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 13) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/13)**2 = 64/169, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/26) * 128/169. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*4]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*3]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*2]; tmp3 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*1]; tmp4 = dataptr[DCTSIZE*4] + wsptr[DCTSIZE*0]; tmp5 = dataptr[DCTSIZE*5] + dataptr[DCTSIZE*7]; tmp6 = dataptr[DCTSIZE*6]; tmp10 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*4]; tmp11 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*3]; tmp12 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*2]; tmp13 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*1]; tmp14 = dataptr[DCTSIZE*4] - wsptr[DCTSIZE*0]; tmp15 = dataptr[DCTSIZE*5] - dataptr[DCTSIZE*7]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 + tmp6, FIX(0.757396450)), /* 128/169 */ CONST_BITS+1); tmp6 += tmp6; tmp0 -= tmp6; tmp1 -= tmp6; tmp2 -= tmp6; tmp3 -= tmp6; tmp4 -= tmp6; tmp5 -= tmp6; dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.039995521)) + /* c2 */ MULTIPLY(tmp1, FIX(0.801745081)) + /* c6 */ MULTIPLY(tmp2, FIX(0.379824504)) - /* c10 */ MULTIPLY(tmp3, FIX(0.129109289)) - /* c12 */ MULTIPLY(tmp4, FIX(0.608465700)) - /* c8 */ MULTIPLY(tmp5, FIX(0.948429952)), /* c4 */ CONST_BITS+1); z1 = MULTIPLY(tmp0 - tmp2, FIX(0.875087516)) - /* (c4+c6)/2 */ MULTIPLY(tmp3 - tmp4, FIX(0.330085509)) - /* (c2-c10)/2 */ MULTIPLY(tmp1 - tmp5, FIX(0.239678205)); /* (c8-c12)/2 */ z2 = MULTIPLY(tmp0 + tmp2, FIX(0.073342435)) - /* (c4-c6)/2 */ MULTIPLY(tmp3 + tmp4, FIX(0.709910013)) + /* (c2+c10)/2 */ MULTIPLY(tmp1 + tmp5, FIX(0.368787494)); /* (c8+c12)/2 */ dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS+1); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 - z2, CONST_BITS+1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.001514908)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(0.881514751)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.710284161)) + /* c7 */ MULTIPLY(tmp14 + tmp15, FIX(0.256335874)); /* c11 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.530003162)) + /* c3+c5+c7-c1 */ MULTIPLY(tmp14, FIX(0.241438564)); /* c9-c11 */ tmp4 = MULTIPLY(tmp14 - tmp15, FIX(0.710284161)) - /* c7 */ MULTIPLY(tmp11 + tmp12, FIX(0.256335874)); /* c11 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(0.881514751)); /* -c5 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(0.634110155)) - /* c5+c9+c11-c3 */ MULTIPLY(tmp14, FIX(1.773594819)); /* c1+c7 */ tmp6 = MULTIPLY(tmp12 + tmp13, - FIX(0.497774438)); /* -c9 */ tmp2 += tmp4 + tmp6 - MULTIPLY(tmp12, FIX(1.190715098)) + /* c1+c5-c9-c11 */ MULTIPLY(tmp15, FIX(1.711799069)); /* c3+c7 */ tmp3 += tmp5 + tmp6 + MULTIPLY(tmp13, FIX(1.670519935)) - /* c3+c5+c9-c7 */ MULTIPLY(tmp15, FIX(1.319646532)); /* c1+c11 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp0, CONST_BITS+1); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp1, CONST_BITS+1); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp2, CONST_BITS+1); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp3, CONST_BITS+1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 14x14 sample block. */ GLOBAL(void) jpeg_fdct_14x14 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; DCTELEM workspace[8*6]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT. * cK represents sqrt(2) * cos(K*pi/28). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[11]); tmp13 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[7]); tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[11]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) (tmp10 + tmp11 + tmp12 + tmp13 - 14 * CENTERJSAMPLE); tmp13 += tmp13; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.274162392)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.314692123)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.881747734)), /* c8 */ CONST_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(1.105676686)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.273079590)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.613604268)), /* c10 */ CONST_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.719280954)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(1.378756276)), /* c2 */ CONST_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[7] = (DCTELEM) (tmp0 - tmp10 + tmp3 - tmp11 - tmp6); tmp3 <<= CONST_BITS; tmp10 = MULTIPLY(tmp10, - FIX(0.158341681)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(1.405321284)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(1.197448846)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.752406978)); /* c9 */ dataptr[5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(2.373959773)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(1.119999435)), /* c1+c11-c9 */ CONST_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(1.334852607)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.467085129)); /* c11 */ dataptr[3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.424103948)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(3.069855259)), /* c1+c5+c11 */ CONST_BITS); dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 + tmp6 - MULTIPLY(tmp0 + tmp6, FIX(1.126980169)), /* c3+c5-c1 */ CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 14) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/14)**2 = 16/49, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/28) * 32/49. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*5]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*3]; tmp13 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*2]; tmp4 = dataptr[DCTSIZE*4] + wsptr[DCTSIZE*1]; tmp5 = dataptr[DCTSIZE*5] + wsptr[DCTSIZE*0]; tmp6 = dataptr[DCTSIZE*6] + dataptr[DCTSIZE*7]; tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*5]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*3]; tmp3 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*2]; tmp4 = dataptr[DCTSIZE*4] - wsptr[DCTSIZE*1]; tmp5 = dataptr[DCTSIZE*5] - wsptr[DCTSIZE*0]; tmp6 = dataptr[DCTSIZE*6] - dataptr[DCTSIZE*7]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12 + tmp13, FIX(0.653061224)), /* 32/49 */ CONST_BITS+1); tmp13 += tmp13; dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(0.832106052)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.205513223)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.575835255)), /* c8 */ CONST_BITS+1); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(0.722074570)); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.178337691)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.400721155)), /* c10 */ CONST_BITS+1); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.122795725)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(0.900412262)), /* c2 */ CONST_BITS+1); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp10 + tmp3 - tmp11 - tmp6, FIX(0.653061224)), /* 32/49 */ CONST_BITS+1); tmp3 = MULTIPLY(tmp3 , FIX(0.653061224)); /* 32/49 */ tmp10 = MULTIPLY(tmp10, - FIX(0.103406812)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(0.917760839)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(0.782007410)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.491367823)); /* c9 */ dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(1.550341076)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(0.731428202)), /* c1+c11-c9 */ CONST_BITS+1); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(0.871740478)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.305035186)); /* c11 */ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.276965844)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(2.004803435)), /* c1+c5+c11 */ CONST_BITS+1); dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 - MULTIPLY(tmp0, FIX(0.735987049)) /* c3+c5-c1 */ - MULTIPLY(tmp6, FIX(0.082925825)), /* c9-c11-c13 */ CONST_BITS+1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 15x15 sample block. */ GLOBAL(void) jpeg_fdct_15x15 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM workspace[8*7]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT. * cK represents sqrt(2) * cos(K*pi/30). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[14]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[13]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[12]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[11]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[10]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[9]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[8]); tmp7 = GETJSAMPLE(elemptr[7]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[14]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[13]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[12]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[11]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[10]); tmp15 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[9]); tmp16 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[8]); z1 = tmp0 + tmp4 + tmp5; z2 = tmp1 + tmp3 + tmp6; z3 = tmp2 + tmp7; /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) (z1 + z2 + z3 - 15 * CENTERJSAMPLE); z3 += z3; dataptr[6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z3, FIX(1.144122806)) - /* c6 */ MULTIPLY(z2 - z3, FIX(0.437016024)), /* c12 */ CONST_BITS); tmp2 += ((tmp1 + tmp4) >> 1) - tmp7 - tmp7; z1 = MULTIPLY(tmp3 - tmp2, FIX(1.531135173)) - /* c2+c14 */ MULTIPLY(tmp6 - tmp2, FIX(2.238241955)); /* c4+c8 */ z2 = MULTIPLY(tmp5 - tmp2, FIX(0.798468008)) - /* c8-c14 */ MULTIPLY(tmp0 - tmp2, FIX(0.091361227)); /* c2-c4 */ z3 = MULTIPLY(tmp0 - tmp3, FIX(1.383309603)) + /* c2 */ MULTIPLY(tmp6 - tmp5, FIX(0.946293579)) + /* c8 */ MULTIPLY(tmp1 - tmp4, FIX(0.790569415)); /* (c6+c12)/2 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z3, CONST_BITS); dataptr[4] = (DCTELEM) DESCALE(z2 + z3, CONST_BITS); /* Odd part */ tmp2 = MULTIPLY(tmp10 - tmp12 - tmp13 + tmp15 + tmp16, FIX(1.224744871)); /* c5 */ tmp1 = MULTIPLY(tmp10 - tmp14 - tmp15, FIX(1.344997024)) + /* c3 */ MULTIPLY(tmp11 - tmp13 - tmp16, FIX(0.831253876)); /* c9 */ tmp12 = MULTIPLY(tmp12, FIX(1.224744871)); /* c5 */ tmp4 = MULTIPLY(tmp10 - tmp16, FIX(1.406466353)) + /* c1 */ MULTIPLY(tmp11 + tmp14, FIX(1.344997024)) + /* c3 */ MULTIPLY(tmp13 + tmp15, FIX(0.575212477)); /* c11 */ tmp0 = MULTIPLY(tmp13, FIX(0.475753014)) - /* c7-c11 */ MULTIPLY(tmp14, FIX(0.513743148)) + /* c3-c9 */ MULTIPLY(tmp16, FIX(1.700497885)) + tmp4 + tmp12; /* c1+c13 */ tmp3 = MULTIPLY(tmp10, - FIX(0.355500862)) - /* -(c1-c7) */ MULTIPLY(tmp11, FIX(2.176250899)) - /* c3+c9 */ MULTIPLY(tmp15, FIX(0.869244010)) + tmp4 - tmp12; /* c11+c13 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 15) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/15)**2 = 64/225, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/30) * 256/225. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*6]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*5]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*4]; tmp3 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*3]; tmp4 = dataptr[DCTSIZE*4] + wsptr[DCTSIZE*2]; tmp5 = dataptr[DCTSIZE*5] + wsptr[DCTSIZE*1]; tmp6 = dataptr[DCTSIZE*6] + wsptr[DCTSIZE*0]; tmp7 = dataptr[DCTSIZE*7]; tmp10 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*6]; tmp11 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*5]; tmp12 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*4]; tmp13 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*3]; tmp14 = dataptr[DCTSIZE*4] - wsptr[DCTSIZE*2]; tmp15 = dataptr[DCTSIZE*5] - wsptr[DCTSIZE*1]; tmp16 = dataptr[DCTSIZE*6] - wsptr[DCTSIZE*0]; z1 = tmp0 + tmp4 + tmp5; z2 = tmp1 + tmp3 + tmp6; z3 = tmp2 + tmp7; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(z1 + z2 + z3, FIX(1.137777778)), /* 256/225 */ CONST_BITS+2); z3 += z3; dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z3, FIX(1.301757503)) - /* c6 */ MULTIPLY(z2 - z3, FIX(0.497227121)), /* c12 */ CONST_BITS+2); tmp2 += ((tmp1 + tmp4) >> 1) - tmp7 - tmp7; z1 = MULTIPLY(tmp3 - tmp2, FIX(1.742091575)) - /* c2+c14 */ MULTIPLY(tmp6 - tmp2, FIX(2.546621957)); /* c4+c8 */ z2 = MULTIPLY(tmp5 - tmp2, FIX(0.908479156)) - /* c8-c14 */ MULTIPLY(tmp0 - tmp2, FIX(0.103948774)); /* c2-c4 */ z3 = MULTIPLY(tmp0 - tmp3, FIX(1.573898926)) + /* c2 */ MULTIPLY(tmp6 - tmp5, FIX(1.076671805)) + /* c8 */ MULTIPLY(tmp1 - tmp4, FIX(0.899492312)); /* (c6+c12)/2 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + z3, CONST_BITS+2); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(z2 + z3, CONST_BITS+2); /* Odd part */ tmp2 = MULTIPLY(tmp10 - tmp12 - tmp13 + tmp15 + tmp16, FIX(1.393487498)); /* c5 */ tmp1 = MULTIPLY(tmp10 - tmp14 - tmp15, FIX(1.530307725)) + /* c3 */ MULTIPLY(tmp11 - tmp13 - tmp16, FIX(0.945782187)); /* c9 */ tmp12 = MULTIPLY(tmp12, FIX(1.393487498)); /* c5 */ tmp4 = MULTIPLY(tmp10 - tmp16, FIX(1.600246161)) + /* c1 */ MULTIPLY(tmp11 + tmp14, FIX(1.530307725)) + /* c3 */ MULTIPLY(tmp13 + tmp15, FIX(0.654463974)); /* c11 */ tmp0 = MULTIPLY(tmp13, FIX(0.541301207)) - /* c7-c11 */ MULTIPLY(tmp14, FIX(0.584525538)) + /* c3-c9 */ MULTIPLY(tmp16, FIX(1.934788705)) + tmp4 + tmp12; /* c1+c13 */ tmp3 = MULTIPLY(tmp10, - FIX(0.404480980)) - /* -(c1-c7) */ MULTIPLY(tmp11, FIX(2.476089912)) - /* c3+c9 */ MULTIPLY(tmp15, FIX(0.989006518)) + tmp4 - tmp12; /* c11+c13 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp0, CONST_BITS+2); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp1, CONST_BITS+2); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp2, CONST_BITS+2); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp3, CONST_BITS+2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 16x16 sample block. */ GLOBAL(void) jpeg_fdct_16x16 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; DCTELEM workspace[DCTSIZE2]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) + GETJSAMPLE(elemptr[8]); tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) - GETJSAMPLE(elemptr[8]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 16 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS-PASS1_BITS); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS-PASS1_BITS); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS-PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS-PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS-PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == DCTSIZE * 2) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/16)**2 = 1/2**2. * cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*4] + wsptr[DCTSIZE*3]; tmp5 = dataptr[DCTSIZE*5] + wsptr[DCTSIZE*2]; tmp6 = dataptr[DCTSIZE*6] + wsptr[DCTSIZE*1]; tmp7 = dataptr[DCTSIZE*7] + wsptr[DCTSIZE*0]; tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*4] - wsptr[DCTSIZE*3]; tmp5 = dataptr[DCTSIZE*5] - wsptr[DCTSIZE*2]; tmp6 = dataptr[DCTSIZE*6] - wsptr[DCTSIZE*1]; tmp7 = dataptr[DCTSIZE*7] - wsptr[DCTSIZE*0]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11 + tmp12 + tmp13, PASS1_BITS+2); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS+PASS1_BITS+2); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+10 */ CONST_BITS+PASS1_BITS+2); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS+PASS1_BITS+2); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10, CONST_BITS+PASS1_BITS+2); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp11, CONST_BITS+PASS1_BITS+2); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp12, CONST_BITS+PASS1_BITS+2); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp13, CONST_BITS+PASS1_BITS+2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 16x8 sample block. * * 16-point FDCT in pass 1 (rows), 8-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_16x8 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; INT32 z1; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 16-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; ctr = 0; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) + GETJSAMPLE(elemptr[8]); tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) - GETJSAMPLE(elemptr[8]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 16 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS-PASS1_BITS); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS-PASS1_BITS); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS-PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS-PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS-PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by 8/16 = 1/2. * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "c1" should be "c6". */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS+1); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS+1); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, FIX_0_765366865), /* c2-c6 */ CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 - MULTIPLY(tmp13, FIX_1_847759065), /* c2+c6 */ CONST_BITS+PASS1_BITS+1); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* -c3+c5 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp0 += z1 + tmp12; tmp3 += z1 + tmp13; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp1 += z1 + tmp13; tmp2 += z1 + tmp12; dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp0, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp1, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp2, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp3, CONST_BITS+PASS1_BITS+1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 14x7 sample block. * * 14-point FDCT in pass 1 (rows), 7-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_14x7 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero bottom row of output coefficient block. */ MEMZERO(&data[DCTSIZE*7], SIZEOF(DCTELEM) * DCTSIZE); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 14-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/28). */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[11]); tmp13 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[7]); tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[11]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 14 * CENTERJSAMPLE) << PASS1_BITS); tmp13 += tmp13; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.274162392)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.314692123)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.881747734)), /* c8 */ CONST_BITS-PASS1_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(1.105676686)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.273079590)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.613604268)), /* c10 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.719280954)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(1.378756276)), /* c2 */ CONST_BITS-PASS1_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[7] = (DCTELEM) ((tmp0 - tmp10 + tmp3 - tmp11 - tmp6) << PASS1_BITS); tmp3 <<= CONST_BITS; tmp10 = MULTIPLY(tmp10, - FIX(0.158341681)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(1.405321284)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(1.197448846)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.752406978)); /* c9 */ dataptr[5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(2.373959773)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(1.119999435)), /* c1+c11-c9 */ CONST_BITS-PASS1_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(1.334852607)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.467085129)); /* c11 */ dataptr[3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.424103948)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(3.069855259)), /* c1+c5+c11 */ CONST_BITS-PASS1_BITS); dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 + tmp6 - MULTIPLY(tmp0 + tmp6, FIX(1.126980169)), /* c3+c5-c1 */ CONST_BITS-PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/14)*(8/7) = 32/49, which we * partially fold into the constant multipliers and final shifting: * 7-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/14) * 64/49. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*6]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*5]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*4]; tmp3 = dataptr[DCTSIZE*3]; tmp10 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*6]; tmp11 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*5]; tmp12 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*4]; z1 = tmp0 + tmp2; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(z1 + tmp1 + tmp3, FIX(1.306122449)), /* 64/49 */ CONST_BITS+PASS1_BITS+1); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.461784020)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(1.202428084)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.411026446)); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS+PASS1_BITS+1); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(1.151670509)); /* c4 */ dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.923568041)), /* c2+c6-c4 */ CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS+PASS1_BITS+1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.221765677)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.222383464)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.800824523)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.801442310)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(2.443531355)); /* c3+c1-c5 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp0, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp1, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp2, CONST_BITS+PASS1_BITS+1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 12x6 sample block. * * 12-point FDCT in pass 1 (rows), 6-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_12x6 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 2 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE*6], SIZEOF(DCTELEM) * DCTSIZE * 2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 12-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/24). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[6]); tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 12 * CENTERJSAMPLE) << PASS1_BITS); dataptr[6] = (DCTELEM) ((tmp13 - tmp14 - tmp15) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.224744871)), /* c4 */ CONST_BITS-PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(tmp14 - tmp15 + MULTIPLY(tmp13 + tmp15, FIX(1.366025404)), /* c2 */ CONST_BITS-PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX_0_541196100); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX_0_765366865); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX_1_847759065); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.121971054)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.860918669)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.580774953)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.184591911)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.184591911)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.339493912)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.860918669)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.725788011)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(1.121971054)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.306562965)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX_0_541196100); /* c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS-PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS-PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS-PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/12)*(8/6) = 8/9, which we * partially fold into the constant multipliers and final shifting: * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*5]; tmp11 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*5]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*3]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS+PASS1_BITS+1); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS+1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 10x5 sample block. * * 10-point FDCT in pass 1 (rows), 5-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_10x5 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 3 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE*5], SIZEOF(DCTELEM) * DCTSIZE * 3); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 10-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/20). */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[8]); tmp12 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[5]); tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[8]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[5]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 10 * CENTERJSAMPLE) << PASS1_BITS); tmp12 += tmp12; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.144122806)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.437016024)), /* c8 */ CONST_BITS-PASS1_BITS); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(0.831253876)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.513743148)), /* c2-c6 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.176250899)), /* c2+c6 */ CONST_BITS-PASS1_BITS); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[5] = (DCTELEM) ((tmp10 - tmp11 - tmp2) << PASS1_BITS); tmp2 <<= CONST_BITS; dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.396802247)) + /* c1 */ MULTIPLY(tmp1, FIX(1.260073511)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.642039522)) + /* c7 */ MULTIPLY(tmp4, FIX(0.221231742)), /* c9 */ CONST_BITS-PASS1_BITS); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(0.951056516)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.587785252)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.309016994)) + /* (c3-c7)/2 */ (tmp11 << (CONST_BITS - 1)) - tmp2; dataptr[3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS-PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS-PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/10)*(8/5) = 32/25, which we * fold into the constant multipliers: * 5-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/10) * 32/25. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*4]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*3]; tmp2 = dataptr[DCTSIZE*2]; tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*4]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*3]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS+PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(1.011928851)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.452548340)); /* (c2-c4)/2 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS+PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(1.064004961)); /* c3 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.657591230)), /* c1-c3 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.785601151)), /* c1+c3 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on an 8x4 sample block. * * 8-point FDCT in pass 1 (rows), 4-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_8x4 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 4 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE*4], SIZEOF(DCTELEM) * DCTSIZE * 4); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We must also scale the output by 8/4 = 2, which we add here. * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "c1" should be "c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << (PASS1_BITS+1)); dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << (PASS1_BITS+1)); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-2); dataptr[2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS-1); dataptr[6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS-1); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-2); tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* -c3+c5 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp0 += z1 + tmp12; tmp3 += z1 + tmp13; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp1 += z1 + tmp13; tmp2 += z1 + tmp12; dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0, CONST_BITS-PASS1_BITS-1); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp1, CONST_BITS-PASS1_BITS-1); dataptr[5] = (DCTELEM) RIGHT_SHIFT(tmp2, CONST_BITS-PASS1_BITS-1); dataptr[7] = (DCTELEM) RIGHT_SHIFT(tmp3, CONST_BITS-PASS1_BITS-1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * 4-point FDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*3] + (ONE << (PASS1_BITS-1)); tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*2]; tmp10 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*3]; tmp11 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*2]; dataptr[DCTSIZE*0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); dataptr[DCTSIZE*2] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS+PASS1_BITS-1); dataptr[DCTSIZE*1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x3 sample block. * * 6-point FDCT in pass 1 (rows), 3-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_6x3 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We scale the results further by 2 as part of output adaption * scaling for different DCT size. * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << (PASS1_BITS+1)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS-PASS1_BITS-1); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS-PASS1_BITS-1); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS-PASS1_BITS-1); dataptr[1] = (DCTELEM) (tmp10 + ((tmp0 + tmp1) << (PASS1_BITS+1))); dataptr[3] = (DCTELEM) ((tmp0 - tmp1 - tmp2) << (PASS1_BITS+1)); dataptr[5] = (DCTELEM) (tmp10 + ((tmp2 - tmp1) << (PASS1_BITS+1))); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/3) = 32/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * 3-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/6) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*2]; tmp1 = dataptr[DCTSIZE*1]; tmp2 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*2]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(1.257078722)), /* c2 */ CONST_BITS+PASS1_BITS); /* Odd part */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(2.177324216)), /* c1 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x2 sample block. * * 4-point FDCT in pass 1 (rows), 2-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_4x2 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We must also scale the output by (8/4)*(8/2) = 2**3, which we add here. * 4-point FDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 2; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS+3)); dataptr[2] = (DCTELEM) ((tmp0 - tmp1) << (PASS1_BITS+3)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-4); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS-3); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS-3); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE*0] + (ONE << (PASS1_BITS-1)); tmp1 = dataptr[DCTSIZE*1]; dataptr[DCTSIZE*0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); /* Odd part */ dataptr[DCTSIZE*1] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x1 sample block. * * 2-point FDCT in pass 1 (rows), 1-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_2x1 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { DCTELEM tmp0, tmp1; JSAMPROW elemptr; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); elemptr = sample_data[0] + start_col; tmp0 = GETJSAMPLE(elemptr[0]); tmp1 = GETJSAMPLE(elemptr[1]); /* We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/2)*(8/1) = 2**5. */ /* Even part */ /* Apply unsigned->signed conversion. */ data[0] = (tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 5; /* Odd part */ data[1] = (tmp0 - tmp1) << 5; } /* * Perform the forward DCT on an 8x16 sample block. * * 8-point FDCT in pass 1 (rows), 16-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_8x16 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; INT32 z1; DCTELEM workspace[DCTSIZE2]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "c1" should be "c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 - MULTIPLY(tmp13, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* -c3+c5 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp0 += z1 + tmp12; tmp3 += z1 + tmp13; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp1 += z1 + tmp13; tmp2 += z1 + tmp12; dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS-PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS-PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS-PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == DCTSIZE * 2) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by 8/16 = 1/2. * 16-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*4] + wsptr[DCTSIZE*3]; tmp5 = dataptr[DCTSIZE*5] + wsptr[DCTSIZE*2]; tmp6 = dataptr[DCTSIZE*6] + wsptr[DCTSIZE*1]; tmp7 = dataptr[DCTSIZE*7] + wsptr[DCTSIZE*0]; tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*4] - wsptr[DCTSIZE*3]; tmp5 = dataptr[DCTSIZE*5] - wsptr[DCTSIZE*2]; tmp6 = dataptr[DCTSIZE*6] - wsptr[DCTSIZE*1]; tmp7 = dataptr[DCTSIZE*7] - wsptr[DCTSIZE*0]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11 + tmp12 + tmp13, PASS1_BITS+1); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS+PASS1_BITS+1); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS+PASS1_BITS+1); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp11, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp12, CONST_BITS+PASS1_BITS+1); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp13, CONST_BITS+PASS1_BITS+1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 7x14 sample block. * * 7-point FDCT in pass 1 (rows), 14-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_7x14 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM workspace[8*6]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 7-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/14). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[6]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[5]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[4]); tmp3 = GETJSAMPLE(elemptr[3]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[6]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[5]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[4]); z1 = tmp0 + tmp2; /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((z1 + tmp1 + tmp3 - 7 * CENTERJSAMPLE) << PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.353553391)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(0.920609002)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.314692123)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS-PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(0.881747734)); /* c4 */ dataptr[4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.707106781)), /* c2+c6-c4 */ CONST_BITS-PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS-PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.613604268)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(1.870828693)); /* c3+c1-c5 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS-PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS-PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 14) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/7)*(8/14) = 32/49, which we * fold into the constant multipliers: * 14-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/28) * 32/49. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 7; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*5]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*3]; tmp13 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*2]; tmp4 = dataptr[DCTSIZE*4] + wsptr[DCTSIZE*1]; tmp5 = dataptr[DCTSIZE*5] + wsptr[DCTSIZE*0]; tmp6 = dataptr[DCTSIZE*6] + dataptr[DCTSIZE*7]; tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*5]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*3]; tmp3 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*2]; tmp4 = dataptr[DCTSIZE*4] - wsptr[DCTSIZE*1]; tmp5 = dataptr[DCTSIZE*5] - wsptr[DCTSIZE*0]; tmp6 = dataptr[DCTSIZE*6] - dataptr[DCTSIZE*7]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12 + tmp13, FIX(0.653061224)), /* 32/49 */ CONST_BITS+PASS1_BITS); tmp13 += tmp13; dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(0.832106052)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.205513223)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.575835255)), /* c8 */ CONST_BITS+PASS1_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(0.722074570)); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.178337691)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.400721155)), /* c10 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.122795725)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(0.900412262)), /* c2 */ CONST_BITS+PASS1_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp10 + tmp3 - tmp11 - tmp6, FIX(0.653061224)), /* 32/49 */ CONST_BITS+PASS1_BITS); tmp3 = MULTIPLY(tmp3 , FIX(0.653061224)); /* 32/49 */ tmp10 = MULTIPLY(tmp10, - FIX(0.103406812)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(0.917760839)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(0.782007410)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.491367823)); /* c9 */ dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(1.550341076)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(0.731428202)), /* c1+c11-c9 */ CONST_BITS+PASS1_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(0.871740478)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.305035186)); /* c11 */ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.276965844)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(2.004803435)), /* c1+c5+c11 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 - MULTIPLY(tmp0, FIX(0.735987049)) /* c3+c5-c1 */ - MULTIPLY(tmp6, FIX(0.082925825)), /* c9-c11-c13 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x12 sample block. * * 6-point FDCT in pass 1 (rows), 12-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_6x12 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM workspace[8*4]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS-PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS-PASS1_BITS); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS-PASS1_BITS); dataptr[1] = (DCTELEM) (tmp10 + ((tmp0 + tmp1) << PASS1_BITS)); dataptr[3] = (DCTELEM) ((tmp0 - tmp1 - tmp2) << PASS1_BITS); dataptr[5] = (DCTELEM) (tmp10 + ((tmp2 - tmp1) << PASS1_BITS)); ctr++; if (ctr != DCTSIZE) { if (ctr == 12) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/12) = 8/9, which we * fold into the constant multipliers: * 12-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/24) * 8/9. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*3]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*2]; tmp2 = dataptr[DCTSIZE*2] + wsptr[DCTSIZE*1]; tmp3 = dataptr[DCTSIZE*3] + wsptr[DCTSIZE*0]; tmp4 = dataptr[DCTSIZE*4] + dataptr[DCTSIZE*7]; tmp5 = dataptr[DCTSIZE*5] + dataptr[DCTSIZE*6]; tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*3]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*2]; tmp2 = dataptr[DCTSIZE*2] - wsptr[DCTSIZE*1]; tmp3 = dataptr[DCTSIZE*3] - wsptr[DCTSIZE*0]; tmp4 = dataptr[DCTSIZE*4] - dataptr[DCTSIZE*7]; tmp5 = dataptr[DCTSIZE*5] - dataptr[DCTSIZE*6]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(0.888888889)), /* 8/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(MULTIPLY(tmp13 - tmp14 - tmp15, FIX(0.888888889)), /* 8/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.088662108)), /* c4 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp14 - tmp15, FIX(0.888888889)) + /* 8/9 */ MULTIPLY(tmp13 + tmp15, FIX(1.214244803)), /* c2 */ CONST_BITS+PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX(0.481063200)); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX(0.680326102)); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX(1.642452502)); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(0.997307603)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.765261039)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.516244403)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.164081699)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.164081699)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.079550144)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.765261039)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.645144899)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(0.997307603)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.161389302)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX(0.481063200)); /* c9 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp11, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp12, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp13, CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 5x10 sample block. * * 5-point FDCT in pass 1 (rows), 10-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_5x10 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM workspace[8*2]; DCTELEM *dataptr; DCTELEM *wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * 5-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/10). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[3]); tmp2 = GETJSAMPLE(elemptr[2]); tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp10 + tmp2 - 5 * CENTERJSAMPLE) << PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(0.790569415)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.353553391)); /* (c2-c4)/2 */ dataptr[2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS-PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS-PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(0.831253876)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.513743148)), /* c1-c3 */ CONST_BITS-PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.176250899)), /* c1+c3 */ CONST_BITS-PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 10) break; /* Done. */ dataptr += DCTSIZE; /* advance pointer to next row */ } else dataptr = workspace; /* switch pointer to extended workspace */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/5)*(8/10) = 32/25, which we * fold into the constant multipliers: * 10-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/20) * 32/25. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 5; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + wsptr[DCTSIZE*1]; tmp1 = dataptr[DCTSIZE*1] + wsptr[DCTSIZE*0]; tmp12 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*7]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*6]; tmp4 = dataptr[DCTSIZE*4] + dataptr[DCTSIZE*5]; tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = dataptr[DCTSIZE*0] - wsptr[DCTSIZE*1]; tmp1 = dataptr[DCTSIZE*1] - wsptr[DCTSIZE*0]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*7]; tmp3 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*6]; tmp4 = dataptr[DCTSIZE*4] - dataptr[DCTSIZE*5]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(1.28)), /* 32/25 */ CONST_BITS+PASS1_BITS); tmp12 += tmp12; dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.464477191)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.559380511)), /* c8 */ CONST_BITS+PASS1_BITS); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(1.064004961)); /* c6 */ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.657591230)), /* c2-c6 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.785601151)), /* c2+c6 */ CONST_BITS+PASS1_BITS); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS+PASS1_BITS); tmp2 = MULTIPLY(tmp2, FIX(1.28)); /* 32/25 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.787906876)) + /* c1 */ MULTIPLY(tmp1, FIX(1.612894094)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.821810588)) + /* c7 */ MULTIPLY(tmp4, FIX(0.283176630)), /* c9 */ CONST_BITS+PASS1_BITS); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(1.217352341)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.752365123)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.395541753)) + /* (c3-c7)/2 */ MULTIPLY(tmp11, FIX(0.64)) - tmp2; /* 16/25 */ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x8 sample block. * * 4-point FDCT in pass 1 (rows), 8-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_4x8 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We must also scale the output by 8/4 = 2, which we add here. * 4-point FDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS+1)); dataptr[2] = (DCTELEM) ((tmp0 - tmp1) << (PASS1_BITS+1)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-2); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS-1); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS-1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "c1" should be "c6". */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; /* Add fudge factor here for final descale. */ tmp10 = tmp0 + tmp3 + (ONE << (PASS1_BITS-1)); tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; dataptr[DCTSIZE*0] = (DCTELEM) RIGHT_SHIFT(tmp10 + tmp11, PASS1_BITS); dataptr[DCTSIZE*4] = (DCTELEM) RIGHT_SHIFT(tmp10 - tmp11, PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS+PASS1_BITS-1); dataptr[DCTSIZE*2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), /* c2-c6 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), /* c2+c6 */ CONST_BITS+PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS+PASS1_BITS-1); tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* -c3+c5 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp0 += z1 + tmp12; tmp3 += z1 + tmp13; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp1 += z1 + tmp13; tmp2 += z1 + tmp12; dataptr[DCTSIZE*1] = (DCTELEM) RIGHT_SHIFT(tmp0, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) RIGHT_SHIFT(tmp1, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*5] = (DCTELEM) RIGHT_SHIFT(tmp2, CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*7] = (DCTELEM) RIGHT_SHIFT(tmp3, CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 3x6 sample block. * * 3-point FDCT in pass 1 (rows), 6-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_3x6 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT; * furthermore, we scale the results by 2**PASS1_BITS. * We scale the results further by 2 as part of output adaption * scaling for different DCT size. * 3-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/6). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[2]); tmp1 = GETJSAMPLE(elemptr[1]); tmp2 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 3 * CENTERJSAMPLE) << (PASS1_BITS+1)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(0.707106781)), /* c2 */ CONST_BITS-PASS1_BITS-1); /* Odd part */ dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(1.224744871)), /* c1 */ CONST_BITS-PASS1_BITS-1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/3) = 32/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*5]; tmp11 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*5]; tmp1 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*4]; tmp2 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*3]; dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS+PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS+PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x4 sample block. * * 2-point FDCT in pass 1 (rows), 4-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_2x4 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM *dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. * Note results are scaled up by sqrt(8) compared to a true DCT. * We must also scale the output by (8/2)*(8/4) = 2**3, which we add here. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]); tmp1 = GETJSAMPLE(elemptr[1]); /* Apply unsigned->signed conversion. */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 3); /* Odd part */ dataptr[1] = (DCTELEM) ((tmp0 - tmp1) << 3); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * 4-point FDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 2; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*3]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*2]; tmp10 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*3]; tmp11 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*2]; dataptr[DCTSIZE*0] = (DCTELEM) (tmp0 + tmp1); dataptr[DCTSIZE*2] = (DCTELEM) (tmp0 - tmp1); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-1); dataptr[DCTSIZE*1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS); dataptr[DCTSIZE*3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 1x2 sample block. * * 1-point FDCT in pass 1 (rows), 2-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_1x2 (DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col) { DCTELEM tmp0, tmp1; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: empty. */ /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/1)*(8/2) = 2**5. */ /* Even part */ tmp0 = GETJSAMPLE(sample_data[0][start_col]); tmp1 = GETJSAMPLE(sample_data[1][start_col]); /* Apply unsigned->signed conversion. */ data[DCTSIZE*0] = (tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 5; /* Odd part */ data[DCTSIZE*1] = (tmp0 - tmp1) << 5; } #endif /* DCT_SCALING_SUPPORTED */ #endif /* DCT_ISLOW_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jidctflt.c ================================================ /* * jidctflt.c * * Copyright (C) 1994-1998, Thomas G. Lane. * Modified 2010-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a floating-point implementation of the * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine * must also perform dequantization of the input coefficients. * * This implementation should be more accurate than either of the integer * IDCT implementations. However, it may not give the same results on all * machines because of differences in roundoff behavior. Speed will depend * on the hardware's floating point capacity. * * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT * on each row (or vice versa, but it's more convenient to emit a row at * a time). Direct algorithms are also available, but they are much more * complex and seem not to be any faster when reduced to code. * * This implementation is based on Arai, Agui, and Nakajima's algorithm for * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in * Japanese, but the algorithm is described in the Pennebaker & Mitchell * JPEG textbook (see REFERENCES section in file README). The following code * is based directly on figure 4-8 in P&M. * While an 8-point DCT cannot be done in less than 11 multiplies, it is * possible to arrange the computation so that many of the multiplies are * simple scalings of the final outputs. These multiplies can then be * folded into the multiplications or divisions by the JPEG quantization * table entries. The AA&N method leaves only 5 multiplies and 29 adds * to be done in the DCT itself. * The primary disadvantage of this method is that with a fixed-point * implementation, accuracy is lost due to imprecise representation of the * scaled quantization values. However, that problem does not arise if * we use floating point arithmetic. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ #ifdef DCT_FLOAT_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ #endif /* Dequantize a coefficient by multiplying it by the multiplier-table * entry; produce a float result. */ #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval)) /* * Perform dequantization and inverse DCT on one block of coefficients. * * cK represents cos(K*pi/16). */ GLOBAL(void) jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; FAST_FLOAT tmp10, tmp11, tmp12, tmp13; FAST_FLOAT z5, z10, z11, z12, z13; JCOEFPTR inptr; FLOAT_MULT_TYPE * quantptr; FAST_FLOAT * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */ /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = DCTSIZE; ctr > 0; ctr--) { /* Due to quantization, we will usually find that many of the input * coefficients are zero, especially the AC terms. We can exploit this * by short-circuiting the IDCT calculation for any column in which all * the AC terms are zero. In that case each output is equal to the * DC coefficient (with scale factor as needed). * With typical images and quantization tables, half or more of the * column DCT calculations can be simplified this way. */ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) { /* AC terms all zero */ FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); wsptr[DCTSIZE*0] = dcval; wsptr[DCTSIZE*1] = dcval; wsptr[DCTSIZE*2] = dcval; wsptr[DCTSIZE*3] = dcval; wsptr[DCTSIZE*4] = dcval; wsptr[DCTSIZE*5] = dcval; wsptr[DCTSIZE*6] = dcval; wsptr[DCTSIZE*7] = dcval; inptr++; /* advance pointers to next column */ quantptr++; wsptr++; continue; } /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp10 = tmp0 + tmp2; /* phase 3 */ tmp11 = tmp0 - tmp2; tmp13 = tmp1 + tmp3; /* phases 5-3 */ tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */ tmp0 = tmp10 + tmp13; /* phase 2 */ tmp3 = tmp10 - tmp13; tmp1 = tmp11 + tmp12; tmp2 = tmp11 - tmp12; /* Odd part */ tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); z13 = tmp6 + tmp5; /* phase 6 */ z10 = tmp6 - tmp5; z11 = tmp4 + tmp7; z12 = tmp4 - tmp7; tmp7 = z11 + z13; /* phase 5 */ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */ tmp10 = z5 - z12 * ((FAST_FLOAT) 1.082392200); /* 2*(c2-c6) */ tmp12 = z5 - z10 * ((FAST_FLOAT) 2.613125930); /* 2*(c2+c6) */ tmp6 = tmp12 - tmp7; /* phase 2 */ tmp5 = tmp11 - tmp6; tmp4 = tmp10 - tmp5; wsptr[DCTSIZE*0] = tmp0 + tmp7; wsptr[DCTSIZE*7] = tmp0 - tmp7; wsptr[DCTSIZE*1] = tmp1 + tmp6; wsptr[DCTSIZE*6] = tmp1 - tmp6; wsptr[DCTSIZE*2] = tmp2 + tmp5; wsptr[DCTSIZE*5] = tmp2 - tmp5; wsptr[DCTSIZE*3] = tmp3 + tmp4; wsptr[DCTSIZE*4] = tmp3 - tmp4; inptr++; /* advance pointers to next column */ quantptr++; wsptr++; } /* Pass 2: process rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < DCTSIZE; ctr++) { outptr = output_buf[ctr] + output_col; /* Rows of zeroes can be exploited in the same way as we did with columns. * However, the column calculation has created many nonzero AC terms, so * the simplification applies less often (typically 5% to 10% of the time). * And testing floats for zero is relatively expensive, so we don't bother. */ /* Even part */ /* Prepare range-limit and float->int conversion */ z5 = wsptr[0] + (((FAST_FLOAT) RANGE_CENTER) + ((FAST_FLOAT) 0.5)); tmp10 = z5 + wsptr[4]; tmp11 = z5 - wsptr[4]; tmp13 = wsptr[2] + wsptr[6]; tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */ tmp0 = tmp10 + tmp13; tmp3 = tmp10 - tmp13; tmp1 = tmp11 + tmp12; tmp2 = tmp11 - tmp12; /* Odd part */ z13 = wsptr[5] + wsptr[3]; z10 = wsptr[5] - wsptr[3]; z11 = wsptr[1] + wsptr[7]; z12 = wsptr[1] - wsptr[7]; tmp7 = z11 + z13; /* phase 5 */ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */ tmp10 = z5 - z12 * ((FAST_FLOAT) 1.082392200); /* 2*(c2-c6) */ tmp12 = z5 - z10 * ((FAST_FLOAT) 2.613125930); /* 2*(c2+c6) */ tmp6 = tmp12 - tmp7; /* phase 2 */ tmp5 = tmp11 - tmp6; tmp4 = tmp10 - tmp5; /* Final output stage: float->int conversion and range-limit */ outptr[0] = range_limit[(int) (tmp0 + tmp7) & RANGE_MASK]; outptr[7] = range_limit[(int) (tmp0 - tmp7) & RANGE_MASK]; outptr[1] = range_limit[(int) (tmp1 + tmp6) & RANGE_MASK]; outptr[6] = range_limit[(int) (tmp1 - tmp6) & RANGE_MASK]; outptr[2] = range_limit[(int) (tmp2 + tmp5) & RANGE_MASK]; outptr[5] = range_limit[(int) (tmp2 - tmp5) & RANGE_MASK]; outptr[3] = range_limit[(int) (tmp3 + tmp4) & RANGE_MASK]; outptr[4] = range_limit[(int) (tmp3 - tmp4) & RANGE_MASK]; wsptr += DCTSIZE; /* advance pointer to next row */ } } #endif /* DCT_FLOAT_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jidctfst.c ================================================ /* * jidctfst.c * * Copyright (C) 1994-1998, Thomas G. Lane. * Modified 2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a fast, not so accurate integer implementation of the * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine * must also perform dequantization of the input coefficients. * * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT * on each row (or vice versa, but it's more convenient to emit a row at * a time). Direct algorithms are also available, but they are much more * complex and seem not to be any faster when reduced to code. * * This implementation is based on Arai, Agui, and Nakajima's algorithm for * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in * Japanese, but the algorithm is described in the Pennebaker & Mitchell * JPEG textbook (see REFERENCES section in file README). The following code * is based directly on figure 4-8 in P&M. * While an 8-point DCT cannot be done in less than 11 multiplies, it is * possible to arrange the computation so that many of the multiplies are * simple scalings of the final outputs. These multiplies can then be * folded into the multiplications or divisions by the JPEG quantization * table entries. The AA&N method leaves only 5 multiplies and 29 adds * to be done in the DCT itself. * The primary disadvantage of this method is that with fixed-point math, * accuracy is lost due to imprecise representation of the scaled * quantization values. The smaller the quantization table entry, the less * precise the scaled value, so this implementation does worse with high- * quality-setting files than with low-quality ones. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ #ifdef DCT_IFAST_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ #endif /* Scaling decisions are generally the same as in the LL&M algorithm; * see jidctint.c for more details. However, we choose to descale * (right shift) multiplication products as soon as they are formed, * rather than carrying additional fractional bits into subsequent additions. * This compromises accuracy slightly, but it lets us save a few shifts. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples) * everywhere except in the multiplications proper; this saves a good deal * of work on 16-bit-int machines. * * The dequantized coefficients are not integers because the AA&N scaling * factors have been incorporated. We represent them scaled up by PASS1_BITS, * so that the first and second IDCT rounds have the same input scaling. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to * avoid a descaling shift; this compromises accuracy rather drastically * for small quantization table entries, but it saves a lot of shifts. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway, * so we use a much larger scaling factor to preserve accuracy. * * A final compromise is to represent the multiplicative constants to only * 8 fractional bits, rather than 13. This saves some shifting work on some * machines, and may also reduce the cost of multiplication (since there * are fewer one-bits in the constants). */ #if BITS_IN_JSAMPLE == 8 #define CONST_BITS 8 #define PASS1_BITS 2 #else #define CONST_BITS 8 #define PASS1_BITS 1 /* lose a little precision to avoid overflow */ #endif /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 8 #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */ #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */ #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */ #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */ #else #define FIX_1_082392200 FIX(1.082392200) #define FIX_1_414213562 FIX(1.414213562) #define FIX_1_847759065 FIX(1.847759065) #define FIX_2_613125930 FIX(2.613125930) #endif /* We can gain a little more speed, with a further compromise in accuracy, * by omitting the addition in a descaling shift. This yields an incorrectly * rounded result half the time... */ #ifndef USE_ACCURATE_ROUNDING #undef DESCALE #define DESCALE(x,n) RIGHT_SHIFT(x, n) #endif /* Multiply a DCTELEM variable by an INT32 constant, and immediately * descale to yield a DCTELEM result. */ #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS)) /* Dequantize a coefficient by multiplying it by the multiplier-table * entry; produce a DCTELEM result. For 8-bit data a 16x16->16 * multiplication will do. For 12-bit data, the multiplier table is * declared INT32, so a 32-bit multiply will be used. */ #if BITS_IN_JSAMPLE == 8 #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval)) #else #define DEQUANTIZE(coef,quantval) \ DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS) #endif /* * Perform dequantization and inverse DCT on one block of coefficients. * * cK represents cos(K*pi/16). */ GLOBAL(void) jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; DCTELEM tmp10, tmp11, tmp12, tmp13; DCTELEM z5, z10, z11, z12, z13; JCOEFPTR inptr; IFAST_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[DCTSIZE2]; /* buffers data between passes */ SHIFT_TEMPS /* for DESCALE */ ISHIFT_TEMPS /* for IRIGHT_SHIFT */ /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (IFAST_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = DCTSIZE; ctr > 0; ctr--) { /* Due to quantization, we will usually find that many of the input * coefficients are zero, especially the AC terms. We can exploit this * by short-circuiting the IDCT calculation for any column in which all * the AC terms are zero. In that case each output is equal to the * DC coefficient (with scale factor as needed). * With typical images and quantization tables, half or more of the * column DCT calculations can be simplified this way. */ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) { /* AC terms all zero */ int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); wsptr[DCTSIZE*0] = dcval; wsptr[DCTSIZE*1] = dcval; wsptr[DCTSIZE*2] = dcval; wsptr[DCTSIZE*3] = dcval; wsptr[DCTSIZE*4] = dcval; wsptr[DCTSIZE*5] = dcval; wsptr[DCTSIZE*6] = dcval; wsptr[DCTSIZE*7] = dcval; inptr++; /* advance pointers to next column */ quantptr++; wsptr++; continue; } /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp10 = tmp0 + tmp2; /* phase 3 */ tmp11 = tmp0 - tmp2; tmp13 = tmp1 + tmp3; /* phases 5-3 */ tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */ tmp0 = tmp10 + tmp13; /* phase 2 */ tmp3 = tmp10 - tmp13; tmp1 = tmp11 + tmp12; tmp2 = tmp11 - tmp12; /* Odd part */ tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); z13 = tmp6 + tmp5; /* phase 6 */ z10 = tmp6 - tmp5; z11 = tmp4 + tmp7; z12 = tmp4 - tmp7; tmp7 = z11 + z13; /* phase 5 */ tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */ z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */ tmp10 = z5 - MULTIPLY(z12, FIX_1_082392200); /* 2*(c2-c6) */ tmp12 = z5 - MULTIPLY(z10, FIX_2_613125930); /* 2*(c2+c6) */ tmp6 = tmp12 - tmp7; /* phase 2 */ tmp5 = tmp11 - tmp6; tmp4 = tmp10 - tmp5; wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7); wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7); wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6); wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6); wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5); wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5); wsptr[DCTSIZE*3] = (int) (tmp3 + tmp4); wsptr[DCTSIZE*4] = (int) (tmp3 - tmp4); inptr++; /* advance pointers to next column */ quantptr++; wsptr++; } /* Pass 2: process rows from work array, store into output array. * Note that we must descale the results by a factor of 8 == 2**3, * and also undo the PASS1_BITS scaling. */ wsptr = workspace; for (ctr = 0; ctr < DCTSIZE; ctr++) { outptr = output_buf[ctr] + output_col; /* Add range center and fudge factor for final descale and range-limit. */ z5 = (DCTELEM) wsptr[0] + ((((DCTELEM) RANGE_CENTER) << (PASS1_BITS+3)) + (1 << (PASS1_BITS+2))); /* Rows of zeroes can be exploited in the same way as we did with columns. * However, the column calculation has created many nonzero AC terms, so * the simplification applies less often (typically 5% to 10% of the time). * On machines with very fast multiplication, it's possible that the * test takes more time than it's worth. In that case this section * may be commented out. */ #ifndef NO_ZERO_ROW_TEST if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 && wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) { /* AC terms all zero */ JSAMPLE dcval = range_limit[(int) IRIGHT_SHIFT(z5, PASS1_BITS+3) & RANGE_MASK]; outptr[0] = dcval; outptr[1] = dcval; outptr[2] = dcval; outptr[3] = dcval; outptr[4] = dcval; outptr[5] = dcval; outptr[6] = dcval; outptr[7] = dcval; wsptr += DCTSIZE; /* advance pointer to next row */ continue; } #endif /* Even part */ tmp10 = z5 + (DCTELEM) wsptr[4]; tmp11 = z5 - (DCTELEM) wsptr[4]; tmp13 = (DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]; tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562) - tmp13; /* 2*c4 */ tmp0 = tmp10 + tmp13; tmp3 = tmp10 - tmp13; tmp1 = tmp11 + tmp12; tmp2 = tmp11 - tmp12; /* Odd part */ z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3]; z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3]; z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7]; z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7]; tmp7 = z11 + z13; /* phase 5 */ tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */ z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */ tmp10 = z5 - MULTIPLY(z12, FIX_1_082392200); /* 2*(c2-c6) */ tmp12 = z5 - MULTIPLY(z10, FIX_2_613125930); /* 2*(c2+c6) */ tmp6 = tmp12 - tmp7; /* phase 2 */ tmp5 = tmp11 - tmp6; tmp4 = tmp10 - tmp5; /* Final output stage: scale down by a factor of 8 and range-limit */ outptr[0] = range_limit[(int) IRIGHT_SHIFT(tmp0 + tmp7, PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) IRIGHT_SHIFT(tmp0 - tmp7, PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) IRIGHT_SHIFT(tmp1 + tmp6, PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) IRIGHT_SHIFT(tmp1 - tmp6, PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) IRIGHT_SHIFT(tmp2 + tmp5, PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) IRIGHT_SHIFT(tmp2 - tmp5, PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) IRIGHT_SHIFT(tmp3 + tmp4, PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) IRIGHT_SHIFT(tmp3 - tmp4, PASS1_BITS+3) & RANGE_MASK]; wsptr += DCTSIZE; /* advance pointer to next row */ } } #endif /* DCT_IFAST_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jidctint.c ================================================ /* * jidctint.c * * Copyright (C) 1991-1998, Thomas G. Lane. * Modification developed 2002-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a slow-but-accurate integer implementation of the * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine * must also perform dequantization of the input coefficients. * * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT * on each row (or vice versa, but it's more convenient to emit a row at * a time). Direct algorithms are also available, but they are much more * complex and seem not to be any faster when reduced to code. * * This implementation is based on an algorithm described in * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. * The primary algorithm described there uses 11 multiplies and 29 adds. * We use their alternate method with 12 multiplies and 32 adds. * The advantage of this method is that no data path contains more than one * multiplication; this allows a very simple and accurate implementation in * scaled fixed-point arithmetic, with a minimal number of shifts. * * We also provide IDCT routines with various output sample block sizes for * direct resolution reduction or enlargement and for direct resolving the * common 2x1 and 1x2 subsampling cases without additional resampling: NxN * (N=1...16), 2NxN, and Nx2N (N=1...8) pixels for one 8x8 input DCT block. * * For N<8 we simply take the corresponding low-frequency coefficients of * the 8x8 input DCT block and apply an NxN point IDCT on the sub-block * to yield the downscaled outputs. * This can be seen as direct low-pass downsampling from the DCT domain * point of view rather than the usual spatial domain point of view, * yielding significant computational savings and results at least * as good as common bilinear (averaging) spatial downsampling. * * For N>8 we apply a partial NxN IDCT on the 8 input coefficients as * lower frequencies and higher frequencies assumed to be zero. * It turns out that the computational effort is similar to the 8x8 IDCT * regarding the output size. * Furthermore, the scaling and descaling is the same for all IDCT sizes. * * CAUTION: We rely on the FIX() macro except for the N=1,2,4,8 cases * since there would be too many additional constants to pre-calculate. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ #ifdef DCT_ISLOW_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCT blocks. /* deliberate syntax err */ #endif /* * The poop on this scaling stuff is as follows: * * Each 1-D IDCT step produces outputs which are a factor of sqrt(N) * larger than the true IDCT outputs. The final outputs are therefore * a factor of N larger than desired; since N=8 this can be cured by * a simple right shift at the end of the algorithm. The advantage of * this arrangement is that we save two multiplications per 1-D IDCT, * because the y0 and y4 inputs need not be divided by sqrt(N). * * We have to do addition and subtraction of the integer inputs, which * is no problem, and multiplication by fractional constants, which is * a problem to do in integer arithmetic. We multiply all the constants * by CONST_SCALE and convert them to integer constants (thus retaining * CONST_BITS bits of precision in the constants). After doing a * multiplication we have to divide the product by CONST_SCALE, with proper * rounding, to produce the correct output. This division can be done * cheaply as a right shift of CONST_BITS bits. We postpone shifting * as long as possible so that partial sums can be added together with * full fractional precision. * * The outputs of the first pass are scaled up by PASS1_BITS bits so that * they are represented to better-than-integral precision. These outputs * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word * with the recommended scaling. (To scale up 12-bit sample data further, an * intermediate INT32 array would be needed.) * * To avoid overflow of the 32-bit intermediate results in pass 2, we must * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis * shows that the values given below are the most effective. */ #if BITS_IN_JSAMPLE == 8 #define CONST_BITS 13 #define PASS1_BITS 2 #else #define CONST_BITS 13 #define PASS1_BITS 1 /* lose a little precision to avoid overflow */ #endif /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 13 #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */ #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */ #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */ #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */ #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */ #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */ #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */ #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */ #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */ #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */ #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */ #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */ #else #define FIX_0_298631336 FIX(0.298631336) #define FIX_0_390180644 FIX(0.390180644) #define FIX_0_541196100 FIX(0.541196100) #define FIX_0_765366865 FIX(0.765366865) #define FIX_0_899976223 FIX(0.899976223) #define FIX_1_175875602 FIX(1.175875602) #define FIX_1_501321110 FIX(1.501321110) #define FIX_1_847759065 FIX(1.847759065) #define FIX_1_961570560 FIX(1.961570560) #define FIX_2_053119869 FIX(2.053119869) #define FIX_2_562915447 FIX(2.562915447) #define FIX_3_072711026 FIX(3.072711026) #endif /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. * For 8-bit samples with the recommended scaling, all the variable * and constant values involved are no more than 16 bits wide, so a * 16x16->32 bit multiply can be used instead of a full 32x32 multiply. * For 12-bit samples, a full 32-bit multiplication will be needed. */ #if BITS_IN_JSAMPLE == 8 #define MULTIPLY(var,const) MULTIPLY16C16(var,const) #else #define MULTIPLY(var,const) ((var) * (const)) #endif /* Dequantize a coefficient by multiplying it by the multiplier-table * entry; produce an int result. In this module, both inputs and result * are 16 bits or less, so either int or short multiply will work. */ #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval)) /* * Perform dequantization and inverse DCT on one block of coefficients. * * cK represents sqrt(2) * cos(K*pi/16). */ GLOBAL(void) jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[DCTSIZE2]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * Note results are scaled up by sqrt(8) compared to a true IDCT; * furthermore, we scale the results by 2**PASS1_BITS. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = DCTSIZE; ctr > 0; ctr--) { /* Due to quantization, we will usually find that many of the input * coefficients are zero, especially the AC terms. We can exploit this * by short-circuiting the IDCT calculation for any column in which all * the AC terms are zero. In that case each output is equal to the * DC coefficient (with scale factor as needed). * With typical images and quantization tables, half or more of the * column DCT calculations can be simplified this way. */ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) { /* AC terms all zero */ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS; wsptr[DCTSIZE*0] = dcval; wsptr[DCTSIZE*1] = dcval; wsptr[DCTSIZE*2] = dcval; wsptr[DCTSIZE*3] = dcval; wsptr[DCTSIZE*4] = dcval; wsptr[DCTSIZE*5] = dcval; wsptr[DCTSIZE*6] = dcval; wsptr[DCTSIZE*7] = dcval; inptr++; /* advance pointers to next column */ quantptr++; wsptr++; continue; } /* Even part: reverse the even part of the forward DCT. * The rotator is c(-6). */ z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z2 <<= CONST_BITS; z3 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z2 += ONE << (CONST_BITS-PASS1_BITS-1); tmp0 = z2 + z3; tmp1 = z2 - z3; z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp2 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp3 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ tmp10 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; tmp11 = tmp1 + tmp3; tmp12 = tmp1 - tmp3; /* Odd part per figure 8; the matrix is unitary and hence its * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = tmp0 + tmp2; z3 = tmp1 + tmp3; z1 = MULTIPLY(z2 + z3, FIX_1_175875602); /* c3 */ z2 = MULTIPLY(z2, - FIX_1_961570560); /* -c3-c5 */ z3 = MULTIPLY(z3, - FIX_0_390180644); /* -c3+c5 */ z2 += z1; z3 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp0 += z1 + z2; tmp3 += z1 + z3; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp1 += z1 + z3; tmp2 += z1 + z2; /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ wsptr[DCTSIZE*0] = (int) RIGHT_SHIFT(tmp10 + tmp3, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*7] = (int) RIGHT_SHIFT(tmp10 - tmp3, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*1] = (int) RIGHT_SHIFT(tmp11 + tmp2, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*6] = (int) RIGHT_SHIFT(tmp11 - tmp2, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*2] = (int) RIGHT_SHIFT(tmp12 + tmp1, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*5] = (int) RIGHT_SHIFT(tmp12 - tmp1, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*3] = (int) RIGHT_SHIFT(tmp13 + tmp0, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*4] = (int) RIGHT_SHIFT(tmp13 - tmp0, CONST_BITS-PASS1_BITS); inptr++; /* advance pointers to next column */ quantptr++; wsptr++; } /* Pass 2: process rows from work array, store into output array. * Note that we must descale the results by a factor of 8 == 2**3, * and also undo the PASS1_BITS scaling. */ wsptr = workspace; for (ctr = 0; ctr < DCTSIZE; ctr++) { outptr = output_buf[ctr] + output_col; /* Add range center and fudge factor for final descale and range-limit. */ z2 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); /* Rows of zeroes can be exploited in the same way as we did with columns. * However, the column calculation has created many nonzero AC terms, so * the simplification applies less often (typically 5% to 10% of the time). * On machines with very fast multiplication, it's possible that the * test takes more time than it's worth. In that case this section * may be commented out. */ #ifndef NO_ZERO_ROW_TEST if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 && wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) { /* AC terms all zero */ JSAMPLE dcval = range_limit[(int) RIGHT_SHIFT(z2, PASS1_BITS+3) & RANGE_MASK]; outptr[0] = dcval; outptr[1] = dcval; outptr[2] = dcval; outptr[3] = dcval; outptr[4] = dcval; outptr[5] = dcval; outptr[6] = dcval; outptr[7] = dcval; wsptr += DCTSIZE; /* advance pointer to next row */ continue; } #endif /* Even part: reverse the even part of the forward DCT. * The rotator is c(-6). */ z3 = (INT32) wsptr[4]; tmp0 = (z2 + z3) << CONST_BITS; tmp1 = (z2 - z3) << CONST_BITS; z2 = (INT32) wsptr[2]; z3 = (INT32) wsptr[6]; z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp2 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp3 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ tmp10 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; tmp11 = tmp1 + tmp3; tmp12 = tmp1 - tmp3; /* Odd part per figure 8; the matrix is unitary and hence its * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. */ tmp0 = (INT32) wsptr[7]; tmp1 = (INT32) wsptr[5]; tmp2 = (INT32) wsptr[3]; tmp3 = (INT32) wsptr[1]; z2 = tmp0 + tmp2; z3 = tmp1 + tmp3; z1 = MULTIPLY(z2 + z3, FIX_1_175875602); /* c3 */ z2 = MULTIPLY(z2, - FIX_1_961570560); /* -c3-c5 */ z3 = MULTIPLY(z3, - FIX_0_390180644); /* -c3+c5 */ z2 += z1; z3 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp0 += z1 + z2; tmp3 += z1 + z3; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp1 += z1 + z3; tmp2 += z1 + z2; /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp13 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp13 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += DCTSIZE; /* advance pointer to next row */ } } #ifdef IDCT_SCALING_SUPPORTED /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 7x7 output block. * * Optimized algorithm with 12 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/14). */ GLOBAL(void) jpeg_idct_7x7 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp10, tmp11, tmp12, tmp13; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[7*7]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 7; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp13 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp13 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp13 += ONE << (CONST_BITS-PASS1_BITS-1); z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp10 = MULTIPLY(z2 - z3, FIX(0.881747734)); /* c4 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.314692123)); /* c6 */ tmp11 = tmp10 + tmp12 + tmp13 - MULTIPLY(z2, FIX(1.841218003)); /* c2+c4-c6 */ tmp0 = z1 + z3; z2 -= tmp0; tmp0 = MULTIPLY(tmp0, FIX(1.274162392)) + tmp13; /* c2 */ tmp10 += tmp0 - MULTIPLY(z3, FIX(0.077722536)); /* c2-c4-c6 */ tmp12 += tmp0 - MULTIPLY(z1, FIX(2.470602249)); /* c2+c4+c6 */ tmp13 += MULTIPLY(z2, FIX(1.414213562)); /* c0 */ /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp1 = MULTIPLY(z1 + z2, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(z1 - z2, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(z2 + z3, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; z2 = MULTIPLY(z1 + z3, FIX(0.613604268)); /* c5 */ tmp0 += z2; tmp2 += z2 + MULTIPLY(z3, FIX(1.870828693)); /* c3+c1-c5 */ /* Final output stage */ wsptr[7*0] = (int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS-PASS1_BITS); wsptr[7*6] = (int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS-PASS1_BITS); wsptr[7*1] = (int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS-PASS1_BITS); wsptr[7*5] = (int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS-PASS1_BITS); wsptr[7*2] = (int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS-PASS1_BITS); wsptr[7*4] = (int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS-PASS1_BITS); wsptr[7*3] = (int) RIGHT_SHIFT(tmp13, CONST_BITS-PASS1_BITS); } /* Pass 2: process 7 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 7; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp13 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp13 <<= CONST_BITS; z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[4]; z3 = (INT32) wsptr[6]; tmp10 = MULTIPLY(z2 - z3, FIX(0.881747734)); /* c4 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.314692123)); /* c6 */ tmp11 = tmp10 + tmp12 + tmp13 - MULTIPLY(z2, FIX(1.841218003)); /* c2+c4-c6 */ tmp0 = z1 + z3; z2 -= tmp0; tmp0 = MULTIPLY(tmp0, FIX(1.274162392)) + tmp13; /* c2 */ tmp10 += tmp0 - MULTIPLY(z3, FIX(0.077722536)); /* c2-c4-c6 */ tmp12 += tmp0 - MULTIPLY(z1, FIX(2.470602249)); /* c2+c4+c6 */ tmp13 += MULTIPLY(z2, FIX(1.414213562)); /* c0 */ /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; tmp1 = MULTIPLY(z1 + z2, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(z1 - z2, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(z2 + z3, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; z2 = MULTIPLY(z1 + z3, FIX(0.613604268)); /* c5 */ tmp0 += z2; tmp2 += z2 + MULTIPLY(z3, FIX(1.870828693)); /* c3+c1-c5 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 7; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 6x6 output block. * * Optimized algorithm with 3 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/12). */ GLOBAL(void) jpeg_idct_6x6 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp10, tmp11, tmp12; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[6*6]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 6; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp0 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-1); tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); tmp10 = MULTIPLY(tmp2, FIX(0.707106781)); /* c4 */ tmp1 = tmp0 + tmp10; tmp11 = RIGHT_SHIFT(tmp0 - tmp10 - tmp10, CONST_BITS-PASS1_BITS); tmp10 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp0 = MULTIPLY(tmp10, FIX(1.224744871)); /* c2 */ tmp10 = tmp1 + tmp0; tmp12 = tmp1 - tmp0; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp1 = MULTIPLY(z1 + z3, FIX(0.366025404)); /* c5 */ tmp0 = tmp1 + ((z1 + z2) << CONST_BITS); tmp2 = tmp1 + ((z3 - z2) << CONST_BITS); tmp1 = (z1 - z2 - z3) << PASS1_BITS; /* Final output stage */ wsptr[6*0] = (int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS-PASS1_BITS); wsptr[6*5] = (int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS-PASS1_BITS); wsptr[6*1] = (int) (tmp11 + tmp1); wsptr[6*4] = (int) (tmp11 - tmp1); wsptr[6*2] = (int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS-PASS1_BITS); wsptr[6*3] = (int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS-PASS1_BITS); } /* Pass 2: process 6 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 6; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp0 <<= CONST_BITS; tmp2 = (INT32) wsptr[4]; tmp10 = MULTIPLY(tmp2, FIX(0.707106781)); /* c4 */ tmp1 = tmp0 + tmp10; tmp11 = tmp0 - tmp10 - tmp10; tmp10 = (INT32) wsptr[2]; tmp0 = MULTIPLY(tmp10, FIX(1.224744871)); /* c2 */ tmp10 = tmp1 + tmp0; tmp12 = tmp1 - tmp0; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; tmp1 = MULTIPLY(z1 + z3, FIX(0.366025404)); /* c5 */ tmp0 = tmp1 + ((z1 + z2) << CONST_BITS); tmp2 = tmp1 + ((z3 - z2) << CONST_BITS); tmp1 = (z1 - z2 - z3) << CONST_BITS; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 6; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 5x5 output block. * * Optimized algorithm with 5 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/10). */ GLOBAL(void) jpeg_idct_5x5 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp10, tmp11, tmp12; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[5*5]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 5; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp12 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp12 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp12 += ONE << (CONST_BITS-PASS1_BITS-1); tmp0 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp1 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z1 = MULTIPLY(tmp0 + tmp1, FIX(0.790569415)); /* (c2+c4)/2 */ z2 = MULTIPLY(tmp0 - tmp1, FIX(0.353553391)); /* (c2-c4)/2 */ z3 = tmp12 + z2; tmp10 = z3 + z1; tmp11 = z3 - z1; tmp12 -= z2 << 2; /* Odd part */ z2 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c3 */ tmp0 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c1-c3 */ tmp1 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c1+c3 */ /* Final output stage */ wsptr[5*0] = (int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS-PASS1_BITS); wsptr[5*4] = (int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS-PASS1_BITS); wsptr[5*1] = (int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS-PASS1_BITS); wsptr[5*3] = (int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS-PASS1_BITS); wsptr[5*2] = (int) RIGHT_SHIFT(tmp12, CONST_BITS-PASS1_BITS); } /* Pass 2: process 5 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 5; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp12 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp12 <<= CONST_BITS; tmp0 = (INT32) wsptr[2]; tmp1 = (INT32) wsptr[4]; z1 = MULTIPLY(tmp0 + tmp1, FIX(0.790569415)); /* (c2+c4)/2 */ z2 = MULTIPLY(tmp0 - tmp1, FIX(0.353553391)); /* (c2-c4)/2 */ z3 = tmp12 + z2; tmp10 = z3 + z1; tmp11 = z3 - z1; tmp12 -= z2 << 2; /* Odd part */ z2 = (INT32) wsptr[1]; z3 = (INT32) wsptr[3]; z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c3 */ tmp0 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c1-c3 */ tmp1 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c1+c3 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 5; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 4x4 output block. * * Optimized algorithm with 3 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point IDCT]. */ GLOBAL(void) jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp2, tmp10, tmp12; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[4*4]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 4; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp10 = (tmp0 + tmp2) << PASS1_BITS; tmp12 = (tmp0 - tmp2) << PASS1_BITS; /* Odd part */ /* Same rotation as in the even part of the 8x8 LL&M IDCT */ z2 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); tmp0 = RIGHT_SHIFT(z1 + MULTIPLY(z2, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS); tmp2 = RIGHT_SHIFT(z1 - MULTIPLY(z3, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS); /* Final output stage */ wsptr[4*0] = (int) (tmp10 + tmp0); wsptr[4*3] = (int) (tmp10 - tmp0); wsptr[4*1] = (int) (tmp12 + tmp2); wsptr[4*2] = (int) (tmp12 - tmp2); } /* Pass 2: process 4 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 4; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp2 = (INT32) wsptr[2]; tmp10 = (tmp0 + tmp2) << CONST_BITS; tmp12 = (tmp0 - tmp2) << CONST_BITS; /* Odd part */ /* Same rotation as in the even part of the 8x8 LL&M IDCT */ z2 = (INT32) wsptr[1]; z3 = (INT32) wsptr[3]; z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp0 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp2 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 4; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 3x3 output block. * * Optimized algorithm with 2 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/6). */ GLOBAL(void) jpeg_idct_3x3 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp2, tmp10, tmp12; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[3*3]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 3; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp0 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-1); tmp2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp12 = MULTIPLY(tmp2, FIX(0.707106781)); /* c2 */ tmp10 = tmp0 + tmp12; tmp2 = tmp0 - tmp12 - tmp12; /* Odd part */ tmp12 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); tmp0 = MULTIPLY(tmp12, FIX(1.224744871)); /* c1 */ /* Final output stage */ wsptr[3*0] = (int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS-PASS1_BITS); wsptr[3*2] = (int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS-PASS1_BITS); wsptr[3*1] = (int) RIGHT_SHIFT(tmp2, CONST_BITS-PASS1_BITS); } /* Pass 2: process 3 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 3; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp0 <<= CONST_BITS; tmp2 = (INT32) wsptr[2]; tmp12 = MULTIPLY(tmp2, FIX(0.707106781)); /* c2 */ tmp10 = tmp0 + tmp12; tmp2 = tmp0 - tmp12 - tmp12; /* Odd part */ tmp12 = (INT32) wsptr[1]; tmp0 = MULTIPLY(tmp12, FIX(1.224744871)); /* c1 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 3; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 2x2 output block. * * Multiplication-less algorithm. */ GLOBAL(void) jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; ISLOW_MULT_TYPE * quantptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); ISHIFT_TEMPS /* Pass 1: process columns from input. */ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; /* Column 0 */ tmp4 = DEQUANTIZE(coef_block[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp5 = DEQUANTIZE(coef_block[DCTSIZE*1], quantptr[DCTSIZE*1]); /* Add range center and fudge factor for final descale and range-limit. */ tmp4 += (((DCTELEM) RANGE_CENTER) << 3) + (1 << 2); tmp0 = tmp4 + tmp5; tmp2 = tmp4 - tmp5; /* Column 1 */ tmp4 = DEQUANTIZE(coef_block[DCTSIZE*0+1], quantptr[DCTSIZE*0+1]); tmp5 = DEQUANTIZE(coef_block[DCTSIZE*1+1], quantptr[DCTSIZE*1+1]); tmp1 = tmp4 + tmp5; tmp3 = tmp4 - tmp5; /* Pass 2: process 2 rows, store into output array. */ /* Row 0 */ outptr = output_buf[0] + output_col; outptr[0] = range_limit[(int) IRIGHT_SHIFT(tmp0 + tmp1, 3) & RANGE_MASK]; outptr[1] = range_limit[(int) IRIGHT_SHIFT(tmp0 - tmp1, 3) & RANGE_MASK]; /* Row 1 */ outptr = output_buf[1] + output_col; outptr[0] = range_limit[(int) IRIGHT_SHIFT(tmp2 + tmp3, 3) & RANGE_MASK]; outptr[1] = range_limit[(int) IRIGHT_SHIFT(tmp2 - tmp3, 3) & RANGE_MASK]; } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 1x1 output block. * * We hardly need an inverse DCT routine for this: just take the * average pixel value, which is one-eighth of the DC coefficient. */ GLOBAL(void) jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { DCTELEM dcval; ISLOW_MULT_TYPE * quantptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); ISHIFT_TEMPS /* 1x1 is trivial: just take the DC coefficient divided by 8. */ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; dcval = DEQUANTIZE(coef_block[0], quantptr[0]); /* Add range center and fudge factor for descale and range-limit. */ dcval += (((DCTELEM) RANGE_CENTER) << 3) + (1 << 2); output_buf[0][output_col] = range_limit[(int) IRIGHT_SHIFT(dcval, 3) & RANGE_MASK]; } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 9x9 output block. * * Optimized algorithm with 10 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/18). */ GLOBAL(void) jpeg_idct_9x9 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp10, tmp11, tmp12, tmp13, tmp14; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*9]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp0 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-1); z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp3 = MULTIPLY(z3, FIX(0.707106781)); /* c6 */ tmp1 = tmp0 + tmp3; tmp2 = tmp0 - tmp3 - tmp3; tmp0 = MULTIPLY(z1 - z2, FIX(0.707106781)); /* c6 */ tmp11 = tmp2 + tmp0; tmp14 = tmp2 - tmp0 - tmp0; tmp0 = MULTIPLY(z1 + z2, FIX(1.328926049)); /* c2 */ tmp2 = MULTIPLY(z1, FIX(1.083350441)); /* c4 */ tmp3 = MULTIPLY(z2, FIX(0.245575608)); /* c8 */ tmp10 = tmp1 + tmp0 - tmp3; tmp12 = tmp1 - tmp0 + tmp2; tmp13 = tmp1 - tmp2 + tmp3; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); z2 = MULTIPLY(z2, - FIX(1.224744871)); /* -c3 */ tmp2 = MULTIPLY(z1 + z3, FIX(0.909038955)); /* c5 */ tmp3 = MULTIPLY(z1 + z4, FIX(0.483689525)); /* c7 */ tmp0 = tmp2 + tmp3 - z2; tmp1 = MULTIPLY(z3 - z4, FIX(1.392728481)); /* c1 */ tmp2 += z2 - tmp1; tmp3 += z2 + tmp1; tmp1 = MULTIPLY(z1 - z3 - z4, FIX(1.224744871)); /* c3 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp13 + tmp3, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp13 - tmp3, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp14, CONST_BITS-PASS1_BITS); } /* Pass 2: process 9 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 9; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp0 <<= CONST_BITS; z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[4]; z3 = (INT32) wsptr[6]; tmp3 = MULTIPLY(z3, FIX(0.707106781)); /* c6 */ tmp1 = tmp0 + tmp3; tmp2 = tmp0 - tmp3 - tmp3; tmp0 = MULTIPLY(z1 - z2, FIX(0.707106781)); /* c6 */ tmp11 = tmp2 + tmp0; tmp14 = tmp2 - tmp0 - tmp0; tmp0 = MULTIPLY(z1 + z2, FIX(1.328926049)); /* c2 */ tmp2 = MULTIPLY(z1, FIX(1.083350441)); /* c4 */ tmp3 = MULTIPLY(z2, FIX(0.245575608)); /* c8 */ tmp10 = tmp1 + tmp0 - tmp3; tmp12 = tmp1 - tmp0 + tmp2; tmp13 = tmp1 - tmp2 + tmp3; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; z2 = MULTIPLY(z2, - FIX(1.224744871)); /* -c3 */ tmp2 = MULTIPLY(z1 + z3, FIX(0.909038955)); /* c5 */ tmp3 = MULTIPLY(z1 + z4, FIX(0.483689525)); /* c7 */ tmp0 = tmp2 + tmp3 - z2; tmp1 = MULTIPLY(z3 - z4, FIX(1.392728481)); /* c1 */ tmp2 += z2 - tmp1; tmp3 += z2 + tmp1; tmp1 = MULTIPLY(z1 - z3 - z4, FIX(1.224744871)); /* c3 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp13 + tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp13 - tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 10x10 output block. * * Optimized algorithm with 12 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/20). */ GLOBAL(void) jpeg_idct_10x10 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14; INT32 tmp20, tmp21, tmp22, tmp23, tmp24; INT32 z1, z2, z3, z4, z5; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*10]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z3 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z3 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z3 += ONE << (CONST_BITS-PASS1_BITS-1); z4 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z1 = MULTIPLY(z4, FIX(1.144122806)); /* c4 */ z2 = MULTIPLY(z4, FIX(0.437016024)); /* c8 */ tmp10 = z3 + z1; tmp11 = z3 - z2; tmp22 = RIGHT_SHIFT(z3 - ((z1 - z2) << 1), /* c0 = (c4-c8)*2 */ CONST_BITS-PASS1_BITS); z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c6 */ tmp12 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c2-c6 */ tmp13 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c2+c6 */ tmp20 = tmp10 + tmp12; tmp24 = tmp10 - tmp12; tmp21 = tmp11 + tmp13; tmp23 = tmp11 - tmp13; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = z2 + z4; tmp13 = z2 - z4; tmp12 = MULTIPLY(tmp13, FIX(0.309016994)); /* (c3-c7)/2 */ z5 = z3 << CONST_BITS; z2 = MULTIPLY(tmp11, FIX(0.951056516)); /* (c3+c7)/2 */ z4 = z5 + tmp12; tmp10 = MULTIPLY(z1, FIX(1.396802247)) + z2 + z4; /* c1 */ tmp14 = MULTIPLY(z1, FIX(0.221231742)) - z2 + z4; /* c9 */ z2 = MULTIPLY(tmp11, FIX(0.587785252)); /* (c1-c9)/2 */ z4 = z5 - tmp12 - (tmp13 << (CONST_BITS - 1)); tmp12 = (z1 - tmp13 - z3) << PASS1_BITS; tmp11 = MULTIPLY(z1, FIX(1.260073511)) - z2 - z4; /* c3 */ tmp13 = MULTIPLY(z1, FIX(0.642039522)) - z2 + z4; /* c7 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) (tmp22 + tmp12); wsptr[8*7] = (int) (tmp22 - tmp12); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); } /* Pass 2: process 10 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 10; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z3 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z3 <<= CONST_BITS; z4 = (INT32) wsptr[4]; z1 = MULTIPLY(z4, FIX(1.144122806)); /* c4 */ z2 = MULTIPLY(z4, FIX(0.437016024)); /* c8 */ tmp10 = z3 + z1; tmp11 = z3 - z2; tmp22 = z3 - ((z1 - z2) << 1); /* c0 = (c4-c8)*2 */ z2 = (INT32) wsptr[2]; z3 = (INT32) wsptr[6]; z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c6 */ tmp12 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c2-c6 */ tmp13 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c2+c6 */ tmp20 = tmp10 + tmp12; tmp24 = tmp10 - tmp12; tmp21 = tmp11 + tmp13; tmp23 = tmp11 - tmp13; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z3 <<= CONST_BITS; z4 = (INT32) wsptr[7]; tmp11 = z2 + z4; tmp13 = z2 - z4; tmp12 = MULTIPLY(tmp13, FIX(0.309016994)); /* (c3-c7)/2 */ z2 = MULTIPLY(tmp11, FIX(0.951056516)); /* (c3+c7)/2 */ z4 = z3 + tmp12; tmp10 = MULTIPLY(z1, FIX(1.396802247)) + z2 + z4; /* c1 */ tmp14 = MULTIPLY(z1, FIX(0.221231742)) - z2 + z4; /* c9 */ z2 = MULTIPLY(tmp11, FIX(0.587785252)); /* (c1-c9)/2 */ z4 = z3 - tmp12 - (tmp13 << (CONST_BITS - 1)); tmp12 = ((z1 - tmp13) << CONST_BITS) - z3; tmp11 = MULTIPLY(z1, FIX(1.260073511)) - z2 - z4; /* c3 */ tmp13 = MULTIPLY(z1, FIX(0.642039522)) - z2 + z4; /* c7 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 11x11 output block. * * Optimized algorithm with 24 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/22). */ GLOBAL(void) jpeg_idct_11x11 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*11]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp10 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp10 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp10 += ONE << (CONST_BITS-PASS1_BITS-1); z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp20 = MULTIPLY(z2 - z3, FIX(2.546640132)); /* c2+c4 */ tmp23 = MULTIPLY(z2 - z1, FIX(0.430815045)); /* c2-c6 */ z4 = z1 + z3; tmp24 = MULTIPLY(z4, - FIX(1.155664402)); /* -(c2-c10) */ z4 -= z2; tmp25 = tmp10 + MULTIPLY(z4, FIX(1.356927976)); /* c2 */ tmp21 = tmp20 + tmp23 + tmp25 - MULTIPLY(z2, FIX(1.821790775)); /* c2+c4+c10-c6 */ tmp20 += tmp25 + MULTIPLY(z3, FIX(2.115825087)); /* c4+c6 */ tmp23 += tmp25 - MULTIPLY(z1, FIX(1.513598477)); /* c6+c8 */ tmp24 += tmp25; tmp22 = tmp24 - MULTIPLY(z3, FIX(0.788749120)); /* c8+c10 */ tmp24 += MULTIPLY(z2, FIX(1.944413522)) - /* c2+c8 */ MULTIPLY(z1, FIX(1.390975730)); /* c4+c10 */ tmp25 = tmp10 - MULTIPLY(z4, FIX(1.414213562)); /* c0 */ /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = z1 + z2; tmp14 = MULTIPLY(tmp11 + z3 + z4, FIX(0.398430003)); /* c9 */ tmp11 = MULTIPLY(tmp11, FIX(0.887983902)); /* c3-c9 */ tmp12 = MULTIPLY(z1 + z3, FIX(0.670361295)); /* c5-c9 */ tmp13 = tmp14 + MULTIPLY(z1 + z4, FIX(0.366151574)); /* c7-c9 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(z1, FIX(0.923107866)); /* c7+c5+c3-c1-2*c9 */ z1 = tmp14 - MULTIPLY(z2 + z3, FIX(1.163011579)); /* c7+c9 */ tmp11 += z1 + MULTIPLY(z2, FIX(2.073276588)); /* c1+c7+3*c9-c3 */ tmp12 += z1 - MULTIPLY(z3, FIX(1.192193623)); /* c3+c5-c7-c9 */ z1 = MULTIPLY(z2 + z4, - FIX(1.798248910)); /* -(c1+c9) */ tmp11 += z1; tmp13 += z1 + MULTIPLY(z4, FIX(2.102458632)); /* c1+c5+c9-c7 */ tmp14 += MULTIPLY(z2, - FIX(1.467221301)) + /* -(c5+c9) */ MULTIPLY(z3, FIX(1.001388905)) - /* c1-c9 */ MULTIPLY(z4, FIX(1.684843907)); /* c3+c9 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*10] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp25, CONST_BITS-PASS1_BITS); } /* Pass 2: process 11 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 11; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp10 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp10 <<= CONST_BITS; z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[4]; z3 = (INT32) wsptr[6]; tmp20 = MULTIPLY(z2 - z3, FIX(2.546640132)); /* c2+c4 */ tmp23 = MULTIPLY(z2 - z1, FIX(0.430815045)); /* c2-c6 */ z4 = z1 + z3; tmp24 = MULTIPLY(z4, - FIX(1.155664402)); /* -(c2-c10) */ z4 -= z2; tmp25 = tmp10 + MULTIPLY(z4, FIX(1.356927976)); /* c2 */ tmp21 = tmp20 + tmp23 + tmp25 - MULTIPLY(z2, FIX(1.821790775)); /* c2+c4+c10-c6 */ tmp20 += tmp25 + MULTIPLY(z3, FIX(2.115825087)); /* c4+c6 */ tmp23 += tmp25 - MULTIPLY(z1, FIX(1.513598477)); /* c6+c8 */ tmp24 += tmp25; tmp22 = tmp24 - MULTIPLY(z3, FIX(0.788749120)); /* c8+c10 */ tmp24 += MULTIPLY(z2, FIX(1.944413522)) - /* c2+c8 */ MULTIPLY(z1, FIX(1.390975730)); /* c4+c10 */ tmp25 = tmp10 - MULTIPLY(z4, FIX(1.414213562)); /* c0 */ /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; tmp11 = z1 + z2; tmp14 = MULTIPLY(tmp11 + z3 + z4, FIX(0.398430003)); /* c9 */ tmp11 = MULTIPLY(tmp11, FIX(0.887983902)); /* c3-c9 */ tmp12 = MULTIPLY(z1 + z3, FIX(0.670361295)); /* c5-c9 */ tmp13 = tmp14 + MULTIPLY(z1 + z4, FIX(0.366151574)); /* c7-c9 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(z1, FIX(0.923107866)); /* c7+c5+c3-c1-2*c9 */ z1 = tmp14 - MULTIPLY(z2 + z3, FIX(1.163011579)); /* c7+c9 */ tmp11 += z1 + MULTIPLY(z2, FIX(2.073276588)); /* c1+c7+3*c9-c3 */ tmp12 += z1 - MULTIPLY(z3, FIX(1.192193623)); /* c3+c5-c7-c9 */ z1 = MULTIPLY(z2 + z4, - FIX(1.798248910)); /* -(c1+c9) */ tmp11 += z1; tmp13 += z1 + MULTIPLY(z4, FIX(2.102458632)); /* c1+c5+c9-c7 */ tmp14 += MULTIPLY(z2, - FIX(1.467221301)) + /* -(c5+c9) */ MULTIPLY(z3, FIX(1.001388905)) - /* c1-c9 */ MULTIPLY(z4, FIX(1.684843907)); /* c3+c9 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 12x12 output block. * * Optimized algorithm with 15 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/24). */ GLOBAL(void) jpeg_idct_12x12 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*12]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z3 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z3 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z3 += ONE << (CONST_BITS-PASS1_BITS-1); z4 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z4 = MULTIPLY(z4, FIX(1.224744871)); /* c4 */ tmp10 = z3 + z4; tmp11 = z3 - z4; z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z4 = MULTIPLY(z1, FIX(1.366025404)); /* c2 */ z1 <<= CONST_BITS; z2 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z2 <<= CONST_BITS; tmp12 = z1 - z2; tmp21 = z3 + tmp12; tmp24 = z3 - tmp12; tmp12 = z4 + z2; tmp20 = tmp10 + tmp12; tmp25 = tmp10 - tmp12; tmp12 = z4 - z1 - z2; tmp22 = tmp11 + tmp12; tmp23 = tmp11 - tmp12; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = MULTIPLY(z2, FIX(1.306562965)); /* c3 */ tmp14 = MULTIPLY(z2, - FIX_0_541196100); /* -c9 */ tmp10 = z1 + z3; tmp15 = MULTIPLY(tmp10 + z4, FIX(0.860918669)); /* c7 */ tmp12 = tmp15 + MULTIPLY(tmp10, FIX(0.261052384)); /* c5-c7 */ tmp10 = tmp12 + tmp11 + MULTIPLY(z1, FIX(0.280143716)); /* c1-c5 */ tmp13 = MULTIPLY(z3 + z4, - FIX(1.045510580)); /* -(c7+c11) */ tmp12 += tmp13 + tmp14 - MULTIPLY(z3, FIX(1.478575242)); /* c1+c5-c7-c11 */ tmp13 += tmp15 - tmp11 + MULTIPLY(z4, FIX(1.586706681)); /* c1+c11 */ tmp15 += tmp14 - MULTIPLY(z1, FIX(0.676326758)) - /* c7-c11 */ MULTIPLY(z4, FIX(1.982889723)); /* c5+c7 */ z1 -= z4; z2 -= z3; z3 = MULTIPLY(z1 + z2, FIX_0_541196100); /* c9 */ tmp11 = z3 + MULTIPLY(z1, FIX_0_765366865); /* c3-c9 */ tmp14 = z3 - MULTIPLY(z2, FIX_1_847759065); /* c3+c9 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*11] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*10] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS-PASS1_BITS); } /* Pass 2: process 12 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 12; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z3 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z3 <<= CONST_BITS; z4 = (INT32) wsptr[4]; z4 = MULTIPLY(z4, FIX(1.224744871)); /* c4 */ tmp10 = z3 + z4; tmp11 = z3 - z4; z1 = (INT32) wsptr[2]; z4 = MULTIPLY(z1, FIX(1.366025404)); /* c2 */ z1 <<= CONST_BITS; z2 = (INT32) wsptr[6]; z2 <<= CONST_BITS; tmp12 = z1 - z2; tmp21 = z3 + tmp12; tmp24 = z3 - tmp12; tmp12 = z4 + z2; tmp20 = tmp10 + tmp12; tmp25 = tmp10 - tmp12; tmp12 = z4 - z1 - z2; tmp22 = tmp11 + tmp12; tmp23 = tmp11 - tmp12; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; tmp11 = MULTIPLY(z2, FIX(1.306562965)); /* c3 */ tmp14 = MULTIPLY(z2, - FIX_0_541196100); /* -c9 */ tmp10 = z1 + z3; tmp15 = MULTIPLY(tmp10 + z4, FIX(0.860918669)); /* c7 */ tmp12 = tmp15 + MULTIPLY(tmp10, FIX(0.261052384)); /* c5-c7 */ tmp10 = tmp12 + tmp11 + MULTIPLY(z1, FIX(0.280143716)); /* c1-c5 */ tmp13 = MULTIPLY(z3 + z4, - FIX(1.045510580)); /* -(c7+c11) */ tmp12 += tmp13 + tmp14 - MULTIPLY(z3, FIX(1.478575242)); /* c1+c5-c7-c11 */ tmp13 += tmp15 - tmp11 + MULTIPLY(z4, FIX(1.586706681)); /* c1+c11 */ tmp15 += tmp14 - MULTIPLY(z1, FIX(0.676326758)) - /* c7-c11 */ MULTIPLY(z4, FIX(1.982889723)); /* c5+c7 */ z1 -= z4; z2 -= z3; z3 = MULTIPLY(z1 + z2, FIX_0_541196100); /* c9 */ tmp11 = z3 + MULTIPLY(z1, FIX_0_765366865); /* c3-c9 */ tmp14 = z3 - MULTIPLY(z2, FIX_1_847759065); /* c3+c9 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 13x13 output block. * * Optimized algorithm with 29 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/26). */ GLOBAL(void) jpeg_idct_13x13 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*13]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z1 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z4 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp10 = z3 + z4; tmp11 = z3 - z4; tmp12 = MULTIPLY(tmp10, FIX(1.155388986)); /* (c4+c6)/2 */ tmp13 = MULTIPLY(tmp11, FIX(0.096834934)) + z1; /* (c4-c6)/2 */ tmp20 = MULTIPLY(z2, FIX(1.373119086)) + tmp12 + tmp13; /* c2 */ tmp22 = MULTIPLY(z2, FIX(0.501487041)) - tmp12 + tmp13; /* c10 */ tmp12 = MULTIPLY(tmp10, FIX(0.316450131)); /* (c8-c12)/2 */ tmp13 = MULTIPLY(tmp11, FIX(0.486914739)) + z1; /* (c8+c12)/2 */ tmp21 = MULTIPLY(z2, FIX(1.058554052)) - tmp12 + tmp13; /* c6 */ tmp25 = MULTIPLY(z2, - FIX(1.252223920)) + tmp12 + tmp13; /* c4 */ tmp12 = MULTIPLY(tmp10, FIX(0.435816023)); /* (c2-c10)/2 */ tmp13 = MULTIPLY(tmp11, FIX(0.937303064)) - z1; /* (c2+c10)/2 */ tmp23 = MULTIPLY(z2, - FIX(0.170464608)) - tmp12 - tmp13; /* c12 */ tmp24 = MULTIPLY(z2, - FIX(0.803364869)) + tmp12 - tmp13; /* c8 */ tmp26 = MULTIPLY(tmp11 - z2, FIX(1.414213562)) + z1; /* c0 */ /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = MULTIPLY(z1 + z2, FIX(1.322312651)); /* c3 */ tmp12 = MULTIPLY(z1 + z3, FIX(1.163874945)); /* c5 */ tmp15 = z1 + z4; tmp13 = MULTIPLY(tmp15, FIX(0.937797057)); /* c7 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(z1, FIX(2.020082300)); /* c7+c5+c3-c1 */ tmp14 = MULTIPLY(z2 + z3, - FIX(0.338443458)); /* -c11 */ tmp11 += tmp14 + MULTIPLY(z2, FIX(0.837223564)); /* c5+c9+c11-c3 */ tmp12 += tmp14 - MULTIPLY(z3, FIX(1.572116027)); /* c1+c5-c9-c11 */ tmp14 = MULTIPLY(z2 + z4, - FIX(1.163874945)); /* -c5 */ tmp11 += tmp14; tmp13 += tmp14 + MULTIPLY(z4, FIX(2.205608352)); /* c3+c5+c9-c7 */ tmp14 = MULTIPLY(z3 + z4, - FIX(0.657217813)); /* -c9 */ tmp12 += tmp14; tmp13 += tmp14; tmp15 = MULTIPLY(tmp15, FIX(0.338443458)); /* c11 */ tmp14 = tmp15 + MULTIPLY(z1, FIX(0.318774355)) - /* c9-c11 */ MULTIPLY(z2, FIX(0.466105296)); /* c1-c7 */ z1 = MULTIPLY(z3 - z2, FIX(0.937797057)); /* c7 */ tmp14 += z1; tmp15 += z1 + MULTIPLY(z3, FIX(0.384515595)) - /* c3-c7 */ MULTIPLY(z4, FIX(1.742345811)); /* c1+c11 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*12] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*11] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*10] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp26, CONST_BITS-PASS1_BITS); } /* Pass 2: process 13 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 13; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z1 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z1 <<= CONST_BITS; z2 = (INT32) wsptr[2]; z3 = (INT32) wsptr[4]; z4 = (INT32) wsptr[6]; tmp10 = z3 + z4; tmp11 = z3 - z4; tmp12 = MULTIPLY(tmp10, FIX(1.155388986)); /* (c4+c6)/2 */ tmp13 = MULTIPLY(tmp11, FIX(0.096834934)) + z1; /* (c4-c6)/2 */ tmp20 = MULTIPLY(z2, FIX(1.373119086)) + tmp12 + tmp13; /* c2 */ tmp22 = MULTIPLY(z2, FIX(0.501487041)) - tmp12 + tmp13; /* c10 */ tmp12 = MULTIPLY(tmp10, FIX(0.316450131)); /* (c8-c12)/2 */ tmp13 = MULTIPLY(tmp11, FIX(0.486914739)) + z1; /* (c8+c12)/2 */ tmp21 = MULTIPLY(z2, FIX(1.058554052)) - tmp12 + tmp13; /* c6 */ tmp25 = MULTIPLY(z2, - FIX(1.252223920)) + tmp12 + tmp13; /* c4 */ tmp12 = MULTIPLY(tmp10, FIX(0.435816023)); /* (c2-c10)/2 */ tmp13 = MULTIPLY(tmp11, FIX(0.937303064)) - z1; /* (c2+c10)/2 */ tmp23 = MULTIPLY(z2, - FIX(0.170464608)) - tmp12 - tmp13; /* c12 */ tmp24 = MULTIPLY(z2, - FIX(0.803364869)) + tmp12 - tmp13; /* c8 */ tmp26 = MULTIPLY(tmp11 - z2, FIX(1.414213562)) + z1; /* c0 */ /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; tmp11 = MULTIPLY(z1 + z2, FIX(1.322312651)); /* c3 */ tmp12 = MULTIPLY(z1 + z3, FIX(1.163874945)); /* c5 */ tmp15 = z1 + z4; tmp13 = MULTIPLY(tmp15, FIX(0.937797057)); /* c7 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(z1, FIX(2.020082300)); /* c7+c5+c3-c1 */ tmp14 = MULTIPLY(z2 + z3, - FIX(0.338443458)); /* -c11 */ tmp11 += tmp14 + MULTIPLY(z2, FIX(0.837223564)); /* c5+c9+c11-c3 */ tmp12 += tmp14 - MULTIPLY(z3, FIX(1.572116027)); /* c1+c5-c9-c11 */ tmp14 = MULTIPLY(z2 + z4, - FIX(1.163874945)); /* -c5 */ tmp11 += tmp14; tmp13 += tmp14 + MULTIPLY(z4, FIX(2.205608352)); /* c3+c5+c9-c7 */ tmp14 = MULTIPLY(z3 + z4, - FIX(0.657217813)); /* -c9 */ tmp12 += tmp14; tmp13 += tmp14; tmp15 = MULTIPLY(tmp15, FIX(0.338443458)); /* c11 */ tmp14 = tmp15 + MULTIPLY(z1, FIX(0.318774355)) - /* c9-c11 */ MULTIPLY(z2, FIX(0.466105296)); /* c1-c7 */ z1 = MULTIPLY(z3 - z2, FIX(0.937797057)); /* c7 */ tmp14 += z1; tmp15 += z1 + MULTIPLY(z3, FIX(0.384515595)) - /* c3-c7 */ MULTIPLY(z4, FIX(1.742345811)); /* c1+c11 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[12] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp26, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 14x14 output block. * * Optimized algorithm with 20 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/28). */ GLOBAL(void) jpeg_idct_14x14 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*14]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z1 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); z4 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z2 = MULTIPLY(z4, FIX(1.274162392)); /* c4 */ z3 = MULTIPLY(z4, FIX(0.314692123)); /* c12 */ z4 = MULTIPLY(z4, FIX(0.881747734)); /* c8 */ tmp10 = z1 + z2; tmp11 = z1 + z3; tmp12 = z1 - z4; tmp23 = RIGHT_SHIFT(z1 - ((z2 + z3 - z4) << 1), /* c0 = (c4+c12-c8)*2 */ CONST_BITS-PASS1_BITS); z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z3 = MULTIPLY(z1 + z2, FIX(1.105676686)); /* c6 */ tmp13 = z3 + MULTIPLY(z1, FIX(0.273079590)); /* c2-c6 */ tmp14 = z3 - MULTIPLY(z2, FIX(1.719280954)); /* c6+c10 */ tmp15 = MULTIPLY(z1, FIX(0.613604268)) - /* c10 */ MULTIPLY(z2, FIX(1.378756276)); /* c2 */ tmp20 = tmp10 + tmp13; tmp26 = tmp10 - tmp13; tmp21 = tmp11 + tmp14; tmp25 = tmp11 - tmp14; tmp22 = tmp12 + tmp15; tmp24 = tmp12 - tmp15; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp13 = z4 << CONST_BITS; tmp14 = z1 + z3; tmp11 = MULTIPLY(z1 + z2, FIX(1.334852607)); /* c3 */ tmp12 = MULTIPLY(tmp14, FIX(1.197448846)); /* c5 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(z1, FIX(1.126980169)); /* c3+c5-c1 */ tmp14 = MULTIPLY(tmp14, FIX(0.752406978)); /* c9 */ tmp16 = tmp14 - MULTIPLY(z1, FIX(1.061150426)); /* c9+c11-c13 */ z1 -= z2; tmp15 = MULTIPLY(z1, FIX(0.467085129)) - tmp13; /* c11 */ tmp16 += tmp15; z1 += z4; z4 = MULTIPLY(z2 + z3, - FIX(0.158341681)) - tmp13; /* -c13 */ tmp11 += z4 - MULTIPLY(z2, FIX(0.424103948)); /* c3-c9-c13 */ tmp12 += z4 - MULTIPLY(z3, FIX(2.373959773)); /* c3+c5-c13 */ z4 = MULTIPLY(z3 - z2, FIX(1.405321284)); /* c1 */ tmp14 += z4 + tmp13 - MULTIPLY(z3, FIX(1.6906431334)); /* c1+c9-c11 */ tmp15 += z4 + MULTIPLY(z2, FIX(0.674957567)); /* c1+c11-c5 */ tmp13 = (z1 - z3) << PASS1_BITS; /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*13] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*12] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*11] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) (tmp23 + tmp13); wsptr[8*10] = (int) (tmp23 - tmp13); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp26 + tmp16, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp26 - tmp16, CONST_BITS-PASS1_BITS); } /* Pass 2: process 14 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 14; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z1 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z1 <<= CONST_BITS; z4 = (INT32) wsptr[4]; z2 = MULTIPLY(z4, FIX(1.274162392)); /* c4 */ z3 = MULTIPLY(z4, FIX(0.314692123)); /* c12 */ z4 = MULTIPLY(z4, FIX(0.881747734)); /* c8 */ tmp10 = z1 + z2; tmp11 = z1 + z3; tmp12 = z1 - z4; tmp23 = z1 - ((z2 + z3 - z4) << 1); /* c0 = (c4+c12-c8)*2 */ z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[6]; z3 = MULTIPLY(z1 + z2, FIX(1.105676686)); /* c6 */ tmp13 = z3 + MULTIPLY(z1, FIX(0.273079590)); /* c2-c6 */ tmp14 = z3 - MULTIPLY(z2, FIX(1.719280954)); /* c6+c10 */ tmp15 = MULTIPLY(z1, FIX(0.613604268)) - /* c10 */ MULTIPLY(z2, FIX(1.378756276)); /* c2 */ tmp20 = tmp10 + tmp13; tmp26 = tmp10 - tmp13; tmp21 = tmp11 + tmp14; tmp25 = tmp11 - tmp14; tmp22 = tmp12 + tmp15; tmp24 = tmp12 - tmp15; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; z4 <<= CONST_BITS; tmp14 = z1 + z3; tmp11 = MULTIPLY(z1 + z2, FIX(1.334852607)); /* c3 */ tmp12 = MULTIPLY(tmp14, FIX(1.197448846)); /* c5 */ tmp10 = tmp11 + tmp12 + z4 - MULTIPLY(z1, FIX(1.126980169)); /* c3+c5-c1 */ tmp14 = MULTIPLY(tmp14, FIX(0.752406978)); /* c9 */ tmp16 = tmp14 - MULTIPLY(z1, FIX(1.061150426)); /* c9+c11-c13 */ z1 -= z2; tmp15 = MULTIPLY(z1, FIX(0.467085129)) - z4; /* c11 */ tmp16 += tmp15; tmp13 = MULTIPLY(z2 + z3, - FIX(0.158341681)) - z4; /* -c13 */ tmp11 += tmp13 - MULTIPLY(z2, FIX(0.424103948)); /* c3-c9-c13 */ tmp12 += tmp13 - MULTIPLY(z3, FIX(2.373959773)); /* c3+c5-c13 */ tmp13 = MULTIPLY(z3 - z2, FIX(1.405321284)); /* c1 */ tmp14 += tmp13 + z4 - MULTIPLY(z3, FIX(1.6906431334)); /* c1+c9-c11 */ tmp15 += tmp13 + MULTIPLY(z2, FIX(0.674957567)); /* c1+c11-c5 */ tmp13 = ((z1 - z3) << CONST_BITS) + z4; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[13] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[12] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp26 + tmp16, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp26 - tmp16, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 15x15 output block. * * Optimized algorithm with 22 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/30). */ GLOBAL(void) jpeg_idct_15x15 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26, tmp27; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*15]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z1 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z4 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp10 = MULTIPLY(z4, FIX(0.437016024)); /* c12 */ tmp11 = MULTIPLY(z4, FIX(1.144122806)); /* c6 */ tmp12 = z1 - tmp10; tmp13 = z1 + tmp11; z1 -= (tmp11 - tmp10) << 1; /* c0 = (c6-c12)*2 */ z4 = z2 - z3; z3 += z2; tmp10 = MULTIPLY(z3, FIX(1.337628990)); /* (c2+c4)/2 */ tmp11 = MULTIPLY(z4, FIX(0.045680613)); /* (c2-c4)/2 */ z2 = MULTIPLY(z2, FIX(1.439773946)); /* c4+c14 */ tmp20 = tmp13 + tmp10 + tmp11; tmp23 = tmp12 - tmp10 + tmp11 + z2; tmp10 = MULTIPLY(z3, FIX(0.547059574)); /* (c8+c14)/2 */ tmp11 = MULTIPLY(z4, FIX(0.399234004)); /* (c8-c14)/2 */ tmp25 = tmp13 - tmp10 - tmp11; tmp26 = tmp12 + tmp10 - tmp11 - z2; tmp10 = MULTIPLY(z3, FIX(0.790569415)); /* (c6+c12)/2 */ tmp11 = MULTIPLY(z4, FIX(0.353553391)); /* (c6-c12)/2 */ tmp21 = tmp12 + tmp10 + tmp11; tmp24 = tmp13 - tmp10 + tmp11; tmp11 += tmp11; tmp22 = z1 + tmp11; /* c10 = c6-c12 */ tmp27 = z1 - tmp11 - tmp11; /* c0 = (c6-c12)*2 */ /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z4 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z3 = MULTIPLY(z4, FIX(1.224744871)); /* c5 */ z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp13 = z2 - z4; tmp15 = MULTIPLY(z1 + tmp13, FIX(0.831253876)); /* c9 */ tmp11 = tmp15 + MULTIPLY(z1, FIX(0.513743148)); /* c3-c9 */ tmp14 = tmp15 - MULTIPLY(tmp13, FIX(2.176250899)); /* c3+c9 */ tmp13 = MULTIPLY(z2, - FIX(0.831253876)); /* -c9 */ tmp15 = MULTIPLY(z2, - FIX(1.344997024)); /* -c3 */ z2 = z1 - z4; tmp12 = z3 + MULTIPLY(z2, FIX(1.406466353)); /* c1 */ tmp10 = tmp12 + MULTIPLY(z4, FIX(2.457431844)) - tmp15; /* c1+c7 */ tmp16 = tmp12 - MULTIPLY(z1, FIX(1.112434820)) + tmp13; /* c1-c13 */ tmp12 = MULTIPLY(z2, FIX(1.224744871)) - z3; /* c5 */ z2 = MULTIPLY(z1 + z4, FIX(0.575212477)); /* c11 */ tmp13 += z2 + MULTIPLY(z1, FIX(0.475753014)) - z3; /* c7-c11 */ tmp15 += z2 - MULTIPLY(z4, FIX(0.869244010)) + z3; /* c11+c13 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*14] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*13] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*12] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*11] = (int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[8*10] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp26 + tmp16, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp26 - tmp16, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp27, CONST_BITS-PASS1_BITS); } /* Pass 2: process 15 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 15; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z1 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z1 <<= CONST_BITS; z2 = (INT32) wsptr[2]; z3 = (INT32) wsptr[4]; z4 = (INT32) wsptr[6]; tmp10 = MULTIPLY(z4, FIX(0.437016024)); /* c12 */ tmp11 = MULTIPLY(z4, FIX(1.144122806)); /* c6 */ tmp12 = z1 - tmp10; tmp13 = z1 + tmp11; z1 -= (tmp11 - tmp10) << 1; /* c0 = (c6-c12)*2 */ z4 = z2 - z3; z3 += z2; tmp10 = MULTIPLY(z3, FIX(1.337628990)); /* (c2+c4)/2 */ tmp11 = MULTIPLY(z4, FIX(0.045680613)); /* (c2-c4)/2 */ z2 = MULTIPLY(z2, FIX(1.439773946)); /* c4+c14 */ tmp20 = tmp13 + tmp10 + tmp11; tmp23 = tmp12 - tmp10 + tmp11 + z2; tmp10 = MULTIPLY(z3, FIX(0.547059574)); /* (c8+c14)/2 */ tmp11 = MULTIPLY(z4, FIX(0.399234004)); /* (c8-c14)/2 */ tmp25 = tmp13 - tmp10 - tmp11; tmp26 = tmp12 + tmp10 - tmp11 - z2; tmp10 = MULTIPLY(z3, FIX(0.790569415)); /* (c6+c12)/2 */ tmp11 = MULTIPLY(z4, FIX(0.353553391)); /* (c6-c12)/2 */ tmp21 = tmp12 + tmp10 + tmp11; tmp24 = tmp13 - tmp10 + tmp11; tmp11 += tmp11; tmp22 = z1 + tmp11; /* c10 = c6-c12 */ tmp27 = z1 - tmp11 - tmp11; /* c0 = (c6-c12)*2 */ /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z4 = (INT32) wsptr[5]; z3 = MULTIPLY(z4, FIX(1.224744871)); /* c5 */ z4 = (INT32) wsptr[7]; tmp13 = z2 - z4; tmp15 = MULTIPLY(z1 + tmp13, FIX(0.831253876)); /* c9 */ tmp11 = tmp15 + MULTIPLY(z1, FIX(0.513743148)); /* c3-c9 */ tmp14 = tmp15 - MULTIPLY(tmp13, FIX(2.176250899)); /* c3+c9 */ tmp13 = MULTIPLY(z2, - FIX(0.831253876)); /* -c9 */ tmp15 = MULTIPLY(z2, - FIX(1.344997024)); /* -c3 */ z2 = z1 - z4; tmp12 = z3 + MULTIPLY(z2, FIX(1.406466353)); /* c1 */ tmp10 = tmp12 + MULTIPLY(z4, FIX(2.457431844)) - tmp15; /* c1+c7 */ tmp16 = tmp12 - MULTIPLY(z1, FIX(1.112434820)) + tmp13; /* c1-c13 */ tmp12 = MULTIPLY(z2, FIX(1.224744871)) - z3; /* c5 */ z2 = MULTIPLY(z1 + z4, FIX(0.575212477)); /* c11 */ tmp13 += z2 + MULTIPLY(z1, FIX(0.475753014)) - z3; /* c7-c11 */ tmp15 += z2 - MULTIPLY(z4, FIX(0.869244010)) + z3; /* c11+c13 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[14] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[13] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[12] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp26 + tmp16, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp26 - tmp16, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp27, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 16x16 output block. * * Optimized algorithm with 28 multiplications in the 1-D kernel. * cK represents sqrt(2) * cos(K*pi/32). */ GLOBAL(void) jpeg_idct_16x16 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp10, tmp11, tmp12, tmp13; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26, tmp27; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*16]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp0 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp0 += 1 << (CONST_BITS-PASS1_BITS-1); z1 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); tmp1 = MULTIPLY(z1, FIX(1.306562965)); /* c4[16] = c2[8] */ tmp2 = MULTIPLY(z1, FIX_0_541196100); /* c12[16] = c6[8] */ tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp12 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z3 = z1 - z2; z4 = MULTIPLY(z3, FIX(0.275899379)); /* c14[16] = c7[8] */ z3 = MULTIPLY(z3, FIX(1.387039845)); /* c2[16] = c1[8] */ tmp0 = z3 + MULTIPLY(z2, FIX_2_562915447); /* (c6+c2)[16] = (c3+c1)[8] */ tmp1 = z4 + MULTIPLY(z1, FIX_0_899976223); /* (c6-c14)[16] = (c3-c7)[8] */ tmp2 = z3 - MULTIPLY(z1, FIX(0.601344887)); /* (c2-c10)[16] = (c1-c5)[8] */ tmp3 = z4 - MULTIPLY(z2, FIX(0.509795579)); /* (c10-c14)[16] = (c5-c7)[8] */ tmp20 = tmp10 + tmp0; tmp27 = tmp10 - tmp0; tmp21 = tmp12 + tmp1; tmp26 = tmp12 - tmp1; tmp22 = tmp13 + tmp2; tmp25 = tmp13 - tmp2; tmp23 = tmp11 + tmp3; tmp24 = tmp11 - tmp3; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = z1 + z3; tmp1 = MULTIPLY(z1 + z2, FIX(1.353318001)); /* c3 */ tmp2 = MULTIPLY(tmp11, FIX(1.247225013)); /* c5 */ tmp3 = MULTIPLY(z1 + z4, FIX(1.093201867)); /* c7 */ tmp10 = MULTIPLY(z1 - z4, FIX(0.897167586)); /* c9 */ tmp11 = MULTIPLY(tmp11, FIX(0.666655658)); /* c11 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.410524528)); /* c13 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(z1, FIX(2.286341144)); /* c7+c5+c3-c1 */ tmp13 = tmp10 + tmp11 + tmp12 - MULTIPLY(z1, FIX(1.835730603)); /* c9+c11+c13-c15 */ z1 = MULTIPLY(z2 + z3, FIX(0.138617169)); /* c15 */ tmp1 += z1 + MULTIPLY(z2, FIX(0.071888074)); /* c9+c11-c3-c15 */ tmp2 += z1 - MULTIPLY(z3, FIX(1.125726048)); /* c5+c7+c15-c3 */ z1 = MULTIPLY(z3 - z2, FIX(1.407403738)); /* c1 */ tmp11 += z1 - MULTIPLY(z3, FIX(0.766367282)); /* c1+c11-c9-c13 */ tmp12 += z1 + MULTIPLY(z2, FIX(1.971951411)); /* c1+c5+c13-c7 */ z2 += z4; z1 = MULTIPLY(z2, - FIX(0.666655658)); /* -c11 */ tmp1 += z1; tmp3 += z1 + MULTIPLY(z4, FIX(1.065388962)); /* c3+c11+c15-c7 */ z2 = MULTIPLY(z2, - FIX(1.247225013)); /* -c5 */ tmp10 += z2 + MULTIPLY(z4, FIX(3.141271809)); /* c1+c5+c9-c13 */ tmp12 += z2; z2 = MULTIPLY(z3 + z4, - FIX(1.353318001)); /* -c3 */ tmp2 += z2; tmp3 += z2; z2 = MULTIPLY(z4 - z3, FIX(0.410524528)); /* c13 */ tmp10 += z2; tmp11 += z2; /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp0, CONST_BITS-PASS1_BITS); wsptr[8*15] = (int) RIGHT_SHIFT(tmp20 - tmp0, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp1, CONST_BITS-PASS1_BITS); wsptr[8*14] = (int) RIGHT_SHIFT(tmp21 - tmp1, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp2, CONST_BITS-PASS1_BITS); wsptr[8*13] = (int) RIGHT_SHIFT(tmp22 - tmp2, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23 + tmp3, CONST_BITS-PASS1_BITS); wsptr[8*12] = (int) RIGHT_SHIFT(tmp23 - tmp3, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*11] = (int) RIGHT_SHIFT(tmp24 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp25 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*10] = (int) RIGHT_SHIFT(tmp25 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp26 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp26 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp27 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp27 - tmp13, CONST_BITS-PASS1_BITS); } /* Pass 2: process 16 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 16; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp0 <<= CONST_BITS; z1 = (INT32) wsptr[4]; tmp1 = MULTIPLY(z1, FIX(1.306562965)); /* c4[16] = c2[8] */ tmp2 = MULTIPLY(z1, FIX_0_541196100); /* c12[16] = c6[8] */ tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp12 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[6]; z3 = z1 - z2; z4 = MULTIPLY(z3, FIX(0.275899379)); /* c14[16] = c7[8] */ z3 = MULTIPLY(z3, FIX(1.387039845)); /* c2[16] = c1[8] */ tmp0 = z3 + MULTIPLY(z2, FIX_2_562915447); /* (c6+c2)[16] = (c3+c1)[8] */ tmp1 = z4 + MULTIPLY(z1, FIX_0_899976223); /* (c6-c14)[16] = (c3-c7)[8] */ tmp2 = z3 - MULTIPLY(z1, FIX(0.601344887)); /* (c2-c10)[16] = (c1-c5)[8] */ tmp3 = z4 - MULTIPLY(z2, FIX(0.509795579)); /* (c10-c14)[16] = (c5-c7)[8] */ tmp20 = tmp10 + tmp0; tmp27 = tmp10 - tmp0; tmp21 = tmp12 + tmp1; tmp26 = tmp12 - tmp1; tmp22 = tmp13 + tmp2; tmp25 = tmp13 - tmp2; tmp23 = tmp11 + tmp3; tmp24 = tmp11 - tmp3; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; tmp11 = z1 + z3; tmp1 = MULTIPLY(z1 + z2, FIX(1.353318001)); /* c3 */ tmp2 = MULTIPLY(tmp11, FIX(1.247225013)); /* c5 */ tmp3 = MULTIPLY(z1 + z4, FIX(1.093201867)); /* c7 */ tmp10 = MULTIPLY(z1 - z4, FIX(0.897167586)); /* c9 */ tmp11 = MULTIPLY(tmp11, FIX(0.666655658)); /* c11 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.410524528)); /* c13 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(z1, FIX(2.286341144)); /* c7+c5+c3-c1 */ tmp13 = tmp10 + tmp11 + tmp12 - MULTIPLY(z1, FIX(1.835730603)); /* c9+c11+c13-c15 */ z1 = MULTIPLY(z2 + z3, FIX(0.138617169)); /* c15 */ tmp1 += z1 + MULTIPLY(z2, FIX(0.071888074)); /* c9+c11-c3-c15 */ tmp2 += z1 - MULTIPLY(z3, FIX(1.125726048)); /* c5+c7+c15-c3 */ z1 = MULTIPLY(z3 - z2, FIX(1.407403738)); /* c1 */ tmp11 += z1 - MULTIPLY(z3, FIX(0.766367282)); /* c1+c11-c9-c13 */ tmp12 += z1 + MULTIPLY(z2, FIX(1.971951411)); /* c1+c5+c13-c7 */ z2 += z4; z1 = MULTIPLY(z2, - FIX(0.666655658)); /* -c11 */ tmp1 += z1; tmp3 += z1 + MULTIPLY(z4, FIX(1.065388962)); /* c3+c11+c15-c7 */ z2 = MULTIPLY(z2, - FIX(1.247225013)); /* -c5 */ tmp10 += z2 + MULTIPLY(z4, FIX(3.141271809)); /* c1+c5+c9-c13 */ tmp12 += z2; z2 = MULTIPLY(z3 + z4, - FIX(1.353318001)); /* -c3 */ tmp2 += z2; tmp3 += z2; z2 = MULTIPLY(z4 - z3, FIX(0.410524528)); /* c13 */ tmp10 += z2; tmp11 += z2; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[15] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[14] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[13] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[12] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp26 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp26 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp27 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp27 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 16x8 output block. * * 8-point IDCT in pass 1 (columns), 16-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_16x8 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp10, tmp11, tmp12, tmp13; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26, tmp27; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*8]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * Note results are scaled up by sqrt(8) compared to a true IDCT; * furthermore, we scale the results by 2**PASS1_BITS. * 8-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = DCTSIZE; ctr > 0; ctr--) { /* Due to quantization, we will usually find that many of the input * coefficients are zero, especially the AC terms. We can exploit this * by short-circuiting the IDCT calculation for any column in which all * the AC terms are zero. In that case each output is equal to the * DC coefficient (with scale factor as needed). * With typical images and quantization tables, half or more of the * column DCT calculations can be simplified this way. */ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) { /* AC terms all zero */ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS; wsptr[DCTSIZE*0] = dcval; wsptr[DCTSIZE*1] = dcval; wsptr[DCTSIZE*2] = dcval; wsptr[DCTSIZE*3] = dcval; wsptr[DCTSIZE*4] = dcval; wsptr[DCTSIZE*5] = dcval; wsptr[DCTSIZE*6] = dcval; wsptr[DCTSIZE*7] = dcval; inptr++; /* advance pointers to next column */ quantptr++; wsptr++; continue; } /* Even part: reverse the even part of the forward DCT. * The rotator is c(-6). */ z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp2 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp3 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z2 <<= CONST_BITS; z3 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z2 += ONE << (CONST_BITS-PASS1_BITS-1); tmp0 = z2 + z3; tmp1 = z2 - z3; tmp10 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; tmp11 = tmp1 + tmp3; tmp12 = tmp1 - tmp3; /* Odd part per figure 8; the matrix is unitary and hence its * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = tmp0 + tmp2; z3 = tmp1 + tmp3; z1 = MULTIPLY(z2 + z3, FIX_1_175875602); /* c3 */ z2 = MULTIPLY(z2, - FIX_1_961570560); /* -c3-c5 */ z3 = MULTIPLY(z3, - FIX_0_390180644); /* -c3+c5 */ z2 += z1; z3 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp0 += z1 + z2; tmp3 += z1 + z3; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp1 += z1 + z3; tmp2 += z1 + z2; /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ wsptr[DCTSIZE*0] = (int) RIGHT_SHIFT(tmp10 + tmp3, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*7] = (int) RIGHT_SHIFT(tmp10 - tmp3, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*1] = (int) RIGHT_SHIFT(tmp11 + tmp2, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*6] = (int) RIGHT_SHIFT(tmp11 - tmp2, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*2] = (int) RIGHT_SHIFT(tmp12 + tmp1, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*5] = (int) RIGHT_SHIFT(tmp12 - tmp1, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*3] = (int) RIGHT_SHIFT(tmp13 + tmp0, CONST_BITS-PASS1_BITS); wsptr[DCTSIZE*4] = (int) RIGHT_SHIFT(tmp13 - tmp0, CONST_BITS-PASS1_BITS); inptr++; /* advance pointers to next column */ quantptr++; wsptr++; } /* Pass 2: process 8 rows from work array, store into output array. * 16-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ wsptr = workspace; for (ctr = 0; ctr < 8; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp0 <<= CONST_BITS; z1 = (INT32) wsptr[4]; tmp1 = MULTIPLY(z1, FIX(1.306562965)); /* c4[16] = c2[8] */ tmp2 = MULTIPLY(z1, FIX_0_541196100); /* c12[16] = c6[8] */ tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp12 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[6]; z3 = z1 - z2; z4 = MULTIPLY(z3, FIX(0.275899379)); /* c14[16] = c7[8] */ z3 = MULTIPLY(z3, FIX(1.387039845)); /* c2[16] = c1[8] */ tmp0 = z3 + MULTIPLY(z2, FIX_2_562915447); /* (c6+c2)[16] = (c3+c1)[8] */ tmp1 = z4 + MULTIPLY(z1, FIX_0_899976223); /* (c6-c14)[16] = (c3-c7)[8] */ tmp2 = z3 - MULTIPLY(z1, FIX(0.601344887)); /* (c2-c10)[16] = (c1-c5)[8] */ tmp3 = z4 - MULTIPLY(z2, FIX(0.509795579)); /* (c10-c14)[16] = (c5-c7)[8] */ tmp20 = tmp10 + tmp0; tmp27 = tmp10 - tmp0; tmp21 = tmp12 + tmp1; tmp26 = tmp12 - tmp1; tmp22 = tmp13 + tmp2; tmp25 = tmp13 - tmp2; tmp23 = tmp11 + tmp3; tmp24 = tmp11 - tmp3; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; tmp11 = z1 + z3; tmp1 = MULTIPLY(z1 + z2, FIX(1.353318001)); /* c3 */ tmp2 = MULTIPLY(tmp11, FIX(1.247225013)); /* c5 */ tmp3 = MULTIPLY(z1 + z4, FIX(1.093201867)); /* c7 */ tmp10 = MULTIPLY(z1 - z4, FIX(0.897167586)); /* c9 */ tmp11 = MULTIPLY(tmp11, FIX(0.666655658)); /* c11 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.410524528)); /* c13 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(z1, FIX(2.286341144)); /* c7+c5+c3-c1 */ tmp13 = tmp10 + tmp11 + tmp12 - MULTIPLY(z1, FIX(1.835730603)); /* c9+c11+c13-c15 */ z1 = MULTIPLY(z2 + z3, FIX(0.138617169)); /* c15 */ tmp1 += z1 + MULTIPLY(z2, FIX(0.071888074)); /* c9+c11-c3-c15 */ tmp2 += z1 - MULTIPLY(z3, FIX(1.125726048)); /* c5+c7+c15-c3 */ z1 = MULTIPLY(z3 - z2, FIX(1.407403738)); /* c1 */ tmp11 += z1 - MULTIPLY(z3, FIX(0.766367282)); /* c1+c11-c9-c13 */ tmp12 += z1 + MULTIPLY(z2, FIX(1.971951411)); /* c1+c5+c13-c7 */ z2 += z4; z1 = MULTIPLY(z2, - FIX(0.666655658)); /* -c11 */ tmp1 += z1; tmp3 += z1 + MULTIPLY(z4, FIX(1.065388962)); /* c3+c11+c15-c7 */ z2 = MULTIPLY(z2, - FIX(1.247225013)); /* -c5 */ tmp10 += z2 + MULTIPLY(z4, FIX(3.141271809)); /* c1+c5+c9-c13 */ tmp12 += z2; z2 = MULTIPLY(z3 + z4, - FIX(1.353318001)); /* -c3 */ tmp2 += z2; tmp3 += z2; z2 = MULTIPLY(z4 - z3, FIX(0.410524528)); /* c13 */ tmp10 += z2; tmp11 += z2; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[15] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[14] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[13] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[12] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp26 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp26 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp27 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp27 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 14x7 output block. * * 7-point IDCT in pass 1 (columns), 14-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_14x7 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*7]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 7-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/14). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp23 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp23 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp23 += ONE << (CONST_BITS-PASS1_BITS-1); z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); tmp20 = MULTIPLY(z2 - z3, FIX(0.881747734)); /* c4 */ tmp22 = MULTIPLY(z1 - z2, FIX(0.314692123)); /* c6 */ tmp21 = tmp20 + tmp22 + tmp23 - MULTIPLY(z2, FIX(1.841218003)); /* c2+c4-c6 */ tmp10 = z1 + z3; z2 -= tmp10; tmp10 = MULTIPLY(tmp10, FIX(1.274162392)) + tmp23; /* c2 */ tmp20 += tmp10 - MULTIPLY(z3, FIX(0.077722536)); /* c2-c4-c6 */ tmp22 += tmp10 - MULTIPLY(z1, FIX(2.470602249)); /* c2+c4+c6 */ tmp23 += MULTIPLY(z2, FIX(1.414213562)); /* c0 */ /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp11 = MULTIPLY(z1 + z2, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp10 = tmp11 - tmp12; tmp11 += tmp12; tmp12 = MULTIPLY(z2 + z3, - FIX(1.378756276)); /* -c1 */ tmp11 += tmp12; z2 = MULTIPLY(z1 + z3, FIX(0.613604268)); /* c5 */ tmp10 += z2; tmp12 += z2 + MULTIPLY(z3, FIX(1.870828693)); /* c3+c1-c5 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23, CONST_BITS-PASS1_BITS); } /* Pass 2: process 7 rows from work array, store into output array. * 14-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/28). */ wsptr = workspace; for (ctr = 0; ctr < 7; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z1 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z1 <<= CONST_BITS; z4 = (INT32) wsptr[4]; z2 = MULTIPLY(z4, FIX(1.274162392)); /* c4 */ z3 = MULTIPLY(z4, FIX(0.314692123)); /* c12 */ z4 = MULTIPLY(z4, FIX(0.881747734)); /* c8 */ tmp10 = z1 + z2; tmp11 = z1 + z3; tmp12 = z1 - z4; tmp23 = z1 - ((z2 + z3 - z4) << 1); /* c0 = (c4+c12-c8)*2 */ z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[6]; z3 = MULTIPLY(z1 + z2, FIX(1.105676686)); /* c6 */ tmp13 = z3 + MULTIPLY(z1, FIX(0.273079590)); /* c2-c6 */ tmp14 = z3 - MULTIPLY(z2, FIX(1.719280954)); /* c6+c10 */ tmp15 = MULTIPLY(z1, FIX(0.613604268)) - /* c10 */ MULTIPLY(z2, FIX(1.378756276)); /* c2 */ tmp20 = tmp10 + tmp13; tmp26 = tmp10 - tmp13; tmp21 = tmp11 + tmp14; tmp25 = tmp11 - tmp14; tmp22 = tmp12 + tmp15; tmp24 = tmp12 - tmp15; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; z4 <<= CONST_BITS; tmp14 = z1 + z3; tmp11 = MULTIPLY(z1 + z2, FIX(1.334852607)); /* c3 */ tmp12 = MULTIPLY(tmp14, FIX(1.197448846)); /* c5 */ tmp10 = tmp11 + tmp12 + z4 - MULTIPLY(z1, FIX(1.126980169)); /* c3+c5-c1 */ tmp14 = MULTIPLY(tmp14, FIX(0.752406978)); /* c9 */ tmp16 = tmp14 - MULTIPLY(z1, FIX(1.061150426)); /* c9+c11-c13 */ z1 -= z2; tmp15 = MULTIPLY(z1, FIX(0.467085129)) - z4; /* c11 */ tmp16 += tmp15; tmp13 = MULTIPLY(z2 + z3, - FIX(0.158341681)) - z4; /* -c13 */ tmp11 += tmp13 - MULTIPLY(z2, FIX(0.424103948)); /* c3-c9-c13 */ tmp12 += tmp13 - MULTIPLY(z3, FIX(2.373959773)); /* c3+c5-c13 */ tmp13 = MULTIPLY(z3 - z2, FIX(1.405321284)); /* c1 */ tmp14 += tmp13 + z4 - MULTIPLY(z3, FIX(1.6906431334)); /* c1+c9-c11 */ tmp15 += tmp13 + MULTIPLY(z2, FIX(0.674957567)); /* c1+c11-c5 */ tmp13 = ((z1 - z3) << CONST_BITS) + z4; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[13] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[12] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp26 + tmp16, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp26 - tmp16, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 12x6 output block. * * 6-point IDCT in pass 1 (columns), 12-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_12x6 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*6]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 6-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp10 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp10 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp10 += ONE << (CONST_BITS-PASS1_BITS-1); tmp12 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); tmp20 = MULTIPLY(tmp12, FIX(0.707106781)); /* c4 */ tmp11 = tmp10 + tmp20; tmp21 = RIGHT_SHIFT(tmp10 - tmp20 - tmp20, CONST_BITS-PASS1_BITS); tmp20 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp10 = MULTIPLY(tmp20, FIX(1.224744871)); /* c2 */ tmp20 = tmp11 + tmp10; tmp22 = tmp11 - tmp10; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp11 = MULTIPLY(z1 + z3, FIX(0.366025404)); /* c5 */ tmp10 = tmp11 + ((z1 + z2) << CONST_BITS); tmp12 = tmp11 + ((z3 - z2) << CONST_BITS); tmp11 = (z1 - z2 - z3) << PASS1_BITS; /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) (tmp21 + tmp11); wsptr[8*4] = (int) (tmp21 - tmp11); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); } /* Pass 2: process 6 rows from work array, store into output array. * 12-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/24). */ wsptr = workspace; for (ctr = 0; ctr < 6; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z3 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z3 <<= CONST_BITS; z4 = (INT32) wsptr[4]; z4 = MULTIPLY(z4, FIX(1.224744871)); /* c4 */ tmp10 = z3 + z4; tmp11 = z3 - z4; z1 = (INT32) wsptr[2]; z4 = MULTIPLY(z1, FIX(1.366025404)); /* c2 */ z1 <<= CONST_BITS; z2 = (INT32) wsptr[6]; z2 <<= CONST_BITS; tmp12 = z1 - z2; tmp21 = z3 + tmp12; tmp24 = z3 - tmp12; tmp12 = z4 + z2; tmp20 = tmp10 + tmp12; tmp25 = tmp10 - tmp12; tmp12 = z4 - z1 - z2; tmp22 = tmp11 + tmp12; tmp23 = tmp11 - tmp12; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z4 = (INT32) wsptr[7]; tmp11 = MULTIPLY(z2, FIX(1.306562965)); /* c3 */ tmp14 = MULTIPLY(z2, - FIX_0_541196100); /* -c9 */ tmp10 = z1 + z3; tmp15 = MULTIPLY(tmp10 + z4, FIX(0.860918669)); /* c7 */ tmp12 = tmp15 + MULTIPLY(tmp10, FIX(0.261052384)); /* c5-c7 */ tmp10 = tmp12 + tmp11 + MULTIPLY(z1, FIX(0.280143716)); /* c1-c5 */ tmp13 = MULTIPLY(z3 + z4, - FIX(1.045510580)); /* -(c7+c11) */ tmp12 += tmp13 + tmp14 - MULTIPLY(z3, FIX(1.478575242)); /* c1+c5-c7-c11 */ tmp13 += tmp15 - tmp11 + MULTIPLY(z4, FIX(1.586706681)); /* c1+c11 */ tmp15 += tmp14 - MULTIPLY(z1, FIX(0.676326758)) - /* c7-c11 */ MULTIPLY(z4, FIX(1.982889723)); /* c5+c7 */ z1 -= z4; z2 -= z3; z3 = MULTIPLY(z1 + z2, FIX_0_541196100); /* c9 */ tmp11 = z3 + MULTIPLY(z1, FIX_0_765366865); /* c3-c9 */ tmp14 = z3 - MULTIPLY(z2, FIX_1_847759065); /* c3+c9 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[11] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[10] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 10x5 output block. * * 5-point IDCT in pass 1 (columns), 10-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_10x5 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14; INT32 tmp20, tmp21, tmp22, tmp23, tmp24; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*5]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 5-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/10). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp12 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp12 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp12 += ONE << (CONST_BITS-PASS1_BITS-1); tmp13 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp14 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z1 = MULTIPLY(tmp13 + tmp14, FIX(0.790569415)); /* (c2+c4)/2 */ z2 = MULTIPLY(tmp13 - tmp14, FIX(0.353553391)); /* (c2-c4)/2 */ z3 = tmp12 + z2; tmp10 = z3 + z1; tmp11 = z3 - z1; tmp12 -= z2 << 2; /* Odd part */ z2 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c3 */ tmp13 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c1-c3 */ tmp14 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c1+c3 */ /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp10 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp10 - tmp13, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp11 + tmp14, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp11 - tmp14, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp12, CONST_BITS-PASS1_BITS); } /* Pass 2: process 5 rows from work array, store into output array. * 10-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/20). */ wsptr = workspace; for (ctr = 0; ctr < 5; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ z3 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z3 <<= CONST_BITS; z4 = (INT32) wsptr[4]; z1 = MULTIPLY(z4, FIX(1.144122806)); /* c4 */ z2 = MULTIPLY(z4, FIX(0.437016024)); /* c8 */ tmp10 = z3 + z1; tmp11 = z3 - z2; tmp22 = z3 - ((z1 - z2) << 1); /* c0 = (c4-c8)*2 */ z2 = (INT32) wsptr[2]; z3 = (INT32) wsptr[6]; z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c6 */ tmp12 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c2-c6 */ tmp13 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c2+c6 */ tmp20 = tmp10 + tmp12; tmp24 = tmp10 - tmp12; tmp21 = tmp11 + tmp13; tmp23 = tmp11 - tmp13; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; z3 <<= CONST_BITS; z4 = (INT32) wsptr[7]; tmp11 = z2 + z4; tmp13 = z2 - z4; tmp12 = MULTIPLY(tmp13, FIX(0.309016994)); /* (c3-c7)/2 */ z2 = MULTIPLY(tmp11, FIX(0.951056516)); /* (c3+c7)/2 */ z4 = z3 + tmp12; tmp10 = MULTIPLY(z1, FIX(1.396802247)) + z2 + z4; /* c1 */ tmp14 = MULTIPLY(z1, FIX(0.221231742)) - z2 + z4; /* c9 */ z2 = MULTIPLY(tmp11, FIX(0.587785252)); /* (c1-c9)/2 */ z4 = z3 - tmp12 - (tmp13 << (CONST_BITS - 1)); tmp12 = ((z1 - tmp13) << CONST_BITS) - z3; tmp11 = MULTIPLY(z1, FIX(1.260073511)) - z2 - z4; /* c3 */ tmp13 = MULTIPLY(z1, FIX(0.642039522)) - z2 + z4; /* c7 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[9] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[8] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 8; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 8x4 output block. * * 4-point IDCT in pass 1 (columns), 8-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_8x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*4]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 4-point IDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point IDCT]. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp10 = (tmp0 + tmp2) << PASS1_BITS; tmp12 = (tmp0 - tmp2) << PASS1_BITS; /* Odd part */ /* Same rotation as in the even part of the 8x8 LL&M IDCT */ z2 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); tmp0 = RIGHT_SHIFT(z1 + MULTIPLY(z2, FIX_0_765366865), /* c2-c6 */ CONST_BITS-PASS1_BITS); tmp2 = RIGHT_SHIFT(z1 - MULTIPLY(z3, FIX_1_847759065), /* c2+c6 */ CONST_BITS-PASS1_BITS); /* Final output stage */ wsptr[8*0] = (int) (tmp10 + tmp0); wsptr[8*3] = (int) (tmp10 - tmp0); wsptr[8*1] = (int) (tmp12 + tmp2); wsptr[8*2] = (int) (tmp12 - tmp2); } /* Pass 2: process rows from work array, store into output array. * Note that we must descale the results by a factor of 8 == 2**3, * and also undo the PASS1_BITS scaling. * 8-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ wsptr = workspace; for (ctr = 0; ctr < 4; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part: reverse the even part of the forward DCT. * The rotator is c(-6). */ /* Add range center and fudge factor for final descale and range-limit. */ z2 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z3 = (INT32) wsptr[4]; tmp0 = (z2 + z3) << CONST_BITS; tmp1 = (z2 - z3) << CONST_BITS; z2 = (INT32) wsptr[2]; z3 = (INT32) wsptr[6]; z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp2 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp3 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ tmp10 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; tmp11 = tmp1 + tmp3; tmp12 = tmp1 - tmp3; /* Odd part per figure 8; the matrix is unitary and hence its * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. */ tmp0 = (INT32) wsptr[7]; tmp1 = (INT32) wsptr[5]; tmp2 = (INT32) wsptr[3]; tmp3 = (INT32) wsptr[1]; z2 = tmp0 + tmp2; z3 = tmp1 + tmp3; z1 = MULTIPLY(z2 + z3, FIX_1_175875602); /* c3 */ z2 = MULTIPLY(z2, - FIX_1_961570560); /* -c3-c5 */ z3 = MULTIPLY(z3, - FIX_0_390180644); /* -c3+c5 */ z2 += z1; z3 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp0 += z1 + z2; tmp3 += z1 + z3; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp1 += z1 + z3; tmp2 += z1 + z2; /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp13 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp13 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += DCTSIZE; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 6x3 output block. * * 3-point IDCT in pass 1 (columns), 6-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_6x3 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp10, tmp11, tmp12; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[6*3]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 3-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/6). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 6; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp0 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-1); tmp2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp12 = MULTIPLY(tmp2, FIX(0.707106781)); /* c2 */ tmp10 = tmp0 + tmp12; tmp2 = tmp0 - tmp12 - tmp12; /* Odd part */ tmp12 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); tmp0 = MULTIPLY(tmp12, FIX(1.224744871)); /* c1 */ /* Final output stage */ wsptr[6*0] = (int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS-PASS1_BITS); wsptr[6*2] = (int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS-PASS1_BITS); wsptr[6*1] = (int) RIGHT_SHIFT(tmp2, CONST_BITS-PASS1_BITS); } /* Pass 2: process 3 rows from work array, store into output array. * 6-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ wsptr = workspace; for (ctr = 0; ctr < 3; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp0 <<= CONST_BITS; tmp2 = (INT32) wsptr[4]; tmp10 = MULTIPLY(tmp2, FIX(0.707106781)); /* c4 */ tmp1 = tmp0 + tmp10; tmp11 = tmp0 - tmp10 - tmp10; tmp10 = (INT32) wsptr[2]; tmp0 = MULTIPLY(tmp10, FIX(1.224744871)); /* c2 */ tmp10 = tmp1 + tmp0; tmp12 = tmp1 - tmp0; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; tmp1 = MULTIPLY(z1 + z3, FIX(0.366025404)); /* c5 */ tmp0 = tmp1 + ((z1 + z2) << CONST_BITS); tmp2 = tmp1 + ((z3 - z2) << CONST_BITS); tmp1 = (z1 - z2 - z3) << CONST_BITS; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 6; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 4x2 output block. * * 2-point IDCT in pass 1 (columns), 4-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_4x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp2, tmp10, tmp12; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; INT32 * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; INT32 workspace[4*2]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 4; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp10 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); /* Odd part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); /* Final output stage */ wsptr[4*0] = tmp10 + tmp0; wsptr[4*1] = tmp10 - tmp0; } /* Pass 2: process 2 rows from work array, store into output array. * 4-point IDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point IDCT]. */ wsptr = workspace; for (ctr = 0; ctr < 2; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = wsptr[0] + ((((INT32) RANGE_CENTER) << 3) + (ONE << 2)); tmp2 = wsptr[2]; tmp10 = (tmp0 + tmp2) << CONST_BITS; tmp12 = (tmp0 - tmp2) << CONST_BITS; /* Odd part */ /* Same rotation as in the even part of the 8x8 LL&M IDCT */ z2 = wsptr[1]; z3 = wsptr[3]; z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp0 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp2 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS+3) & RANGE_MASK]; wsptr += 4; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 2x1 output block. * * 1-point IDCT in pass 1 (columns), 2-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_2x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { DCTELEM tmp0, tmp1; ISLOW_MULT_TYPE * quantptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); ISHIFT_TEMPS /* Pass 1: empty. */ /* Pass 2: process 1 row from input, store into output array. */ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; outptr = output_buf[0] + output_col; /* Even part */ tmp0 = DEQUANTIZE(coef_block[0], quantptr[0]); /* Add range center and fudge factor for final descale and range-limit. */ tmp0 += (((DCTELEM) RANGE_CENTER) << 3) + (1 << 2); /* Odd part */ tmp1 = DEQUANTIZE(coef_block[1], quantptr[1]); /* Final output stage */ outptr[0] = range_limit[(int) IRIGHT_SHIFT(tmp0 + tmp1, 3) & RANGE_MASK]; outptr[1] = range_limit[(int) IRIGHT_SHIFT(tmp0 - tmp1, 3) & RANGE_MASK]; } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 8x16 output block. * * 16-point IDCT in pass 1 (columns), 8-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_8x16 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp10, tmp11, tmp12, tmp13; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26, tmp27; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[8*16]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 16-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 8; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp0 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-1); z1 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); tmp1 = MULTIPLY(z1, FIX(1.306562965)); /* c4[16] = c2[8] */ tmp2 = MULTIPLY(z1, FIX_0_541196100); /* c12[16] = c6[8] */ tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp12 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z3 = z1 - z2; z4 = MULTIPLY(z3, FIX(0.275899379)); /* c14[16] = c7[8] */ z3 = MULTIPLY(z3, FIX(1.387039845)); /* c2[16] = c1[8] */ tmp0 = z3 + MULTIPLY(z2, FIX_2_562915447); /* (c6+c2)[16] = (c3+c1)[8] */ tmp1 = z4 + MULTIPLY(z1, FIX_0_899976223); /* (c6-c14)[16] = (c3-c7)[8] */ tmp2 = z3 - MULTIPLY(z1, FIX(0.601344887)); /* (c2-c10)[16] = (c1-c5)[8] */ tmp3 = z4 - MULTIPLY(z2, FIX(0.509795579)); /* (c10-c14)[16] = (c5-c7)[8] */ tmp20 = tmp10 + tmp0; tmp27 = tmp10 - tmp0; tmp21 = tmp12 + tmp1; tmp26 = tmp12 - tmp1; tmp22 = tmp13 + tmp2; tmp25 = tmp13 - tmp2; tmp23 = tmp11 + tmp3; tmp24 = tmp11 - tmp3; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = z1 + z3; tmp1 = MULTIPLY(z1 + z2, FIX(1.353318001)); /* c3 */ tmp2 = MULTIPLY(tmp11, FIX(1.247225013)); /* c5 */ tmp3 = MULTIPLY(z1 + z4, FIX(1.093201867)); /* c7 */ tmp10 = MULTIPLY(z1 - z4, FIX(0.897167586)); /* c9 */ tmp11 = MULTIPLY(tmp11, FIX(0.666655658)); /* c11 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.410524528)); /* c13 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(z1, FIX(2.286341144)); /* c7+c5+c3-c1 */ tmp13 = tmp10 + tmp11 + tmp12 - MULTIPLY(z1, FIX(1.835730603)); /* c9+c11+c13-c15 */ z1 = MULTIPLY(z2 + z3, FIX(0.138617169)); /* c15 */ tmp1 += z1 + MULTIPLY(z2, FIX(0.071888074)); /* c9+c11-c3-c15 */ tmp2 += z1 - MULTIPLY(z3, FIX(1.125726048)); /* c5+c7+c15-c3 */ z1 = MULTIPLY(z3 - z2, FIX(1.407403738)); /* c1 */ tmp11 += z1 - MULTIPLY(z3, FIX(0.766367282)); /* c1+c11-c9-c13 */ tmp12 += z1 + MULTIPLY(z2, FIX(1.971951411)); /* c1+c5+c13-c7 */ z2 += z4; z1 = MULTIPLY(z2, - FIX(0.666655658)); /* -c11 */ tmp1 += z1; tmp3 += z1 + MULTIPLY(z4, FIX(1.065388962)); /* c3+c11+c15-c7 */ z2 = MULTIPLY(z2, - FIX(1.247225013)); /* -c5 */ tmp10 += z2 + MULTIPLY(z4, FIX(3.141271809)); /* c1+c5+c9-c13 */ tmp12 += z2; z2 = MULTIPLY(z3 + z4, - FIX(1.353318001)); /* -c3 */ tmp2 += z2; tmp3 += z2; z2 = MULTIPLY(z4 - z3, FIX(0.410524528)); /* c13 */ tmp10 += z2; tmp11 += z2; /* Final output stage */ wsptr[8*0] = (int) RIGHT_SHIFT(tmp20 + tmp0, CONST_BITS-PASS1_BITS); wsptr[8*15] = (int) RIGHT_SHIFT(tmp20 - tmp0, CONST_BITS-PASS1_BITS); wsptr[8*1] = (int) RIGHT_SHIFT(tmp21 + tmp1, CONST_BITS-PASS1_BITS); wsptr[8*14] = (int) RIGHT_SHIFT(tmp21 - tmp1, CONST_BITS-PASS1_BITS); wsptr[8*2] = (int) RIGHT_SHIFT(tmp22 + tmp2, CONST_BITS-PASS1_BITS); wsptr[8*13] = (int) RIGHT_SHIFT(tmp22 - tmp2, CONST_BITS-PASS1_BITS); wsptr[8*3] = (int) RIGHT_SHIFT(tmp23 + tmp3, CONST_BITS-PASS1_BITS); wsptr[8*12] = (int) RIGHT_SHIFT(tmp23 - tmp3, CONST_BITS-PASS1_BITS); wsptr[8*4] = (int) RIGHT_SHIFT(tmp24 + tmp10, CONST_BITS-PASS1_BITS); wsptr[8*11] = (int) RIGHT_SHIFT(tmp24 - tmp10, CONST_BITS-PASS1_BITS); wsptr[8*5] = (int) RIGHT_SHIFT(tmp25 + tmp11, CONST_BITS-PASS1_BITS); wsptr[8*10] = (int) RIGHT_SHIFT(tmp25 - tmp11, CONST_BITS-PASS1_BITS); wsptr[8*6] = (int) RIGHT_SHIFT(tmp26 + tmp12, CONST_BITS-PASS1_BITS); wsptr[8*9] = (int) RIGHT_SHIFT(tmp26 - tmp12, CONST_BITS-PASS1_BITS); wsptr[8*7] = (int) RIGHT_SHIFT(tmp27 + tmp13, CONST_BITS-PASS1_BITS); wsptr[8*8] = (int) RIGHT_SHIFT(tmp27 - tmp13, CONST_BITS-PASS1_BITS); } /* Pass 2: process rows from work array, store into output array. * Note that we must descale the results by a factor of 8 == 2**3, * and also undo the PASS1_BITS scaling. * 8-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ wsptr = workspace; for (ctr = 0; ctr < 16; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part: reverse the even part of the forward DCT. * The rotator is c(-6). */ /* Add range center and fudge factor for final descale and range-limit. */ z2 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); z3 = (INT32) wsptr[4]; tmp0 = (z2 + z3) << CONST_BITS; tmp1 = (z2 - z3) << CONST_BITS; z2 = (INT32) wsptr[2]; z3 = (INT32) wsptr[6]; z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp2 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp3 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ tmp10 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; tmp11 = tmp1 + tmp3; tmp12 = tmp1 - tmp3; /* Odd part per figure 8; the matrix is unitary and hence its * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. */ tmp0 = (INT32) wsptr[7]; tmp1 = (INT32) wsptr[5]; tmp2 = (INT32) wsptr[3]; tmp3 = (INT32) wsptr[1]; z2 = tmp0 + tmp2; z3 = tmp1 + tmp3; z1 = MULTIPLY(z2 + z3, FIX_1_175875602); /* c3 */ z2 = MULTIPLY(z2, - FIX_1_961570560); /* -c3-c5 */ z3 = MULTIPLY(z3, - FIX_0_390180644); /* -c3+c5 */ z2 += z1; z3 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp0 += z1 + z2; tmp3 += z1 + z3; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp1 += z1 + z3; tmp2 += z1 + z2; /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[7] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp3, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp1, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp13 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp13 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += DCTSIZE; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 7x14 output block. * * 14-point IDCT in pass 1 (columns), 7-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_7x14 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25, tmp26; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[7*14]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 14-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/28). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 7; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z1 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS-PASS1_BITS-1); z4 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z2 = MULTIPLY(z4, FIX(1.274162392)); /* c4 */ z3 = MULTIPLY(z4, FIX(0.314692123)); /* c12 */ z4 = MULTIPLY(z4, FIX(0.881747734)); /* c8 */ tmp10 = z1 + z2; tmp11 = z1 + z3; tmp12 = z1 - z4; tmp23 = RIGHT_SHIFT(z1 - ((z2 + z3 - z4) << 1), /* c0 = (c4+c12-c8)*2 */ CONST_BITS-PASS1_BITS); z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z2 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z3 = MULTIPLY(z1 + z2, FIX(1.105676686)); /* c6 */ tmp13 = z3 + MULTIPLY(z1, FIX(0.273079590)); /* c2-c6 */ tmp14 = z3 - MULTIPLY(z2, FIX(1.719280954)); /* c6+c10 */ tmp15 = MULTIPLY(z1, FIX(0.613604268)) - /* c10 */ MULTIPLY(z2, FIX(1.378756276)); /* c2 */ tmp20 = tmp10 + tmp13; tmp26 = tmp10 - tmp13; tmp21 = tmp11 + tmp14; tmp25 = tmp11 - tmp14; tmp22 = tmp12 + tmp15; tmp24 = tmp12 - tmp15; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp13 = z4 << CONST_BITS; tmp14 = z1 + z3; tmp11 = MULTIPLY(z1 + z2, FIX(1.334852607)); /* c3 */ tmp12 = MULTIPLY(tmp14, FIX(1.197448846)); /* c5 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(z1, FIX(1.126980169)); /* c3+c5-c1 */ tmp14 = MULTIPLY(tmp14, FIX(0.752406978)); /* c9 */ tmp16 = tmp14 - MULTIPLY(z1, FIX(1.061150426)); /* c9+c11-c13 */ z1 -= z2; tmp15 = MULTIPLY(z1, FIX(0.467085129)) - tmp13; /* c11 */ tmp16 += tmp15; z1 += z4; z4 = MULTIPLY(z2 + z3, - FIX(0.158341681)) - tmp13; /* -c13 */ tmp11 += z4 - MULTIPLY(z2, FIX(0.424103948)); /* c3-c9-c13 */ tmp12 += z4 - MULTIPLY(z3, FIX(2.373959773)); /* c3+c5-c13 */ z4 = MULTIPLY(z3 - z2, FIX(1.405321284)); /* c1 */ tmp14 += z4 + tmp13 - MULTIPLY(z3, FIX(1.6906431334)); /* c1+c9-c11 */ tmp15 += z4 + MULTIPLY(z2, FIX(0.674957567)); /* c1+c11-c5 */ tmp13 = (z1 - z3) << PASS1_BITS; /* Final output stage */ wsptr[7*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[7*13] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[7*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[7*12] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[7*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[7*11] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[7*3] = (int) (tmp23 + tmp13); wsptr[7*10] = (int) (tmp23 - tmp13); wsptr[7*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[7*9] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); wsptr[7*5] = (int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS-PASS1_BITS); wsptr[7*8] = (int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS-PASS1_BITS); wsptr[7*6] = (int) RIGHT_SHIFT(tmp26 + tmp16, CONST_BITS-PASS1_BITS); wsptr[7*7] = (int) RIGHT_SHIFT(tmp26 - tmp16, CONST_BITS-PASS1_BITS); } /* Pass 2: process 14 rows from work array, store into output array. * 7-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/14). */ wsptr = workspace; for (ctr = 0; ctr < 14; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp23 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp23 <<= CONST_BITS; z1 = (INT32) wsptr[2]; z2 = (INT32) wsptr[4]; z3 = (INT32) wsptr[6]; tmp20 = MULTIPLY(z2 - z3, FIX(0.881747734)); /* c4 */ tmp22 = MULTIPLY(z1 - z2, FIX(0.314692123)); /* c6 */ tmp21 = tmp20 + tmp22 + tmp23 - MULTIPLY(z2, FIX(1.841218003)); /* c2+c4-c6 */ tmp10 = z1 + z3; z2 -= tmp10; tmp10 = MULTIPLY(tmp10, FIX(1.274162392)) + tmp23; /* c2 */ tmp20 += tmp10 - MULTIPLY(z3, FIX(0.077722536)); /* c2-c4-c6 */ tmp22 += tmp10 - MULTIPLY(z1, FIX(2.470602249)); /* c2+c4+c6 */ tmp23 += MULTIPLY(z2, FIX(1.414213562)); /* c0 */ /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; tmp11 = MULTIPLY(z1 + z2, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp12 = MULTIPLY(z1 - z2, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp10 = tmp11 - tmp12; tmp11 += tmp12; tmp12 = MULTIPLY(z2 + z3, - FIX(1.378756276)); /* -c1 */ tmp11 += tmp12; z2 = MULTIPLY(z1 + z3, FIX(0.613604268)); /* c5 */ tmp10 += z2; tmp12 += z2 + MULTIPLY(z3, FIX(1.870828693)); /* c3+c1-c5 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[6] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp23, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 7; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 6x12 output block. * * 12-point IDCT in pass 1 (columns), 6-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_6x12 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; INT32 tmp20, tmp21, tmp22, tmp23, tmp24, tmp25; INT32 z1, z2, z3, z4; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[6*12]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 12-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/24). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 6; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z3 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z3 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z3 += ONE << (CONST_BITS-PASS1_BITS-1); z4 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z4 = MULTIPLY(z4, FIX(1.224744871)); /* c4 */ tmp10 = z3 + z4; tmp11 = z3 - z4; z1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z4 = MULTIPLY(z1, FIX(1.366025404)); /* c2 */ z1 <<= CONST_BITS; z2 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z2 <<= CONST_BITS; tmp12 = z1 - z2; tmp21 = z3 + tmp12; tmp24 = z3 - tmp12; tmp12 = z4 + z2; tmp20 = tmp10 + tmp12; tmp25 = tmp10 - tmp12; tmp12 = z4 - z1 - z2; tmp22 = tmp11 + tmp12; tmp23 = tmp11 - tmp12; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = MULTIPLY(z2, FIX(1.306562965)); /* c3 */ tmp14 = MULTIPLY(z2, - FIX_0_541196100); /* -c9 */ tmp10 = z1 + z3; tmp15 = MULTIPLY(tmp10 + z4, FIX(0.860918669)); /* c7 */ tmp12 = tmp15 + MULTIPLY(tmp10, FIX(0.261052384)); /* c5-c7 */ tmp10 = tmp12 + tmp11 + MULTIPLY(z1, FIX(0.280143716)); /* c1-c5 */ tmp13 = MULTIPLY(z3 + z4, - FIX(1.045510580)); /* -(c7+c11) */ tmp12 += tmp13 + tmp14 - MULTIPLY(z3, FIX(1.478575242)); /* c1+c5-c7-c11 */ tmp13 += tmp15 - tmp11 + MULTIPLY(z4, FIX(1.586706681)); /* c1+c11 */ tmp15 += tmp14 - MULTIPLY(z1, FIX(0.676326758)) - /* c7-c11 */ MULTIPLY(z4, FIX(1.982889723)); /* c5+c7 */ z1 -= z4; z2 -= z3; z3 = MULTIPLY(z1 + z2, FIX_0_541196100); /* c9 */ tmp11 = z3 + MULTIPLY(z1, FIX_0_765366865); /* c3-c9 */ tmp14 = z3 - MULTIPLY(z2, FIX_1_847759065); /* c3+c9 */ /* Final output stage */ wsptr[6*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[6*11] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[6*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[6*10] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[6*2] = (int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS-PASS1_BITS); wsptr[6*9] = (int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS-PASS1_BITS); wsptr[6*3] = (int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS-PASS1_BITS); wsptr[6*8] = (int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS-PASS1_BITS); wsptr[6*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[6*7] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); wsptr[6*5] = (int) RIGHT_SHIFT(tmp25 + tmp15, CONST_BITS-PASS1_BITS); wsptr[6*6] = (int) RIGHT_SHIFT(tmp25 - tmp15, CONST_BITS-PASS1_BITS); } /* Pass 2: process 12 rows from work array, store into output array. * 6-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ wsptr = workspace; for (ctr = 0; ctr < 12; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp10 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp10 <<= CONST_BITS; tmp12 = (INT32) wsptr[4]; tmp20 = MULTIPLY(tmp12, FIX(0.707106781)); /* c4 */ tmp11 = tmp10 + tmp20; tmp21 = tmp10 - tmp20 - tmp20; tmp20 = (INT32) wsptr[2]; tmp10 = MULTIPLY(tmp20, FIX(1.224744871)); /* c2 */ tmp20 = tmp11 + tmp10; tmp22 = tmp11 - tmp10; /* Odd part */ z1 = (INT32) wsptr[1]; z2 = (INT32) wsptr[3]; z3 = (INT32) wsptr[5]; tmp11 = MULTIPLY(z1 + z3, FIX(0.366025404)); /* c5 */ tmp10 = tmp11 + ((z1 + z2) << CONST_BITS); tmp12 = tmp11 + ((z3 - z2) << CONST_BITS); tmp11 = (z1 - z2 - z3) << CONST_BITS; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[5] = range_limit[(int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp22 + tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp22 - tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 6; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 5x10 output block. * * 10-point IDCT in pass 1 (columns), 5-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_5x10 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp10, tmp11, tmp12, tmp13, tmp14; INT32 tmp20, tmp21, tmp22, tmp23, tmp24; INT32 z1, z2, z3, z4, z5; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[5*10]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 10-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/20). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 5; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ z3 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z3 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z3 += ONE << (CONST_BITS-PASS1_BITS-1); z4 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z1 = MULTIPLY(z4, FIX(1.144122806)); /* c4 */ z2 = MULTIPLY(z4, FIX(0.437016024)); /* c8 */ tmp10 = z3 + z1; tmp11 = z3 - z2; tmp22 = RIGHT_SHIFT(z3 - ((z1 - z2) << 1), /* c0 = (c4-c8)*2 */ CONST_BITS-PASS1_BITS); z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c6 */ tmp12 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c2-c6 */ tmp13 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c2+c6 */ tmp20 = tmp10 + tmp12; tmp24 = tmp10 - tmp12; tmp21 = tmp11 + tmp13; tmp23 = tmp11 - tmp13; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); z4 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp11 = z2 + z4; tmp13 = z2 - z4; tmp12 = MULTIPLY(tmp13, FIX(0.309016994)); /* (c3-c7)/2 */ z5 = z3 << CONST_BITS; z2 = MULTIPLY(tmp11, FIX(0.951056516)); /* (c3+c7)/2 */ z4 = z5 + tmp12; tmp10 = MULTIPLY(z1, FIX(1.396802247)) + z2 + z4; /* c1 */ tmp14 = MULTIPLY(z1, FIX(0.221231742)) - z2 + z4; /* c9 */ z2 = MULTIPLY(tmp11, FIX(0.587785252)); /* (c1-c9)/2 */ z4 = z5 - tmp12 - (tmp13 << (CONST_BITS - 1)); tmp12 = (z1 - tmp13 - z3) << PASS1_BITS; tmp11 = MULTIPLY(z1, FIX(1.260073511)) - z2 - z4; /* c3 */ tmp13 = MULTIPLY(z1, FIX(0.642039522)) - z2 + z4; /* c7 */ /* Final output stage */ wsptr[5*0] = (int) RIGHT_SHIFT(tmp20 + tmp10, CONST_BITS-PASS1_BITS); wsptr[5*9] = (int) RIGHT_SHIFT(tmp20 - tmp10, CONST_BITS-PASS1_BITS); wsptr[5*1] = (int) RIGHT_SHIFT(tmp21 + tmp11, CONST_BITS-PASS1_BITS); wsptr[5*8] = (int) RIGHT_SHIFT(tmp21 - tmp11, CONST_BITS-PASS1_BITS); wsptr[5*2] = (int) (tmp22 + tmp12); wsptr[5*7] = (int) (tmp22 - tmp12); wsptr[5*3] = (int) RIGHT_SHIFT(tmp23 + tmp13, CONST_BITS-PASS1_BITS); wsptr[5*6] = (int) RIGHT_SHIFT(tmp23 - tmp13, CONST_BITS-PASS1_BITS); wsptr[5*4] = (int) RIGHT_SHIFT(tmp24 + tmp14, CONST_BITS-PASS1_BITS); wsptr[5*5] = (int) RIGHT_SHIFT(tmp24 - tmp14, CONST_BITS-PASS1_BITS); } /* Pass 2: process 10 rows from work array, store into output array. * 5-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/10). */ wsptr = workspace; for (ctr = 0; ctr < 10; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp12 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp12 <<= CONST_BITS; tmp13 = (INT32) wsptr[2]; tmp14 = (INT32) wsptr[4]; z1 = MULTIPLY(tmp13 + tmp14, FIX(0.790569415)); /* (c2+c4)/2 */ z2 = MULTIPLY(tmp13 - tmp14, FIX(0.353553391)); /* (c2-c4)/2 */ z3 = tmp12 + z2; tmp10 = z3 + z1; tmp11 = z3 - z1; tmp12 -= z2 << 2; /* Odd part */ z2 = (INT32) wsptr[1]; z3 = (INT32) wsptr[3]; z1 = MULTIPLY(z2 + z3, FIX(0.831253876)); /* c3 */ tmp13 = z1 + MULTIPLY(z2, FIX(0.513743148)); /* c1-c3 */ tmp14 = z1 - MULTIPLY(z3, FIX(2.176250899)); /* c1+c3 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[4] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp13, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp11 + tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp11 - tmp14, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 5; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 4x8 output block. * * 8-point IDCT in pass 1 (columns), 4-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_4x8 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[4*8]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * Note results are scaled up by sqrt(8) compared to a true IDCT; * furthermore, we scale the results by 2**PASS1_BITS. * 8-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 4; ctr > 0; ctr--) { /* Due to quantization, we will usually find that many of the input * coefficients are zero, especially the AC terms. We can exploit this * by short-circuiting the IDCT calculation for any column in which all * the AC terms are zero. In that case each output is equal to the * DC coefficient (with scale factor as needed). * With typical images and quantization tables, half or more of the * column DCT calculations can be simplified this way. */ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 && inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 && inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) { /* AC terms all zero */ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS; wsptr[4*0] = dcval; wsptr[4*1] = dcval; wsptr[4*2] = dcval; wsptr[4*3] = dcval; wsptr[4*4] = dcval; wsptr[4*5] = dcval; wsptr[4*6] = dcval; wsptr[4*7] = dcval; inptr++; /* advance pointers to next column */ quantptr++; wsptr++; continue; } /* Even part: reverse the even part of the forward DCT. * The rotator is c(-6). */ z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]); z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp2 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp3 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); z2 <<= CONST_BITS; z3 <<= CONST_BITS; /* Add fudge factor here for final descale. */ z2 += ONE << (CONST_BITS-PASS1_BITS-1); tmp0 = z2 + z3; tmp1 = z2 - z3; tmp10 = tmp0 + tmp2; tmp13 = tmp0 - tmp2; tmp11 = tmp1 + tmp3; tmp12 = tmp1 - tmp3; /* Odd part per figure 8; the matrix is unitary and hence its * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]); tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = tmp0 + tmp2; z3 = tmp1 + tmp3; z1 = MULTIPLY(z2 + z3, FIX_1_175875602); /* c3 */ z2 = MULTIPLY(z2, - FIX_1_961570560); /* -c3-c5 */ z3 = MULTIPLY(z3, - FIX_0_390180644); /* -c3+c5 */ z2 += z1; z3 += z1; z1 = MULTIPLY(tmp0 + tmp3, - FIX_0_899976223); /* -c3+c7 */ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp0 += z1 + z2; tmp3 += z1 + z3; z1 = MULTIPLY(tmp1 + tmp2, - FIX_2_562915447); /* -c1-c3 */ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp1 += z1 + z3; tmp2 += z1 + z2; /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ wsptr[4*0] = (int) RIGHT_SHIFT(tmp10 + tmp3, CONST_BITS-PASS1_BITS); wsptr[4*7] = (int) RIGHT_SHIFT(tmp10 - tmp3, CONST_BITS-PASS1_BITS); wsptr[4*1] = (int) RIGHT_SHIFT(tmp11 + tmp2, CONST_BITS-PASS1_BITS); wsptr[4*6] = (int) RIGHT_SHIFT(tmp11 - tmp2, CONST_BITS-PASS1_BITS); wsptr[4*2] = (int) RIGHT_SHIFT(tmp12 + tmp1, CONST_BITS-PASS1_BITS); wsptr[4*5] = (int) RIGHT_SHIFT(tmp12 - tmp1, CONST_BITS-PASS1_BITS); wsptr[4*3] = (int) RIGHT_SHIFT(tmp13 + tmp0, CONST_BITS-PASS1_BITS); wsptr[4*4] = (int) RIGHT_SHIFT(tmp13 - tmp0, CONST_BITS-PASS1_BITS); inptr++; /* advance pointers to next column */ quantptr++; wsptr++; } /* Pass 2: process 8 rows from work array, store into output array. * 4-point IDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point IDCT]. */ wsptr = workspace; for (ctr = 0; ctr < 8; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp2 = (INT32) wsptr[2]; tmp10 = (tmp0 + tmp2) << CONST_BITS; tmp12 = (tmp0 - tmp2) << CONST_BITS; /* Odd part */ /* Same rotation as in the even part of the 8x8 LL&M IDCT */ z2 = (INT32) wsptr[1]; z3 = (INT32) wsptr[3]; z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp0 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp2 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[3] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 4; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a reduced-size 3x6 output block. * * 6-point IDCT in pass 1 (columns), 3-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_3x6 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp1, tmp2, tmp10, tmp11, tmp12; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; int * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; int workspace[3*6]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 6-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 3; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp0 <<= CONST_BITS; /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS-PASS1_BITS-1); tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]); tmp10 = MULTIPLY(tmp2, FIX(0.707106781)); /* c4 */ tmp1 = tmp0 + tmp10; tmp11 = RIGHT_SHIFT(tmp0 - tmp10 - tmp10, CONST_BITS-PASS1_BITS); tmp10 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp0 = MULTIPLY(tmp10, FIX(1.224744871)); /* c2 */ tmp10 = tmp1 + tmp0; tmp12 = tmp1 - tmp0; /* Odd part */ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z3 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]); tmp1 = MULTIPLY(z1 + z3, FIX(0.366025404)); /* c5 */ tmp0 = tmp1 + ((z1 + z2) << CONST_BITS); tmp2 = tmp1 + ((z3 - z2) << CONST_BITS); tmp1 = (z1 - z2 - z3) << PASS1_BITS; /* Final output stage */ wsptr[3*0] = (int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS-PASS1_BITS); wsptr[3*5] = (int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS-PASS1_BITS); wsptr[3*1] = (int) (tmp11 + tmp1); wsptr[3*4] = (int) (tmp11 - tmp1); wsptr[3*2] = (int) RIGHT_SHIFT(tmp12 + tmp2, CONST_BITS-PASS1_BITS); wsptr[3*3] = (int) RIGHT_SHIFT(tmp12 - tmp2, CONST_BITS-PASS1_BITS); } /* Pass 2: process 6 rows from work array, store into output array. * 3-point IDCT kernel, cK represents sqrt(2) * cos(K*pi/6). */ wsptr = workspace; for (ctr = 0; ctr < 6; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp0 = (INT32) wsptr[0] + ((((INT32) RANGE_CENTER) << (PASS1_BITS+3)) + (ONE << (PASS1_BITS+2))); tmp0 <<= CONST_BITS; tmp2 = (INT32) wsptr[2]; tmp12 = MULTIPLY(tmp2, FIX(0.707106781)); /* c2 */ tmp10 = tmp0 + tmp12; tmp2 = tmp0 - tmp12 - tmp12; /* Odd part */ tmp12 = (INT32) wsptr[1]; tmp0 = MULTIPLY(tmp12, FIX(1.224744871)); /* c1 */ /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[2] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp2, CONST_BITS+PASS1_BITS+3) & RANGE_MASK]; wsptr += 3; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 2x4 output block. * * 4-point IDCT in pass 1 (columns), 2-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_2x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { INT32 tmp0, tmp2, tmp10, tmp12; INT32 z1, z2, z3; JCOEFPTR inptr; ISLOW_MULT_TYPE * quantptr; INT32 * wsptr; JSAMPROW outptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); int ctr; INT32 workspace[2*4]; /* buffers data between passes */ SHIFT_TEMPS /* Pass 1: process columns from input, store into work array. * 4-point IDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point IDCT]. */ inptr = coef_block; quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; wsptr = workspace; for (ctr = 0; ctr < 2; ctr++, inptr++, quantptr++, wsptr++) { /* Even part */ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]); tmp2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]); tmp10 = (tmp0 + tmp2) << CONST_BITS; tmp12 = (tmp0 - tmp2) << CONST_BITS; /* Odd part */ /* Same rotation as in the even part of the 8x8 LL&M IDCT */ z2 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]); z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]); z1 = MULTIPLY(z2 + z3, FIX_0_541196100); /* c6 */ tmp0 = z1 + MULTIPLY(z2, FIX_0_765366865); /* c2-c6 */ tmp2 = z1 - MULTIPLY(z3, FIX_1_847759065); /* c2+c6 */ /* Final output stage */ wsptr[2*0] = tmp10 + tmp0; wsptr[2*3] = tmp10 - tmp0; wsptr[2*1] = tmp12 + tmp2; wsptr[2*2] = tmp12 - tmp2; } /* Pass 2: process 4 rows from work array, store into output array. */ wsptr = workspace; for (ctr = 0; ctr < 4; ctr++) { outptr = output_buf[ctr] + output_col; /* Even part */ /* Add range center and fudge factor for final descale and range-limit. */ tmp10 = wsptr[0] + ((((INT32) RANGE_CENTER) << (CONST_BITS+3)) + (ONE << (CONST_BITS+2))); /* Odd part */ tmp0 = wsptr[1]; /* Final output stage */ outptr[0] = range_limit[(int) RIGHT_SHIFT(tmp10 + tmp0, CONST_BITS+3) & RANGE_MASK]; outptr[1] = range_limit[(int) RIGHT_SHIFT(tmp10 - tmp0, CONST_BITS+3) & RANGE_MASK]; wsptr += 2; /* advance pointer to next row */ } } /* * Perform dequantization and inverse DCT on one block of coefficients, * producing a 1x2 output block. * * 2-point IDCT in pass 1 (columns), 1-point in pass 2 (rows). */ GLOBAL(void) jpeg_idct_1x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col) { DCTELEM tmp0, tmp1; ISLOW_MULT_TYPE * quantptr; JSAMPLE *range_limit = IDCT_range_limit(cinfo); ISHIFT_TEMPS /* Process 1 column from input, store into output array. */ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table; /* Even part */ tmp0 = DEQUANTIZE(coef_block[DCTSIZE*0], quantptr[DCTSIZE*0]); /* Add range center and fudge factor for final descale and range-limit. */ tmp0 += (((DCTELEM) RANGE_CENTER) << 3) + (1 << 2); /* Odd part */ tmp1 = DEQUANTIZE(coef_block[DCTSIZE*1], quantptr[DCTSIZE*1]); /* Final output stage */ output_buf[0][output_col] = range_limit[(int) IRIGHT_SHIFT(tmp0 + tmp1, 3) & RANGE_MASK]; output_buf[1][output_col] = range_limit[(int) IRIGHT_SHIFT(tmp0 - tmp1, 3) & RANGE_MASK]; } #endif /* IDCT_SCALING_SUPPORTED */ #endif /* DCT_ISLOW_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jinclude.h ================================================ /* * jinclude.h * * Copyright (C) 1991-1994, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file exists to provide a single place to fix any problems with * including the wrong system include files. (Common problems are taken * care of by the standard jconfig symbols, but on really weird systems * you may have to edit this file.) * * NOTE: this file is NOT intended to be included by applications using the * JPEG library. Most applications need only include jpeglib.h. */ /* Include auto-config file to find out which system include files we need. */ #include "jconfig.h" /* auto configuration options */ #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */ /* * We need the NULL macro and size_t typedef. * On an ANSI-conforming system it is sufficient to include . * Otherwise, we get them from or ; we may have to * pull in as well. * Note that the core JPEG library does not require ; * only the default error handler and data source/destination modules do. * But we must pull it in because of the references to FILE in jpeglib.h. * You can remove those references if you want to compile without . */ #ifdef HAVE_STDDEF_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #ifdef NEED_SYS_TYPES_H #include #endif #include /* * We need memory copying and zeroing functions, plus strncpy(). * ANSI and System V implementations declare these in . * BSD doesn't have the mem() functions, but it does have bcopy()/bzero(). * Some systems may declare memset and memcpy in . * * NOTE: we assume the size parameters to these functions are of type size_t. * Change the casts in these macros if not! */ #ifdef NEED_BSD_STRINGS #include #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size)) #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size)) #else /* not BSD, assume ANSI/SysV string lib */ #include #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size)) #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size)) #endif /* * In ANSI C, and indeed any rational implementation, size_t is also the * type returned by sizeof(). However, it seems there are some irrational * implementations out there, in which sizeof() returns an int even though * size_t is defined as long or unsigned long. To ensure consistent results * we always use this SIZEOF() macro in place of using sizeof() directly. */ #define SIZEOF(object) ((size_t) sizeof(object)) /* * The modules that use fread() and fwrite() always invoke them through * these macros. On some systems you may need to twiddle the argument casts. * CAUTION: argument order is different from underlying functions! */ #define JFREAD(file,buf,sizeofbuf) \ ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file))) #define JFWRITE(file,buf,sizeofbuf) \ ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file))) ================================================ FILE: tess-two/jni/libjpeg/jmemansi.c ================================================ /* * jmemansi.c * * Copyright (C) 1992-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file provides a simple generic implementation of the system- * dependent portion of the JPEG memory manager. This implementation * assumes that you have the ANSI-standard library routine tmpfile(). * Also, the problem of determining the amount of memory available * is shoved onto the user. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jmemsys.h" /* import the system-dependent declarations */ #ifndef HAVE_STDLIB_H /* should declare malloc(),free() */ extern void * malloc JPP((size_t size)); extern void free JPP((void *ptr)); #endif #ifndef SEEK_SET /* pre-ANSI systems may not define this; */ #define SEEK_SET 0 /* if not, assume 0 is correct */ #endif /* * Memory allocation and freeing are controlled by the regular library * routines malloc() and free(). */ GLOBAL(void *) jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject) { return (void *) malloc(sizeofobject); } GLOBAL(void) jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject) { free(object); } /* * "Large" objects are treated the same as "small" ones. * NB: although we include FAR keywords in the routine declarations, * this file won't actually work in 80x86 small/medium model; at least, * you probably won't be able to process useful-size images in only 64KB. */ GLOBAL(void FAR *) jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject) { return (void FAR *) malloc(sizeofobject); } GLOBAL(void) jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject) { free(object); } /* * This routine computes the total memory space available for allocation. * It's impossible to do this in a portable way; our current solution is * to make the user tell us (with a default value set at compile time). * If you can actually get the available space, it's a good idea to subtract * a slop factor of 5% or so. */ #ifndef DEFAULT_MAX_MEM /* so can override from makefile */ #define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */ #endif GLOBAL(long) jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, long max_bytes_needed, long already_allocated) { return cinfo->mem->max_memory_to_use - already_allocated; } /* * Backing store (temporary file) management. * Backing store objects are only used when the value returned by * jpeg_mem_available is less than the total space needed. You can dispense * with these routines if you have plenty of virtual memory; see jmemnobs.c. */ METHODDEF(void) read_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { if (fseek(info->temp_file, file_offset, SEEK_SET)) ERREXIT(cinfo, JERR_TFILE_SEEK); if (JFREAD(info->temp_file, buffer_address, byte_count) != (size_t) byte_count) ERREXIT(cinfo, JERR_TFILE_READ); } METHODDEF(void) write_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { if (fseek(info->temp_file, file_offset, SEEK_SET)) ERREXIT(cinfo, JERR_TFILE_SEEK); if (JFWRITE(info->temp_file, buffer_address, byte_count) != (size_t) byte_count) ERREXIT(cinfo, JERR_TFILE_WRITE); } METHODDEF(void) close_backing_store (j_common_ptr cinfo, backing_store_ptr info) { fclose(info->temp_file); /* Since this implementation uses tmpfile() to create the file, * no explicit file deletion is needed. */ } /* * Initial opening of a backing-store object. * * This version uses tmpfile(), which constructs a suitable file name * behind the scenes. We don't have to use info->temp_name[] at all; * indeed, we can't even find out the actual name of the temp file. */ GLOBAL(void) jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { if ((info->temp_file = tmpfile()) == NULL) ERREXITS(cinfo, JERR_TFILE_CREATE, ""); info->read_backing_store = read_backing_store; info->write_backing_store = write_backing_store; info->close_backing_store = close_backing_store; } /* * These routines take care of any system-dependent initialization and * cleanup required. */ GLOBAL(long) jpeg_mem_init (j_common_ptr cinfo) { return DEFAULT_MAX_MEM; /* default for max_memory_to_use */ } GLOBAL(void) jpeg_mem_term (j_common_ptr cinfo) { /* no work */ } ================================================ FILE: tess-two/jni/libjpeg/jmemdos.c ================================================ /* * jmemdos.c * * Copyright (C) 1992-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file provides an MS-DOS-compatible implementation of the system- * dependent portion of the JPEG memory manager. Temporary data can be * stored in extended or expanded memory as well as in regular DOS files. * * If you use this file, you must be sure that NEED_FAR_POINTERS is defined * if you compile in a small-data memory model; it should NOT be defined if * you use a large-data memory model. This file is not recommended if you * are using a flat-memory-space 386 environment such as DJGCC or Watcom C. * Also, this code will NOT work if struct fields are aligned on greater than * 2-byte boundaries. * * Based on code contributed by Ge' Weijers. */ /* * If you have both extended and expanded memory, you may want to change the * order in which they are tried in jopen_backing_store. On a 286 machine * expanded memory is usually faster, since extended memory access involves * an expensive protected-mode-and-back switch. On 386 and better, extended * memory is usually faster. As distributed, the code tries extended memory * first (what? not everyone has a 386? :-). * * You can disable use of extended/expanded memory entirely by altering these * definitions or overriding them from the Makefile (eg, -DEMS_SUPPORTED=0). */ #ifndef XMS_SUPPORTED #define XMS_SUPPORTED 1 #endif #ifndef EMS_SUPPORTED #define EMS_SUPPORTED 1 #endif #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jmemsys.h" /* import the system-dependent declarations */ #ifndef HAVE_STDLIB_H /* should declare these */ extern void * malloc JPP((size_t size)); extern void free JPP((void *ptr)); extern char * getenv JPP((const char * name)); #endif #ifdef NEED_FAR_POINTERS #ifdef __TURBOC__ /* These definitions work for Borland C (Turbo C) */ #include /* need farmalloc(), farfree() */ #define far_malloc(x) farmalloc(x) #define far_free(x) farfree(x) #else /* These definitions work for Microsoft C and compatible compilers */ #include /* need _fmalloc(), _ffree() */ #define far_malloc(x) _fmalloc(x) #define far_free(x) _ffree(x) #endif #else /* not NEED_FAR_POINTERS */ #define far_malloc(x) malloc(x) #define far_free(x) free(x) #endif /* NEED_FAR_POINTERS */ #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */ #define READ_BINARY "r" #else #define READ_BINARY "rb" #endif #ifndef USE_MSDOS_MEMMGR /* make sure user got configuration right */ You forgot to define USE_MSDOS_MEMMGR in jconfig.h. /* deliberate syntax error */ #endif #if MAX_ALLOC_CHUNK >= 65535L /* make sure jconfig.h got this right */ MAX_ALLOC_CHUNK should be less than 64K. /* deliberate syntax error */ #endif /* * Declarations for assembly-language support routines (see jmemdosa.asm). * * The functions are declared "far" as are all their pointer arguments; * this ensures the assembly source code will work regardless of the * compiler memory model. We assume "short" is 16 bits, "long" is 32. */ typedef void far * XMSDRIVER; /* actually a pointer to code */ typedef struct { /* registers for calling XMS driver */ unsigned short ax, dx, bx; void far * ds_si; } XMScontext; typedef struct { /* registers for calling EMS driver */ unsigned short ax, dx, bx; void far * ds_si; } EMScontext; extern short far jdos_open JPP((short far * handle, char far * filename)); extern short far jdos_close JPP((short handle)); extern short far jdos_seek JPP((short handle, long offset)); extern short far jdos_read JPP((short handle, void far * buffer, unsigned short count)); extern short far jdos_write JPP((short handle, void far * buffer, unsigned short count)); extern void far jxms_getdriver JPP((XMSDRIVER far *)); extern void far jxms_calldriver JPP((XMSDRIVER, XMScontext far *)); extern short far jems_available JPP((void)); extern void far jems_calldriver JPP((EMScontext far *)); /* * Selection of a file name for a temporary file. * This is highly system-dependent, and you may want to customize it. */ static int next_file_num; /* to distinguish among several temp files */ LOCAL(void) select_file_name (char * fname) { const char * env; char * ptr; FILE * tfile; /* Keep generating file names till we find one that's not in use */ for (;;) { /* Get temp directory name from environment TMP or TEMP variable; * if none, use "." */ if ((env = (const char *) getenv("TMP")) == NULL) if ((env = (const char *) getenv("TEMP")) == NULL) env = "."; if (*env == '\0') /* null string means "." */ env = "."; ptr = fname; /* copy name to fname */ while (*env != '\0') *ptr++ = *env++; if (ptr[-1] != '\\' && ptr[-1] != '/') *ptr++ = '\\'; /* append backslash if not in env variable */ /* Append a suitable file name */ next_file_num++; /* advance counter */ sprintf(ptr, "JPG%03d.TMP", next_file_num); /* Probe to see if file name is already in use */ if ((tfile = fopen(fname, READ_BINARY)) == NULL) break; fclose(tfile); /* oops, it's there; close tfile & try again */ } } /* * Near-memory allocation and freeing are controlled by the regular library * routines malloc() and free(). */ GLOBAL(void *) jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject) { return (void *) malloc(sizeofobject); } GLOBAL(void) jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject) { free(object); } /* * "Large" objects are allocated in far memory, if possible */ GLOBAL(void FAR *) jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject) { return (void FAR *) far_malloc(sizeofobject); } GLOBAL(void) jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject) { far_free(object); } /* * This routine computes the total memory space available for allocation. * It's impossible to do this in a portable way; our current solution is * to make the user tell us (with a default value set at compile time). * If you can actually get the available space, it's a good idea to subtract * a slop factor of 5% or so. */ #ifndef DEFAULT_MAX_MEM /* so can override from makefile */ #define DEFAULT_MAX_MEM 300000L /* for total usage about 450K */ #endif GLOBAL(long) jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, long max_bytes_needed, long already_allocated) { return cinfo->mem->max_memory_to_use - already_allocated; } /* * Backing store (temporary file) management. * Backing store objects are only used when the value returned by * jpeg_mem_available is less than the total space needed. You can dispense * with these routines if you have plenty of virtual memory; see jmemnobs.c. */ /* * For MS-DOS we support three types of backing storage: * 1. Conventional DOS files. We access these by direct DOS calls rather * than via the stdio package. This provides a bit better performance, * but the real reason is that the buffers to be read or written are FAR. * The stdio library for small-data memory models can't cope with that. * 2. Extended memory, accessed per the XMS V2.0 specification. * 3. Expanded memory, accessed per the LIM/EMS 4.0 specification. * You'll need copies of those specs to make sense of the related code. * The specs are available by Internet FTP from the SIMTEL archives * (oak.oakland.edu and its various mirror sites). See files * pub/msdos/microsoft/xms20.arc and pub/msdos/info/limems41.zip. */ /* * Access methods for a DOS file. */ METHODDEF(void) read_file_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { if (jdos_seek(info->handle.file_handle, file_offset)) ERREXIT(cinfo, JERR_TFILE_SEEK); /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */ if (byte_count > 65535L) /* safety check */ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK); if (jdos_read(info->handle.file_handle, buffer_address, (unsigned short) byte_count)) ERREXIT(cinfo, JERR_TFILE_READ); } METHODDEF(void) write_file_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { if (jdos_seek(info->handle.file_handle, file_offset)) ERREXIT(cinfo, JERR_TFILE_SEEK); /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */ if (byte_count > 65535L) /* safety check */ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK); if (jdos_write(info->handle.file_handle, buffer_address, (unsigned short) byte_count)) ERREXIT(cinfo, JERR_TFILE_WRITE); } METHODDEF(void) close_file_store (j_common_ptr cinfo, backing_store_ptr info) { jdos_close(info->handle.file_handle); /* close the file */ remove(info->temp_name); /* delete the file */ /* If your system doesn't have remove(), try unlink() instead. * remove() is the ANSI-standard name for this function, but * unlink() was more common in pre-ANSI systems. */ TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name); } LOCAL(boolean) open_file_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { short handle; select_file_name(info->temp_name); if (jdos_open((short far *) & handle, (char far *) info->temp_name)) { /* might as well exit since jpeg_open_backing_store will fail anyway */ ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); return FALSE; } info->handle.file_handle = handle; info->read_backing_store = read_file_store; info->write_backing_store = write_file_store; info->close_backing_store = close_file_store; TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name); return TRUE; /* succeeded */ } /* * Access methods for extended memory. */ #if XMS_SUPPORTED static XMSDRIVER xms_driver; /* saved address of XMS driver */ typedef union { /* either long offset or real-mode pointer */ long offset; void far * ptr; } XMSPTR; typedef struct { /* XMS move specification structure */ long length; XMSH src_handle; XMSPTR src; XMSH dst_handle; XMSPTR dst; } XMSspec; #define ODD(X) (((X) & 1L) != 0) METHODDEF(void) read_xms_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { XMScontext ctx; XMSspec spec; char endbuffer[2]; /* The XMS driver can't cope with an odd length, so handle the last byte * specially if byte_count is odd. We don't expect this to be common. */ spec.length = byte_count & (~ 1L); spec.src_handle = info->handle.xms_handle; spec.src.offset = file_offset; spec.dst_handle = 0; spec.dst.ptr = buffer_address; ctx.ds_si = (void far *) & spec; ctx.ax = 0x0b00; /* EMB move */ jxms_calldriver(xms_driver, (XMScontext far *) & ctx); if (ctx.ax != 1) ERREXIT(cinfo, JERR_XMS_READ); if (ODD(byte_count)) { read_xms_store(cinfo, info, (void FAR *) endbuffer, file_offset + byte_count - 1L, 2L); ((char FAR *) buffer_address)[byte_count - 1L] = endbuffer[0]; } } METHODDEF(void) write_xms_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { XMScontext ctx; XMSspec spec; char endbuffer[2]; /* The XMS driver can't cope with an odd length, so handle the last byte * specially if byte_count is odd. We don't expect this to be common. */ spec.length = byte_count & (~ 1L); spec.src_handle = 0; spec.src.ptr = buffer_address; spec.dst_handle = info->handle.xms_handle; spec.dst.offset = file_offset; ctx.ds_si = (void far *) & spec; ctx.ax = 0x0b00; /* EMB move */ jxms_calldriver(xms_driver, (XMScontext far *) & ctx); if (ctx.ax != 1) ERREXIT(cinfo, JERR_XMS_WRITE); if (ODD(byte_count)) { read_xms_store(cinfo, info, (void FAR *) endbuffer, file_offset + byte_count - 1L, 2L); endbuffer[0] = ((char FAR *) buffer_address)[byte_count - 1L]; write_xms_store(cinfo, info, (void FAR *) endbuffer, file_offset + byte_count - 1L, 2L); } } METHODDEF(void) close_xms_store (j_common_ptr cinfo, backing_store_ptr info) { XMScontext ctx; ctx.dx = info->handle.xms_handle; ctx.ax = 0x0a00; jxms_calldriver(xms_driver, (XMScontext far *) & ctx); TRACEMS1(cinfo, 1, JTRC_XMS_CLOSE, info->handle.xms_handle); /* we ignore any error return from the driver */ } LOCAL(boolean) open_xms_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { XMScontext ctx; /* Get address of XMS driver */ jxms_getdriver((XMSDRIVER far *) & xms_driver); if (xms_driver == NULL) return FALSE; /* no driver to be had */ /* Get version number, must be >= 2.00 */ ctx.ax = 0x0000; jxms_calldriver(xms_driver, (XMScontext far *) & ctx); if (ctx.ax < (unsigned short) 0x0200) return FALSE; /* Try to get space (expressed in kilobytes) */ ctx.dx = (unsigned short) ((total_bytes_needed + 1023L) >> 10); ctx.ax = 0x0900; jxms_calldriver(xms_driver, (XMScontext far *) & ctx); if (ctx.ax != 1) return FALSE; /* Succeeded, save the handle and away we go */ info->handle.xms_handle = ctx.dx; info->read_backing_store = read_xms_store; info->write_backing_store = write_xms_store; info->close_backing_store = close_xms_store; TRACEMS1(cinfo, 1, JTRC_XMS_OPEN, ctx.dx); return TRUE; /* succeeded */ } #endif /* XMS_SUPPORTED */ /* * Access methods for expanded memory. */ #if EMS_SUPPORTED /* The EMS move specification structure requires word and long fields aligned * at odd byte boundaries. Some compilers will align struct fields at even * byte boundaries. While it's usually possible to force byte alignment, * that causes an overall performance penalty and may pose problems in merging * JPEG into a larger application. Instead we accept some rather dirty code * here. Note this code would fail if the hardware did not allow odd-byte * word & long accesses, but all 80x86 CPUs do. */ typedef void far * EMSPTR; typedef union { /* EMS move specification structure */ long length; /* It's easy to access first 4 bytes */ char bytes[18]; /* Misaligned fields in here! */ } EMSspec; /* Macros for accessing misaligned fields */ #define FIELD_AT(spec,offset,type) (*((type *) &(spec.bytes[offset]))) #define SRC_TYPE(spec) FIELD_AT(spec,4,char) #define SRC_HANDLE(spec) FIELD_AT(spec,5,EMSH) #define SRC_OFFSET(spec) FIELD_AT(spec,7,unsigned short) #define SRC_PAGE(spec) FIELD_AT(spec,9,unsigned short) #define SRC_PTR(spec) FIELD_AT(spec,7,EMSPTR) #define DST_TYPE(spec) FIELD_AT(spec,11,char) #define DST_HANDLE(spec) FIELD_AT(spec,12,EMSH) #define DST_OFFSET(spec) FIELD_AT(spec,14,unsigned short) #define DST_PAGE(spec) FIELD_AT(spec,16,unsigned short) #define DST_PTR(spec) FIELD_AT(spec,14,EMSPTR) #define EMSPAGESIZE 16384L /* gospel, see the EMS specs */ #define HIBYTE(W) (((W) >> 8) & 0xFF) #define LOBYTE(W) ((W) & 0xFF) METHODDEF(void) read_ems_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { EMScontext ctx; EMSspec spec; spec.length = byte_count; SRC_TYPE(spec) = 1; SRC_HANDLE(spec) = info->handle.ems_handle; SRC_PAGE(spec) = (unsigned short) (file_offset / EMSPAGESIZE); SRC_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE); DST_TYPE(spec) = 0; DST_HANDLE(spec) = 0; DST_PTR(spec) = buffer_address; ctx.ds_si = (void far *) & spec; ctx.ax = 0x5700; /* move memory region */ jems_calldriver((EMScontext far *) & ctx); if (HIBYTE(ctx.ax) != 0) ERREXIT(cinfo, JERR_EMS_READ); } METHODDEF(void) write_ems_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { EMScontext ctx; EMSspec spec; spec.length = byte_count; SRC_TYPE(spec) = 0; SRC_HANDLE(spec) = 0; SRC_PTR(spec) = buffer_address; DST_TYPE(spec) = 1; DST_HANDLE(spec) = info->handle.ems_handle; DST_PAGE(spec) = (unsigned short) (file_offset / EMSPAGESIZE); DST_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE); ctx.ds_si = (void far *) & spec; ctx.ax = 0x5700; /* move memory region */ jems_calldriver((EMScontext far *) & ctx); if (HIBYTE(ctx.ax) != 0) ERREXIT(cinfo, JERR_EMS_WRITE); } METHODDEF(void) close_ems_store (j_common_ptr cinfo, backing_store_ptr info) { EMScontext ctx; ctx.ax = 0x4500; ctx.dx = info->handle.ems_handle; jems_calldriver((EMScontext far *) & ctx); TRACEMS1(cinfo, 1, JTRC_EMS_CLOSE, info->handle.ems_handle); /* we ignore any error return from the driver */ } LOCAL(boolean) open_ems_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { EMScontext ctx; /* Is EMS driver there? */ if (! jems_available()) return FALSE; /* Get status, make sure EMS is OK */ ctx.ax = 0x4000; jems_calldriver((EMScontext far *) & ctx); if (HIBYTE(ctx.ax) != 0) return FALSE; /* Get version, must be >= 4.0 */ ctx.ax = 0x4600; jems_calldriver((EMScontext far *) & ctx); if (HIBYTE(ctx.ax) != 0 || LOBYTE(ctx.ax) < 0x40) return FALSE; /* Try to allocate requested space */ ctx.ax = 0x4300; ctx.bx = (unsigned short) ((total_bytes_needed + EMSPAGESIZE-1L) / EMSPAGESIZE); jems_calldriver((EMScontext far *) & ctx); if (HIBYTE(ctx.ax) != 0) return FALSE; /* Succeeded, save the handle and away we go */ info->handle.ems_handle = ctx.dx; info->read_backing_store = read_ems_store; info->write_backing_store = write_ems_store; info->close_backing_store = close_ems_store; TRACEMS1(cinfo, 1, JTRC_EMS_OPEN, ctx.dx); return TRUE; /* succeeded */ } #endif /* EMS_SUPPORTED */ /* * Initial opening of a backing-store object. */ GLOBAL(void) jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { /* Try extended memory, then expanded memory, then regular file. */ #if XMS_SUPPORTED if (open_xms_store(cinfo, info, total_bytes_needed)) return; #endif #if EMS_SUPPORTED if (open_ems_store(cinfo, info, total_bytes_needed)) return; #endif if (open_file_store(cinfo, info, total_bytes_needed)) return; ERREXITS(cinfo, JERR_TFILE_CREATE, ""); } /* * These routines take care of any system-dependent initialization and * cleanup required. */ GLOBAL(long) jpeg_mem_init (j_common_ptr cinfo) { next_file_num = 0; /* initialize temp file name generator */ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */ } GLOBAL(void) jpeg_mem_term (j_common_ptr cinfo) { /* Microsoft C, at least in v6.00A, will not successfully reclaim freed * blocks of size > 32Kbytes unless we give it a kick in the rear, like so: */ #ifdef NEED_FHEAPMIN _fheapmin(); #endif } ================================================ FILE: tess-two/jni/libjpeg/jmemdosa.asm ================================================ ; ; jmemdosa.asm ; ; Copyright (C) 1992, Thomas G. Lane. ; This file is part of the Independent JPEG Group's software. ; For conditions of distribution and use, see the accompanying README file. ; ; This file contains low-level interface routines to support the MS-DOS ; backing store manager (jmemdos.c). Routines are provided to access disk ; files through direct DOS calls, and to access XMS and EMS drivers. ; ; This file should assemble with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). If you haven't got ; a compatible assembler, better fall back to jmemansi.c or jmemname.c. ; ; To minimize dependence on the C compiler's register usage conventions, ; we save and restore all 8086 registers, even though most compilers only ; require SI,DI,DS to be preserved. Also, we use only 16-bit-wide return ; values, which everybody returns in AX. ; ; Based on code contributed by Ge' Weijers. ; JMEMDOSA_TXT segment byte public 'CODE' assume cs:JMEMDOSA_TXT public _jdos_open public _jdos_close public _jdos_seek public _jdos_read public _jdos_write public _jxms_getdriver public _jxms_calldriver public _jems_available public _jems_calldriver ; ; short far jdos_open (short far * handle, char far * filename) ; ; Create and open a temporary file ; _jdos_open proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds mov cx,0 ; normal file attributes lds dx,dword ptr [bp+10] ; get filename pointer mov ah,3ch ; create file int 21h jc open_err ; if failed, return error code lds bx,dword ptr [bp+6] ; get handle pointer mov word ptr [bx],ax ; save the handle xor ax,ax ; return zero for OK open_err: pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jdos_open endp ; ; short far jdos_close (short handle) ; ; Close the file handle ; _jdos_close proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds mov bx,word ptr [bp+6] ; file handle mov ah,3eh ; close file int 21h jc close_err ; if failed, return error code xor ax,ax ; return zero for OK close_err: pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jdos_close endp ; ; short far jdos_seek (short handle, long offset) ; ; Set file position ; _jdos_seek proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds mov bx,word ptr [bp+6] ; file handle mov dx,word ptr [bp+8] ; LS offset mov cx,word ptr [bp+10] ; MS offset mov ax,4200h ; absolute seek int 21h jc seek_err ; if failed, return error code xor ax,ax ; return zero for OK seek_err: pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jdos_seek endp ; ; short far jdos_read (short handle, void far * buffer, unsigned short count) ; ; Read from file ; _jdos_read proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds mov bx,word ptr [bp+6] ; file handle lds dx,dword ptr [bp+8] ; buffer address mov cx,word ptr [bp+12] ; number of bytes mov ah,3fh ; read file int 21h jc read_err ; if failed, return error code cmp ax,word ptr [bp+12] ; make sure all bytes were read je read_ok mov ax,1 ; else return 1 for not OK jmp short read_err read_ok: xor ax,ax ; return zero for OK read_err: pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jdos_read endp ; ; short far jdos_write (short handle, void far * buffer, unsigned short count) ; ; Write to file ; _jdos_write proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds mov bx,word ptr [bp+6] ; file handle lds dx,dword ptr [bp+8] ; buffer address mov cx,word ptr [bp+12] ; number of bytes mov ah,40h ; write file int 21h jc write_err ; if failed, return error code cmp ax,word ptr [bp+12] ; make sure all bytes written je write_ok mov ax,1 ; else return 1 for not OK jmp short write_err write_ok: xor ax,ax ; return zero for OK write_err: pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jdos_write endp ; ; void far jxms_getdriver (XMSDRIVER far *) ; ; Get the address of the XMS driver, or NULL if not available ; _jxms_getdriver proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds mov ax,4300h ; call multiplex interrupt with int 2fh ; a magic cookie, hex 4300 cmp al,80h ; AL should contain hex 80 je xmsavail xor dx,dx ; no XMS driver available xor ax,ax ; return a nil pointer jmp short xmsavail_done xmsavail: mov ax,4310h ; fetch driver address with int 2fh ; another magic cookie mov dx,es ; copy address to dx:ax mov ax,bx xmsavail_done: les bx,dword ptr [bp+6] ; get pointer to return value mov word ptr es:[bx],ax mov word ptr es:[bx+2],dx pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jxms_getdriver endp ; ; void far jxms_calldriver (XMSDRIVER, XMScontext far *) ; ; The XMScontext structure contains values for the AX,DX,BX,SI,DS registers. ; These are loaded, the XMS call is performed, and the new values of the ; AX,DX,BX registers are written back to the context structure. ; _jxms_calldriver proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds les bx,dword ptr [bp+10] ; get XMScontext pointer mov ax,word ptr es:[bx] ; load registers mov dx,word ptr es:[bx+2] mov si,word ptr es:[bx+6] mov ds,word ptr es:[bx+8] mov bx,word ptr es:[bx+4] call dword ptr [bp+6] ; call the driver mov cx,bx ; save returned BX for a sec les bx,dword ptr [bp+10] ; get XMScontext pointer mov word ptr es:[bx],ax ; put back ax,dx,bx mov word ptr es:[bx+2],dx mov word ptr es:[bx+4],cx pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jxms_calldriver endp ; ; short far jems_available (void) ; ; Have we got an EMS driver? (this comes straight from the EMS 4.0 specs) ; _jems_available proc far push si ; save all registers for safety push di push bx push cx push dx push es push ds mov ax,3567h ; get interrupt vector 67h int 21h push cs pop ds mov di,000ah ; check offs 10 in returned seg lea si,ASCII_device_name ; against literal string mov cx,8 cld repe cmpsb jne no_ems mov ax,1 ; match, it's there jmp short avail_done no_ems: xor ax,ax ; it's not there avail_done: pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si ret ASCII_device_name db "EMMXXXX0" _jems_available endp ; ; void far jems_calldriver (EMScontext far *) ; ; The EMScontext structure contains values for the AX,DX,BX,SI,DS registers. ; These are loaded, the EMS trap is performed, and the new values of the ; AX,DX,BX registers are written back to the context structure. ; _jems_calldriver proc far push bp ; linkage mov bp,sp push si ; save all registers for safety push di push bx push cx push dx push es push ds les bx,dword ptr [bp+6] ; get EMScontext pointer mov ax,word ptr es:[bx] ; load registers mov dx,word ptr es:[bx+2] mov si,word ptr es:[bx+6] mov ds,word ptr es:[bx+8] mov bx,word ptr es:[bx+4] int 67h ; call the EMS driver mov cx,bx ; save returned BX for a sec les bx,dword ptr [bp+6] ; get EMScontext pointer mov word ptr es:[bx],ax ; put back ax,dx,bx mov word ptr es:[bx+2],dx mov word ptr es:[bx+4],cx pop ds ; restore registers and exit pop es pop dx pop cx pop bx pop di pop si pop bp ret _jems_calldriver endp JMEMDOSA_TXT ends end ================================================ FILE: tess-two/jni/libjpeg/jmemmac.c ================================================ /* * jmemmac.c * * Copyright (C) 1992-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * jmemmac.c provides an Apple Macintosh implementation of the system- * dependent portion of the JPEG memory manager. * * If you use jmemmac.c, then you must define USE_MAC_MEMMGR in the * JPEG_INTERNALS part of jconfig.h. * * jmemmac.c uses the Macintosh toolbox routines NewPtr and DisposePtr * instead of malloc and free. It accurately determines the amount of * memory available by using CompactMem. Notice that if left to its * own devices, this code can chew up all available space in the * application's zone, with the exception of the rather small "slop" * factor computed in jpeg_mem_available(). The application can ensure * that more space is left over by reducing max_memory_to_use. * * Large images are swapped to disk using temporary files and System 7.0+'s * temporary folder functionality. * * Note that jmemmac.c depends on two features of MacOS that were first * introduced in System 7: FindFolder and the FSSpec-based calls. * If your application uses jmemmac.c and is run under System 6 or earlier, * and the jpeg library decides it needs a temporary file, it will abort, * printing error messages about requiring System 7. (If no temporary files * are created, it will run fine.) * * If you want to use jmemmac.c in an application that might be used with * System 6 or earlier, then you should remove dependencies on FindFolder * and the FSSpec calls. You will need to replace FindFolder with some * other mechanism for finding a place to put temporary files, and you * should replace the FSSpec calls with their HFS equivalents: * * FSpDelete -> HDelete * FSpGetFInfo -> HGetFInfo * FSpCreate -> HCreate * FSpOpenDF -> HOpen *** Note: not HOpenDF *** * FSMakeFSSpec -> (fill in spec by hand.) * * (Use HOpen instead of HOpenDF. HOpen is just a glue-interface to PBHOpen, * which is on all HFS macs. HOpenDF is a System 7 addition which avoids the * ages-old problem of names starting with a period.) * * Contributed by Sam Bushell (jsam@iagu.on.net) and * Dan Gildor (gyld@in-touch.com). */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jmemsys.h" /* import the system-dependent declarations */ #ifndef USE_MAC_MEMMGR /* make sure user got configuration right */ You forgot to define USE_MAC_MEMMGR in jconfig.h. /* deliberate syntax error */ #endif #include /* we use the MacOS memory manager */ #include /* we use the MacOS File stuff */ #include /* we use the MacOS HFS stuff */ #include /* for smSystemScript */ #include /* we use Gestalt to test for specific functionality */ #ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */ #define TEMP_FILE_NAME "JPG%03d.TMP" #endif static int next_file_num; /* to distinguish among several temp files */ /* * Memory allocation and freeing are controlled by the MacOS library * routines NewPtr() and DisposePtr(), which allocate fixed-address * storage. Unfortunately, the IJG library isn't smart enough to cope * with relocatable storage. */ GLOBAL(void *) jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject) { return (void *) NewPtr(sizeofobject); } GLOBAL(void) jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject) { DisposePtr((Ptr) object); } /* * "Large" objects are treated the same as "small" ones. * NB: we include FAR keywords in the routine declarations simply for * consistency with the rest of the IJG code; FAR should expand to empty * on rational architectures like the Mac. */ GLOBAL(void FAR *) jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject) { return (void FAR *) NewPtr(sizeofobject); } GLOBAL(void) jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject) { DisposePtr((Ptr) object); } /* * This routine computes the total memory space available for allocation. */ GLOBAL(long) jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, long max_bytes_needed, long already_allocated) { long limit = cinfo->mem->max_memory_to_use - already_allocated; long slop, mem; /* Don't ask for more than what application has told us we may use */ if (max_bytes_needed > limit && limit > 0) max_bytes_needed = limit; /* Find whether there's a big enough free block in the heap. * CompactMem tries to create a contiguous block of the requested size, * and then returns the size of the largest free block (which could be * much more or much less than we asked for). * We add some slop to ensure we don't use up all available memory. */ slop = max_bytes_needed / 16 + 32768L; mem = CompactMem(max_bytes_needed + slop) - slop; if (mem < 0) mem = 0; /* sigh, couldn't even get the slop */ /* Don't take more than the application says we can have */ if (mem > limit && limit > 0) mem = limit; return mem; } /* * Backing store (temporary file) management. * Backing store objects are only used when the value returned by * jpeg_mem_available is less than the total space needed. You can dispense * with these routines if you have plenty of virtual memory; see jmemnobs.c. */ METHODDEF(void) read_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { long bytes = byte_count; long retVal; if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr ) ERREXIT(cinfo, JERR_TFILE_SEEK); retVal = FSRead ( info->temp_file, &bytes, (unsigned char *) buffer_address ); if ( retVal != noErr || bytes != byte_count ) ERREXIT(cinfo, JERR_TFILE_READ); } METHODDEF(void) write_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { long bytes = byte_count; long retVal; if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr ) ERREXIT(cinfo, JERR_TFILE_SEEK); retVal = FSWrite ( info->temp_file, &bytes, (unsigned char *) buffer_address ); if ( retVal != noErr || bytes != byte_count ) ERREXIT(cinfo, JERR_TFILE_WRITE); } METHODDEF(void) close_backing_store (j_common_ptr cinfo, backing_store_ptr info) { FSClose ( info->temp_file ); FSpDelete ( &(info->tempSpec) ); } /* * Initial opening of a backing-store object. * * This version uses FindFolder to find the Temporary Items folder, * and puts the temporary file in there. */ GLOBAL(void) jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { short tmpRef, vRefNum; long dirID; FInfo finderInfo; FSSpec theSpec; Str255 fName; OSErr osErr; long gestaltResponse = 0; /* Check that FSSpec calls are available. */ osErr = Gestalt( gestaltFSAttr, &gestaltResponse ); if ( ( osErr != noErr ) || !( gestaltResponse & (1<temp_name, TEMP_FILE_NAME, next_file_num); strcpy ( (Ptr)fName+1, info->temp_name ); *fName = strlen (info->temp_name); osErr = FSMakeFSSpec ( vRefNum, dirID, fName, &theSpec ); if ( (osErr = FSpGetFInfo ( &theSpec, &finderInfo ) ) != noErr ) break; } osErr = FSpCreate ( &theSpec, '????', '????', smSystemScript ); if ( osErr != noErr ) ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); osErr = FSpOpenDF ( &theSpec, fsRdWrPerm, &(info->temp_file) ); if ( osErr != noErr ) ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); info->tempSpec = theSpec; info->read_backing_store = read_backing_store; info->write_backing_store = write_backing_store; info->close_backing_store = close_backing_store; TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name); } /* * These routines take care of any system-dependent initialization and * cleanup required. */ GLOBAL(long) jpeg_mem_init (j_common_ptr cinfo) { next_file_num = 0; /* max_memory_to_use will be initialized to FreeMem()'s result; * the calling application might later reduce it, for example * to leave room to invoke multiple JPEG objects. * Note that FreeMem returns the total number of free bytes; * it may not be possible to allocate a single block of this size. */ return FreeMem(); } GLOBAL(void) jpeg_mem_term (j_common_ptr cinfo) { /* no work */ } ================================================ FILE: tess-two/jni/libjpeg/jmemmgr.c ================================================ /* * jmemmgr.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2011-2012 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the JPEG system-independent memory management * routines. This code is usable across a wide variety of machines; most * of the system dependencies have been isolated in a separate file. * The major functions provided here are: * * pool-based allocation and freeing of memory; * * policy decisions about how to divide available memory among the * virtual arrays; * * control logic for swapping virtual arrays between main memory and * backing storage. * The separate system-dependent file provides the actual backing-storage * access code, and it contains the policy decision about how much total * main memory to use. * This file is system-dependent in the sense that some of its functions * are unnecessary in some systems. For example, if there is enough virtual * memory so that backing storage will never be used, much of the virtual * array control logic could be removed. (Of course, if you have that much * memory then you shouldn't care about a little bit of unused code...) */ #define JPEG_INTERNALS #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */ #include "jinclude.h" #include "jpeglib.h" #include "jmemsys.h" /* import the system-dependent declarations */ #ifndef NO_GETENV #ifndef HAVE_STDLIB_H /* should declare getenv() */ extern char * getenv JPP((const char * name)); #endif #endif /* * Some important notes: * The allocation routines provided here must never return NULL. * They should exit to error_exit if unsuccessful. * * It's not a good idea to try to merge the sarray and barray routines, * even though they are textually almost the same, because samples are * usually stored as bytes while coefficients are shorts or ints. Thus, * in machines where byte pointers have a different representation from * word pointers, the resulting machine code could not be the same. */ /* * Many machines require storage alignment: longs must start on 4-byte * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc() * always returns pointers that are multiples of the worst-case alignment * requirement, and we had better do so too. * There isn't any really portable way to determine the worst-case alignment * requirement. This module assumes that the alignment requirement is * multiples of sizeof(ALIGN_TYPE). * By default, we define ALIGN_TYPE as double. This is necessary on some * workstations (where doubles really do need 8-byte alignment) and will work * fine on nearly everything. If your machine has lesser alignment needs, * you can save a few bytes by making ALIGN_TYPE smaller. * The only place I know of where this will NOT work is certain Macintosh * 680x0 compilers that define double as a 10-byte IEEE extended float. * Doing 10-byte alignment is counterproductive because longwords won't be * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have * such a compiler. */ #ifndef ALIGN_TYPE /* so can override from jconfig.h */ #define ALIGN_TYPE double #endif /* * We allocate objects from "pools", where each pool is gotten with a single * request to jpeg_get_small() or jpeg_get_large(). There is no per-object * overhead within a pool, except for alignment padding. Each pool has a * header with a link to the next pool of the same class. * Small and large pool headers are identical except that the latter's * link pointer must be FAR on 80x86 machines. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple * of the alignment requirement of ALIGN_TYPE. */ typedef union small_pool_struct * small_pool_ptr; typedef union small_pool_struct { struct { small_pool_ptr next; /* next in list of pools */ size_t bytes_used; /* how many bytes already used within pool */ size_t bytes_left; /* bytes still available in this pool */ } hdr; ALIGN_TYPE dummy; /* included in union to ensure alignment */ } small_pool_hdr; typedef union large_pool_struct FAR * large_pool_ptr; typedef union large_pool_struct { struct { large_pool_ptr next; /* next in list of pools */ size_t bytes_used; /* how many bytes already used within pool */ size_t bytes_left; /* bytes still available in this pool */ } hdr; ALIGN_TYPE dummy; /* included in union to ensure alignment */ } large_pool_hdr; /* * Here is the full definition of a memory manager object. */ typedef struct { struct jpeg_memory_mgr pub; /* public fields */ /* Each pool identifier (lifetime class) names a linked list of pools. */ small_pool_ptr small_list[JPOOL_NUMPOOLS]; large_pool_ptr large_list[JPOOL_NUMPOOLS]; /* Since we only have one lifetime class of virtual arrays, only one * linked list is necessary (for each datatype). Note that the virtual * array control blocks being linked together are actually stored somewhere * in the small-pool list. */ jvirt_sarray_ptr virt_sarray_list; jvirt_barray_ptr virt_barray_list; /* This counts total space obtained from jpeg_get_small/large */ long total_space_allocated; /* alloc_sarray and alloc_barray set this value for use by virtual * array routines. */ JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */ } my_memory_mgr; typedef my_memory_mgr * my_mem_ptr; /* * The control blocks for virtual arrays. * Note that these blocks are allocated in the "small" pool area. * System-dependent info for the associated backing store (if any) is hidden * inside the backing_store_info struct. */ struct jvirt_sarray_control { JSAMPARRAY mem_buffer; /* => the in-memory buffer */ JDIMENSION rows_in_array; /* total virtual array height */ JDIMENSION samplesperrow; /* width of array (and of memory buffer) */ JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */ JDIMENSION rows_in_mem; /* height of memory buffer */ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */ JDIMENSION cur_start_row; /* first logical row # in the buffer */ JDIMENSION first_undef_row; /* row # of first uninitialized row */ boolean pre_zero; /* pre-zero mode requested? */ boolean dirty; /* do current buffer contents need written? */ boolean b_s_open; /* is backing-store data valid? */ jvirt_sarray_ptr next; /* link to next virtual sarray control block */ backing_store_info b_s_info; /* System-dependent control info */ }; struct jvirt_barray_control { JBLOCKARRAY mem_buffer; /* => the in-memory buffer */ JDIMENSION rows_in_array; /* total virtual array height */ JDIMENSION blocksperrow; /* width of array (and of memory buffer) */ JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */ JDIMENSION rows_in_mem; /* height of memory buffer */ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */ JDIMENSION cur_start_row; /* first logical row # in the buffer */ JDIMENSION first_undef_row; /* row # of first uninitialized row */ boolean pre_zero; /* pre-zero mode requested? */ boolean dirty; /* do current buffer contents need written? */ boolean b_s_open; /* is backing-store data valid? */ jvirt_barray_ptr next; /* link to next virtual barray control block */ backing_store_info b_s_info; /* System-dependent control info */ }; #ifdef MEM_STATS /* optional extra stuff for statistics */ LOCAL(void) print_mem_stats (j_common_ptr cinfo, int pool_id) { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; small_pool_ptr shdr_ptr; large_pool_ptr lhdr_ptr; /* Since this is only a debugging stub, we can cheat a little by using * fprintf directly rather than going through the trace message code. * This is helpful because message parm array can't handle longs. */ fprintf(stderr, "Freeing pool %d, total space = %ld\n", pool_id, mem->total_space_allocated); for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL; lhdr_ptr = lhdr_ptr->hdr.next) { fprintf(stderr, " Large chunk used %ld\n", (long) lhdr_ptr->hdr.bytes_used); } for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL; shdr_ptr = shdr_ptr->hdr.next) { fprintf(stderr, " Small chunk used %ld free %ld\n", (long) shdr_ptr->hdr.bytes_used, (long) shdr_ptr->hdr.bytes_left); } } #endif /* MEM_STATS */ LOCAL(noreturn_t) out_of_memory (j_common_ptr cinfo, int which) /* Report an out-of-memory error and stop execution */ /* If we compiled MEM_STATS support, report alloc requests before dying */ { #ifdef MEM_STATS cinfo->err->trace_level = 2; /* force self_destruct to report stats */ #endif ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which); } /* * Allocation of "small" objects. * * For these, we use pooled storage. When a new pool must be created, * we try to get enough space for the current request plus a "slop" factor, * where the slop will be the amount of leftover space in the new pool. * The speed vs. space tradeoff is largely determined by the slop values. * A different slop value is provided for each pool class (lifetime), * and we also distinguish the first pool of a class from later ones. * NOTE: the values given work fairly well on both 16- and 32-bit-int * machines, but may be too small if longs are 64 bits or more. */ static const size_t first_pool_slop[JPOOL_NUMPOOLS] = { 1600, /* first PERMANENT pool */ 16000 /* first IMAGE pool */ }; static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = { 0, /* additional PERMANENT pools */ 5000 /* additional IMAGE pools */ }; #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */ METHODDEF(void *) alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject) /* Allocate a "small" object */ { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; small_pool_ptr hdr_ptr, prev_hdr_ptr; char * data_ptr; size_t odd_bytes, min_request, slop; /* Check for unsatisfiable request (do now to ensure no overflow below) */ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr))) out_of_memory(cinfo, 1); /* request exceeds malloc's ability */ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE); if (odd_bytes > 0) sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes; /* See if space is available in any existing pool */ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS) ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ prev_hdr_ptr = NULL; hdr_ptr = mem->small_list[pool_id]; while (hdr_ptr != NULL) { if (hdr_ptr->hdr.bytes_left >= sizeofobject) break; /* found pool with enough space */ prev_hdr_ptr = hdr_ptr; hdr_ptr = hdr_ptr->hdr.next; } /* Time to make a new pool? */ if (hdr_ptr == NULL) { /* min_request is what we need now, slop is what will be leftover */ min_request = sizeofobject + SIZEOF(small_pool_hdr); if (prev_hdr_ptr == NULL) /* first pool in class? */ slop = first_pool_slop[pool_id]; else slop = extra_pool_slop[pool_id]; /* Don't ask for more than MAX_ALLOC_CHUNK */ if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request)) slop = (size_t) (MAX_ALLOC_CHUNK-min_request); /* Try to get space, if fail reduce slop and try again */ for (;;) { hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop); if (hdr_ptr != NULL) break; slop /= 2; if (slop < MIN_SLOP) /* give up when it gets real small */ out_of_memory(cinfo, 2); /* jpeg_get_small failed */ } mem->total_space_allocated += min_request + slop; /* Success, initialize the new pool header and add to end of list */ hdr_ptr->hdr.next = NULL; hdr_ptr->hdr.bytes_used = 0; hdr_ptr->hdr.bytes_left = sizeofobject + slop; if (prev_hdr_ptr == NULL) /* first pool in class? */ mem->small_list[pool_id] = hdr_ptr; else prev_hdr_ptr->hdr.next = hdr_ptr; } /* OK, allocate the object from the current pool */ data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */ data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */ hdr_ptr->hdr.bytes_used += sizeofobject; hdr_ptr->hdr.bytes_left -= sizeofobject; return (void *) data_ptr; } /* * Allocation of "large" objects. * * The external semantics of these are the same as "small" objects, * except that FAR pointers are used on 80x86. However the pool * management heuristics are quite different. We assume that each * request is large enough that it may as well be passed directly to * jpeg_get_large; the pool management just links everything together * so that we can free it all on demand. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY * structures. The routines that create these structures (see below) * deliberately bunch rows together to ensure a large request size. */ METHODDEF(void FAR *) alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject) /* Allocate a "large" object */ { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; large_pool_ptr hdr_ptr; size_t odd_bytes; /* Check for unsatisfiable request (do now to ensure no overflow below) */ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr))) out_of_memory(cinfo, 3); /* request exceeds malloc's ability */ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE); if (odd_bytes > 0) sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes; /* Always make a new pool */ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS) ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject + SIZEOF(large_pool_hdr)); if (hdr_ptr == NULL) out_of_memory(cinfo, 4); /* jpeg_get_large failed */ mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr); /* Success, initialize the new pool header and add to list */ hdr_ptr->hdr.next = mem->large_list[pool_id]; /* We maintain space counts in each pool header for statistical purposes, * even though they are not needed for allocation. */ hdr_ptr->hdr.bytes_used = sizeofobject; hdr_ptr->hdr.bytes_left = 0; mem->large_list[pool_id] = hdr_ptr; return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */ } /* * Creation of 2-D sample arrays. * The pointers are in near heap, the samples themselves in FAR heap. * * To minimize allocation overhead and to allow I/O of large contiguous * blocks, we allocate the sample rows in groups of as many rows as possible * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request. * NB: the virtual array control routines, later in this file, know about * this chunking of rows. The rowsperchunk value is left in the mem manager * object so that it can be saved away if this sarray is the workspace for * a virtual array. */ METHODDEF(JSAMPARRAY) alloc_sarray (j_common_ptr cinfo, int pool_id, JDIMENSION samplesperrow, JDIMENSION numrows) /* Allocate a 2-D sample array */ { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; JSAMPARRAY result; JSAMPROW workspace; JDIMENSION rowsperchunk, currow, i; long ltemp; /* Calculate max # of rows allowed in one allocation chunk */ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) / ((long) samplesperrow * SIZEOF(JSAMPLE)); if (ltemp <= 0) ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); if (ltemp < (long) numrows) rowsperchunk = (JDIMENSION) ltemp; else rowsperchunk = numrows; mem->last_rowsperchunk = rowsperchunk; /* Get space for row pointers (small object) */ result = (JSAMPARRAY) alloc_small(cinfo, pool_id, (size_t) (numrows * SIZEOF(JSAMPROW))); /* Get the rows themselves (large objects) */ currow = 0; while (currow < numrows) { rowsperchunk = MIN(rowsperchunk, numrows - currow); workspace = (JSAMPROW) alloc_large(cinfo, pool_id, (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow * SIZEOF(JSAMPLE))); for (i = rowsperchunk; i > 0; i--) { result[currow++] = workspace; workspace += samplesperrow; } } return result; } /* * Creation of 2-D coefficient-block arrays. * This is essentially the same as the code for sample arrays, above. */ METHODDEF(JBLOCKARRAY) alloc_barray (j_common_ptr cinfo, int pool_id, JDIMENSION blocksperrow, JDIMENSION numrows) /* Allocate a 2-D coefficient-block array */ { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; JBLOCKARRAY result; JBLOCKROW workspace; JDIMENSION rowsperchunk, currow, i; long ltemp; /* Calculate max # of rows allowed in one allocation chunk */ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) / ((long) blocksperrow * SIZEOF(JBLOCK)); if (ltemp <= 0) ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); if (ltemp < (long) numrows) rowsperchunk = (JDIMENSION) ltemp; else rowsperchunk = numrows; mem->last_rowsperchunk = rowsperchunk; /* Get space for row pointers (small object) */ result = (JBLOCKARRAY) alloc_small(cinfo, pool_id, (size_t) (numrows * SIZEOF(JBLOCKROW))); /* Get the rows themselves (large objects) */ currow = 0; while (currow < numrows) { rowsperchunk = MIN(rowsperchunk, numrows - currow); workspace = (JBLOCKROW) alloc_large(cinfo, pool_id, (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow * SIZEOF(JBLOCK))); for (i = rowsperchunk; i > 0; i--) { result[currow++] = workspace; workspace += blocksperrow; } } return result; } /* * About virtual array management: * * The above "normal" array routines are only used to allocate strip buffers * (as wide as the image, but just a few rows high). Full-image-sized buffers * are handled as "virtual" arrays. The array is still accessed a strip at a * time, but the memory manager must save the whole array for repeated * accesses. The intended implementation is that there is a strip buffer in * memory (as high as is possible given the desired memory limit), plus a * backing file that holds the rest of the array. * * The request_virt_array routines are told the total size of the image and * the maximum number of rows that will be accessed at once. The in-memory * buffer must be at least as large as the maxaccess value. * * The request routines create control blocks but not the in-memory buffers. * That is postponed until realize_virt_arrays is called. At that time the * total amount of space needed is known (approximately, anyway), so free * memory can be divided up fairly. * * The access_virt_array routines are responsible for making a specific strip * area accessible (after reading or writing the backing file, if necessary). * Note that the access routines are told whether the caller intends to modify * the accessed strip; during a read-only pass this saves having to rewrite * data to disk. The access routines are also responsible for pre-zeroing * any newly accessed rows, if pre-zeroing was requested. * * In current usage, the access requests are usually for nonoverlapping * strips; that is, successive access start_row numbers differ by exactly * num_rows = maxaccess. This means we can get good performance with simple * buffer dump/reload logic, by making the in-memory buffer be a multiple * of the access height; then there will never be accesses across bufferload * boundaries. The code will still work with overlapping access requests, * but it doesn't handle bufferload overlaps very efficiently. */ METHODDEF(jvirt_sarray_ptr) request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION samplesperrow, JDIMENSION numrows, JDIMENSION maxaccess) /* Request a virtual 2-D sample array */ { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; jvirt_sarray_ptr result; /* Only IMAGE-lifetime virtual arrays are currently supported */ if (pool_id != JPOOL_IMAGE) ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ /* get control block */ result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id, SIZEOF(struct jvirt_sarray_control)); result->mem_buffer = NULL; /* marks array not yet realized */ result->rows_in_array = numrows; result->samplesperrow = samplesperrow; result->maxaccess = maxaccess; result->pre_zero = pre_zero; result->b_s_open = FALSE; /* no associated backing-store object */ result->next = mem->virt_sarray_list; /* add to list of virtual arrays */ mem->virt_sarray_list = result; return result; } METHODDEF(jvirt_barray_ptr) request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION blocksperrow, JDIMENSION numrows, JDIMENSION maxaccess) /* Request a virtual 2-D coefficient-block array */ { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; jvirt_barray_ptr result; /* Only IMAGE-lifetime virtual arrays are currently supported */ if (pool_id != JPOOL_IMAGE) ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ /* get control block */ result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id, SIZEOF(struct jvirt_barray_control)); result->mem_buffer = NULL; /* marks array not yet realized */ result->rows_in_array = numrows; result->blocksperrow = blocksperrow; result->maxaccess = maxaccess; result->pre_zero = pre_zero; result->b_s_open = FALSE; /* no associated backing-store object */ result->next = mem->virt_barray_list; /* add to list of virtual arrays */ mem->virt_barray_list = result; return result; } METHODDEF(void) realize_virt_arrays (j_common_ptr cinfo) /* Allocate the in-memory buffers for any unrealized virtual arrays */ { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; long space_per_minheight, maximum_space, avail_mem; long minheights, max_minheights; jvirt_sarray_ptr sptr; jvirt_barray_ptr bptr; /* Compute the minimum space needed (maxaccess rows in each buffer) * and the maximum space needed (full image height in each buffer). * These may be of use to the system-dependent jpeg_mem_available routine. */ space_per_minheight = 0; maximum_space = 0; for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) { if (sptr->mem_buffer == NULL) { /* if not realized yet */ space_per_minheight += (long) sptr->maxaccess * (long) sptr->samplesperrow * SIZEOF(JSAMPLE); maximum_space += (long) sptr->rows_in_array * (long) sptr->samplesperrow * SIZEOF(JSAMPLE); } } for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) { if (bptr->mem_buffer == NULL) { /* if not realized yet */ space_per_minheight += (long) bptr->maxaccess * (long) bptr->blocksperrow * SIZEOF(JBLOCK); maximum_space += (long) bptr->rows_in_array * (long) bptr->blocksperrow * SIZEOF(JBLOCK); } } if (space_per_minheight <= 0) return; /* no unrealized arrays, no work */ /* Determine amount of memory to actually use; this is system-dependent. */ avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space, mem->total_space_allocated); /* If the maximum space needed is available, make all the buffers full * height; otherwise parcel it out with the same number of minheights * in each buffer. */ if (avail_mem >= maximum_space) max_minheights = 1000000000L; else { max_minheights = avail_mem / space_per_minheight; /* If there doesn't seem to be enough space, try to get the minimum * anyway. This allows a "stub" implementation of jpeg_mem_available(). */ if (max_minheights <= 0) max_minheights = 1; } /* Allocate the in-memory buffers and initialize backing store as needed. */ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) { if (sptr->mem_buffer == NULL) { /* if not realized yet */ minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L; if (minheights <= max_minheights) { /* This buffer fits in memory */ sptr->rows_in_mem = sptr->rows_in_array; } else { /* It doesn't fit in memory, create backing store. */ sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess); jpeg_open_backing_store(cinfo, & sptr->b_s_info, (long) sptr->rows_in_array * (long) sptr->samplesperrow * (long) SIZEOF(JSAMPLE)); sptr->b_s_open = TRUE; } sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE, sptr->samplesperrow, sptr->rows_in_mem); sptr->rowsperchunk = mem->last_rowsperchunk; sptr->cur_start_row = 0; sptr->first_undef_row = 0; sptr->dirty = FALSE; } } for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) { if (bptr->mem_buffer == NULL) { /* if not realized yet */ minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L; if (minheights <= max_minheights) { /* This buffer fits in memory */ bptr->rows_in_mem = bptr->rows_in_array; } else { /* It doesn't fit in memory, create backing store. */ bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess); jpeg_open_backing_store(cinfo, & bptr->b_s_info, (long) bptr->rows_in_array * (long) bptr->blocksperrow * (long) SIZEOF(JBLOCK)); bptr->b_s_open = TRUE; } bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE, bptr->blocksperrow, bptr->rows_in_mem); bptr->rowsperchunk = mem->last_rowsperchunk; bptr->cur_start_row = 0; bptr->first_undef_row = 0; bptr->dirty = FALSE; } } } LOCAL(void) do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing) /* Do backing store read or write of a virtual sample array */ { long bytesperrow, file_offset, byte_count, rows, thisrow, i; bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE); file_offset = ptr->cur_start_row * bytesperrow; /* Loop to read or write each allocation chunk in mem_buffer */ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) { /* One chunk, but check for short chunk at end of buffer */ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i); /* Transfer no more than is currently defined */ thisrow = (long) ptr->cur_start_row + i; rows = MIN(rows, (long) ptr->first_undef_row - thisrow); /* Transfer no more than fits in file */ rows = MIN(rows, (long) ptr->rows_in_array - thisrow); if (rows <= 0) /* this chunk might be past end of file! */ break; byte_count = rows * bytesperrow; if (writing) (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info, (void FAR *) ptr->mem_buffer[i], file_offset, byte_count); else (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info, (void FAR *) ptr->mem_buffer[i], file_offset, byte_count); file_offset += byte_count; } } LOCAL(void) do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing) /* Do backing store read or write of a virtual coefficient-block array */ { long bytesperrow, file_offset, byte_count, rows, thisrow, i; bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK); file_offset = ptr->cur_start_row * bytesperrow; /* Loop to read or write each allocation chunk in mem_buffer */ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) { /* One chunk, but check for short chunk at end of buffer */ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i); /* Transfer no more than is currently defined */ thisrow = (long) ptr->cur_start_row + i; rows = MIN(rows, (long) ptr->first_undef_row - thisrow); /* Transfer no more than fits in file */ rows = MIN(rows, (long) ptr->rows_in_array - thisrow); if (rows <= 0) /* this chunk might be past end of file! */ break; byte_count = rows * bytesperrow; if (writing) (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info, (void FAR *) ptr->mem_buffer[i], file_offset, byte_count); else (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info, (void FAR *) ptr->mem_buffer[i], file_offset, byte_count); file_offset += byte_count; } } METHODDEF(JSAMPARRAY) access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable) /* Access the part of a virtual sample array starting at start_row */ /* and extending for num_rows rows. writable is true if */ /* caller intends to modify the accessed area. */ { JDIMENSION end_row = start_row + num_rows; JDIMENSION undef_row; /* debugging check */ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess || ptr->mem_buffer == NULL) ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); /* Make the desired part of the virtual array accessible */ if (start_row < ptr->cur_start_row || end_row > ptr->cur_start_row+ptr->rows_in_mem) { if (! ptr->b_s_open) ERREXIT(cinfo, JERR_VIRTUAL_BUG); /* Flush old buffer contents if necessary */ if (ptr->dirty) { do_sarray_io(cinfo, ptr, TRUE); ptr->dirty = FALSE; } /* Decide what part of virtual array to access. * Algorithm: if target address > current window, assume forward scan, * load starting at target address. If target address < current window, * assume backward scan, load so that target area is top of window. * Note that when switching from forward write to forward read, will have * start_row = 0, so the limiting case applies and we load from 0 anyway. */ if (start_row > ptr->cur_start_row) { ptr->cur_start_row = start_row; } else { /* use long arithmetic here to avoid overflow & unsigned problems */ long ltemp; ltemp = (long) end_row - (long) ptr->rows_in_mem; if (ltemp < 0) ltemp = 0; /* don't fall off front end of file */ ptr->cur_start_row = (JDIMENSION) ltemp; } /* Read in the selected part of the array. * During the initial write pass, we will do no actual read * because the selected part is all undefined. */ do_sarray_io(cinfo, ptr, FALSE); } /* Ensure the accessed part of the array is defined; prezero if needed. * To improve locality of access, we only prezero the part of the array * that the caller is about to access, not the entire in-memory array. */ if (ptr->first_undef_row < end_row) { if (ptr->first_undef_row < start_row) { if (writable) /* writer skipped over a section of array */ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); undef_row = start_row; /* but reader is allowed to read ahead */ } else { undef_row = ptr->first_undef_row; } if (writable) ptr->first_undef_row = end_row; if (ptr->pre_zero) { size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE); undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */ end_row -= ptr->cur_start_row; while (undef_row < end_row) { FMEMZERO((void FAR *) ptr->mem_buffer[undef_row], bytesperrow); undef_row++; } } else { if (! writable) /* reader looking at undefined data */ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); } } /* Flag the buffer dirty if caller will write in it */ if (writable) ptr->dirty = TRUE; /* Return address of proper part of the buffer */ return ptr->mem_buffer + (start_row - ptr->cur_start_row); } METHODDEF(JBLOCKARRAY) access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable) /* Access the part of a virtual block array starting at start_row */ /* and extending for num_rows rows. writable is true if */ /* caller intends to modify the accessed area. */ { JDIMENSION end_row = start_row + num_rows; JDIMENSION undef_row; /* debugging check */ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess || ptr->mem_buffer == NULL) ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); /* Make the desired part of the virtual array accessible */ if (start_row < ptr->cur_start_row || end_row > ptr->cur_start_row+ptr->rows_in_mem) { if (! ptr->b_s_open) ERREXIT(cinfo, JERR_VIRTUAL_BUG); /* Flush old buffer contents if necessary */ if (ptr->dirty) { do_barray_io(cinfo, ptr, TRUE); ptr->dirty = FALSE; } /* Decide what part of virtual array to access. * Algorithm: if target address > current window, assume forward scan, * load starting at target address. If target address < current window, * assume backward scan, load so that target area is top of window. * Note that when switching from forward write to forward read, will have * start_row = 0, so the limiting case applies and we load from 0 anyway. */ if (start_row > ptr->cur_start_row) { ptr->cur_start_row = start_row; } else { /* use long arithmetic here to avoid overflow & unsigned problems */ long ltemp; ltemp = (long) end_row - (long) ptr->rows_in_mem; if (ltemp < 0) ltemp = 0; /* don't fall off front end of file */ ptr->cur_start_row = (JDIMENSION) ltemp; } /* Read in the selected part of the array. * During the initial write pass, we will do no actual read * because the selected part is all undefined. */ do_barray_io(cinfo, ptr, FALSE); } /* Ensure the accessed part of the array is defined; prezero if needed. * To improve locality of access, we only prezero the part of the array * that the caller is about to access, not the entire in-memory array. */ if (ptr->first_undef_row < end_row) { if (ptr->first_undef_row < start_row) { if (writable) /* writer skipped over a section of array */ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); undef_row = start_row; /* but reader is allowed to read ahead */ } else { undef_row = ptr->first_undef_row; } if (writable) ptr->first_undef_row = end_row; if (ptr->pre_zero) { size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK); undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */ end_row -= ptr->cur_start_row; while (undef_row < end_row) { FMEMZERO((void FAR *) ptr->mem_buffer[undef_row], bytesperrow); undef_row++; } } else { if (! writable) /* reader looking at undefined data */ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS); } } /* Flag the buffer dirty if caller will write in it */ if (writable) ptr->dirty = TRUE; /* Return address of proper part of the buffer */ return ptr->mem_buffer + (start_row - ptr->cur_start_row); } /* * Release all objects belonging to a specified pool. */ METHODDEF(void) free_pool (j_common_ptr cinfo, int pool_id) { my_mem_ptr mem = (my_mem_ptr) cinfo->mem; small_pool_ptr shdr_ptr; large_pool_ptr lhdr_ptr; size_t space_freed; if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS) ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */ #ifdef MEM_STATS if (cinfo->err->trace_level > 1) print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */ #endif /* If freeing IMAGE pool, close any virtual arrays first */ if (pool_id == JPOOL_IMAGE) { jvirt_sarray_ptr sptr; jvirt_barray_ptr bptr; for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) { if (sptr->b_s_open) { /* there may be no backing store */ sptr->b_s_open = FALSE; /* prevent recursive close if error */ (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info); } } mem->virt_sarray_list = NULL; for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) { if (bptr->b_s_open) { /* there may be no backing store */ bptr->b_s_open = FALSE; /* prevent recursive close if error */ (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info); } } mem->virt_barray_list = NULL; } /* Release large objects */ lhdr_ptr = mem->large_list[pool_id]; mem->large_list[pool_id] = NULL; while (lhdr_ptr != NULL) { large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next; space_freed = lhdr_ptr->hdr.bytes_used + lhdr_ptr->hdr.bytes_left + SIZEOF(large_pool_hdr); jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed); mem->total_space_allocated -= space_freed; lhdr_ptr = next_lhdr_ptr; } /* Release small objects */ shdr_ptr = mem->small_list[pool_id]; mem->small_list[pool_id] = NULL; while (shdr_ptr != NULL) { small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next; space_freed = shdr_ptr->hdr.bytes_used + shdr_ptr->hdr.bytes_left + SIZEOF(small_pool_hdr); jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed); mem->total_space_allocated -= space_freed; shdr_ptr = next_shdr_ptr; } } /* * Close up shop entirely. * Note that this cannot be called unless cinfo->mem is non-NULL. */ METHODDEF(void) self_destruct (j_common_ptr cinfo) { int pool; /* Close all backing store, release all memory. * Releasing pools in reverse order might help avoid fragmentation * with some (brain-damaged) malloc libraries. */ for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) { free_pool(cinfo, pool); } /* Release the memory manager control block too. */ jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr)); cinfo->mem = NULL; /* ensures I will be called only once */ jpeg_mem_term(cinfo); /* system-dependent cleanup */ } /* * Memory manager initialization. * When this is called, only the error manager pointer is valid in cinfo! */ GLOBAL(void) jinit_memory_mgr (j_common_ptr cinfo) { my_mem_ptr mem; long max_to_use; int pool; size_t test_mac; cinfo->mem = NULL; /* for safety if init fails */ /* Check for configuration errors. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably * doesn't reflect any real hardware alignment requirement. * The test is a little tricky: for X>0, X and X-1 have no one-bits * in common if and only if X is a power of 2, ie has only one one-bit. * Some compilers may give an "unreachable code" warning here; ignore it. */ if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0) ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE); /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be * a multiple of SIZEOF(ALIGN_TYPE). * Again, an "unreachable code" warning may be ignored here. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK. */ test_mac = (size_t) MAX_ALLOC_CHUNK; if ((long) test_mac != MAX_ALLOC_CHUNK || (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0) ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK); max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */ /* Attempt to allocate memory manager's control block */ mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr)); if (mem == NULL) { jpeg_mem_term(cinfo); /* system-dependent cleanup */ ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0); } /* OK, fill in the method pointers */ mem->pub.alloc_small = alloc_small; mem->pub.alloc_large = alloc_large; mem->pub.alloc_sarray = alloc_sarray; mem->pub.alloc_barray = alloc_barray; mem->pub.request_virt_sarray = request_virt_sarray; mem->pub.request_virt_barray = request_virt_barray; mem->pub.realize_virt_arrays = realize_virt_arrays; mem->pub.access_virt_sarray = access_virt_sarray; mem->pub.access_virt_barray = access_virt_barray; mem->pub.free_pool = free_pool; mem->pub.self_destruct = self_destruct; /* Make MAX_ALLOC_CHUNK accessible to other modules */ mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK; /* Initialize working state */ mem->pub.max_memory_to_use = max_to_use; for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) { mem->small_list[pool] = NULL; mem->large_list[pool] = NULL; } mem->virt_sarray_list = NULL; mem->virt_barray_list = NULL; mem->total_space_allocated = SIZEOF(my_memory_mgr); /* Declare ourselves open for business */ cinfo->mem = & mem->pub; /* Check for an environment variable JPEGMEM; if found, override the * default max_memory setting from jpeg_mem_init. Note that the * surrounding application may again override this value. * If your system doesn't support getenv(), define NO_GETENV to disable * this feature. */ #ifndef NO_GETENV { char * memenv; if ((memenv = getenv("JPEGMEM")) != NULL) { char ch = 'x'; if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) { if (ch == 'm' || ch == 'M') max_to_use *= 1000L; mem->pub.max_memory_to_use = max_to_use * 1000L; } } } #endif } ================================================ FILE: tess-two/jni/libjpeg/jmemname.c ================================================ /* * jmemname.c * * Copyright (C) 1992-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file provides a generic implementation of the system-dependent * portion of the JPEG memory manager. This implementation assumes that * you must explicitly construct a name for each temp file. * Also, the problem of determining the amount of memory available * is shoved onto the user. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jmemsys.h" /* import the system-dependent declarations */ #ifndef HAVE_STDLIB_H /* should declare malloc(),free() */ extern void * malloc JPP((size_t size)); extern void free JPP((void *ptr)); #endif #ifndef SEEK_SET /* pre-ANSI systems may not define this; */ #define SEEK_SET 0 /* if not, assume 0 is correct */ #endif #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */ #define READ_BINARY "r" #define RW_BINARY "w+" #else #ifdef VMS /* VMS is very nonstandard */ #define READ_BINARY "rb", "ctx=stm" #define RW_BINARY "w+b", "ctx=stm" #else /* standard ANSI-compliant case */ #define READ_BINARY "rb" #define RW_BINARY "w+b" #endif #endif /* * Selection of a file name for a temporary file. * This is system-dependent! * * The code as given is suitable for most Unix systems, and it is easily * modified for most non-Unix systems. Some notes: * 1. The temp file is created in the directory named by TEMP_DIRECTORY. * The default value is /usr/tmp, which is the conventional place for * creating large temp files on Unix. On other systems you'll probably * want to change the file location. You can do this by editing the * #define, or (preferred) by defining TEMP_DIRECTORY in jconfig.h. * * 2. If you need to change the file name as well as its location, * you can override the TEMP_FILE_NAME macro. (Note that this is * actually a printf format string; it must contain %s and %d.) * Few people should need to do this. * * 3. mktemp() is used to ensure that multiple processes running * simultaneously won't select the same file names. If your system * doesn't have mktemp(), define NO_MKTEMP to do it the hard way. * (If you don't have , also define NO_ERRNO_H.) * * 4. You probably want to define NEED_SIGNAL_CATCHER so that cjpeg.c/djpeg.c * will cause the temp files to be removed if you stop the program early. */ #ifndef TEMP_DIRECTORY /* can override from jconfig.h or Makefile */ #define TEMP_DIRECTORY "/usr/tmp/" /* recommended setting for Unix */ #endif static int next_file_num; /* to distinguish among several temp files */ #ifdef NO_MKTEMP #ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */ #define TEMP_FILE_NAME "%sJPG%03d.TMP" #endif #ifndef NO_ERRNO_H #include /* to define ENOENT */ #endif /* ANSI C specifies that errno is a macro, but on older systems it's more * likely to be a plain int variable. And not all versions of errno.h * bother to declare it, so we have to in order to be most portable. Thus: */ #ifndef errno extern int errno; #endif LOCAL(void) select_file_name (char * fname) { FILE * tfile; /* Keep generating file names till we find one that's not in use */ for (;;) { next_file_num++; /* advance counter */ sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num); if ((tfile = fopen(fname, READ_BINARY)) == NULL) { /* fopen could have failed for a reason other than the file not * being there; for example, file there but unreadable. * If isn't available, then we cannot test the cause. */ #ifdef ENOENT if (errno != ENOENT) continue; #endif break; } fclose(tfile); /* oops, it's there; close tfile & try again */ } } #else /* ! NO_MKTEMP */ /* Note that mktemp() requires the initial filename to end in six X's */ #ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */ #define TEMP_FILE_NAME "%sJPG%dXXXXXX" #endif LOCAL(void) select_file_name (char * fname) { next_file_num++; /* advance counter */ sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num); mktemp(fname); /* make sure file name is unique */ /* mktemp replaces the trailing XXXXXX with a unique string of characters */ } #endif /* NO_MKTEMP */ /* * Memory allocation and freeing are controlled by the regular library * routines malloc() and free(). */ GLOBAL(void *) jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject) { return (void *) malloc(sizeofobject); } GLOBAL(void) jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject) { free(object); } /* * "Large" objects are treated the same as "small" ones. * NB: although we include FAR keywords in the routine declarations, * this file won't actually work in 80x86 small/medium model; at least, * you probably won't be able to process useful-size images in only 64KB. */ GLOBAL(void FAR *) jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject) { return (void FAR *) malloc(sizeofobject); } GLOBAL(void) jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject) { free(object); } /* * This routine computes the total memory space available for allocation. * It's impossible to do this in a portable way; our current solution is * to make the user tell us (with a default value set at compile time). * If you can actually get the available space, it's a good idea to subtract * a slop factor of 5% or so. */ #ifndef DEFAULT_MAX_MEM /* so can override from makefile */ #define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */ #endif GLOBAL(long) jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, long max_bytes_needed, long already_allocated) { return cinfo->mem->max_memory_to_use - already_allocated; } /* * Backing store (temporary file) management. * Backing store objects are only used when the value returned by * jpeg_mem_available is less than the total space needed. You can dispense * with these routines if you have plenty of virtual memory; see jmemnobs.c. */ METHODDEF(void) read_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { if (fseek(info->temp_file, file_offset, SEEK_SET)) ERREXIT(cinfo, JERR_TFILE_SEEK); if (JFREAD(info->temp_file, buffer_address, byte_count) != (size_t) byte_count) ERREXIT(cinfo, JERR_TFILE_READ); } METHODDEF(void) write_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count) { if (fseek(info->temp_file, file_offset, SEEK_SET)) ERREXIT(cinfo, JERR_TFILE_SEEK); if (JFWRITE(info->temp_file, buffer_address, byte_count) != (size_t) byte_count) ERREXIT(cinfo, JERR_TFILE_WRITE); } METHODDEF(void) close_backing_store (j_common_ptr cinfo, backing_store_ptr info) { fclose(info->temp_file); /* close the file */ unlink(info->temp_name); /* delete the file */ /* If your system doesn't have unlink(), use remove() instead. * remove() is the ANSI-standard name for this function, but if * your system was ANSI you'd be using jmemansi.c, right? */ TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name); } /* * Initial opening of a backing-store object. */ GLOBAL(void) jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { select_file_name(info->temp_name); if ((info->temp_file = fopen(info->temp_name, RW_BINARY)) == NULL) ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); info->read_backing_store = read_backing_store; info->write_backing_store = write_backing_store; info->close_backing_store = close_backing_store; TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name); } /* * These routines take care of any system-dependent initialization and * cleanup required. */ GLOBAL(long) jpeg_mem_init (j_common_ptr cinfo) { next_file_num = 0; /* initialize temp file name generator */ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */ } GLOBAL(void) jpeg_mem_term (j_common_ptr cinfo) { /* no work */ } ================================================ FILE: tess-two/jni/libjpeg/jmemnobs.c ================================================ /* * jmemnobs.c * * Copyright (C) 1992-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file provides a really simple implementation of the system- * dependent portion of the JPEG memory manager. This implementation * assumes that no backing-store files are needed: all required space * can be obtained from malloc(). * This is very portable in the sense that it'll compile on almost anything, * but you'd better have lots of main memory (or virtual memory) if you want * to process big images. * Note that the max_memory_to_use option is ignored by this implementation. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jmemsys.h" /* import the system-dependent declarations */ #ifndef HAVE_STDLIB_H /* should declare malloc(),free() */ extern void * malloc JPP((size_t size)); extern void free JPP((void *ptr)); #endif /* * Memory allocation and freeing are controlled by the regular library * routines malloc() and free(). */ GLOBAL(void *) jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject) { return (void *) malloc(sizeofobject); } GLOBAL(void) jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject) { free(object); } /* * "Large" objects are treated the same as "small" ones. * NB: although we include FAR keywords in the routine declarations, * this file won't actually work in 80x86 small/medium model; at least, * you probably won't be able to process useful-size images in only 64KB. */ GLOBAL(void FAR *) jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject) { return (void FAR *) malloc(sizeofobject); } GLOBAL(void) jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject) { free(object); } /* * This routine computes the total memory space available for allocation. * Here we always say, "we got all you want bud!" */ GLOBAL(long) jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, long max_bytes_needed, long already_allocated) { return max_bytes_needed; } /* * Backing store (temporary file) management. * Since jpeg_mem_available always promised the moon, * this should never be called and we can just error out. */ GLOBAL(void) jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed) { ERREXIT(cinfo, JERR_NO_BACKING_STORE); } /* * These routines take care of any system-dependent initialization and * cleanup required. Here, there isn't any. */ GLOBAL(long) jpeg_mem_init (j_common_ptr cinfo) { return 0; /* just set max_memory_to_use to 0 */ } GLOBAL(void) jpeg_mem_term (j_common_ptr cinfo) { /* no work */ } ================================================ FILE: tess-two/jni/libjpeg/jmemsys.h ================================================ /* * jmemsys.h * * Copyright (C) 1992-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This include file defines the interface between the system-independent * and system-dependent portions of the JPEG memory manager. No other * modules need include it. (The system-independent portion is jmemmgr.c; * there are several different versions of the system-dependent portion.) * * This file works as-is for the system-dependent memory managers supplied * in the IJG distribution. You may need to modify it if you write a * custom memory manager. If system-dependent changes are needed in * this file, the best method is to #ifdef them based on a configuration * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR * and USE_MAC_MEMMGR. */ /* Short forms of external names for systems with brain-damaged linkers. */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jpeg_get_small jGetSmall #define jpeg_free_small jFreeSmall #define jpeg_get_large jGetLarge #define jpeg_free_large jFreeLarge #define jpeg_mem_available jMemAvail #define jpeg_open_backing_store jOpenBackStore #define jpeg_mem_init jMemInit #define jpeg_mem_term jMemTerm #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* * These two functions are used to allocate and release small chunks of * memory. (Typically the total amount requested through jpeg_get_small is * no more than 20K or so; this will be requested in chunks of a few K each.) * Behavior should be the same as for the standard library functions malloc * and free; in particular, jpeg_get_small must return NULL on failure. * On most systems, these ARE malloc and free. jpeg_free_small is passed the * size of the object being freed, just in case it's needed. * On an 80x86 machine using small-data memory model, these manage near heap. */ EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject)); EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object, size_t sizeofobject)); /* * These two functions are used to allocate and release large chunks of * memory (up to the total free space designated by jpeg_mem_available). * The interface is the same as above, except that on an 80x86 machine, * far pointers are used. On most other machines these are identical to * the jpeg_get/free_small routines; but we keep them separate anyway, * in case a different allocation strategy is desirable for large chunks. */ EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo, size_t sizeofobject)); EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object, size_t sizeofobject)); /* * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may * be requested in a single call to jpeg_get_large (and jpeg_get_small for that * matter, but that case should never come into play). This macro is needed * to model the 64Kb-segment-size limit of far addressing on 80x86 machines. * On those machines, we expect that jconfig.h will provide a proper value. * On machines with 32-bit flat address spaces, any large constant may be used. * * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type * size_t and will be a multiple of sizeof(align_type). */ #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */ #define MAX_ALLOC_CHUNK 1000000000L #endif /* * This routine computes the total space still available for allocation by * jpeg_get_large. If more space than this is needed, backing store will be * used. NOTE: any memory already allocated must not be counted. * * There is a minimum space requirement, corresponding to the minimum * feasible buffer sizes; jmemmgr.c will request that much space even if * jpeg_mem_available returns zero. The maximum space needed, enough to hold * all working storage in memory, is also passed in case it is useful. * Finally, the total space already allocated is passed. If no better * method is available, cinfo->mem->max_memory_to_use - already_allocated * is often a suitable calculation. * * It is OK for jpeg_mem_available to underestimate the space available * (that'll just lead to more backing-store access than is really necessary). * However, an overestimate will lead to failure. Hence it's wise to subtract * a slop factor from the true available space. 5% should be enough. * * On machines with lots of virtual memory, any large constant may be returned. * Conversely, zero may be returned to always use the minimum amount of memory. */ EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo, long min_bytes_needed, long max_bytes_needed, long already_allocated)); /* * This structure holds whatever state is needed to access a single * backing-store object. The read/write/close method pointers are called * by jmemmgr.c to manipulate the backing-store object; all other fields * are private to the system-dependent backing store routines. */ #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */ #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */ typedef unsigned short XMSH; /* type of extended-memory handles */ typedef unsigned short EMSH; /* type of expanded-memory handles */ typedef union { short file_handle; /* DOS file handle if it's a temp file */ XMSH xms_handle; /* handle if it's a chunk of XMS */ EMSH ems_handle; /* handle if it's a chunk of EMS */ } handle_union; #endif /* USE_MSDOS_MEMMGR */ #ifdef USE_MAC_MEMMGR /* Mac-specific junk */ #include #endif /* USE_MAC_MEMMGR */ typedef struct backing_store_struct * backing_store_ptr; typedef struct backing_store_struct { /* Methods for reading/writing/closing this backing-store object */ JMETHOD(void, read_backing_store, (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count)); JMETHOD(void, write_backing_store, (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count)); JMETHOD(void, close_backing_store, (j_common_ptr cinfo, backing_store_ptr info)); /* Private fields for system-dependent backing-store management */ #ifdef USE_MSDOS_MEMMGR /* For the MS-DOS manager (jmemdos.c), we need: */ handle_union handle; /* reference to backing-store storage object */ char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */ #else #ifdef USE_MAC_MEMMGR /* For the Mac manager (jmemmac.c), we need: */ short temp_file; /* file reference number to temp file */ FSSpec tempSpec; /* the FSSpec for the temp file */ char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */ #else /* For a typical implementation with temp files, we need: */ FILE * temp_file; /* stdio reference to temp file */ char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */ #endif #endif } backing_store_info; /* * Initial opening of a backing-store object. This must fill in the * read/write/close pointers in the object. The read/write routines * may take an error exit if the specified maximum file size is exceeded. * (If jpeg_mem_available always returns a large value, this routine can * just take an error exit.) */ EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed)); /* * These routines take care of any system-dependent initialization and * cleanup required. jpeg_mem_init will be called before anything is * allocated (and, therefore, nothing in cinfo is of use except the error * manager pointer). It should return a suitable default value for * max_memory_to_use; this may subsequently be overridden by the surrounding * application. (Note that max_memory_to_use is only important if * jpeg_mem_available chooses to consult it ... no one else will.) * jpeg_mem_term may assume that all requested memory has been freed and that * all opened backing-store objects have been closed. */ EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo)); EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo)); ================================================ FILE: tess-two/jni/libjpeg/jmorecfg.h ================================================ /* * jmorecfg.h * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 1997-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains additional configuration options that customize the * JPEG software for special applications or support machine-dependent * optimizations. Most users will not need to touch this file. */ /* * Define BITS_IN_JSAMPLE as either * 8 for 8-bit sample values (the usual setting) * 9 for 9-bit sample values * 10 for 10-bit sample values * 11 for 11-bit sample values * 12 for 12-bit sample values * Only 8, 9, 10, 11, and 12 bits sample data precision are supported for * full-feature DCT processing. Further depths up to 16-bit may be added * later for the lossless modes of operation. * Run-time selection and conversion of data precision will be added later * and are currently not supported, sorry. * Exception: The transcoding part (jpegtran) supports all settings in a * single instance, since it operates on the level of DCT coefficients and * not sample values. The DCT coefficients are of the same type (16 bits) * in all cases (see below). */ #define BITS_IN_JSAMPLE 8 /* use 8, 9, 10, 11, or 12 */ /* * Maximum number of components (color channels) allowed in JPEG image. * To meet the letter of the JPEG spec, set this to 255. However, darn * few applications need more than 4 channels (maybe 5 for CMYK + alpha * mask). We recommend 10 as a reasonable compromise; use 4 if you are * really short on memory. (Each allowed component costs a hundred or so * bytes of storage, whether actually used in an image or not.) */ #define MAX_COMPONENTS 10 /* maximum number of image components */ /* * Basic data types. * You may need to change these if you have a machine with unusual data * type sizes; for example, "char" not 8 bits, "short" not 16 bits, * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits, * but it had better be at least 16. */ /* Representation of a single sample (pixel element value). * We frequently allocate large arrays of these, so it's important to keep * them small. But if you have memory to burn and access to char or short * arrays is very slow on your hardware, you might want to change these. */ #if BITS_IN_JSAMPLE == 8 /* JSAMPLE should be the smallest type that will hold the values 0..255. * You can use a signed char by having GETJSAMPLE mask it with 0xFF. */ #ifdef HAVE_UNSIGNED_CHAR typedef unsigned char JSAMPLE; #define GETJSAMPLE(value) ((int) (value)) #else /* not HAVE_UNSIGNED_CHAR */ typedef char JSAMPLE; #ifdef CHAR_IS_UNSIGNED #define GETJSAMPLE(value) ((int) (value)) #else #define GETJSAMPLE(value) ((int) (value) & 0xFF) #endif /* CHAR_IS_UNSIGNED */ #endif /* HAVE_UNSIGNED_CHAR */ #define MAXJSAMPLE 255 #define CENTERJSAMPLE 128 #endif /* BITS_IN_JSAMPLE == 8 */ #if BITS_IN_JSAMPLE == 9 /* JSAMPLE should be the smallest type that will hold the values 0..511. * On nearly all machines "short" will do nicely. */ typedef short JSAMPLE; #define GETJSAMPLE(value) ((int) (value)) #define MAXJSAMPLE 511 #define CENTERJSAMPLE 256 #endif /* BITS_IN_JSAMPLE == 9 */ #if BITS_IN_JSAMPLE == 10 /* JSAMPLE should be the smallest type that will hold the values 0..1023. * On nearly all machines "short" will do nicely. */ typedef short JSAMPLE; #define GETJSAMPLE(value) ((int) (value)) #define MAXJSAMPLE 1023 #define CENTERJSAMPLE 512 #endif /* BITS_IN_JSAMPLE == 10 */ #if BITS_IN_JSAMPLE == 11 /* JSAMPLE should be the smallest type that will hold the values 0..2047. * On nearly all machines "short" will do nicely. */ typedef short JSAMPLE; #define GETJSAMPLE(value) ((int) (value)) #define MAXJSAMPLE 2047 #define CENTERJSAMPLE 1024 #endif /* BITS_IN_JSAMPLE == 11 */ #if BITS_IN_JSAMPLE == 12 /* JSAMPLE should be the smallest type that will hold the values 0..4095. * On nearly all machines "short" will do nicely. */ typedef short JSAMPLE; #define GETJSAMPLE(value) ((int) (value)) #define MAXJSAMPLE 4095 #define CENTERJSAMPLE 2048 #endif /* BITS_IN_JSAMPLE == 12 */ /* Representation of a DCT frequency coefficient. * This should be a signed value of at least 16 bits; "short" is usually OK. * Again, we allocate large arrays of these, but you can change to int * if you have memory to burn and "short" is really slow. */ typedef short JCOEF; /* Compressed datastreams are represented as arrays of JOCTET. * These must be EXACTLY 8 bits wide, at least once they are written to * external storage. Note that when using the stdio data source/destination * managers, this is also the data type passed to fread/fwrite. */ #ifdef HAVE_UNSIGNED_CHAR typedef unsigned char JOCTET; #define GETJOCTET(value) (value) #else /* not HAVE_UNSIGNED_CHAR */ typedef char JOCTET; #ifdef CHAR_IS_UNSIGNED #define GETJOCTET(value) (value) #else #define GETJOCTET(value) ((value) & 0xFF) #endif /* CHAR_IS_UNSIGNED */ #endif /* HAVE_UNSIGNED_CHAR */ /* These typedefs are used for various table entries and so forth. * They must be at least as wide as specified; but making them too big * won't cost a huge amount of memory, so we don't provide special * extraction code like we did for JSAMPLE. (In other words, these * typedefs live at a different point on the speed/space tradeoff curve.) */ /* UINT8 must hold at least the values 0..255. */ #ifdef HAVE_UNSIGNED_CHAR typedef unsigned char UINT8; #else /* not HAVE_UNSIGNED_CHAR */ #ifdef CHAR_IS_UNSIGNED typedef char UINT8; #else /* not CHAR_IS_UNSIGNED */ typedef short UINT8; #endif /* CHAR_IS_UNSIGNED */ #endif /* HAVE_UNSIGNED_CHAR */ /* UINT16 must hold at least the values 0..65535. */ #ifdef HAVE_UNSIGNED_SHORT typedef unsigned short UINT16; #else /* not HAVE_UNSIGNED_SHORT */ typedef unsigned int UINT16; #endif /* HAVE_UNSIGNED_SHORT */ /* INT16 must hold at least the values -32768..32767. */ #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */ typedef short INT16; #endif /* INT32 must hold at least signed 32-bit values. */ #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */ #ifndef _BASETSD_H_ /* Microsoft defines it in basetsd.h */ #ifndef _BASETSD_H /* MinGW is slightly different */ #ifndef QGLOBAL_H /* Qt defines it in qglobal.h */ typedef long INT32; #endif #endif #endif #endif /* Datatype used for image dimensions. The JPEG standard only supports * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore * "unsigned int" is sufficient on all machines. However, if you need to * handle larger images and you don't mind deviating from the spec, you * can change this datatype. */ typedef unsigned int JDIMENSION; #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */ /* These macros are used in all function definitions and extern declarations. * You could modify them if you need to change function linkage conventions; * in particular, you'll need to do that to make the library a Windows DLL. * Another application is to make all functions global for use with debuggers * or code profilers that require it. */ /* a function called through method pointers: */ #define METHODDEF(type) static type /* a function used only in its module: */ #define LOCAL(type) static type /* a function referenced thru EXTERNs: */ #define GLOBAL(type) type /* a reference to a GLOBAL function: */ #define EXTERN(type) extern type /* This macro is used to declare a "method", that is, a function pointer. * We want to supply prototype parameters if the compiler can cope. * Note that the arglist parameter must be parenthesized! * Again, you can customize this if you need special linkage keywords. */ #ifdef HAVE_PROTOTYPES #define JMETHOD(type,methodname,arglist) type (*methodname) arglist #else #define JMETHOD(type,methodname,arglist) type (*methodname) () #endif /* The noreturn type identifier is used to declare functions * which cannot return. * Compilers can thus create more optimized code and perform * better checks for warnings and errors. * Static analyzer tools can make improved inferences about * execution paths and are prevented from giving false alerts. * * Unfortunately, the proposed specifications of corresponding * extensions in the Dec 2011 ISO C standard revision (C11), * GCC, MSVC, etc. are not viable. * Thus we introduce a user defined type to declare noreturn * functions at least for clarity. A proper compiler would * have a suitable noreturn type to match in place of void. */ #ifndef HAVE_NORETURN_T typedef void noreturn_t; #endif /* Here is the pseudo-keyword for declaring pointers that must be "far" * on 80x86 machines. Most of the specialized coding for 80x86 is handled * by just saying "FAR *" where such a pointer is needed. In a few places * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol. */ #ifndef FAR #ifdef NEED_FAR_POINTERS #define FAR far #else #define FAR #endif #endif /* * On a few systems, type boolean and/or its values FALSE, TRUE may appear * in standard header files. Or you may have conflicts with application- * specific header files that you want to include together with these files. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work. */ #ifndef HAVE_BOOLEAN #if defined FALSE || defined TRUE || defined QGLOBAL_H /* Qt3 defines FALSE and TRUE as "const" variables in qglobal.h */ typedef int boolean; #ifndef FALSE /* in case these macros already exist */ #define FALSE 0 /* values of boolean */ #endif #ifndef TRUE #define TRUE 1 #endif #else typedef enum { FALSE = 0, TRUE = 1 } boolean; #endif #endif /* * The remaining options affect code selection within the JPEG library, * but they don't need to be visible to most applications using the library. * To minimize application namespace pollution, the symbols won't be * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined. */ #ifdef JPEG_INTERNALS #define JPEG_INTERNAL_OPTIONS #endif #ifdef JPEG_INTERNAL_OPTIONS /* * These defines indicate whether to include various optional functions. * Undefining some of these symbols will produce a smaller but less capable * library. Note that you can leave certain source files out of the * compilation/linking process if you've #undef'd the corresponding symbols. * (You may HAVE to do that if your compiler doesn't like null source files.) */ /* Capability options common to encoder and decoder: */ #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */ #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */ #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */ /* Encoder capability options: */ #define C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ #define DCT_SCALING_SUPPORTED /* Input rescaling via DCT? (Requires DCT_ISLOW)*/ #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */ /* Note: if you selected more than 8-bit data precision, it is dangerous to * turn off ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only * good for 8-bit precision, so arithmetic coding is recommended for higher * precision. The Huffman encoder normally uses entropy optimization to * compute usable tables for higher precision. Otherwise, you'll have to * supply different default Huffman tables. * The exact same statements apply for progressive JPEG: the default tables * don't work for progressive mode. (This may get fixed, however.) */ #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */ /* Decoder capability options: */ #define D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? (Requires DCT_ISLOW)*/ #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */ #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */ #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */ #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */ #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */ #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */ /* more capability options later, no doubt */ /* * Ordering of RGB data in scanlines passed to or from the application. * If your application wants to deal with data in the order B,G,R, just * change these macros. You can also deal with formats such as R,G,B,X * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing * the offsets will also change the order in which colormap data is organized. * RESTRICTIONS: * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats. * 2. The color quantizer modules will not behave desirably if RGB_PIXELSIZE * is not 3 (they don't understand about dummy color components!). So you * can't use color quantization if you change that value. */ #define RGB_RED 0 /* Offset of Red in an RGB scanline element */ #define RGB_GREEN 1 /* Offset of Green */ #define RGB_BLUE 2 /* Offset of Blue */ #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */ /* Definitions for speed-related optimizations. */ /* If your compiler supports inline functions, define INLINE * as the inline keyword; otherwise define it as empty. */ #ifndef INLINE #ifdef __GNUC__ /* for instance, GNU C knows about inline */ #define INLINE __inline__ #endif #ifndef INLINE #define INLINE /* default is to define it as empty */ #endif #endif /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER * as short on such a machine. MULTIPLIER must be at least 16 bits wide. */ #ifndef MULTIPLIER #define MULTIPLIER int /* type for fastest integer multiply */ #endif /* FAST_FLOAT should be either float or double, whichever is done faster * by your compiler. (Note that this type is only used in the floating point * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.) * Typically, float is faster in ANSI C compilers, while double is faster in * pre-ANSI compilers (because they insist on converting to double anyway). * The code below therefore chooses float if we have ANSI-style prototypes. */ #ifndef FAST_FLOAT #ifdef HAVE_PROTOTYPES #define FAST_FLOAT float #else #define FAST_FLOAT double #endif #endif #endif /* JPEG_INTERNAL_OPTIONS */ ================================================ FILE: tess-two/jni/libjpeg/jpegint.h ================================================ /* * jpegint.h * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 1997-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file provides common declarations for the various JPEG modules. * These declarations are considered internal to the JPEG library; most * applications using the library shouldn't need to include this file. */ /* Declarations for both compression & decompression */ typedef enum { /* Operating modes for buffer controllers */ JBUF_PASS_THRU, /* Plain stripwise operation */ /* Remaining modes require a full-image buffer to have been created */ JBUF_SAVE_SOURCE, /* Run source subobject only, save output */ JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */ JBUF_SAVE_AND_PASS /* Run both subobjects, save output */ } J_BUF_MODE; /* Values of global_state field (jdapi.c has some dependencies on ordering!) */ #define CSTATE_START 100 /* after create_compress */ #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */ #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */ #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */ #define DSTATE_START 200 /* after create_decompress */ #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */ #define DSTATE_READY 202 /* found SOS, ready for start_decompress */ #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/ #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */ #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */ #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */ #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */ #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */ #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */ #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */ /* Declarations for compression modules */ /* Master control module */ struct jpeg_comp_master { JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo)); JMETHOD(void, pass_startup, (j_compress_ptr cinfo)); JMETHOD(void, finish_pass, (j_compress_ptr cinfo)); /* State variables made visible to other modules */ boolean call_pass_startup; /* True if pass_startup must be called */ boolean is_last_pass; /* True during last pass */ }; /* Main buffer control (downsampled-data buffer) */ struct jpeg_c_main_controller { JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode)); JMETHOD(void, process_data, (j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail)); }; /* Compression preprocessing (downsampling input buffer control) */ struct jpeg_c_prep_controller { JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode)); JMETHOD(void, pre_process_data, (j_compress_ptr cinfo, JSAMPARRAY input_buf, JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail, JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr, JDIMENSION out_row_groups_avail)); }; /* Coefficient buffer control */ struct jpeg_c_coef_controller { JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode)); JMETHOD(boolean, compress_data, (j_compress_ptr cinfo, JSAMPIMAGE input_buf)); }; /* Colorspace conversion */ struct jpeg_color_converter { JMETHOD(void, start_pass, (j_compress_ptr cinfo)); JMETHOD(void, color_convert, (j_compress_ptr cinfo, JSAMPARRAY input_buf, JSAMPIMAGE output_buf, JDIMENSION output_row, int num_rows)); }; /* Downsampling */ struct jpeg_downsampler { JMETHOD(void, start_pass, (j_compress_ptr cinfo)); JMETHOD(void, downsample, (j_compress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION in_row_index, JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)); boolean need_context_rows; /* TRUE if need rows above & below */ }; /* Forward DCT (also controls coefficient quantization) */ typedef JMETHOD(void, forward_DCT_ptr, (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY sample_data, JBLOCKROW coef_blocks, JDIMENSION start_row, JDIMENSION start_col, JDIMENSION num_blocks)); struct jpeg_forward_dct { JMETHOD(void, start_pass, (j_compress_ptr cinfo)); /* It is useful to allow each component to have a separate FDCT method. */ forward_DCT_ptr forward_DCT[MAX_COMPONENTS]; }; /* Entropy encoding */ struct jpeg_entropy_encoder { JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics)); JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data)); JMETHOD(void, finish_pass, (j_compress_ptr cinfo)); }; /* Marker writing */ struct jpeg_marker_writer { JMETHOD(void, write_file_header, (j_compress_ptr cinfo)); JMETHOD(void, write_frame_header, (j_compress_ptr cinfo)); JMETHOD(void, write_scan_header, (j_compress_ptr cinfo)); JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo)); JMETHOD(void, write_tables_only, (j_compress_ptr cinfo)); /* These routines are exported to allow insertion of extra markers */ /* Probably only COM and APPn markers should be written this way */ JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker, unsigned int datalen)); JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val)); }; /* Declarations for decompression modules */ /* Master control module */ struct jpeg_decomp_master { JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo)); JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo)); /* State variables made visible to other modules */ boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */ }; /* Input control module */ struct jpeg_input_controller { JMETHOD(int, consume_input, (j_decompress_ptr cinfo)); JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo)); JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo)); JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo)); /* State variables made visible to other modules */ boolean has_multiple_scans; /* True if file has multiple scans */ boolean eoi_reached; /* True when EOI has been consumed */ }; /* Main buffer control (downsampled-data buffer) */ struct jpeg_d_main_controller { JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); JMETHOD(void, process_data, (j_decompress_ptr cinfo, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); }; /* Coefficient buffer control */ struct jpeg_d_coef_controller { JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo)); JMETHOD(int, consume_data, (j_decompress_ptr cinfo)); JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo)); JMETHOD(int, decompress_data, (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); /* Pointer to array of coefficient virtual arrays, or NULL if none */ jvirt_barray_ptr *coef_arrays; }; /* Decompression postprocessing (color quantization buffer control) */ struct jpeg_d_post_controller { JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); JMETHOD(void, post_process_data, (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); }; /* Marker reading & parsing */ struct jpeg_marker_reader { JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo)); /* Read markers until SOS or EOI. * Returns same codes as are defined for jpeg_consume_input: * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. */ JMETHOD(int, read_markers, (j_decompress_ptr cinfo)); /* Read a restart marker --- exported for use by entropy decoder only */ jpeg_marker_parser_method read_restart_marker; /* State of marker reader --- nominally internal, but applications * supplying COM or APPn handlers might like to know the state. */ boolean saw_SOI; /* found SOI? */ boolean saw_SOF; /* found SOF? */ int next_restart_num; /* next restart number expected (0-7) */ unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */ }; /* Entropy decoding */ struct jpeg_entropy_decoder { JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)); JMETHOD(void, finish_pass, (j_decompress_ptr cinfo)); }; /* Inverse DCT (also performs dequantization) */ typedef JMETHOD(void, inverse_DCT_method_ptr, (j_decompress_ptr cinfo, jpeg_component_info * compptr, JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col)); struct jpeg_inverse_dct { JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); /* It is useful to allow each component to have a separate IDCT method. */ inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS]; }; /* Upsampling (note that upsampler must also call color converter) */ struct jpeg_upsampler { JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); JMETHOD(void, upsample, (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)); boolean need_context_rows; /* TRUE if need rows above & below */ }; /* Colorspace conversion */ struct jpeg_color_deconverter { JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); JMETHOD(void, color_convert, (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows)); }; /* Color quantization or color precision reduction */ struct jpeg_color_quantizer { JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan)); JMETHOD(void, color_quantize, (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)); JMETHOD(void, finish_pass, (j_decompress_ptr cinfo)); JMETHOD(void, new_color_map, (j_decompress_ptr cinfo)); }; /* Miscellaneous useful macros */ #undef MAX #define MAX(a,b) ((a) > (b) ? (a) : (b)) #undef MIN #define MIN(a,b) ((a) < (b) ? (a) : (b)) /* We assume that right shift corresponds to signed division by 2 with * rounding towards minus infinity. This is correct for typical "arithmetic * shift" instructions that shift in copies of the sign bit. But some * C compilers implement >> with an unsigned shift. For these machines you * must define RIGHT_SHIFT_IS_UNSIGNED. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity. * It is only applied with constant shift counts. SHIFT_TEMPS must be * included in the variables of any routine using RIGHT_SHIFT. */ #ifdef RIGHT_SHIFT_IS_UNSIGNED #define SHIFT_TEMPS INT32 shift_temp; #define RIGHT_SHIFT(x,shft) \ ((shift_temp = (x)) < 0 ? \ (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \ (shift_temp >> (shft))) #else #define SHIFT_TEMPS #define RIGHT_SHIFT(x,shft) ((x) >> (shft)) #endif /* Short forms of external names for systems with brain-damaged linkers. */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jinit_compress_master jICompress #define jinit_c_master_control jICMaster #define jinit_c_main_controller jICMainC #define jinit_c_prep_controller jICPrepC #define jinit_c_coef_controller jICCoefC #define jinit_color_converter jICColor #define jinit_downsampler jIDownsampler #define jinit_forward_dct jIFDCT #define jinit_huff_encoder jIHEncoder #define jinit_arith_encoder jIAEncoder #define jinit_marker_writer jIMWriter #define jinit_master_decompress jIDMaster #define jinit_d_main_controller jIDMainC #define jinit_d_coef_controller jIDCoefC #define jinit_d_post_controller jIDPostC #define jinit_input_controller jIInCtlr #define jinit_marker_reader jIMReader #define jinit_huff_decoder jIHDecoder #define jinit_arith_decoder jIADecoder #define jinit_inverse_dct jIIDCT #define jinit_upsampler jIUpsampler #define jinit_color_deconverter jIDColor #define jinit_1pass_quantizer jI1Quant #define jinit_2pass_quantizer jI2Quant #define jinit_merged_upsampler jIMUpsampler #define jinit_memory_mgr jIMemMgr #define jdiv_round_up jDivRound #define jround_up jRound #define jzero_far jZeroFar #define jcopy_sample_rows jCopySamples #define jcopy_block_row jCopyBlocks #define jpeg_zigzag_order jZIGTable #define jpeg_natural_order jZAGTable #define jpeg_natural_order7 jZAG7Table #define jpeg_natural_order6 jZAG6Table #define jpeg_natural_order5 jZAG5Table #define jpeg_natural_order4 jZAG4Table #define jpeg_natural_order3 jZAG3Table #define jpeg_natural_order2 jZAG2Table #define jpeg_aritab jAriTab #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays * and coefficient-block arrays. This won't work on 80x86 because the arrays * are FAR and we're assuming a small-pointer memory model. However, some * DOS compilers provide far-pointer versions of memcpy() and memset() even * in the small-model libraries. These will be used if USE_FMEM is defined. * Otherwise, the routines in jutils.c do it the hard way. */ #ifndef NEED_FAR_POINTERS /* normal case, same as regular macro */ #define FMEMZERO(target,size) MEMZERO(target,size) #else /* 80x86 case */ #ifdef USE_FMEM #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size)) #else EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero)); #define FMEMZERO(target,size) jzero_far(target, size) #endif #endif /* Compression module initialization routines */ EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo)); EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo, boolean transcode_only)); EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo, boolean need_full_buffer)); EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo, boolean need_full_buffer)); EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo, boolean need_full_buffer)); EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo)); EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo)); EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo)); EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo)); EXTERN(void) jinit_arith_encoder JPP((j_compress_ptr cinfo)); EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo)); /* Decompression module initialization routines */ EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo, boolean need_full_buffer)); EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo, boolean need_full_buffer)); EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo, boolean need_full_buffer)); EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_arith_decoder JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo)); EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo)); /* Memory manager initialization */ EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo)); /* Utility routines in jutils.c */ EXTERN(long) jdiv_round_up JPP((long a, long b)); EXTERN(long) jround_up JPP((long a, long b)); EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row, JSAMPARRAY output_array, int dest_row, int num_rows, JDIMENSION num_cols)); EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row, JDIMENSION num_blocks)); /* Constant tables in jutils.c */ #if 0 /* This table is not actually needed in v6a */ extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */ #endif extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */ extern const int jpeg_natural_order7[]; /* zz to natural order for 7x7 block */ extern const int jpeg_natural_order6[]; /* zz to natural order for 6x6 block */ extern const int jpeg_natural_order5[]; /* zz to natural order for 5x5 block */ extern const int jpeg_natural_order4[]; /* zz to natural order for 4x4 block */ extern const int jpeg_natural_order3[]; /* zz to natural order for 3x3 block */ extern const int jpeg_natural_order2[]; /* zz to natural order for 2x2 block */ /* Arithmetic coding probability estimation tables in jaricom.c */ extern const INT32 jpeg_aritab[]; /* Suppress undefined-structure complaints if necessary. */ #ifdef INCOMPLETE_TYPES_BROKEN #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */ struct jvirt_sarray_control { long dummy; }; struct jvirt_barray_control { long dummy; }; #endif #endif /* INCOMPLETE_TYPES_BROKEN */ ================================================ FILE: tess-two/jni/libjpeg/jpeglib.h ================================================ /* * jpeglib.h * * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2002-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file defines the application interface for the JPEG library. * Most applications using the library need only include this file, * and perhaps jerror.h if they want to know the exact error codes. */ #ifndef JPEGLIB_H #define JPEGLIB_H /* * First we include the configuration files that record how this * installation of the JPEG library is set up. jconfig.h can be * generated automatically for many systems. jmorecfg.h contains * manual configuration options that most people need not worry about. */ #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ #include "jconfig.h" /* widely used configuration options */ #endif #include "jmorecfg.h" /* seldom changed options */ #ifdef __cplusplus #ifndef DONT_USE_EXTERN_C extern "C" { #endif #endif /* Version IDs for the JPEG library. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 90". */ #define JPEG_LIB_VERSION 90 /* Compatibility version 9.0 */ #define JPEG_LIB_VERSION_MAJOR 9 #define JPEG_LIB_VERSION_MINOR 2 /* Various constants determining the sizes of things. * All of these are specified by the JPEG standard, * so don't change them if you want to be compatible. */ #define DCTSIZE 8 /* The basic DCT block is 8x8 coefficients */ #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU * to handle it. We even let you do this from the jconfig.h file. However, * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe * sometimes emits noncompliant files doesn't mean you should too. */ #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ #ifndef D_MAX_BLOCKS_IN_MCU #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ #endif /* Data structures for images (arrays of samples and of DCT coefficients). * On 80x86 machines, the image arrays are too big for near pointers, * but the pointer arrays can fit in near memory. */ typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */ typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */ typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */ /* Types for JPEG compression parameters and working tables. */ /* DCT coefficient quantization tables. */ typedef struct { /* This array gives the coefficient quantizers in natural array order * (not the zigzag order in which they are stored in a JPEG DQT marker). * CAUTION: IJG versions prior to v6a kept this array in zigzag order. */ UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ /* This field is used only during compression. It's initialized FALSE when * the table is created, and set TRUE when it's been output to the file. * You could suppress output of a table by setting this to TRUE. * (See jpeg_suppress_tables for an example.) */ boolean sent_table; /* TRUE when table has been output */ } JQUANT_TBL; /* Huffman coding tables. */ typedef struct { /* These two fields directly represent the contents of a JPEG DHT marker */ UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ /* length k bits; bits[0] is unused */ UINT8 huffval[256]; /* The symbols, in order of incr code length */ /* This field is used only during compression. It's initialized FALSE when * the table is created, and set TRUE when it's been output to the file. * You could suppress output of a table by setting this to TRUE. * (See jpeg_suppress_tables for an example.) */ boolean sent_table; /* TRUE when table has been output */ } JHUFF_TBL; /* Basic info about one component (color channel). */ typedef struct { /* These values are fixed over the whole image. */ /* For compression, they must be supplied by parameter setup; */ /* for decompression, they are read from the SOF marker. */ int component_id; /* identifier for this component (0..255) */ int component_index; /* its index in SOF or cinfo->comp_info[] */ int h_samp_factor; /* horizontal sampling factor (1..4) */ int v_samp_factor; /* vertical sampling factor (1..4) */ int quant_tbl_no; /* quantization table selector (0..3) */ /* These values may vary between scans. */ /* For compression, they must be supplied by parameter setup; */ /* for decompression, they are read from the SOS marker. */ /* The decompressor output side may not use these variables. */ int dc_tbl_no; /* DC entropy table selector (0..3) */ int ac_tbl_no; /* AC entropy table selector (0..3) */ /* Remaining fields should be treated as private by applications. */ /* These values are computed during compression or decompression startup: */ /* Component's size in DCT blocks. * Any dummy blocks added to complete an MCU are not counted; therefore * these values do not depend on whether a scan is interleaved or not. */ JDIMENSION width_in_blocks; JDIMENSION height_in_blocks; /* Size of a DCT block in samples, * reflecting any scaling we choose to apply during the DCT step. * Values from 1 to 16 are supported. * Note that different components may receive different DCT scalings. */ int DCT_h_scaled_size; int DCT_v_scaled_size; /* The downsampled dimensions are the component's actual, unpadded number * of samples at the main buffer (preprocessing/compression interface); * DCT scaling is included, so * downsampled_width = * ceil(image_width * Hi/Hmax * DCT_h_scaled_size/block_size) * and similarly for height. */ JDIMENSION downsampled_width; /* actual width in samples */ JDIMENSION downsampled_height; /* actual height in samples */ /* For decompression, in cases where some of the components will be * ignored (eg grayscale output from YCbCr image), we can skip most * computations for the unused components. * For compression, some of the components will need further quantization * scale by factor of 2 after DCT (eg BG_YCC output from normal RGB input). * The field is first set TRUE for decompression, FALSE for compression * in initial_setup, and then adapted in color conversion setup. */ boolean component_needed; /* These values are computed before starting a scan of the component. */ /* The decompressor output side may not use these variables. */ int MCU_width; /* number of blocks per MCU, horizontally */ int MCU_height; /* number of blocks per MCU, vertically */ int MCU_blocks; /* MCU_width * MCU_height */ int MCU_sample_width; /* MCU width in samples: MCU_width * DCT_h_scaled_size */ int last_col_width; /* # of non-dummy blocks across in last MCU */ int last_row_height; /* # of non-dummy blocks down in last MCU */ /* Saved quantization table for component; NULL if none yet saved. * See jdinput.c comments about the need for this information. * This field is currently used only for decompression. */ JQUANT_TBL * quant_table; /* Private per-component storage for DCT or IDCT subsystem. */ void * dct_table; } jpeg_component_info; /* The script for encoding a multiple-scan file is an array of these: */ typedef struct { int comps_in_scan; /* number of components encoded in this scan */ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ int Ss, Se; /* progressive JPEG spectral selection parms */ int Ah, Al; /* progressive JPEG successive approx. parms */ } jpeg_scan_info; /* The decompressor can save APPn and COM markers in a list of these: */ typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr; struct jpeg_marker_struct { jpeg_saved_marker_ptr next; /* next in list, or NULL */ UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */ unsigned int original_length; /* # bytes of data in the file */ unsigned int data_length; /* # bytes of data saved at data[] */ JOCTET FAR * data; /* the data contained in the marker */ /* the marker length word is not counted in data_length or original_length */ }; /* Known color spaces. */ typedef enum { JCS_UNKNOWN, /* error/unspecified */ JCS_GRAYSCALE, /* monochrome */ JCS_RGB, /* red/green/blue, standard RGB (sRGB) */ JCS_YCbCr, /* Y/Cb/Cr (also known as YUV), standard YCC */ JCS_CMYK, /* C/M/Y/K */ JCS_YCCK, /* Y/Cb/Cr/K */ JCS_BG_RGB, /* big gamut red/green/blue, bg-sRGB */ JCS_BG_YCC /* big gamut Y/Cb/Cr, bg-sYCC */ } J_COLOR_SPACE; /* Supported color transforms. */ typedef enum { JCT_NONE = 0, JCT_SUBTRACT_GREEN = 1 } J_COLOR_TRANSFORM; /* DCT/IDCT algorithm options. */ typedef enum { JDCT_ISLOW, /* slow but accurate integer algorithm */ JDCT_IFAST, /* faster, less accurate integer method */ JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ } J_DCT_METHOD; #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ #define JDCT_DEFAULT JDCT_ISLOW #endif #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ #define JDCT_FASTEST JDCT_IFAST #endif /* Dithering options for decompression. */ typedef enum { JDITHER_NONE, /* no dithering */ JDITHER_ORDERED, /* simple ordered dither */ JDITHER_FS /* Floyd-Steinberg error diffusion dither */ } J_DITHER_MODE; /* Common fields between JPEG compression and decompression master structs. */ #define jpeg_common_fields \ struct jpeg_error_mgr * err; /* Error handler module */\ struct jpeg_memory_mgr * mem; /* Memory manager module */\ struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\ void * client_data; /* Available for use by application */\ boolean is_decompressor; /* So common code can tell which is which */\ int global_state /* For checking call sequence validity */ /* Routines that are to be used by both halves of the library are declared * to receive a pointer to this structure. There are no actual instances of * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. */ struct jpeg_common_struct { jpeg_common_fields; /* Fields common to both master struct types */ /* Additional fields follow in an actual jpeg_compress_struct or * jpeg_decompress_struct. All three structs must agree on these * initial fields! (This would be a lot cleaner in C++.) */ }; typedef struct jpeg_common_struct * j_common_ptr; typedef struct jpeg_compress_struct * j_compress_ptr; typedef struct jpeg_decompress_struct * j_decompress_ptr; /* Master record for a compression instance */ struct jpeg_compress_struct { jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ /* Destination for compressed data */ struct jpeg_destination_mgr * dest; /* Description of source image --- these fields must be filled in by * outer application before starting compression. in_color_space must * be correct before you can even call jpeg_set_defaults(). */ JDIMENSION image_width; /* input image width */ JDIMENSION image_height; /* input image height */ int input_components; /* # of color components in input image */ J_COLOR_SPACE in_color_space; /* colorspace of input image */ double input_gamma; /* image gamma of input image */ /* Compression parameters --- these fields must be set before calling * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to * initialize everything to reasonable defaults, then changing anything * the application specifically wants to change. That way you won't get * burnt when new parameters are added. Also note that there are several * helper routines to simplify changing parameters. */ unsigned int scale_num, scale_denom; /* fraction by which to scale image */ JDIMENSION jpeg_width; /* scaled JPEG image width */ JDIMENSION jpeg_height; /* scaled JPEG image height */ /* Dimensions of actual JPEG image that will be written to file, * derived from input dimensions by scaling factors above. * These fields are computed by jpeg_start_compress(). * You can also use jpeg_calc_jpeg_dimensions() to determine these values * in advance of calling jpeg_start_compress(). */ int data_precision; /* bits of precision in image data */ int num_components; /* # of color components in JPEG image */ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ jpeg_component_info * comp_info; /* comp_info[i] describes component that appears i'th in SOF */ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; int q_scale_factor[NUM_QUANT_TBLS]; /* ptrs to coefficient quantization tables, or NULL if not defined, * and corresponding scale factors (percentage, initialized 100). */ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; /* ptrs to Huffman coding tables, or NULL if not defined */ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ int num_scans; /* # of entries in scan_info array */ const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */ /* The default value of scan_info is NULL, which causes a single-scan * sequential JPEG file to be emitted. To create a multi-scan file, * set num_scans and scan_info to point to an array of scan definitions. */ boolean raw_data_in; /* TRUE=caller supplies downsampled data */ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ boolean CCIR601_sampling; /* TRUE=first samples are cosited */ boolean do_fancy_downsampling; /* TRUE=apply fancy downsampling */ int smoothing_factor; /* 1..100, or 0 for no input smoothing */ J_DCT_METHOD dct_method; /* DCT algorithm selector */ /* The restart interval can be specified in absolute MCUs by setting * restart_interval, or in MCU rows by setting restart_in_rows * (in which case the correct restart_interval will be figured * for each scan). */ unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ int restart_in_rows; /* if > 0, MCU rows per restart interval */ /* Parameters controlling emission of special markers. */ boolean write_JFIF_header; /* should a JFIF marker be written? */ UINT8 JFIF_major_version; /* What to write for the JFIF version number */ UINT8 JFIF_minor_version; /* These three values are not used by the JPEG code, merely copied */ /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ /* ratio is defined by X_density/Y_density even when density_unit=0. */ UINT8 density_unit; /* JFIF code for pixel size units */ UINT16 X_density; /* Horizontal pixel density */ UINT16 Y_density; /* Vertical pixel density */ boolean write_Adobe_marker; /* should an Adobe marker be written? */ J_COLOR_TRANSFORM color_transform; /* Color transform identifier, writes LSE marker if nonzero */ /* State variable: index of next scanline to be written to * jpeg_write_scanlines(). Application may use this to control its * processing loop, e.g., "while (next_scanline < image_height)". */ JDIMENSION next_scanline; /* 0 .. image_height-1 */ /* Remaining fields are known throughout compressor, but generally * should not be touched by a surrounding application. */ /* * These fields are computed during compression startup */ boolean progressive_mode; /* TRUE if scan script uses progressive mode */ int max_h_samp_factor; /* largest h_samp_factor */ int max_v_samp_factor; /* largest v_samp_factor */ int min_DCT_h_scaled_size; /* smallest DCT_h_scaled_size of any component */ int min_DCT_v_scaled_size; /* smallest DCT_v_scaled_size of any component */ JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ /* The coefficient controller receives data in units of MCU rows as defined * for fully interleaved scans (whether the JPEG file is interleaved or not). * There are v_samp_factor * DCTSIZE sample rows of each component in an * "iMCU" (interleaved MCU) row. */ /* * These fields are valid during any one scan. * They describe the components and MCUs actually appearing in the scan. */ int comps_in_scan; /* # of JPEG components in this scan */ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; /* *cur_comp_info[i] describes component that appears i'th in SOS */ JDIMENSION MCUs_per_row; /* # of MCUs across the image */ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ int blocks_in_MCU; /* # of DCT blocks per MCU */ int MCU_membership[C_MAX_BLOCKS_IN_MCU]; /* MCU_membership[i] is index in cur_comp_info of component owning */ /* i'th block in an MCU */ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ int block_size; /* the basic DCT block size: 1..16 */ const int * natural_order; /* natural-order position array */ int lim_Se; /* min( Se, DCTSIZE2-1 ) */ /* * Links to compression subobjects (methods and private variables of modules) */ struct jpeg_comp_master * master; struct jpeg_c_main_controller * main; struct jpeg_c_prep_controller * prep; struct jpeg_c_coef_controller * coef; struct jpeg_marker_writer * marker; struct jpeg_color_converter * cconvert; struct jpeg_downsampler * downsample; struct jpeg_forward_dct * fdct; struct jpeg_entropy_encoder * entropy; jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */ int script_space_size; }; /* Master record for a decompression instance */ struct jpeg_decompress_struct { jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ /* Source of compressed data */ struct jpeg_source_mgr * src; /* Basic description of image --- filled in by jpeg_read_header(). */ /* Application may inspect these values to decide how to process image. */ JDIMENSION image_width; /* nominal image width (from SOF marker) */ JDIMENSION image_height; /* nominal image height */ int num_components; /* # of color components in JPEG image */ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ /* Decompression processing parameters --- these fields must be set before * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes * them to default values. */ J_COLOR_SPACE out_color_space; /* colorspace for output */ unsigned int scale_num, scale_denom; /* fraction by which to scale image */ double output_gamma; /* image gamma wanted in output */ boolean buffered_image; /* TRUE=multiple output passes */ boolean raw_data_out; /* TRUE=downsampled data wanted */ J_DCT_METHOD dct_method; /* IDCT algorithm selector */ boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ boolean quantize_colors; /* TRUE=colormapped output wanted */ /* the following are ignored if not quantize_colors: */ J_DITHER_MODE dither_mode; /* type of color dithering to use */ boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ int desired_number_of_colors; /* max # colors to use in created colormap */ /* these are significant only in buffered-image mode: */ boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ boolean enable_external_quant;/* enable future use of external colormap */ boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ /* Description of actual output image that will be returned to application. * These fields are computed by jpeg_start_decompress(). * You can also use jpeg_calc_output_dimensions() to determine these values * in advance of calling jpeg_start_decompress(). */ JDIMENSION output_width; /* scaled image width */ JDIMENSION output_height; /* scaled image height */ int out_color_components; /* # of color components in out_color_space */ int output_components; /* # of color components returned */ /* output_components is 1 (a colormap index) when quantizing colors; * otherwise it equals out_color_components. */ int rec_outbuf_height; /* min recommended height of scanline buffer */ /* If the buffer passed to jpeg_read_scanlines() is less than this many rows * high, space and time will be wasted due to unnecessary data copying. * Usually rec_outbuf_height will be 1 or 2, at most 4. */ /* When quantizing colors, the output colormap is described by these fields. * The application can supply a colormap by setting colormap non-NULL before * calling jpeg_start_decompress; otherwise a colormap is created during * jpeg_start_decompress or jpeg_start_output. * The map has out_color_components rows and actual_number_of_colors columns. */ int actual_number_of_colors; /* number of entries in use */ JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ /* State variables: these variables indicate the progress of decompression. * The application may examine these but must not modify them. */ /* Row index of next scanline to be read from jpeg_read_scanlines(). * Application may use this to control its processing loop, e.g., * "while (output_scanline < output_height)". */ JDIMENSION output_scanline; /* 0 .. output_height-1 */ /* Current input scan number and number of iMCU rows completed in scan. * These indicate the progress of the decompressor input side. */ int input_scan_number; /* Number of SOS markers seen so far */ JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ /* The "output scan number" is the notional scan being displayed by the * output side. The decompressor will not allow output scan/row number * to get ahead of input scan/row, but it can fall arbitrarily far behind. */ int output_scan_number; /* Nominal scan number being displayed */ JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ /* Current progression status. coef_bits[c][i] indicates the precision * with which component c's DCT coefficient i (in zigzag order) is known. * It is -1 when no data has yet been received, otherwise it is the point * transform (shift) value for the most recent scan of the coefficient * (thus, 0 at completion of the progression). * This pointer is NULL when reading a non-progressive file. */ int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ /* Internal JPEG parameters --- the application usually need not look at * these fields. Note that the decompressor output side may not use * any parameters that can change between scans. */ /* Quantization and Huffman tables are carried forward across input * datastreams when processing abbreviated JPEG datastreams. */ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; /* ptrs to coefficient quantization tables, or NULL if not defined */ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; /* ptrs to Huffman coding tables, or NULL if not defined */ /* These parameters are never carried across datastreams, since they * are given in SOF/SOS markers or defined to be reset by SOI. */ int data_precision; /* bits of precision in image data */ jpeg_component_info * comp_info; /* comp_info[i] describes component that appears i'th in SOF */ boolean is_baseline; /* TRUE if Baseline SOF0 encountered */ boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ /* These fields record data obtained from optional markers recognized by * the JPEG library. */ boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */ UINT8 JFIF_major_version; /* JFIF version number */ UINT8 JFIF_minor_version; UINT8 density_unit; /* JFIF code for pixel size units */ UINT16 X_density; /* Horizontal pixel density */ UINT16 Y_density; /* Vertical pixel density */ boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ UINT8 Adobe_transform; /* Color transform code from Adobe marker */ J_COLOR_TRANSFORM color_transform; /* Color transform identifier derived from LSE marker, otherwise zero */ boolean CCIR601_sampling; /* TRUE=first samples are cosited */ /* Aside from the specific data retained from APPn markers known to the * library, the uninterpreted contents of any or all APPn and COM markers * can be saved in a list for examination by the application. */ jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */ /* Remaining fields are known throughout decompressor, but generally * should not be touched by a surrounding application. */ /* * These fields are computed during decompression startup */ int max_h_samp_factor; /* largest h_samp_factor */ int max_v_samp_factor; /* largest v_samp_factor */ int min_DCT_h_scaled_size; /* smallest DCT_h_scaled_size of any component */ int min_DCT_v_scaled_size; /* smallest DCT_v_scaled_size of any component */ JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ /* The coefficient controller's input and output progress is measured in * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows * in fully interleaved JPEG scans, but are used whether the scan is * interleaved or not. We define an iMCU row as v_samp_factor DCT block * rows of each component. Therefore, the IDCT output contains * v_samp_factor*DCT_v_scaled_size sample rows of a component per iMCU row. */ JSAMPLE * sample_range_limit; /* table for fast range-limiting */ /* * These fields are valid during any one scan. * They describe the components and MCUs actually appearing in the scan. * Note that the decompressor output side must not use these fields. */ int comps_in_scan; /* # of JPEG components in this scan */ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; /* *cur_comp_info[i] describes component that appears i'th in SOS */ JDIMENSION MCUs_per_row; /* # of MCUs across the image */ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ int blocks_in_MCU; /* # of DCT blocks per MCU */ int MCU_membership[D_MAX_BLOCKS_IN_MCU]; /* MCU_membership[i] is index in cur_comp_info of component owning */ /* i'th block in an MCU */ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ /* These fields are derived from Se of first SOS marker. */ int block_size; /* the basic DCT block size: 1..16 */ const int * natural_order; /* natural-order position array for entropy decode */ int lim_Se; /* min( Se, DCTSIZE2-1 ) for entropy decode */ /* This field is shared between entropy decoder and marker parser. * It is either zero or the code of a JPEG marker that has been * read from the data source, but has not yet been processed. */ int unread_marker; /* * Links to decompression subobjects (methods, private variables of modules) */ struct jpeg_decomp_master * master; struct jpeg_d_main_controller * main; struct jpeg_d_coef_controller * coef; struct jpeg_d_post_controller * post; struct jpeg_input_controller * inputctl; struct jpeg_marker_reader * marker; struct jpeg_entropy_decoder * entropy; struct jpeg_inverse_dct * idct; struct jpeg_upsampler * upsample; struct jpeg_color_deconverter * cconvert; struct jpeg_color_quantizer * cquantize; }; /* "Object" declarations for JPEG modules that may be supplied or called * directly by the surrounding application. * As with all objects in the JPEG library, these structs only define the * publicly visible methods and state variables of a module. Additional * private fields may exist after the public ones. */ /* Error handler object */ struct jpeg_error_mgr { /* Error exit handler: does not return to caller */ JMETHOD(noreturn_t, error_exit, (j_common_ptr cinfo)); /* Conditionally emit a trace or warning message */ JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level)); /* Routine that actually outputs a trace or error message */ JMETHOD(void, output_message, (j_common_ptr cinfo)); /* Format a message string for the most recent JPEG error or message */ JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer)); #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ /* Reset error state variables at start of a new image */ JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo)); /* The message ID code and any parameters are saved here. * A message can have one string parameter or up to 8 int parameters. */ int msg_code; #define JMSG_STR_PARM_MAX 80 union { int i[8]; char s[JMSG_STR_PARM_MAX]; } msg_parm; /* Standard state variables for error facility */ int trace_level; /* max msg_level that will be displayed */ /* For recoverable corrupt-data errors, we emit a warning message, * but keep going unless emit_message chooses to abort. emit_message * should count warnings in num_warnings. The surrounding application * can check for bad data by seeing if num_warnings is nonzero at the * end of processing. */ long num_warnings; /* number of corrupt-data warnings */ /* These fields point to the table(s) of error message strings. * An application can change the table pointer to switch to a different * message list (typically, to change the language in which errors are * reported). Some applications may wish to add additional error codes * that will be handled by the JPEG library error mechanism; the second * table pointer is used for this purpose. * * First table includes all errors generated by JPEG library itself. * Error code 0 is reserved for a "no such error string" message. */ const char * const * jpeg_message_table; /* Library errors */ int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ /* Second table can be added by application (see cjpeg/djpeg for example). * It contains strings numbered first_addon_message..last_addon_message. */ const char * const * addon_message_table; /* Non-library errors */ int first_addon_message; /* code for first string in addon table */ int last_addon_message; /* code for last string in addon table */ }; /* Progress monitor object */ struct jpeg_progress_mgr { JMETHOD(void, progress_monitor, (j_common_ptr cinfo)); long pass_counter; /* work units completed in this pass */ long pass_limit; /* total number of work units in this pass */ int completed_passes; /* passes completed so far */ int total_passes; /* total number of passes expected */ }; /* Data destination object for compression */ struct jpeg_destination_mgr { JOCTET * next_output_byte; /* => next byte to write in buffer */ size_t free_in_buffer; /* # of byte spaces remaining in buffer */ JMETHOD(void, init_destination, (j_compress_ptr cinfo)); JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo)); JMETHOD(void, term_destination, (j_compress_ptr cinfo)); }; /* Data source object for decompression */ struct jpeg_source_mgr { const JOCTET * next_input_byte; /* => next byte to read from buffer */ size_t bytes_in_buffer; /* # of bytes remaining in buffer */ JMETHOD(void, init_source, (j_decompress_ptr cinfo)); JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo)); JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes)); JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired)); JMETHOD(void, term_source, (j_decompress_ptr cinfo)); }; /* Memory manager object. * Allocates "small" objects (a few K total), "large" objects (tens of K), * and "really big" objects (virtual arrays with backing store if needed). * The memory manager does not allow individual objects to be freed; rather, * each created object is assigned to a pool, and whole pools can be freed * at once. This is faster and more convenient than remembering exactly what * to free, especially where malloc()/free() are not too speedy. * NB: alloc routines never return NULL. They exit to error_exit if not * successful. */ #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ #define JPOOL_NUMPOOLS 2 typedef struct jvirt_sarray_control * jvirt_sarray_ptr; typedef struct jvirt_barray_control * jvirt_barray_ptr; struct jpeg_memory_mgr { /* Method pointers */ JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id, size_t sizeofobject)); JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id, size_t sizeofobject)); JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id, JDIMENSION samplesperrow, JDIMENSION numrows)); JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id, JDIMENSION blocksperrow, JDIMENSION numrows)); JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION samplesperrow, JDIMENSION numrows, JDIMENSION maxaccess)); JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION blocksperrow, JDIMENSION numrows, JDIMENSION maxaccess)); JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo)); JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo, jvirt_sarray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable)); JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo, jvirt_barray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable)); JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id)); JMETHOD(void, self_destruct, (j_common_ptr cinfo)); /* Limit on memory allocation for this JPEG object. (Note that this is * merely advisory, not a guaranteed maximum; it only affects the space * used for virtual-array buffers.) May be changed by outer application * after creating the JPEG object. */ long max_memory_to_use; /* Maximum allocation request accepted by alloc_large. */ long max_alloc_chunk; }; /* Routine signature for application-supplied marker processing methods. * Need not pass marker code since it is stored in cinfo->unread_marker. */ typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo)); /* Declarations for routines called by application. * The JPP macro hides prototype parameters from compilers that can't cope. * Note JPP requires double parentheses. */ #ifdef HAVE_PROTOTYPES #define JPP(arglist) arglist #else #define JPP(arglist) () #endif /* Short forms of external names for systems with brain-damaged linkers. * We shorten external names to be unique in the first six letters, which * is good enough for all known systems. * (If your compiler itself needs names to be unique in less than 15 * characters, you are out of luck. Get a better compiler.) */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jpeg_std_error jStdError #define jpeg_CreateCompress jCreaCompress #define jpeg_CreateDecompress jCreaDecompress #define jpeg_destroy_compress jDestCompress #define jpeg_destroy_decompress jDestDecompress #define jpeg_stdio_dest jStdDest #define jpeg_stdio_src jStdSrc #define jpeg_mem_dest jMemDest #define jpeg_mem_src jMemSrc #define jpeg_set_defaults jSetDefaults #define jpeg_set_colorspace jSetColorspace #define jpeg_default_colorspace jDefColorspace #define jpeg_set_quality jSetQuality #define jpeg_set_linear_quality jSetLQuality #define jpeg_default_qtables jDefQTables #define jpeg_add_quant_table jAddQuantTable #define jpeg_quality_scaling jQualityScaling #define jpeg_simple_progression jSimProgress #define jpeg_suppress_tables jSuppressTables #define jpeg_alloc_quant_table jAlcQTable #define jpeg_alloc_huff_table jAlcHTable #define jpeg_start_compress jStrtCompress #define jpeg_write_scanlines jWrtScanlines #define jpeg_finish_compress jFinCompress #define jpeg_calc_jpeg_dimensions jCjpegDimensions #define jpeg_write_raw_data jWrtRawData #define jpeg_write_marker jWrtMarker #define jpeg_write_m_header jWrtMHeader #define jpeg_write_m_byte jWrtMByte #define jpeg_write_tables jWrtTables #define jpeg_read_header jReadHeader #define jpeg_start_decompress jStrtDecompress #define jpeg_read_scanlines jReadScanlines #define jpeg_finish_decompress jFinDecompress #define jpeg_read_raw_data jReadRawData #define jpeg_has_multiple_scans jHasMultScn #define jpeg_start_output jStrtOutput #define jpeg_finish_output jFinOutput #define jpeg_input_complete jInComplete #define jpeg_new_colormap jNewCMap #define jpeg_consume_input jConsumeInput #define jpeg_core_output_dimensions jCoreDimensions #define jpeg_calc_output_dimensions jCalcDimensions #define jpeg_save_markers jSaveMarkers #define jpeg_set_marker_processor jSetMarker #define jpeg_read_coefficients jReadCoefs #define jpeg_write_coefficients jWrtCoefs #define jpeg_copy_critical_parameters jCopyCrit #define jpeg_abort_compress jAbrtCompress #define jpeg_abort_decompress jAbrtDecompress #define jpeg_abort jAbort #define jpeg_destroy jDestroy #define jpeg_resync_to_restart jResyncRestart #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* Default error-management setup */ EXTERN(struct jpeg_error_mgr *) jpeg_std_error JPP((struct jpeg_error_mgr * err)); /* Initialization of JPEG compression objects. * jpeg_create_compress() and jpeg_create_decompress() are the exported * names that applications should call. These expand to calls on * jpeg_CreateCompress and jpeg_CreateDecompress with additional information * passed for version mismatch checking. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx. */ #define jpeg_create_compress(cinfo) \ jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \ (size_t) sizeof(struct jpeg_compress_struct)) #define jpeg_create_decompress(cinfo) \ jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \ (size_t) sizeof(struct jpeg_decompress_struct)) EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo, int version, size_t structsize)); EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo, int version, size_t structsize)); /* Destruction of JPEG compression objects */ EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo)); /* Standard data source and destination managers: stdio streams. */ /* Caller is responsible for opening the file before and closing after. */ EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile)); EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile)); /* Data source and destination managers: memory buffers. */ EXTERN(void) jpeg_mem_dest JPP((j_compress_ptr cinfo, unsigned char ** outbuffer, unsigned long * outsize)); EXTERN(void) jpeg_mem_src JPP((j_decompress_ptr cinfo, const unsigned char * inbuffer, unsigned long insize)); /* Default parameter setup for compression */ EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo)); /* Compression parameter setup aids */ EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo, J_COLOR_SPACE colorspace)); EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality, boolean force_baseline)); EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo, int scale_factor, boolean force_baseline)); EXTERN(void) jpeg_default_qtables JPP((j_compress_ptr cinfo, boolean force_baseline)); EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl, const unsigned int *basic_table, int scale_factor, boolean force_baseline)); EXTERN(int) jpeg_quality_scaling JPP((int quality)); EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo, boolean suppress)); EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo)); EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo)); /* Main entry points for compression */ EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo, boolean write_all_tables)); EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION num_lines)); EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo)); /* Precalculate JPEG dimensions for current compression parameters. */ EXTERN(void) jpeg_calc_jpeg_dimensions JPP((j_compress_ptr cinfo)); /* Replaces jpeg_write_scanlines when writing raw downsampled data. */ EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo, JSAMPIMAGE data, JDIMENSION num_lines)); /* Write a special marker. See libjpeg.txt concerning safe usage. */ EXTERN(void) jpeg_write_marker JPP((j_compress_ptr cinfo, int marker, const JOCTET * dataptr, unsigned int datalen)); /* Same, but piecemeal. */ EXTERN(void) jpeg_write_m_header JPP((j_compress_ptr cinfo, int marker, unsigned int datalen)); EXTERN(void) jpeg_write_m_byte JPP((j_compress_ptr cinfo, int val)); /* Alternate compression function: just write an abbreviated table file */ EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo)); /* Decompression startup: read start of JPEG datastream to see what's there */ EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo, boolean require_image)); /* Return value is one of: */ #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ #define JPEG_HEADER_OK 1 /* Found valid image datastream */ #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ /* If you pass require_image = TRUE (normal case), you need not check for * a TABLES_ONLY return code; an abbreviated file will cause an error exit. * JPEG_SUSPENDED is only possible if you use a data source module that can * give a suspension return (the stdio source module doesn't). */ /* Main entry points for decompression */ EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo)); EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines)); EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo)); /* Replaces jpeg_read_scanlines when reading raw downsampled data. */ EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo, JSAMPIMAGE data, JDIMENSION max_lines)); /* Additional entry points for buffered-image mode. */ EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo)); EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo, int scan_number)); EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo)); EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo)); EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo)); EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo)); /* Return value is one of: */ /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ #define JPEG_REACHED_SOS 1 /* Reached start of new scan */ #define JPEG_REACHED_EOI 2 /* Reached end of image */ #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ /* Precalculate output dimensions for current decompression parameters. */ EXTERN(void) jpeg_core_output_dimensions JPP((j_decompress_ptr cinfo)); EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo)); /* Control saving of COM and APPn markers into marker_list. */ EXTERN(void) jpeg_save_markers JPP((j_decompress_ptr cinfo, int marker_code, unsigned int length_limit)); /* Install a special processing method for COM or APPn markers. */ EXTERN(void) jpeg_set_marker_processor JPP((j_decompress_ptr cinfo, int marker_code, jpeg_marker_parser_method routine)); /* Read or write raw DCT coefficients --- useful for lossless transcoding. */ EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo)); EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)); EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo)); /* If you choose to abort compression or decompression before completing * jpeg_finish_(de)compress, then you need to clean up to release memory, * temporary files, etc. You can just call jpeg_destroy_(de)compress * if you're done with the JPEG object, but if you want to clean it up and * reuse it, call this: */ EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo)); /* Generic versions of jpeg_abort and jpeg_destroy that work on either * flavor of JPEG object. These may be more convenient in some places. */ EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo)); EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo)); /* Default restart-marker-resync procedure for use by data source modules */ EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo, int desired)); /* These marker codes are exported since applications and data source modules * are likely to want to use them. */ #define JPEG_RST0 0xD0 /* RST0 marker code */ #define JPEG_EOI 0xD9 /* EOI marker code */ #define JPEG_APP0 0xE0 /* APP0 marker code */ #define JPEG_COM 0xFE /* COM marker code */ /* If we have a brain-damaged compiler that emits warnings (or worse, errors) * for structure definitions that are never filled in, keep it quiet by * supplying dummy definitions for the various substructures. */ #ifdef INCOMPLETE_TYPES_BROKEN #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ struct jvirt_sarray_control { long dummy; }; struct jvirt_barray_control { long dummy; }; struct jpeg_comp_master { long dummy; }; struct jpeg_c_main_controller { long dummy; }; struct jpeg_c_prep_controller { long dummy; }; struct jpeg_c_coef_controller { long dummy; }; struct jpeg_marker_writer { long dummy; }; struct jpeg_color_converter { long dummy; }; struct jpeg_downsampler { long dummy; }; struct jpeg_forward_dct { long dummy; }; struct jpeg_entropy_encoder { long dummy; }; struct jpeg_decomp_master { long dummy; }; struct jpeg_d_main_controller { long dummy; }; struct jpeg_d_coef_controller { long dummy; }; struct jpeg_d_post_controller { long dummy; }; struct jpeg_input_controller { long dummy; }; struct jpeg_marker_reader { long dummy; }; struct jpeg_entropy_decoder { long dummy; }; struct jpeg_inverse_dct { long dummy; }; struct jpeg_upsampler { long dummy; }; struct jpeg_color_deconverter { long dummy; }; struct jpeg_color_quantizer { long dummy; }; #endif /* JPEG_INTERNALS */ #endif /* INCOMPLETE_TYPES_BROKEN */ /* * The JPEG library modules define JPEG_INTERNALS before including this file. * The internal structure declarations are read only when that is true. * Applications using the library should not include jpegint.h, but may wish * to include jerror.h. */ #ifdef JPEG_INTERNALS #include "jpegint.h" /* fetch private declarations */ #include "jerror.h" /* fetch error codes too */ #endif #ifdef __cplusplus #ifndef DONT_USE_EXTERN_C } #endif #endif #endif /* JPEGLIB_H */ ================================================ FILE: tess-two/jni/libjpeg/jpegtran.1 ================================================ .TH JPEGTRAN 1 "20 September 2015" .SH NAME jpegtran \- lossless transformation of JPEG files .SH SYNOPSIS .B jpegtran [ .I options ] [ .I filename ] .LP .SH DESCRIPTION .LP .B jpegtran performs various useful transformations of JPEG files. It can translate the coded representation from one variant of JPEG to another, for example from baseline JPEG to progressive JPEG or vice versa. It can also perform some rearrangements of the image data, for example turning an image from landscape to portrait format by rotation. .PP For EXIF files and JPEG files containing Exif data, you may prefer to use .B exiftran instead. .PP .B jpegtran works by rearranging the compressed data (DCT coefficients), without ever fully decoding the image. Therefore, its transformations are lossless: there is no image degradation at all, which would not be true if you used .B djpeg followed by .B cjpeg to accomplish the same conversion. But by the same token, .B jpegtran cannot perform lossy operations such as changing the image quality. However, while the image data is losslessly transformed, metadata can be removed. See the .B \-copy option for specifics. .PP .B jpegtran reads the named JPEG/JFIF file, or the standard input if no file is named, and produces a JPEG/JFIF file on the standard output. .SH OPTIONS All switch names may be abbreviated; for example, .B \-optimize may be written .B \-opt or .BR \-o . Upper and lower case are equivalent. British spellings are also accepted (e.g., .BR \-optimise ), though for brevity these are not mentioned below. .PP To specify the coded JPEG representation used in the output file, .B jpegtran accepts a subset of the switches recognized by .BR cjpeg : .TP .B \-optimize Perform optimization of entropy encoding parameters. .TP .B \-progressive Create progressive JPEG file. .TP .BI \-restart " N" Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if "B" is attached to the number. .TP .B \-arithmetic Use arithmetic coding. .TP .BI \-scans " file" Use the scan script given in the specified text file. .PP See .BR cjpeg (1) for more details about these switches. If you specify none of these switches, you get a plain baseline-JPEG output file. The quality setting and so forth are determined by the input file. .PP The image can be losslessly transformed by giving one of these switches: .TP .B \-flip horizontal Mirror image horizontally (left-right). .TP .B \-flip vertical Mirror image vertically (top-bottom). .TP .B \-rotate 90 Rotate image 90 degrees clockwise. .TP .B \-rotate 180 Rotate image 180 degrees. .TP .B \-rotate 270 Rotate image 270 degrees clockwise (or 90 ccw). .TP .B \-transpose Transpose image (across UL-to-LR axis). .TP .B \-transverse Transverse transpose (across UR-to-LL axis). .IP The transpose transformation has no restrictions regarding image dimensions. The other transformations operate rather oddly if the image dimensions are not a multiple of the iMCU size (usually 8 or 16 pixels), because they can only transform complete blocks of DCT coefficient data in the desired way. .IP .BR jpegtran 's default behavior when transforming an odd-size image is designed to preserve exact reversibility and mathematical consistency of the transformation set. As stated, transpose is able to flip the entire image area. Horizontal mirroring leaves any partial iMCU column at the right edge untouched, but is able to flip all rows of the image. Similarly, vertical mirroring leaves any partial iMCU row at the bottom edge untouched, but is able to flip all columns. The other transforms can be built up as sequences of transpose and flip operations; for consistency, their actions on edge pixels are defined to be the same as the end result of the corresponding transpose-and-flip sequence. .IP For practical use, you may prefer to discard any untransformable edge pixels rather than having a strange-looking strip along the right and/or bottom edges of a transformed image. To do this, add the .B \-trim switch: .TP .B \-trim Drop non-transformable edge blocks. .IP Obviously, a transformation with .B \-trim is not reversible, so strictly speaking .B jpegtran with this switch is not lossless. Also, the expected mathematical equivalences between the transformations no longer hold. For example, .B \-rot 270 -trim trims only the bottom edge, but .B \-rot 90 -trim followed by .B \-rot 180 -trim trims both edges. .IP If you are only interested in perfect transformation, add the .B \-perfect switch: .TP .B \-perfect Fails with an error if the transformation is not perfect. .IP For example you may want to do .IP .B (jpegtran \-rot 90 -perfect .I foo.jpg .B || djpeg .I foo.jpg .B | pnmflip \-r90 | cjpeg) .IP to do a perfect rotation if available or an approximated one if not. .PP We also offer a lossless-crop option, which discards data outside a given image region but losslessly preserves what is inside. Like the rotate and flip transforms, lossless crop is restricted by the current JPEG format: the upper left corner of the selected region must fall on an iMCU boundary. If this does not hold for the given crop parameters, we silently move the upper left corner up and/or left to make it so, simultaneously increasing the region dimensions to keep the lower right crop corner unchanged. (Thus, the output image covers at least the requested region, but may cover more.) The adjustment of the region dimensions may be optionally disabled by attaching an 'f' character ("force") to the width or height number. The image can be losslessly cropped by giving the switch: .TP .B \-crop WxH+X+Y Crop to a rectangular subarea of width W, height H starting at point X,Y. .PP A complementary lossless-wipe option is provided to discard (gray out) data inside a given image region while losslessly preserving what is outside: .TP .B \-wipe WxH+X+Y Wipe (gray out) a rectangular subarea of width W, height H starting at point X,Y. .PP Other not-strictly-lossless transformation switches are: .TP .B \-grayscale Force grayscale output. .IP This option discards the chrominance channels if the input image is YCbCr (ie, a standard color JPEG), resulting in a grayscale JPEG file. The luminance channel is preserved exactly, so this is a better method of reducing to grayscale than decompression, conversion, and recompression. This switch is particularly handy for fixing a monochrome picture that was mistakenly encoded as a color JPEG. (In such a case, the space savings from getting rid of the near-empty chroma channels won't be large; but the decoding time for a grayscale JPEG is substantially less than that for a color JPEG.) .TP .BI \-scale " M/N" Scale the output image by a factor M/N. .IP Currently supported scale factors are M/N with all M from 1 to 16, where N is the source DCT size, which is 8 for baseline JPEG. If the /N part is omitted, then M specifies the DCT scaled size to be applied on the given input. For baseline JPEG this is equivalent to M/8 scaling, since the source DCT size for baseline JPEG is 8. .B Caution: An implementation of the JPEG SmartScale extension is required for this feature. SmartScale enabled JPEG is not yet widely implemented, so many decoders will be unable to view a SmartScale extended JPEG file at all. .PP .B jpegtran also recognizes these switches that control what to do with "extra" markers, such as comment blocks: .TP .B \-copy none Copy no extra markers from source file. This setting suppresses all comments and other metadata in the source file. .TP .B \-copy comments Copy only comment markers. This setting copies comments from the source file, but discards any other metadata. .TP .B \-copy all Copy all extra markers. This setting preserves metadata found in the source file, such as JFIF thumbnails, Exif data, and Photoshop settings. In some files these extra markers can be sizable. Note that this option will copy thumbnails as-is; they will not be transformed. .IP The default behavior is .BR "\-copy comments" . (Note: in IJG releases v6 and v6a, .B jpegtran always did the equivalent of .BR "\-copy none" .) .PP Additional switches recognized by jpegtran are: .TP .BI \-maxmemory " N" Set limit for amount of memory to use in processing large images. Value is in thousands of bytes, or millions of bytes if "M" is attached to the number. For example, .B \-max 4m selects 4000000 bytes. If more space is needed, temporary files will be used. .TP .BI \-outfile " name" Send output image to the named file, not to standard output. .TP .B \-verbose Enable debug printout. More .BR \-v 's give more output. Also, version information is printed at startup. .TP .B \-debug Same as .BR \-verbose . .SH EXAMPLES .LP This example converts a baseline JPEG file to progressive form: .IP .B jpegtran \-progressive .I foo.jpg .B > .I fooprog.jpg .PP This example rotates an image 90 degrees clockwise, discarding any unrotatable edge pixels: .IP .B jpegtran \-rot 90 -trim .I foo.jpg .B > .I foo90.jpg .SH ENVIRONMENT .TP .B JPEGMEM If this environment variable is set, its value is the default memory limit. The value is specified as described for the .B \-maxmemory switch. .B JPEGMEM overrides the default value specified when the program was compiled, and itself is overridden by an explicit .BR \-maxmemory . .SH SEE ALSO .BR cjpeg (1), .BR djpeg (1), .BR rdjpgcom (1), .BR wrjpgcom (1) .br Wallace, Gregory K. "The JPEG Still Picture Compression Standard", Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44. .SH AUTHOR Independent JPEG Group .SH BUGS The transform options can't transform odd-size images perfectly. Use .B \-trim or .B \-perfect if you don't like the results. .PP The entire image is read into memory and then written out again, even in cases where this isn't really necessary. Expect swapping on large images, especially when using the more complex transform options. ================================================ FILE: tess-two/jni/libjpeg/jpegtran.c ================================================ /* * jpegtran.c * * Copyright (C) 1995-2013, Thomas G. Lane, Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a command-line user interface for JPEG transcoding. * It is very similar to cjpeg.c, and partly to djpeg.c, but provides * lossless transcoding between different JPEG file formats. It also * provides some lossless and sort-of-lossless transformations of JPEG data. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #include "transupp.h" /* Support routines for jpegtran */ #include "jversion.h" /* for version message */ #ifdef USE_CCOMMAND /* command-line reader for Macintosh */ #ifdef __MWERKS__ #include /* Metrowerks needs this */ #include /* ... and this */ #endif #ifdef THINK_C #include /* Think declares it here */ #endif #endif /* * Argument-parsing code. * The switch parser is designed to be useful with DOS-style command line * syntax, ie, intermixed switches and file names, where only the switches * to the left of a given file name affect processing of that file. * The main program in this file doesn't actually use this capability... */ static const char * progname; /* program name for error messages */ static char * outfilename; /* for -outfile switch */ static char * scaleoption; /* -scale switch */ static JCOPY_OPTION copyoption; /* -copy switch */ static jpeg_transform_info transformoption; /* image transformation options */ LOCAL(void) usage (void) /* complain about bad command line */ { fprintf(stderr, "usage: %s [switches] ", progname); #ifdef TWO_FILE_COMMANDLINE fprintf(stderr, "inputfile outputfile\n"); #else fprintf(stderr, "[inputfile]\n"); #endif fprintf(stderr, "Switches (names may be abbreviated):\n"); fprintf(stderr, " -copy none Copy no extra markers from source file\n"); fprintf(stderr, " -copy comments Copy only comment markers (default)\n"); fprintf(stderr, " -copy all Copy all extra markers\n"); #ifdef ENTROPY_OPT_SUPPORTED fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n"); #endif #ifdef C_PROGRESSIVE_SUPPORTED fprintf(stderr, " -progressive Create progressive JPEG file\n"); #endif fprintf(stderr, "Switches for modifying the image:\n"); #if TRANSFORMS_SUPPORTED fprintf(stderr, " -crop WxH+X+Y Crop to a rectangular subarea\n"); fprintf(stderr, " -flip [horizontal|vertical] Mirror image (left-right or top-bottom)\n"); fprintf(stderr, " -grayscale Reduce to grayscale (omit color data)\n"); fprintf(stderr, " -perfect Fail if there is non-transformable edge blocks\n"); fprintf(stderr, " -rotate [90|180|270] Rotate image (degrees clockwise)\n"); #endif fprintf(stderr, " -scale M/N Scale output image by fraction M/N, eg, 1/8\n"); #if TRANSFORMS_SUPPORTED fprintf(stderr, " -transpose Transpose image\n"); fprintf(stderr, " -transverse Transverse transpose image\n"); fprintf(stderr, " -trim Drop non-transformable edge blocks\n"); fprintf(stderr, " -wipe WxH+X+Y Wipe (gray out) a rectangular subarea\n"); #endif fprintf(stderr, "Switches for advanced users:\n"); #ifdef C_ARITH_CODING_SUPPORTED fprintf(stderr, " -arithmetic Use arithmetic coding\n"); #endif fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n"); fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n"); fprintf(stderr, " -outfile name Specify name for output file\n"); fprintf(stderr, " -verbose or -debug Emit debug output\n"); fprintf(stderr, "Switches for wizards:\n"); #ifdef C_MULTISCAN_FILES_SUPPORTED fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n"); #endif exit(EXIT_FAILURE); } LOCAL(void) select_transform (JXFORM_CODE transform) /* Silly little routine to detect multiple transform options, * which we can't handle. */ { #if TRANSFORMS_SUPPORTED if (transformoption.transform == JXFORM_NONE || transformoption.transform == transform) { transformoption.transform = transform; } else { fprintf(stderr, "%s: can only do one image transformation at a time\n", progname); usage(); } #else fprintf(stderr, "%s: sorry, image transformation was not compiled\n", progname); exit(EXIT_FAILURE); #endif } LOCAL(int) parse_switches (j_compress_ptr cinfo, int argc, char **argv, int last_file_arg_seen, boolean for_real) /* Parse optional switches. * Returns argv[] index of first file-name argument (== argc if none). * Any file names with indexes <= last_file_arg_seen are ignored; * they have presumably been processed in a previous iteration. * (Pass 0 for last_file_arg_seen on the first or only iteration.) * for_real is FALSE on the first (dummy) pass; we may skip any expensive * processing. */ { int argn; char * arg; boolean simple_progressive; char * scansarg = NULL; /* saves -scans parm if any */ /* Set up default JPEG parameters. */ simple_progressive = FALSE; outfilename = NULL; scaleoption = NULL; copyoption = JCOPYOPT_DEFAULT; transformoption.transform = JXFORM_NONE; transformoption.perfect = FALSE; transformoption.trim = FALSE; transformoption.force_grayscale = FALSE; transformoption.crop = FALSE; cinfo->err->trace_level = 0; /* Scan command line options, adjust parameters */ for (argn = 1; argn < argc; argn++) { arg = argv[argn]; if (*arg != '-') { /* Not a switch, must be a file name argument */ if (argn <= last_file_arg_seen) { outfilename = NULL; /* -outfile applies to just one input file */ continue; /* ignore this name if previously processed */ } break; /* else done parsing switches */ } arg++; /* advance past switch marker character */ if (keymatch(arg, "arithmetic", 1)) { /* Use arithmetic coding. */ #ifdef C_ARITH_CODING_SUPPORTED cinfo->arith_code = TRUE; #else fprintf(stderr, "%s: sorry, arithmetic coding not supported\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "copy", 2)) { /* Select which extra markers to copy. */ if (++argn >= argc) /* advance to next argument */ usage(); if (keymatch(argv[argn], "none", 1)) { copyoption = JCOPYOPT_NONE; } else if (keymatch(argv[argn], "comments", 1)) { copyoption = JCOPYOPT_COMMENTS; } else if (keymatch(argv[argn], "all", 1)) { copyoption = JCOPYOPT_ALL; } else usage(); } else if (keymatch(arg, "crop", 2)) { /* Perform lossless cropping. */ #if TRANSFORMS_SUPPORTED if (++argn >= argc) /* advance to next argument */ usage(); if (transformoption.crop /* reject multiple crop/wipe requests */ || ! jtransform_parse_crop_spec(&transformoption, argv[argn])) { fprintf(stderr, "%s: bogus -crop argument '%s'\n", progname, argv[argn]); exit(EXIT_FAILURE); } #else select_transform(JXFORM_NONE); /* force an error */ #endif } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) { /* Enable debug printouts. */ /* On first -d, print version identification */ static boolean printed_version = FALSE; if (! printed_version) { fprintf(stderr, "Independent JPEG Group's JPEGTRAN, version %s\n%s\n", JVERSION, JCOPYRIGHT); printed_version = TRUE; } cinfo->err->trace_level++; } else if (keymatch(arg, "flip", 1)) { /* Mirror left-right or top-bottom. */ if (++argn >= argc) /* advance to next argument */ usage(); if (keymatch(argv[argn], "horizontal", 1)) select_transform(JXFORM_FLIP_H); else if (keymatch(argv[argn], "vertical", 1)) select_transform(JXFORM_FLIP_V); else usage(); } else if (keymatch(arg, "grayscale", 1) || keymatch(arg, "greyscale",1)) { /* Force to grayscale. */ #if TRANSFORMS_SUPPORTED transformoption.force_grayscale = TRUE; #else select_transform(JXFORM_NONE); /* force an error */ #endif } else if (keymatch(arg, "maxmemory", 3)) { /* Maximum memory in Kb (or Mb with 'm'). */ long lval; char ch = 'x'; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1) usage(); if (ch == 'm' || ch == 'M') lval *= 1000L; cinfo->mem->max_memory_to_use = lval * 1000L; } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) { /* Enable entropy parm optimization. */ #ifdef ENTROPY_OPT_SUPPORTED cinfo->optimize_coding = TRUE; #else fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "outfile", 4)) { /* Set output file name. */ if (++argn >= argc) /* advance to next argument */ usage(); outfilename = argv[argn]; /* save it away for later use */ } else if (keymatch(arg, "perfect", 2)) { /* Fail if there is any partial edge MCUs that the transform can't * handle. */ transformoption.perfect = TRUE; } else if (keymatch(arg, "progressive", 2)) { /* Select simple progressive mode. */ #ifdef C_PROGRESSIVE_SUPPORTED simple_progressive = TRUE; /* We must postpone execution until num_components is known. */ #else fprintf(stderr, "%s: sorry, progressive output was not compiled\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "restart", 1)) { /* Restart interval in MCU rows (or in MCUs with 'b'). */ long lval; char ch = 'x'; if (++argn >= argc) /* advance to next argument */ usage(); if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1) usage(); if (lval < 0 || lval > 65535L) usage(); if (ch == 'b' || ch == 'B') { cinfo->restart_interval = (unsigned int) lval; cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */ } else { cinfo->restart_in_rows = (int) lval; /* restart_interval will be computed during startup */ } } else if (keymatch(arg, "rotate", 2)) { /* Rotate 90, 180, or 270 degrees (measured clockwise). */ if (++argn >= argc) /* advance to next argument */ usage(); if (keymatch(argv[argn], "90", 2)) select_transform(JXFORM_ROT_90); else if (keymatch(argv[argn], "180", 3)) select_transform(JXFORM_ROT_180); else if (keymatch(argv[argn], "270", 3)) select_transform(JXFORM_ROT_270); else usage(); } else if (keymatch(arg, "scale", 4)) { /* Scale the output image by a fraction M/N. */ if (++argn >= argc) /* advance to next argument */ usage(); scaleoption = argv[argn]; /* We must postpone processing until decompression startup. */ } else if (keymatch(arg, "scans", 1)) { /* Set scan script. */ #ifdef C_MULTISCAN_FILES_SUPPORTED if (++argn >= argc) /* advance to next argument */ usage(); scansarg = argv[argn]; /* We must postpone reading the file in case -progressive appears. */ #else fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n", progname); exit(EXIT_FAILURE); #endif } else if (keymatch(arg, "transpose", 1)) { /* Transpose (across UL-to-LR axis). */ select_transform(JXFORM_TRANSPOSE); } else if (keymatch(arg, "transverse", 6)) { /* Transverse transpose (across UR-to-LL axis). */ select_transform(JXFORM_TRANSVERSE); } else if (keymatch(arg, "trim", 3)) { /* Trim off any partial edge MCUs that the transform can't handle. */ transformoption.trim = TRUE; } else if (keymatch(arg, "wipe", 1)) { #if TRANSFORMS_SUPPORTED if (++argn >= argc) /* advance to next argument */ usage(); if (transformoption.crop /* reject multiple crop/wipe requests */ || ! jtransform_parse_crop_spec(&transformoption, argv[argn])) { fprintf(stderr, "%s: bogus -wipe argument '%s'\n", progname, argv[argn]); exit(EXIT_FAILURE); } select_transform(JXFORM_WIPE); #else select_transform(JXFORM_NONE); /* force an error */ #endif } else { usage(); /* bogus switch */ } } /* Post-switch-scanning cleanup */ if (for_real) { #ifdef C_PROGRESSIVE_SUPPORTED if (simple_progressive) /* process -progressive; -scans can override */ jpeg_simple_progression(cinfo); #endif #ifdef C_MULTISCAN_FILES_SUPPORTED if (scansarg != NULL) /* process -scans if it was present */ if (! read_scan_script(cinfo, scansarg)) usage(); #endif } return argn; /* return index of next arg (file name) */ } /* * The main program. */ int main (int argc, char **argv) { struct jpeg_decompress_struct srcinfo; struct jpeg_compress_struct dstinfo; struct jpeg_error_mgr jsrcerr, jdsterr; #ifdef PROGRESS_REPORT struct cdjpeg_progress_mgr progress; #endif jvirt_barray_ptr * src_coef_arrays; jvirt_barray_ptr * dst_coef_arrays; int file_index; /* We assume all-in-memory processing and can therefore use only a * single file pointer for sequential input and output operation. */ FILE * fp; /* On Mac, fetch a command line. */ #ifdef USE_CCOMMAND argc = ccommand(&argv); #endif progname = argv[0]; if (progname == NULL || progname[0] == 0) progname = "jpegtran"; /* in case C library doesn't provide it */ /* Initialize the JPEG decompression object with default error handling. */ srcinfo.err = jpeg_std_error(&jsrcerr); jpeg_create_decompress(&srcinfo); /* Initialize the JPEG compression object with default error handling. */ dstinfo.err = jpeg_std_error(&jdsterr); jpeg_create_compress(&dstinfo); /* Now safe to enable signal catcher. * Note: we assume only the decompression object will have virtual arrays. */ #ifdef NEED_SIGNAL_CATCHER enable_signal_catcher((j_common_ptr) &srcinfo); #endif /* Scan command line to find file names. * It is convenient to use just one switch-parsing routine, but the switch * values read here are mostly ignored; we will rescan the switches after * opening the input file. Also note that most of the switches affect the * destination JPEG object, so we parse into that and then copy over what * needs to affects the source too. */ file_index = parse_switches(&dstinfo, argc, argv, 0, FALSE); jsrcerr.trace_level = jdsterr.trace_level; srcinfo.mem->max_memory_to_use = dstinfo.mem->max_memory_to_use; #ifdef TWO_FILE_COMMANDLINE /* Must have either -outfile switch or explicit output file name */ if (outfilename == NULL) { if (file_index != argc-2) { fprintf(stderr, "%s: must name one input and one output file\n", progname); usage(); } outfilename = argv[file_index+1]; } else { if (file_index != argc-1) { fprintf(stderr, "%s: must name one input and one output file\n", progname); usage(); } } #else /* Unix style: expect zero or one file name */ if (file_index < argc-1) { fprintf(stderr, "%s: only one input file\n", progname); usage(); } #endif /* TWO_FILE_COMMANDLINE */ /* Open the input file. */ if (file_index < argc) { if ((fp = fopen(argv[file_index], READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s for reading\n", progname, argv[file_index]); exit(EXIT_FAILURE); } } else { /* default input file is stdin */ fp = read_stdin(); } #ifdef PROGRESS_REPORT start_progress_monitor((j_common_ptr) &dstinfo, &progress); #endif /* Specify data source for decompression */ jpeg_stdio_src(&srcinfo, fp); /* Enable saving of extra markers that we want to copy */ jcopy_markers_setup(&srcinfo, copyoption); /* Read file header */ (void) jpeg_read_header(&srcinfo, TRUE); /* Adjust default decompression parameters */ if (scaleoption != NULL) if (sscanf(scaleoption, "%u/%u", &srcinfo.scale_num, &srcinfo.scale_denom) < 1) usage(); /* Any space needed by a transform option must be requested before * jpeg_read_coefficients so that memory allocation will be done right. */ #if TRANSFORMS_SUPPORTED /* Fail right away if -perfect is given and transformation is not perfect. */ if (!jtransform_request_workspace(&srcinfo, &transformoption)) { fprintf(stderr, "%s: transformation is not perfect\n", progname); exit(EXIT_FAILURE); } #endif /* Read source file as DCT coefficients */ src_coef_arrays = jpeg_read_coefficients(&srcinfo); /* Initialize destination compression parameters from source values */ jpeg_copy_critical_parameters(&srcinfo, &dstinfo); /* Adjust destination parameters if required by transform options; * also find out which set of coefficient arrays will hold the output. */ #if TRANSFORMS_SUPPORTED dst_coef_arrays = jtransform_adjust_parameters(&srcinfo, &dstinfo, src_coef_arrays, &transformoption); #else dst_coef_arrays = src_coef_arrays; #endif /* Close input file, if we opened it. * Note: we assume that jpeg_read_coefficients consumed all input * until JPEG_REACHED_EOI, and that jpeg_finish_decompress will * only consume more while (! cinfo->inputctl->eoi_reached). * We cannot call jpeg_finish_decompress here since we still need the * virtual arrays allocated from the source object for processing. */ if (fp != stdin) fclose(fp); /* Open the output file. */ if (outfilename != NULL) { if ((fp = fopen(outfilename, WRITE_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s for writing\n", progname, outfilename); exit(EXIT_FAILURE); } } else { /* default output file is stdout */ fp = write_stdout(); } /* Adjust default compression parameters by re-parsing the options */ file_index = parse_switches(&dstinfo, argc, argv, 0, TRUE); /* Specify data destination for compression */ jpeg_stdio_dest(&dstinfo, fp); /* Start compressor (note no image data is actually written here) */ jpeg_write_coefficients(&dstinfo, dst_coef_arrays); /* Copy to the output file any extra markers that we want to preserve */ jcopy_markers_execute(&srcinfo, &dstinfo, copyoption); /* Execute image transformation, if any */ #if TRANSFORMS_SUPPORTED jtransform_execute_transformation(&srcinfo, &dstinfo, src_coef_arrays, &transformoption); #endif /* Finish compression and release memory */ jpeg_finish_compress(&dstinfo); jpeg_destroy_compress(&dstinfo); (void) jpeg_finish_decompress(&srcinfo); jpeg_destroy_decompress(&srcinfo); /* Close output file, if we opened it */ if (fp != stdout) fclose(fp); #ifdef PROGRESS_REPORT end_progress_monitor((j_common_ptr) &dstinfo); #endif /* All done. */ exit(jsrcerr.num_warnings + jdsterr.num_warnings ?EXIT_WARNING:EXIT_SUCCESS); return 0; /* suppress no-return-value warnings */ } ================================================ FILE: tess-two/jni/libjpeg/jquant1.c ================================================ /* * jquant1.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2011 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains 1-pass color quantization (color mapping) routines. * These routines provide mapping to a fixed color map using equally spaced * color values. Optional Floyd-Steinberg or ordered dithering is available. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #ifdef QUANT_1PASS_SUPPORTED /* * The main purpose of 1-pass quantization is to provide a fast, if not very * high quality, colormapped output capability. A 2-pass quantizer usually * gives better visual quality; however, for quantized grayscale output this * quantizer is perfectly adequate. Dithering is highly recommended with this * quantizer, though you can turn it off if you really want to. * * In 1-pass quantization the colormap must be chosen in advance of seeing the * image. We use a map consisting of all combinations of Ncolors[i] color * values for the i'th component. The Ncolors[] values are chosen so that * their product, the total number of colors, is no more than that requested. * (In most cases, the product will be somewhat less.) * * Since the colormap is orthogonal, the representative value for each color * component can be determined without considering the other components; * then these indexes can be combined into a colormap index by a standard * N-dimensional-array-subscript calculation. Most of the arithmetic involved * can be precalculated and stored in the lookup table colorindex[]. * colorindex[i][j] maps pixel value j in component i to the nearest * representative value (grid plane) for that component; this index is * multiplied by the array stride for component i, so that the * index of the colormap entry closest to a given pixel value is just * sum( colorindex[component-number][pixel-component-value] ) * Aside from being fast, this scheme allows for variable spacing between * representative values with no additional lookup cost. * * If gamma correction has been applied in color conversion, it might be wise * to adjust the color grid spacing so that the representative colors are * equidistant in linear space. At this writing, gamma correction is not * implemented by jdcolor, so nothing is done here. */ /* Declarations for ordered dithering. * * We use a standard 16x16 ordered dither array. The basic concept of ordered * dithering is described in many references, for instance Dale Schumacher's * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991). * In place of Schumacher's comparisons against a "threshold" value, we add a * "dither" value to the input pixel and then round the result to the nearest * output value. The dither value is equivalent to (0.5 - threshold) times * the distance between output values. For ordered dithering, we assume that * the output colors are equally spaced; if not, results will probably be * worse, since the dither may be too much or too little at a given point. * * The normal calculation would be to form pixel value + dither, range-limit * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual. * We can skip the separate range-limiting step by extending the colorindex * table in both directions. */ #define ODITHER_SIZE 16 /* dimension of dither matrix */ /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */ #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */ #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */ typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE]; typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE]; static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = { /* Bayer's order-4 dither array. Generated by the code given in * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I. * The values in this array must range from 0 to ODITHER_CELLS-1. */ { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 }, { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 }, { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 }, { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 }, { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 }, { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 }, { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 }, { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 }, { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 }, { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 }, { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 }, { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 }, { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 }, { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 }, { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 }, { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 } }; /* Declarations for Floyd-Steinberg dithering. * * Errors are accumulated into the array fserrors[], at a resolution of * 1/16th of a pixel count. The error at a given pixel is propagated * to its not-yet-processed neighbors using the standard F-S fractions, * ... (here) 7/16 * 3/16 5/16 1/16 * We work left-to-right on even rows, right-to-left on odd rows. * * We can get away with a single array (holding one row's worth of errors) * by using it to store the current row's errors at pixel columns not yet * processed, but the next row's errors at columns already processed. We * need only a few extra variables to hold the errors immediately around the * current column. (If we are lucky, those variables are in registers, but * even if not, they're probably cheaper to access than array elements are.) * * The fserrors[] array is indexed [component#][position]. * We provide (#columns + 2) entries per component; the extra entry at each * end saves us from special-casing the first and last pixels. * * Note: on a wide image, we might not have enough room in a PC's near data * segment to hold the error array; so it is allocated with alloc_large. */ #if BITS_IN_JSAMPLE == 8 typedef INT16 FSERROR; /* 16 bits should be enough */ typedef int LOCFSERROR; /* use 'int' for calculation temps */ #else typedef INT32 FSERROR; /* may need more than 16 bits */ typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */ #endif typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */ /* Private subobject */ #define MAX_Q_COMPS 4 /* max components I can handle */ typedef struct { struct jpeg_color_quantizer pub; /* public fields */ /* Initially allocated colormap is saved here */ JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */ int sv_actual; /* number of entries in use */ JSAMPARRAY colorindex; /* Precomputed mapping for speed */ /* colorindex[i][j] = index of color closest to pixel value j in component i, * premultiplied as described above. Since colormap indexes must fit into * JSAMPLEs, the entries of this array will too. */ boolean is_padded; /* is the colorindex padded for odither? */ int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */ /* Variables for ordered dithering */ int row_index; /* cur row's vertical index in dither matrix */ ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */ /* Variables for Floyd-Steinberg dithering */ FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */ boolean on_odd_row; /* flag to remember which row we are on */ } my_cquantizer; typedef my_cquantizer * my_cquantize_ptr; /* * Policy-making subroutines for create_colormap and create_colorindex. * These routines determine the colormap to be used. The rest of the module * only assumes that the colormap is orthogonal. * * * select_ncolors decides how to divvy up the available colors * among the components. * * output_value defines the set of representative values for a component. * * largest_input_value defines the mapping from input values to * representative values for a component. * Note that the latter two routines may impose different policies for * different components, though this is not currently done. */ LOCAL(int) select_ncolors (j_decompress_ptr cinfo, int Ncolors[]) /* Determine allocation of desired colors to components, */ /* and fill in Ncolors[] array to indicate choice. */ /* Return value is total number of colors (product of Ncolors[] values). */ { int nc = cinfo->out_color_components; /* number of color components */ int max_colors = cinfo->desired_number_of_colors; int total_colors, iroot, i, j; boolean changed; long temp; static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE }; /* We can allocate at least the nc'th root of max_colors per component. */ /* Compute floor(nc'th root of max_colors). */ iroot = 1; do { iroot++; temp = iroot; /* set temp = iroot ** nc */ for (i = 1; i < nc; i++) temp *= iroot; } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */ iroot--; /* now iroot = floor(root) */ /* Must have at least 2 color values per component */ if (iroot < 2) ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp); /* Initialize to iroot color values for each component */ total_colors = 1; for (i = 0; i < nc; i++) { Ncolors[i] = iroot; total_colors *= iroot; } /* We may be able to increment the count for one or more components without * exceeding max_colors, though we know not all can be incremented. * Sometimes, the first component can be incremented more than once! * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.) * In RGB colorspace, try to increment G first, then R, then B. */ do { changed = FALSE; for (i = 0; i < nc; i++) { j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i); /* calculate new total_colors if Ncolors[j] is incremented */ temp = total_colors / Ncolors[j]; temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */ if (temp > (long) max_colors) break; /* won't fit, done with this pass */ Ncolors[j]++; /* OK, apply the increment */ total_colors = (int) temp; changed = TRUE; } } while (changed); return total_colors; } LOCAL(int) output_value (j_decompress_ptr cinfo, int ci, int j, int maxj) /* Return j'th output value, where j will range from 0 to maxj */ /* The output values must fall in 0..MAXJSAMPLE in increasing order */ { /* We always provide values 0 and MAXJSAMPLE for each component; * any additional values are equally spaced between these limits. * (Forcing the upper and lower values to the limits ensures that * dithering can't produce a color outside the selected gamut.) */ return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj); } LOCAL(int) largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj) /* Return largest input value that should map to j'th output value */ /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */ { /* Breakpoints are halfway between values returned by output_value */ return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj)); } /* * Create the colormap. */ LOCAL(void) create_colormap (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; JSAMPARRAY colormap; /* Created colormap */ int total_colors; /* Number of distinct output colors */ int i,j,k, nci, blksize, blkdist, ptr, val; /* Select number of colors for each component */ total_colors = select_ncolors(cinfo, cquantize->Ncolors); /* Report selected color counts */ if (cinfo->out_color_components == 3) TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS, total_colors, cquantize->Ncolors[0], cquantize->Ncolors[1], cquantize->Ncolors[2]); else TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors); /* Allocate and fill in the colormap. */ /* The colors are ordered in the map in standard row-major order, */ /* i.e. rightmost (highest-indexed) color changes most rapidly. */ colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components); /* blksize is number of adjacent repeated entries for a component */ /* blkdist is distance between groups of identical entries for a component */ blkdist = total_colors; for (i = 0; i < cinfo->out_color_components; i++) { /* fill in colormap entries for i'th color component */ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ blksize = blkdist / nci; for (j = 0; j < nci; j++) { /* Compute j'th output value (out of nci) for component */ val = output_value(cinfo, i, j, nci-1); /* Fill in all colormap entries that have this value of this component */ for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) { /* fill in blksize entries beginning at ptr */ for (k = 0; k < blksize; k++) colormap[i][ptr+k] = (JSAMPLE) val; } } blkdist = blksize; /* blksize of this color is blkdist of next */ } /* Save the colormap in private storage, * where it will survive color quantization mode changes. */ cquantize->sv_colormap = colormap; cquantize->sv_actual = total_colors; } /* * Create the color index table. */ LOCAL(void) create_colorindex (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; JSAMPROW indexptr; int i,j,k, nci, blksize, val, pad; /* For ordered dither, we pad the color index tables by MAXJSAMPLE in * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE). * This is not necessary in the other dithering modes. However, we * flag whether it was done in case user changes dithering mode. */ if (cinfo->dither_mode == JDITHER_ORDERED) { pad = MAXJSAMPLE*2; cquantize->is_padded = TRUE; } else { pad = 0; cquantize->is_padded = FALSE; } cquantize->colorindex = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) (MAXJSAMPLE+1 + pad), (JDIMENSION) cinfo->out_color_components); /* blksize is number of adjacent repeated entries for a component */ blksize = cquantize->sv_actual; for (i = 0; i < cinfo->out_color_components; i++) { /* fill in colorindex entries for i'th color component */ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ blksize = blksize / nci; /* adjust colorindex pointers to provide padding at negative indexes. */ if (pad) cquantize->colorindex[i] += MAXJSAMPLE; /* in loop, val = index of current output value, */ /* and k = largest j that maps to current val */ indexptr = cquantize->colorindex[i]; val = 0; k = largest_input_value(cinfo, i, 0, nci-1); for (j = 0; j <= MAXJSAMPLE; j++) { while (j > k) /* advance val if past boundary */ k = largest_input_value(cinfo, i, ++val, nci-1); /* premultiply so that no multiplication needed in main processing */ indexptr[j] = (JSAMPLE) (val * blksize); } /* Pad at both ends if necessary */ if (pad) for (j = 1; j <= MAXJSAMPLE; j++) { indexptr[-j] = indexptr[0]; indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE]; } } } /* * Create an ordered-dither array for a component having ncolors * distinct output values. */ LOCAL(ODITHER_MATRIX_PTR) make_odither_array (j_decompress_ptr cinfo, int ncolors) { ODITHER_MATRIX_PTR odither; int j,k; INT32 num,den; odither = (ODITHER_MATRIX_PTR) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(ODITHER_MATRIX)); /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1). * Hence the dither value for the matrix cell with fill order f * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1). * On 16-bit-int machine, be careful to avoid overflow. */ den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1)); for (j = 0; j < ODITHER_SIZE; j++) { for (k = 0; k < ODITHER_SIZE; k++) { num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k]))) * MAXJSAMPLE; /* Ensure round towards zero despite C's lack of consistency * about rounding negative values in integer division... */ odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den); } } return odither; } /* * Create the ordered-dither tables. * Components having the same number of representative colors may * share a dither table. */ LOCAL(void) create_odither_tables (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; ODITHER_MATRIX_PTR odither; int i, j, nci; for (i = 0; i < cinfo->out_color_components; i++) { nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ odither = NULL; /* search for matching prior component */ for (j = 0; j < i; j++) { if (nci == cquantize->Ncolors[j]) { odither = cquantize->odither[j]; break; } } if (odither == NULL) /* need a new table? */ odither = make_odither_array(cinfo, nci); cquantize->odither[i] = odither; } } /* * Map some rows of pixels to the output colormapped representation. */ METHODDEF(void) color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* General case, no dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; JSAMPARRAY colorindex = cquantize->colorindex; register int pixcode, ci; register JSAMPROW ptrin, ptrout; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; register int nc = cinfo->out_color_components; for (row = 0; row < num_rows; row++) { ptrin = input_buf[row]; ptrout = output_buf[row]; for (col = width; col > 0; col--) { pixcode = 0; for (ci = 0; ci < nc; ci++) { pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]); } *ptrout++ = (JSAMPLE) pixcode; } } } METHODDEF(void) color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* Fast path for out_color_components==3, no dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register int pixcode; register JSAMPROW ptrin, ptrout; JSAMPROW colorindex0 = cquantize->colorindex[0]; JSAMPROW colorindex1 = cquantize->colorindex[1]; JSAMPROW colorindex2 = cquantize->colorindex[2]; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { ptrin = input_buf[row]; ptrout = output_buf[row]; for (col = width; col > 0; col--) { pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]); pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]); pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]); *ptrout++ = (JSAMPLE) pixcode; } } } METHODDEF(void) quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* General case, with ordered dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register JSAMPROW input_ptr; register JSAMPROW output_ptr; JSAMPROW colorindex_ci; int * dither; /* points to active row of dither matrix */ int row_index, col_index; /* current indexes into dither matrix */ int nc = cinfo->out_color_components; int ci; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { /* Initialize output values to 0 so can process components separately */ FMEMZERO((void FAR *) output_buf[row], (size_t) (width * SIZEOF(JSAMPLE))); row_index = cquantize->row_index; for (ci = 0; ci < nc; ci++) { input_ptr = input_buf[row] + ci; output_ptr = output_buf[row]; colorindex_ci = cquantize->colorindex[ci]; dither = cquantize->odither[ci][row_index]; col_index = 0; for (col = width; col > 0; col--) { /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE, * select output value, accumulate into output code for this pixel. * Range-limiting need not be done explicitly, as we have extended * the colorindex table to produce the right answers for out-of-range * inputs. The maximum dither is +- MAXJSAMPLE; this sets the * required amount of padding. */ *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]]; input_ptr += nc; output_ptr++; col_index = (col_index + 1) & ODITHER_MASK; } } /* Advance row index for next row */ row_index = (row_index + 1) & ODITHER_MASK; cquantize->row_index = row_index; } } METHODDEF(void) quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* Fast path for out_color_components==3, with ordered dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register int pixcode; register JSAMPROW input_ptr; register JSAMPROW output_ptr; JSAMPROW colorindex0 = cquantize->colorindex[0]; JSAMPROW colorindex1 = cquantize->colorindex[1]; JSAMPROW colorindex2 = cquantize->colorindex[2]; int * dither0; /* points to active row of dither matrix */ int * dither1; int * dither2; int row_index, col_index; /* current indexes into dither matrix */ int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { row_index = cquantize->row_index; input_ptr = input_buf[row]; output_ptr = output_buf[row]; dither0 = cquantize->odither[0][row_index]; dither1 = cquantize->odither[1][row_index]; dither2 = cquantize->odither[2][row_index]; col_index = 0; for (col = width; col > 0; col--) { pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) + dither0[col_index]]); pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) + dither1[col_index]]); pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) + dither2[col_index]]); *output_ptr++ = (JSAMPLE) pixcode; col_index = (col_index + 1) & ODITHER_MASK; } row_index = (row_index + 1) & ODITHER_MASK; cquantize->row_index = row_index; } } METHODDEF(void) quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* General case, with Floyd-Steinberg dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register LOCFSERROR cur; /* current error or pixel value */ LOCFSERROR belowerr; /* error for pixel below cur */ LOCFSERROR bpreverr; /* error for below/prev col */ LOCFSERROR bnexterr; /* error for below/next col */ LOCFSERROR delta; register FSERRPTR errorptr; /* => fserrors[] at column before current */ register JSAMPROW input_ptr; register JSAMPROW output_ptr; JSAMPROW colorindex_ci; JSAMPROW colormap_ci; int pixcode; int nc = cinfo->out_color_components; int dir; /* 1 for left-to-right, -1 for right-to-left */ int dirnc; /* dir * nc */ int ci; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; JSAMPLE *range_limit = cinfo->sample_range_limit; SHIFT_TEMPS for (row = 0; row < num_rows; row++) { /* Initialize output values to 0 so can process components separately */ FMEMZERO((void FAR *) output_buf[row], (size_t) (width * SIZEOF(JSAMPLE))); for (ci = 0; ci < nc; ci++) { input_ptr = input_buf[row] + ci; output_ptr = output_buf[row]; if (cquantize->on_odd_row) { /* work right to left in this row */ input_ptr += (width-1) * nc; /* so point to rightmost pixel */ output_ptr += width-1; dir = -1; dirnc = -nc; errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */ } else { /* work left to right in this row */ dir = 1; dirnc = nc; errorptr = cquantize->fserrors[ci]; /* => entry before first column */ } colorindex_ci = cquantize->colorindex[ci]; colormap_ci = cquantize->sv_colormap[ci]; /* Preset error values: no error propagated to first pixel from left */ cur = 0; /* and no error propagated to row below yet */ belowerr = bpreverr = 0; for (col = width; col > 0; col--) { /* cur holds the error propagated from the previous pixel on the * current line. Add the error propagated from the previous line * to form the complete error correction term for this pixel, and * round the error term (which is expressed * 16) to an integer. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct * for either sign of the error value. * Note: errorptr points to *previous* column's array entry. */ cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4); /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE. * The maximum error is +- MAXJSAMPLE; this sets the required size * of the range_limit array. */ cur += GETJSAMPLE(*input_ptr); cur = GETJSAMPLE(range_limit[cur]); /* Select output value, accumulate into output code for this pixel */ pixcode = GETJSAMPLE(colorindex_ci[cur]); *output_ptr += (JSAMPLE) pixcode; /* Compute actual representation error at this pixel */ /* Note: we can do this even though we don't have the final */ /* pixel code, because the colormap is orthogonal. */ cur -= GETJSAMPLE(colormap_ci[pixcode]); /* Compute error fractions to be propagated to adjacent pixels. * Add these into the running sums, and simultaneously shift the * next-line error sums left by 1 column. */ bnexterr = cur; delta = cur * 2; cur += delta; /* form error * 3 */ errorptr[0] = (FSERROR) (bpreverr + cur); cur += delta; /* form error * 5 */ bpreverr = belowerr + cur; belowerr = bnexterr; cur += delta; /* form error * 7 */ /* At this point cur contains the 7/16 error value to be propagated * to the next pixel on the current line, and all the errors for the * next line have been shifted over. We are therefore ready to move on. */ input_ptr += dirnc; /* advance input ptr to next column */ output_ptr += dir; /* advance output ptr to next column */ errorptr += dir; /* advance errorptr to current column */ } /* Post-loop cleanup: we must unload the final error value into the * final fserrors[] entry. Note we need not unload belowerr because * it is for the dummy column before or after the actual array. */ errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */ } cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE); } } /* * Allocate workspace for Floyd-Steinberg errors. */ LOCAL(void) alloc_fs_workspace (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; size_t arraysize; int i; arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR)); for (i = 0; i < cinfo->out_color_components; i++) { cquantize->fserrors[i] = (FSERRPTR) (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize); } } /* * Initialize for one-pass color quantization. */ METHODDEF(void) start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; size_t arraysize; int i; /* Install my colormap. */ cinfo->colormap = cquantize->sv_colormap; cinfo->actual_number_of_colors = cquantize->sv_actual; /* Initialize for desired dithering mode. */ switch (cinfo->dither_mode) { case JDITHER_NONE: if (cinfo->out_color_components == 3) cquantize->pub.color_quantize = color_quantize3; else cquantize->pub.color_quantize = color_quantize; break; case JDITHER_ORDERED: if (cinfo->out_color_components == 3) cquantize->pub.color_quantize = quantize3_ord_dither; else cquantize->pub.color_quantize = quantize_ord_dither; cquantize->row_index = 0; /* initialize state for ordered dither */ /* If user changed to ordered dither from another mode, * we must recreate the color index table with padding. * This will cost extra space, but probably isn't very likely. */ if (! cquantize->is_padded) create_colorindex(cinfo); /* Create ordered-dither tables if we didn't already. */ if (cquantize->odither[0] == NULL) create_odither_tables(cinfo); break; case JDITHER_FS: cquantize->pub.color_quantize = quantize_fs_dither; cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */ /* Allocate Floyd-Steinberg workspace if didn't already. */ if (cquantize->fserrors[0] == NULL) alloc_fs_workspace(cinfo); /* Initialize the propagated errors to zero. */ arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR)); for (i = 0; i < cinfo->out_color_components; i++) FMEMZERO((void FAR *) cquantize->fserrors[i], arraysize); break; default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } } /* * Finish up at the end of the pass. */ METHODDEF(void) finish_pass_1_quant (j_decompress_ptr cinfo) { /* no work in 1-pass case */ } /* * Switch to a new external colormap between output passes. * Shouldn't get to this module! */ METHODDEF(void) new_color_map_1_quant (j_decompress_ptr cinfo) { ERREXIT(cinfo, JERR_MODE_CHANGE); } /* * Module initialization routine for 1-pass color quantization. */ GLOBAL(void) jinit_1pass_quantizer (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize; cquantize = (my_cquantize_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_cquantizer)); cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize; cquantize->pub.start_pass = start_pass_1_quant; cquantize->pub.finish_pass = finish_pass_1_quant; cquantize->pub.new_color_map = new_color_map_1_quant; cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */ cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */ /* Make sure my internal arrays won't overflow */ if (cinfo->out_color_components > MAX_Q_COMPS) ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS); /* Make sure colormap indexes can be represented by JSAMPLEs */ if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1)) ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1); /* Create the colormap and color index table. */ create_colormap(cinfo); create_colorindex(cinfo); /* Allocate Floyd-Steinberg workspace now if requested. * We do this now since it is FAR storage and may affect the memory * manager's space calculations. If the user changes to FS dither * mode in a later pass, we will allocate the space then, and will * possibly overrun the max_memory_to_use setting. */ if (cinfo->dither_mode == JDITHER_FS) alloc_fs_workspace(cinfo); } #endif /* QUANT_1PASS_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jquant2.c ================================================ /* * jquant2.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2011 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains 2-pass color quantization (color mapping) routines. * These routines provide selection of a custom color map for an image, * followed by mapping of the image to that color map, with optional * Floyd-Steinberg dithering. * It is also possible to use just the second pass to map to an arbitrary * externally-given color map. * * Note: ordered dithering is not supported, since there isn't any fast * way to compute intercolor distances; it's unclear that ordered dither's * fundamental assumptions even hold with an irregularly spaced color map. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #ifdef QUANT_2PASS_SUPPORTED /* * This module implements the well-known Heckbert paradigm for color * quantization. Most of the ideas used here can be traced back to * Heckbert's seminal paper * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display", * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304. * * In the first pass over the image, we accumulate a histogram showing the * usage count of each possible color. To keep the histogram to a reasonable * size, we reduce the precision of the input; typical practice is to retain * 5 or 6 bits per color, so that 8 or 4 different input values are counted * in the same histogram cell. * * Next, the color-selection step begins with a box representing the whole * color space, and repeatedly splits the "largest" remaining box until we * have as many boxes as desired colors. Then the mean color in each * remaining box becomes one of the possible output colors. * * The second pass over the image maps each input pixel to the closest output * color (optionally after applying a Floyd-Steinberg dithering correction). * This mapping is logically trivial, but making it go fast enough requires * considerable care. * * Heckbert-style quantizers vary a good deal in their policies for choosing * the "largest" box and deciding where to cut it. The particular policies * used here have proved out well in experimental comparisons, but better ones * may yet be found. * * In earlier versions of the IJG code, this module quantized in YCbCr color * space, processing the raw upsampled data without a color conversion step. * This allowed the color conversion math to be done only once per colormap * entry, not once per pixel. However, that optimization precluded other * useful optimizations (such as merging color conversion with upsampling) * and it also interfered with desired capabilities such as quantizing to an * externally-supplied colormap. We have therefore abandoned that approach. * The present code works in the post-conversion color space, typically RGB. * * To improve the visual quality of the results, we actually work in scaled * RGB space, giving G distances more weight than R, and R in turn more than * B. To do everything in integer math, we must use integer scale factors. * The 2/3/1 scale factors used here correspond loosely to the relative * weights of the colors in the NTSC grayscale equation. * If you want to use this code to quantize a non-RGB color space, you'll * probably need to change these scale factors. */ #define R_SCALE 2 /* scale R distances by this much */ #define G_SCALE 3 /* scale G distances by this much */ #define B_SCALE 1 /* and B by this much */ /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B * and B,G,R orders. If you define some other weird order in jmorecfg.h, * you'll get compile errors until you extend this logic. In that case * you'll probably want to tweak the histogram sizes too. */ #if RGB_RED == 0 #define C0_SCALE R_SCALE #endif #if RGB_BLUE == 0 #define C0_SCALE B_SCALE #endif #if RGB_GREEN == 1 #define C1_SCALE G_SCALE #endif #if RGB_RED == 2 #define C2_SCALE R_SCALE #endif #if RGB_BLUE == 2 #define C2_SCALE B_SCALE #endif /* * First we have the histogram data structure and routines for creating it. * * The number of bits of precision can be adjusted by changing these symbols. * We recommend keeping 6 bits for G and 5 each for R and B. * If you have plenty of memory and cycles, 6 bits all around gives marginally * better results; if you are short of memory, 5 bits all around will save * some space but degrade the results. * To maintain a fully accurate histogram, we'd need to allocate a "long" * (preferably unsigned long) for each cell. In practice this is overkill; * we can get by with 16 bits per cell. Few of the cell counts will overflow, * and clamping those that do overflow to the maximum value will give close- * enough results. This reduces the recommended histogram size from 256Kb * to 128Kb, which is a useful savings on PC-class machines. * (In the second pass the histogram space is re-used for pixel mapping data; * in that capacity, each cell must be able to store zero to the number of * desired colors. 16 bits/cell is plenty for that too.) * Since the JPEG code is intended to run in small memory model on 80x86 * machines, we can't just allocate the histogram in one chunk. Instead * of a true 3-D array, we use a row of pointers to 2-D arrays. Each * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that * on 80x86 machines, the pointer row is in near memory but the actual * arrays are in far memory (same arrangement as we use for image arrays). */ #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */ /* These will do the right thing for either R,G,B or B,G,R color order, * but you may not like the results for other color orders. */ #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */ #define HIST_C1_BITS 6 /* bits of precision in G histogram */ #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */ /* Number of elements along histogram axes. */ #define HIST_C0_ELEMS (1<cquantize; register JSAMPROW ptr; register histptr histp; register hist3d histogram = cquantize->histogram; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { ptr = input_buf[row]; for (col = width; col > 0; col--) { /* get pixel value and index into the histogram */ histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT] [GETJSAMPLE(ptr[1]) >> C1_SHIFT] [GETJSAMPLE(ptr[2]) >> C2_SHIFT]; /* increment, check for overflow and undo increment if so. */ if (++(*histp) <= 0) (*histp)--; ptr += 3; } } } /* * Next we have the really interesting routines: selection of a colormap * given the completed histogram. * These routines work with a list of "boxes", each representing a rectangular * subset of the input color space (to histogram precision). */ typedef struct { /* The bounds of the box (inclusive); expressed as histogram indexes */ int c0min, c0max; int c1min, c1max; int c2min, c2max; /* The volume (actually 2-norm) of the box */ INT32 volume; /* The number of nonzero histogram cells within this box */ long colorcount; } box; typedef box * boxptr; LOCAL(boxptr) find_biggest_color_pop (boxptr boxlist, int numboxes) /* Find the splittable box with the largest color population */ /* Returns NULL if no splittable boxes remain */ { register boxptr boxp; register int i; register long maxc = 0; boxptr which = NULL; for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) { if (boxp->colorcount > maxc && boxp->volume > 0) { which = boxp; maxc = boxp->colorcount; } } return which; } LOCAL(boxptr) find_biggest_volume (boxptr boxlist, int numboxes) /* Find the splittable box with the largest (scaled) volume */ /* Returns NULL if no splittable boxes remain */ { register boxptr boxp; register int i; register INT32 maxv = 0; boxptr which = NULL; for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) { if (boxp->volume > maxv) { which = boxp; maxv = boxp->volume; } } return which; } LOCAL(void) update_box (j_decompress_ptr cinfo, boxptr boxp) /* Shrink the min/max bounds of a box to enclose only nonzero elements, */ /* and recompute its volume and population */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; hist3d histogram = cquantize->histogram; histptr histp; int c0,c1,c2; int c0min,c0max,c1min,c1max,c2min,c2max; INT32 dist0,dist1,dist2; long ccount; c0min = boxp->c0min; c0max = boxp->c0max; c1min = boxp->c1min; c1max = boxp->c1max; c2min = boxp->c2min; c2max = boxp->c2max; if (c0max > c0min) for (c0 = c0min; c0 <= c0max; c0++) for (c1 = c1min; c1 <= c1max; c1++) { histp = & histogram[c0][c1][c2min]; for (c2 = c2min; c2 <= c2max; c2++) if (*histp++ != 0) { boxp->c0min = c0min = c0; goto have_c0min; } } have_c0min: if (c0max > c0min) for (c0 = c0max; c0 >= c0min; c0--) for (c1 = c1min; c1 <= c1max; c1++) { histp = & histogram[c0][c1][c2min]; for (c2 = c2min; c2 <= c2max; c2++) if (*histp++ != 0) { boxp->c0max = c0max = c0; goto have_c0max; } } have_c0max: if (c1max > c1min) for (c1 = c1min; c1 <= c1max; c1++) for (c0 = c0min; c0 <= c0max; c0++) { histp = & histogram[c0][c1][c2min]; for (c2 = c2min; c2 <= c2max; c2++) if (*histp++ != 0) { boxp->c1min = c1min = c1; goto have_c1min; } } have_c1min: if (c1max > c1min) for (c1 = c1max; c1 >= c1min; c1--) for (c0 = c0min; c0 <= c0max; c0++) { histp = & histogram[c0][c1][c2min]; for (c2 = c2min; c2 <= c2max; c2++) if (*histp++ != 0) { boxp->c1max = c1max = c1; goto have_c1max; } } have_c1max: if (c2max > c2min) for (c2 = c2min; c2 <= c2max; c2++) for (c0 = c0min; c0 <= c0max; c0++) { histp = & histogram[c0][c1min][c2]; for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS) if (*histp != 0) { boxp->c2min = c2min = c2; goto have_c2min; } } have_c2min: if (c2max > c2min) for (c2 = c2max; c2 >= c2min; c2--) for (c0 = c0min; c0 <= c0max; c0++) { histp = & histogram[c0][c1min][c2]; for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS) if (*histp != 0) { boxp->c2max = c2max = c2; goto have_c2max; } } have_c2max: /* Update box volume. * We use 2-norm rather than real volume here; this biases the method * against making long narrow boxes, and it has the side benefit that * a box is splittable iff norm > 0. * Since the differences are expressed in histogram-cell units, * we have to shift back to JSAMPLE units to get consistent distances; * after which, we scale according to the selected distance scale factors. */ dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE; dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE; dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE; boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2; /* Now scan remaining volume of box and compute population */ ccount = 0; for (c0 = c0min; c0 <= c0max; c0++) for (c1 = c1min; c1 <= c1max; c1++) { histp = & histogram[c0][c1][c2min]; for (c2 = c2min; c2 <= c2max; c2++, histp++) if (*histp != 0) { ccount++; } } boxp->colorcount = ccount; } LOCAL(int) median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes, int desired_colors) /* Repeatedly select and split the largest box until we have enough boxes */ { int n,lb; int c0,c1,c2,cmax; register boxptr b1,b2; while (numboxes < desired_colors) { /* Select box to split. * Current algorithm: by population for first half, then by volume. */ if (numboxes*2 <= desired_colors) { b1 = find_biggest_color_pop(boxlist, numboxes); } else { b1 = find_biggest_volume(boxlist, numboxes); } if (b1 == NULL) /* no splittable boxes left! */ break; b2 = &boxlist[numboxes]; /* where new box will go */ /* Copy the color bounds to the new box. */ b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max; b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min; /* Choose which axis to split the box on. * Current algorithm: longest scaled axis. * See notes in update_box about scaling distances. */ c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE; c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE; c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE; /* We want to break any ties in favor of green, then red, blue last. * This code does the right thing for R,G,B or B,G,R color orders only. */ #if RGB_RED == 0 cmax = c1; n = 1; if (c0 > cmax) { cmax = c0; n = 0; } if (c2 > cmax) { n = 2; } #else cmax = c1; n = 1; if (c2 > cmax) { cmax = c2; n = 2; } if (c0 > cmax) { n = 0; } #endif /* Choose split point along selected axis, and update box bounds. * Current algorithm: split at halfway point. * (Since the box has been shrunk to minimum volume, * any split will produce two nonempty subboxes.) * Note that lb value is max for lower box, so must be < old max. */ switch (n) { case 0: lb = (b1->c0max + b1->c0min) / 2; b1->c0max = lb; b2->c0min = lb+1; break; case 1: lb = (b1->c1max + b1->c1min) / 2; b1->c1max = lb; b2->c1min = lb+1; break; case 2: lb = (b1->c2max + b1->c2min) / 2; b1->c2max = lb; b2->c2min = lb+1; break; } /* Update stats for boxes */ update_box(cinfo, b1); update_box(cinfo, b2); numboxes++; } return numboxes; } LOCAL(void) compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor) /* Compute representative color for a box, put it in colormap[icolor] */ { /* Current algorithm: mean weighted by pixels (not colors) */ /* Note it is important to get the rounding correct! */ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; hist3d histogram = cquantize->histogram; histptr histp; int c0,c1,c2; int c0min,c0max,c1min,c1max,c2min,c2max; long count; long total = 0; long c0total = 0; long c1total = 0; long c2total = 0; c0min = boxp->c0min; c0max = boxp->c0max; c1min = boxp->c1min; c1max = boxp->c1max; c2min = boxp->c2min; c2max = boxp->c2max; for (c0 = c0min; c0 <= c0max; c0++) for (c1 = c1min; c1 <= c1max; c1++) { histp = & histogram[c0][c1][c2min]; for (c2 = c2min; c2 <= c2max; c2++) { if ((count = *histp++) != 0) { total += count; c0total += ((c0 << C0_SHIFT) + ((1<>1)) * count; c1total += ((c1 << C1_SHIFT) + ((1<>1)) * count; c2total += ((c2 << C2_SHIFT) + ((1<>1)) * count; } } } cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total); cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total); cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total); } LOCAL(void) select_colors (j_decompress_ptr cinfo, int desired_colors) /* Master routine for color selection */ { boxptr boxlist; int numboxes; int i; /* Allocate workspace for box list */ boxlist = (boxptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box)); /* Initialize one box containing whole space */ numboxes = 1; boxlist[0].c0min = 0; boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT; boxlist[0].c1min = 0; boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT; boxlist[0].c2min = 0; boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT; /* Shrink it to actually-used volume and set its statistics */ update_box(cinfo, & boxlist[0]); /* Perform median-cut to produce final box list */ numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors); /* Compute the representative color for each box, fill colormap */ for (i = 0; i < numboxes; i++) compute_color(cinfo, & boxlist[i], i); cinfo->actual_number_of_colors = numboxes; TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes); } /* * These routines are concerned with the time-critical task of mapping input * colors to the nearest color in the selected colormap. * * We re-use the histogram space as an "inverse color map", essentially a * cache for the results of nearest-color searches. All colors within a * histogram cell will be mapped to the same colormap entry, namely the one * closest to the cell's center. This may not be quite the closest entry to * the actual input color, but it's almost as good. A zero in the cache * indicates we haven't found the nearest color for that cell yet; the array * is cleared to zeroes before starting the mapping pass. When we find the * nearest color for a cell, its colormap index plus one is recorded in the * cache for future use. The pass2 scanning routines call fill_inverse_cmap * when they need to use an unfilled entry in the cache. * * Our method of efficiently finding nearest colors is based on the "locally * sorted search" idea described by Heckbert and on the incremental distance * calculation described by Spencer W. Thomas in chapter III.1 of Graphics * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that * the distances from a given colormap entry to each cell of the histogram can * be computed quickly using an incremental method: the differences between * distances to adjacent cells themselves differ by a constant. This allows a * fairly fast implementation of the "brute force" approach of computing the * distance from every colormap entry to every histogram cell. Unfortunately, * it needs a work array to hold the best-distance-so-far for each histogram * cell (because the inner loop has to be over cells, not colormap entries). * The work array elements have to be INT32s, so the work array would need * 256Kb at our recommended precision. This is not feasible in DOS machines. * * To get around these problems, we apply Thomas' method to compute the * nearest colors for only the cells within a small subbox of the histogram. * The work array need be only as big as the subbox, so the memory usage * problem is solved. Furthermore, we need not fill subboxes that are never * referenced in pass2; many images use only part of the color gamut, so a * fair amount of work is saved. An additional advantage of this * approach is that we can apply Heckbert's locality criterion to quickly * eliminate colormap entries that are far away from the subbox; typically * three-fourths of the colormap entries are rejected by Heckbert's criterion, * and we need not compute their distances to individual cells in the subbox. * The speed of this approach is heavily influenced by the subbox size: too * small means too much overhead, too big loses because Heckbert's criterion * can't eliminate as many colormap entries. Empirically the best subbox * size seems to be about 1/512th of the histogram (1/8th in each direction). * * Thomas' article also describes a refined method which is asymptotically * faster than the brute-force method, but it is also far more complex and * cannot efficiently be applied to small subboxes. It is therefore not * useful for programs intended to be portable to DOS machines. On machines * with plenty of memory, filling the whole histogram in one shot with Thomas' * refined method might be faster than the present code --- but then again, * it might not be any faster, and it's certainly more complicated. */ /* log2(histogram cells in update box) for each axis; this can be adjusted */ #define BOX_C0_LOG (HIST_C0_BITS-3) #define BOX_C1_LOG (HIST_C1_BITS-3) #define BOX_C2_LOG (HIST_C2_BITS-3) #define BOX_C0_ELEMS (1<actual_number_of_colors; int maxc0, maxc1, maxc2; int centerc0, centerc1, centerc2; int i, x, ncolors; INT32 minmaxdist, min_dist, max_dist, tdist; INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */ /* Compute true coordinates of update box's upper corner and center. * Actually we compute the coordinates of the center of the upper-corner * histogram cell, which are the upper bounds of the volume we care about. * Note that since ">>" rounds down, the "center" values may be closer to * min than to max; hence comparisons to them must be "<=", not "<". */ maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT)); centerc0 = (minc0 + maxc0) >> 1; maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT)); centerc1 = (minc1 + maxc1) >> 1; maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT)); centerc2 = (minc2 + maxc2) >> 1; /* For each color in colormap, find: * 1. its minimum squared-distance to any point in the update box * (zero if color is within update box); * 2. its maximum squared-distance to any point in the update box. * Both of these can be found by considering only the corners of the box. * We save the minimum distance for each color in mindist[]; * only the smallest maximum distance is of interest. */ minmaxdist = 0x7FFFFFFFL; for (i = 0; i < numcolors; i++) { /* We compute the squared-c0-distance term, then add in the other two. */ x = GETJSAMPLE(cinfo->colormap[0][i]); if (x < minc0) { tdist = (x - minc0) * C0_SCALE; min_dist = tdist*tdist; tdist = (x - maxc0) * C0_SCALE; max_dist = tdist*tdist; } else if (x > maxc0) { tdist = (x - maxc0) * C0_SCALE; min_dist = tdist*tdist; tdist = (x - minc0) * C0_SCALE; max_dist = tdist*tdist; } else { /* within cell range so no contribution to min_dist */ min_dist = 0; if (x <= centerc0) { tdist = (x - maxc0) * C0_SCALE; max_dist = tdist*tdist; } else { tdist = (x - minc0) * C0_SCALE; max_dist = tdist*tdist; } } x = GETJSAMPLE(cinfo->colormap[1][i]); if (x < minc1) { tdist = (x - minc1) * C1_SCALE; min_dist += tdist*tdist; tdist = (x - maxc1) * C1_SCALE; max_dist += tdist*tdist; } else if (x > maxc1) { tdist = (x - maxc1) * C1_SCALE; min_dist += tdist*tdist; tdist = (x - minc1) * C1_SCALE; max_dist += tdist*tdist; } else { /* within cell range so no contribution to min_dist */ if (x <= centerc1) { tdist = (x - maxc1) * C1_SCALE; max_dist += tdist*tdist; } else { tdist = (x - minc1) * C1_SCALE; max_dist += tdist*tdist; } } x = GETJSAMPLE(cinfo->colormap[2][i]); if (x < minc2) { tdist = (x - minc2) * C2_SCALE; min_dist += tdist*tdist; tdist = (x - maxc2) * C2_SCALE; max_dist += tdist*tdist; } else if (x > maxc2) { tdist = (x - maxc2) * C2_SCALE; min_dist += tdist*tdist; tdist = (x - minc2) * C2_SCALE; max_dist += tdist*tdist; } else { /* within cell range so no contribution to min_dist */ if (x <= centerc2) { tdist = (x - maxc2) * C2_SCALE; max_dist += tdist*tdist; } else { tdist = (x - minc2) * C2_SCALE; max_dist += tdist*tdist; } } mindist[i] = min_dist; /* save away the results */ if (max_dist < minmaxdist) minmaxdist = max_dist; } /* Now we know that no cell in the update box is more than minmaxdist * away from some colormap entry. Therefore, only colors that are * within minmaxdist of some part of the box need be considered. */ ncolors = 0; for (i = 0; i < numcolors; i++) { if (mindist[i] <= minmaxdist) colorlist[ncolors++] = (JSAMPLE) i; } return ncolors; } LOCAL(void) find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2, int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[]) /* Find the closest colormap entry for each cell in the update box, * given the list of candidate colors prepared by find_nearby_colors. * Return the indexes of the closest entries in the bestcolor[] array. * This routine uses Thomas' incremental distance calculation method to * find the distance from a colormap entry to successive cells in the box. */ { int ic0, ic1, ic2; int i, icolor; register INT32 * bptr; /* pointer into bestdist[] array */ JSAMPLE * cptr; /* pointer into bestcolor[] array */ INT32 dist0, dist1; /* initial distance values */ register INT32 dist2; /* current distance in inner loop */ INT32 xx0, xx1; /* distance increments */ register INT32 xx2; INT32 inc0, inc1, inc2; /* initial values for increments */ /* This array holds the distance to the nearest-so-far color for each cell */ INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS]; /* Initialize best-distance for each cell of the update box */ bptr = bestdist; for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--) *bptr++ = 0x7FFFFFFFL; /* For each color selected by find_nearby_colors, * compute its distance to the center of each cell in the box. * If that's less than best-so-far, update best distance and color number. */ /* Nominal steps between cell centers ("x" in Thomas article) */ #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE) #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE) #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE) for (i = 0; i < numcolors; i++) { icolor = GETJSAMPLE(colorlist[i]); /* Compute (square of) distance from minc0/c1/c2 to this color */ inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE; dist0 = inc0*inc0; inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE; dist0 += inc1*inc1; inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE; dist0 += inc2*inc2; /* Form the initial difference increments */ inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0; inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1; inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2; /* Now loop over all cells in box, updating distance per Thomas method */ bptr = bestdist; cptr = bestcolor; xx0 = inc0; for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) { dist1 = dist0; xx1 = inc1; for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) { dist2 = dist1; xx2 = inc2; for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) { if (dist2 < *bptr) { *bptr = dist2; *cptr = (JSAMPLE) icolor; } dist2 += xx2; xx2 += 2 * STEP_C2 * STEP_C2; bptr++; cptr++; } dist1 += xx1; xx1 += 2 * STEP_C1 * STEP_C1; } dist0 += xx0; xx0 += 2 * STEP_C0 * STEP_C0; } } } LOCAL(void) fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2) /* Fill the inverse-colormap entries in the update box that contains */ /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */ /* we can fill as many others as we wish.) */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; hist3d histogram = cquantize->histogram; int minc0, minc1, minc2; /* lower left corner of update box */ int ic0, ic1, ic2; register JSAMPLE * cptr; /* pointer into bestcolor[] array */ register histptr cachep; /* pointer into main cache array */ /* This array lists the candidate colormap indexes. */ JSAMPLE colorlist[MAXNUMCOLORS]; int numcolors; /* number of candidate colors */ /* This array holds the actually closest colormap index for each cell. */ JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS]; /* Convert cell coordinates to update box ID */ c0 >>= BOX_C0_LOG; c1 >>= BOX_C1_LOG; c2 >>= BOX_C2_LOG; /* Compute true coordinates of update box's origin corner. * Actually we compute the coordinates of the center of the corner * histogram cell, which are the lower bounds of the volume we care about. */ minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1); minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1); minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1); /* Determine which colormap entries are close enough to be candidates * for the nearest entry to some cell in the update box. */ numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist); /* Determine the actually nearest colors. */ find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist, bestcolor); /* Save the best color numbers (plus 1) in the main cache array */ c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */ c1 <<= BOX_C1_LOG; c2 <<= BOX_C2_LOG; cptr = bestcolor; for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) { for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) { cachep = & histogram[c0+ic0][c1+ic1][c2]; for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) { *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1); } } } } /* * Map some rows of pixels to the output colormapped representation. */ METHODDEF(void) pass2_no_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* This version performs no dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; hist3d histogram = cquantize->histogram; register JSAMPROW inptr, outptr; register histptr cachep; register int c0, c1, c2; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { inptr = input_buf[row]; outptr = output_buf[row]; for (col = width; col > 0; col--) { /* get pixel value and index into the cache */ c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT; c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT; c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT; cachep = & histogram[c0][c1][c2]; /* If we have not seen this color before, find nearest colormap entry */ /* and update the cache */ if (*cachep == 0) fill_inverse_cmap(cinfo, c0,c1,c2); /* Now emit the colormap index for this cell */ *outptr++ = (JSAMPLE) (*cachep - 1); } } } METHODDEF(void) pass2_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* This version performs Floyd-Steinberg dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; hist3d histogram = cquantize->histogram; register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */ LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */ LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */ register FSERRPTR errorptr; /* => fserrors[] at column before current */ JSAMPROW inptr; /* => current input pixel */ JSAMPROW outptr; /* => current output pixel */ histptr cachep; int dir; /* +1 or -1 depending on direction */ int dir3; /* 3*dir, for advancing inptr & errorptr */ int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; JSAMPLE *range_limit = cinfo->sample_range_limit; int *error_limit = cquantize->error_limiter; JSAMPROW colormap0 = cinfo->colormap[0]; JSAMPROW colormap1 = cinfo->colormap[1]; JSAMPROW colormap2 = cinfo->colormap[2]; SHIFT_TEMPS for (row = 0; row < num_rows; row++) { inptr = input_buf[row]; outptr = output_buf[row]; if (cquantize->on_odd_row) { /* work right to left in this row */ inptr += (width-1) * 3; /* so point to rightmost pixel */ outptr += width-1; dir = -1; dir3 = -3; errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */ cquantize->on_odd_row = FALSE; /* flip for next time */ } else { /* work left to right in this row */ dir = 1; dir3 = 3; errorptr = cquantize->fserrors; /* => entry before first real column */ cquantize->on_odd_row = TRUE; /* flip for next time */ } /* Preset error values: no error propagated to first pixel from left */ cur0 = cur1 = cur2 = 0; /* and no error propagated to row below yet */ belowerr0 = belowerr1 = belowerr2 = 0; bpreverr0 = bpreverr1 = bpreverr2 = 0; for (col = width; col > 0; col--) { /* curN holds the error propagated from the previous pixel on the * current line. Add the error propagated from the previous line * to form the complete error correction term for this pixel, and * round the error term (which is expressed * 16) to an integer. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct * for either sign of the error value. * Note: errorptr points to *previous* column's array entry. */ cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4); cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4); cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4); /* Limit the error using transfer function set by init_error_limit. * See comments with init_error_limit for rationale. */ cur0 = error_limit[cur0]; cur1 = error_limit[cur1]; cur2 = error_limit[cur2]; /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE. * The maximum error is +- MAXJSAMPLE (or less with error limiting); * this sets the required size of the range_limit array. */ cur0 += GETJSAMPLE(inptr[0]); cur1 += GETJSAMPLE(inptr[1]); cur2 += GETJSAMPLE(inptr[2]); cur0 = GETJSAMPLE(range_limit[cur0]); cur1 = GETJSAMPLE(range_limit[cur1]); cur2 = GETJSAMPLE(range_limit[cur2]); /* Index into the cache with adjusted pixel value */ cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT]; /* If we have not seen this color before, find nearest colormap */ /* entry and update the cache */ if (*cachep == 0) fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT); /* Now emit the colormap index for this cell */ { register int pixcode = *cachep - 1; *outptr = (JSAMPLE) pixcode; /* Compute representation error for this pixel */ cur0 -= GETJSAMPLE(colormap0[pixcode]); cur1 -= GETJSAMPLE(colormap1[pixcode]); cur2 -= GETJSAMPLE(colormap2[pixcode]); } /* Compute error fractions to be propagated to adjacent pixels. * Add these into the running sums, and simultaneously shift the * next-line error sums left by 1 column. */ { register LOCFSERROR bnexterr, delta; bnexterr = cur0; /* Process component 0 */ delta = cur0 * 2; cur0 += delta; /* form error * 3 */ errorptr[0] = (FSERROR) (bpreverr0 + cur0); cur0 += delta; /* form error * 5 */ bpreverr0 = belowerr0 + cur0; belowerr0 = bnexterr; cur0 += delta; /* form error * 7 */ bnexterr = cur1; /* Process component 1 */ delta = cur1 * 2; cur1 += delta; /* form error * 3 */ errorptr[1] = (FSERROR) (bpreverr1 + cur1); cur1 += delta; /* form error * 5 */ bpreverr1 = belowerr1 + cur1; belowerr1 = bnexterr; cur1 += delta; /* form error * 7 */ bnexterr = cur2; /* Process component 2 */ delta = cur2 * 2; cur2 += delta; /* form error * 3 */ errorptr[2] = (FSERROR) (bpreverr2 + cur2); cur2 += delta; /* form error * 5 */ bpreverr2 = belowerr2 + cur2; belowerr2 = bnexterr; cur2 += delta; /* form error * 7 */ } /* At this point curN contains the 7/16 error value to be propagated * to the next pixel on the current line, and all the errors for the * next line have been shifted over. We are therefore ready to move on. */ inptr += dir3; /* Advance pixel pointers to next column */ outptr += dir; errorptr += dir3; /* advance errorptr to current column */ } /* Post-loop cleanup: we must unload the final error values into the * final fserrors[] entry. Note we need not unload belowerrN because * it is for the dummy column before or after the actual array. */ errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */ errorptr[1] = (FSERROR) bpreverr1; errorptr[2] = (FSERROR) bpreverr2; } } /* * Initialize the error-limiting transfer function (lookup table). * The raw F-S error computation can potentially compute error values of up to * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be * much less, otherwise obviously wrong pixels will be created. (Typical * effects include weird fringes at color-area boundaries, isolated bright * pixels in a dark area, etc.) The standard advice for avoiding this problem * is to ensure that the "corners" of the color cube are allocated as output * colors; then repeated errors in the same direction cannot cause cascading * error buildup. However, that only prevents the error from getting * completely out of hand; Aaron Giles reports that error limiting improves * the results even with corner colors allocated. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty * well, but the smoother transfer function used below is even better. Thanks * to Aaron Giles for this idea. */ LOCAL(void) init_error_limit (j_decompress_ptr cinfo) /* Allocate and fill in the error_limiter table */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; int * table; int in, out; table = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int)); table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */ cquantize->error_limiter = table; #define STEPSIZE ((MAXJSAMPLE+1)/16) /* Map errors 1:1 up to +- MAXJSAMPLE/16 */ out = 0; for (in = 0; in < STEPSIZE; in++, out++) { table[in] = out; table[-in] = -out; } /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */ for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) { table[in] = out; table[-in] = -out; } /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */ for (; in <= MAXJSAMPLE; in++) { table[in] = out; table[-in] = -out; } #undef STEPSIZE } /* * Finish up at the end of each pass. */ METHODDEF(void) finish_pass1 (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; /* Select the representative colors and fill in cinfo->colormap */ cinfo->colormap = cquantize->sv_colormap; select_colors(cinfo, cquantize->desired); /* Force next pass to zero the color index table */ cquantize->needs_zeroed = TRUE; } METHODDEF(void) finish_pass2 (j_decompress_ptr cinfo) { /* no work */ } /* * Initialize for each processing pass. */ METHODDEF(void) start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; hist3d histogram = cquantize->histogram; int i; /* Only F-S dithering or no dithering is supported. */ /* If user asks for ordered dither, give him F-S. */ if (cinfo->dither_mode != JDITHER_NONE) cinfo->dither_mode = JDITHER_FS; if (is_pre_scan) { /* Set up method pointers */ cquantize->pub.color_quantize = prescan_quantize; cquantize->pub.finish_pass = finish_pass1; cquantize->needs_zeroed = TRUE; /* Always zero histogram */ } else { /* Set up method pointers */ if (cinfo->dither_mode == JDITHER_FS) cquantize->pub.color_quantize = pass2_fs_dither; else cquantize->pub.color_quantize = pass2_no_dither; cquantize->pub.finish_pass = finish_pass2; /* Make sure color count is acceptable */ i = cinfo->actual_number_of_colors; if (i < 1) ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1); if (i > MAXNUMCOLORS) ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS); if (cinfo->dither_mode == JDITHER_FS) { size_t arraysize = (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))); /* Allocate Floyd-Steinberg workspace if we didn't already. */ if (cquantize->fserrors == NULL) cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize); /* Initialize the propagated errors to zero. */ FMEMZERO((void FAR *) cquantize->fserrors, arraysize); /* Make the error-limit table if we didn't already. */ if (cquantize->error_limiter == NULL) init_error_limit(cinfo); cquantize->on_odd_row = FALSE; } } /* Zero the histogram or inverse color map, if necessary */ if (cquantize->needs_zeroed) { for (i = 0; i < HIST_C0_ELEMS; i++) { FMEMZERO((void FAR *) histogram[i], HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell)); } cquantize->needs_zeroed = FALSE; } } /* * Switch to a new external colormap between output passes. */ METHODDEF(void) new_color_map_2_quant (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; /* Reset the inverse color map */ cquantize->needs_zeroed = TRUE; } /* * Module initialization routine for 2-pass color quantization. */ GLOBAL(void) jinit_2pass_quantizer (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize; int i; cquantize = (my_cquantize_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_cquantizer)); cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize; cquantize->pub.start_pass = start_pass_2_quant; cquantize->pub.new_color_map = new_color_map_2_quant; cquantize->fserrors = NULL; /* flag optional arrays not allocated */ cquantize->error_limiter = NULL; /* Make sure jdmaster didn't give me a case I can't handle */ if (cinfo->out_color_components != 3) ERREXIT(cinfo, JERR_NOTIMPL); /* Allocate the histogram/inverse colormap storage */ cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d)); for (i = 0; i < HIST_C0_ELEMS; i++) { cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell)); } cquantize->needs_zeroed = TRUE; /* histogram is garbage now */ /* Allocate storage for the completed colormap, if required. * We do this now since it is FAR storage and may affect * the memory manager's space calculations. */ if (cinfo->enable_2pass_quant) { /* Make sure color count is acceptable */ int desired = cinfo->desired_number_of_colors; /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */ if (desired < 8) ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8); /* Make sure colormap indexes can be represented by JSAMPLEs */ if (desired > MAXNUMCOLORS) ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS); cquantize->sv_colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3); cquantize->desired = desired; } else cquantize->sv_colormap = NULL; /* Only F-S dithering or no dithering is supported. */ /* If user asks for ordered dither, give him F-S. */ if (cinfo->dither_mode != JDITHER_NONE) cinfo->dither_mode = JDITHER_FS; /* Allocate Floyd-Steinberg workspace if necessary. * This isn't really needed until pass 2, but again it is FAR storage. * Although we will cope with a later change in dither_mode, * we do not promise to honor max_memory_to_use if dither_mode changes. */ if (cinfo->dither_mode == JDITHER_FS) { cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR)))); /* Might as well create the error-limiting table too. */ init_error_limit(cinfo); } } #endif /* QUANT_2PASS_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/jutils.c ================================================ /* * jutils.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2009-2011 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains tables and miscellaneous utility routines needed * for both compression and decompression. * Note we prefix all global names with "j" to minimize conflicts with * a surrounding application. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element * of a DCT block read in natural order (left to right, top to bottom). */ #if 0 /* This table is not actually needed in v6a */ const int jpeg_zigzag_order[DCTSIZE2] = { 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 }; #endif /* * jpeg_natural_order[i] is the natural-order position of the i'th element * of zigzag order. * * When reading corrupted data, the Huffman decoders could attempt * to reference an entry beyond the end of this array (if the decoded * zero run length reaches past the end of the block). To prevent * wild stores without adding an inner-loop test, we put some extra * "63"s after the real entries. This will cause the extra coefficient * to be stored in location 63 of the block, not somewhere random. * The worst case would be a run-length of 15, which means we need 16 * fake entries. */ const int jpeg_natural_order[DCTSIZE2+16] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ 63, 63, 63, 63, 63, 63, 63, 63 }; const int jpeg_natural_order7[7*7+16] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 14, 21, 28, 35, 42, 49, 50, 43, 36, 29, 22, 30, 37, 44, 51, 52, 45, 38, 46, 53, 54, 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ 63, 63, 63, 63, 63, 63, 63, 63 }; const int jpeg_natural_order6[6*6+16] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 41, 34, 27, 20, 13, 21, 28, 35, 42, 43, 36, 29, 37, 44, 45, 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ 63, 63, 63, 63, 63, 63, 63, 63 }; const int jpeg_natural_order5[5*5+16] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 12, 19, 26, 33, 34, 27, 20, 28, 35, 36, 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ 63, 63, 63, 63, 63, 63, 63, 63 }; const int jpeg_natural_order4[4*4+16] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 25, 18, 11, 19, 26, 27, 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ 63, 63, 63, 63, 63, 63, 63, 63 }; const int jpeg_natural_order3[3*3+16] = { 0, 1, 8, 16, 9, 2, 10, 17, 18, 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ 63, 63, 63, 63, 63, 63, 63, 63 }; const int jpeg_natural_order2[2*2+16] = { 0, 1, 8, 9, 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ 63, 63, 63, 63, 63, 63, 63, 63 }; /* * Arithmetic utilities */ GLOBAL(long) jdiv_round_up (long a, long b) /* Compute a/b rounded up to next integer, ie, ceil(a/b) */ /* Assumes a >= 0, b > 0 */ { return (a + b - 1L) / b; } GLOBAL(long) jround_up (long a, long b) /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */ /* Assumes a >= 0, b > 0 */ { a += b - 1L; return a - (a % b); } /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays * and coefficient-block arrays. This won't work on 80x86 because the arrays * are FAR and we're assuming a small-pointer memory model. However, some * DOS compilers provide far-pointer versions of memcpy() and memset() even * in the small-model libraries. These will be used if USE_FMEM is defined. * Otherwise, the routines below do it the hard way. (The performance cost * is not all that great, because these routines aren't very heavily used.) */ #ifndef NEED_FAR_POINTERS /* normal case, same as regular macro */ #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size) #else /* 80x86 case, define if we can */ #ifdef USE_FMEM #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size)) #else /* This function is for use by the FMEMZERO macro defined in jpegint.h. * Do not call this function directly, use the FMEMZERO macro instead. */ GLOBAL(void) jzero_far (void FAR * target, size_t bytestozero) /* Zero out a chunk of FAR memory. */ /* This might be sample-array data, block-array data, or alloc_large data. */ { register char FAR * ptr = (char FAR *) target; register size_t count; for (count = bytestozero; count > 0; count--) { *ptr++ = 0; } } #endif #endif GLOBAL(void) jcopy_sample_rows (JSAMPARRAY input_array, int source_row, JSAMPARRAY output_array, int dest_row, int num_rows, JDIMENSION num_cols) /* Copy some rows of samples from one place to another. * num_rows rows are copied from input_array[source_row++] * to output_array[dest_row++]; these areas may overlap for duplication. * The source and destination arrays must be at least as wide as num_cols. */ { register JSAMPROW inptr, outptr; #ifdef FMEMCOPY register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE)); #else register JDIMENSION count; #endif register int row; input_array += source_row; output_array += dest_row; for (row = num_rows; row > 0; row--) { inptr = *input_array++; outptr = *output_array++; #ifdef FMEMCOPY FMEMCOPY(outptr, inptr, count); #else for (count = num_cols; count > 0; count--) *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */ #endif } } GLOBAL(void) jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row, JDIMENSION num_blocks) /* Copy a row of coefficient blocks from one place to another. */ { #ifdef FMEMCOPY FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF))); #else register JCOEFPTR inptr, outptr; register long count; inptr = (JCOEFPTR) input_row; outptr = (JCOEFPTR) output_row; for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) { *outptr++ = *inptr++; } #endif } ================================================ FILE: tess-two/jni/libjpeg/jversion.h ================================================ /* * jversion.h * * Copyright (C) 1991-2016, Thomas G. Lane, Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains software version identification. */ #define JVERSION "9b 17-Jan-2016" #define JCOPYRIGHT "Copyright (C) 2016, Thomas G. Lane, Guido Vollbeding" ================================================ FILE: tess-two/jni/libjpeg/libjpeg.txt ================================================ USING THE IJG JPEG LIBRARY Copyright (C) 1994-2013, Thomas G. Lane, Guido Vollbeding. This file is part of the Independent JPEG Group's software. For conditions of distribution and use, see the accompanying README file. This file describes how to use the IJG JPEG library within an application program. Read it if you want to write a program that uses the library. The file example.c provides heavily commented skeleton code for calling the JPEG library. Also see jpeglib.h (the include file to be used by application programs) for full details about data structures and function parameter lists. The library source code, of course, is the ultimate reference. Note that there have been *major* changes from the application interface presented by IJG version 4 and earlier versions. The old design had several inherent limitations, and it had accumulated a lot of cruft as we added features while trying to minimize application-interface changes. We have sacrificed backward compatibility in the version 5 rewrite, but we think the improvements justify this. TABLE OF CONTENTS ----------------- Overview: Functions provided by the library Outline of typical usage Basic library usage: Data formats Compression details Decompression details Mechanics of usage: include files, linking, etc Advanced features: Compression parameter selection Decompression parameter selection Special color spaces Error handling Compressed data handling (source and destination managers) I/O suspension Progressive JPEG support Buffered-image mode Abbreviated datastreams and multiple images Special markers Raw (downsampled) image data Really raw data: DCT coefficients Progress monitoring Memory management Memory usage Library compile-time options Portability considerations Notes for MS-DOS implementors You should read at least the overview and basic usage sections before trying to program with the library. The sections on advanced features can be read if and when you need them. OVERVIEW ======== Functions provided by the library --------------------------------- The IJG JPEG library provides C code to read and write JPEG-compressed image files. The surrounding application program receives or supplies image data a scanline at a time, using a straightforward uncompressed image format. All details of color conversion and other preprocessing/postprocessing can be handled by the library. The library includes a substantial amount of code that is not covered by the JPEG standard but is necessary for typical applications of JPEG. These functions preprocess the image before JPEG compression or postprocess it after decompression. They include colorspace conversion, downsampling/upsampling, and color quantization. The application indirectly selects use of this code by specifying the format in which it wishes to supply or receive image data. For example, if colormapped output is requested, then the decompression library automatically invokes color quantization. A wide range of quality vs. speed tradeoffs are possible in JPEG processing, and even more so in decompression postprocessing. The decompression library provides multiple implementations that cover most of the useful tradeoffs, ranging from very-high-quality down to fast-preview operation. On the compression side we have generally not provided low-quality choices, since compression is normally less time-critical. It should be understood that the low-quality modes may not meet the JPEG standard's accuracy requirements; nonetheless, they are useful for viewers. A word about functions *not* provided by the library. We handle a subset of the ISO JPEG standard; most baseline, extended-sequential, and progressive JPEG processes are supported. (Our subset includes all features now in common use.) Unsupported ISO options include: * Hierarchical storage * Lossless JPEG * DNL marker * Nonintegral subsampling ratios We support 8-bit to 12-bit data precision, but this is a compile-time choice rather than a run-time choice; hence it is difficult to use different precisions in a single application. By itself, the library handles only interchange JPEG datastreams --- in particular the widely used JFIF file format. The library can be used by surrounding code to process interchange or abbreviated JPEG datastreams that are embedded in more complex file formats. (For example, this library is used by the free LIBTIFF library to support JPEG compression in TIFF.) Outline of typical usage ------------------------ The rough outline of a JPEG compression operation is: Allocate and initialize a JPEG compression object Specify the destination for the compressed data (eg, a file) Set parameters for compression, including image size & colorspace jpeg_start_compress(...); while (scan lines remain to be written) jpeg_write_scanlines(...); jpeg_finish_compress(...); Release the JPEG compression object A JPEG compression object holds parameters and working state for the JPEG library. We make creation/destruction of the object separate from starting or finishing compression of an image; the same object can be re-used for a series of image compression operations. This makes it easy to re-use the same parameter settings for a sequence of images. Re-use of a JPEG object also has important implications for processing abbreviated JPEG datastreams, as discussed later. The image data to be compressed is supplied to jpeg_write_scanlines() from in-memory buffers. If the application is doing file-to-file compression, reading image data from the source file is the application's responsibility. The library emits compressed data by calling a "data destination manager", which typically will write the data into a file; but the application can provide its own destination manager to do something else. Similarly, the rough outline of a JPEG decompression operation is: Allocate and initialize a JPEG decompression object Specify the source of the compressed data (eg, a file) Call jpeg_read_header() to obtain image info Set parameters for decompression jpeg_start_decompress(...); while (scan lines remain to be read) jpeg_read_scanlines(...); jpeg_finish_decompress(...); Release the JPEG decompression object This is comparable to the compression outline except that reading the datastream header is a separate step. This is helpful because information about the image's size, colorspace, etc is available when the application selects decompression parameters. For example, the application can choose an output scaling ratio that will fit the image into the available screen size. The decompression library obtains compressed data by calling a data source manager, which typically will read the data from a file; but other behaviors can be obtained with a custom source manager. Decompressed data is delivered into in-memory buffers passed to jpeg_read_scanlines(). It is possible to abort an incomplete compression or decompression operation by calling jpeg_abort(); or, if you do not need to retain the JPEG object, simply release it by calling jpeg_destroy(). JPEG compression and decompression objects are two separate struct types. However, they share some common fields, and certain routines such as jpeg_destroy() can work on either type of object. The JPEG library has no static variables: all state is in the compression or decompression object. Therefore it is possible to process multiple compression and decompression operations concurrently, using multiple JPEG objects. Both compression and decompression can be done in an incremental memory-to- memory fashion, if suitable source/destination managers are used. See the section on "I/O suspension" for more details. BASIC LIBRARY USAGE =================== Data formats ------------ Before diving into procedural details, it is helpful to understand the image data format that the JPEG library expects or returns. The standard input image format is a rectangular array of pixels, with each pixel having the same number of "component" or "sample" values (color channels). You must specify how many components there are and the colorspace interpretation of the components. Most applications will use RGB data (three components per pixel) or grayscale data (one component per pixel). PLEASE NOTE THAT RGB DATA IS THREE SAMPLES PER PIXEL, GRAYSCALE ONLY ONE. A remarkable number of people manage to miss this, only to find that their programs don't work with grayscale JPEG files. There is no provision for colormapped input. JPEG files are always full-color or full grayscale (or sometimes another colorspace such as CMYK). You can feed in a colormapped image by expanding it to full-color format. However JPEG often doesn't work very well with source data that has been colormapped, because of dithering noise. This is discussed in more detail in the JPEG FAQ and the other references mentioned in the README file. Pixels are stored by scanlines, with each scanline running from left to right. The component values for each pixel are adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit RGB color. Each scanline is an array of data type JSAMPLE --- which is typically "unsigned char", unless you've changed jmorecfg.h. (You can also change the RGB pixel layout, say to B,G,R order, by modifying jmorecfg.h. But see the restrictions listed in that file before doing so.) A 2-D array of pixels is formed by making a list of pointers to the starts of scanlines; so the scanlines need not be physically adjacent in memory. Even if you process just one scanline at a time, you must make a one-element pointer array to conform to this structure. Pointers to JSAMPLE rows are of type JSAMPROW, and the pointer to the pointer array is of type JSAMPARRAY. The library accepts or supplies one or more complete scanlines per call. It is not possible to process part of a row at a time. Scanlines are always processed top-to-bottom. You can process an entire image in one call if you have it all in memory, but usually it's simplest to process one scanline at a time. For best results, source data values should have the precision specified by BITS_IN_JSAMPLE (normally 8 bits). For instance, if you choose to compress data that's only 6 bits/channel, you should left-justify each value in a byte before passing it to the compressor. If you need to compress data that has more than 8 bits/channel, compile with BITS_IN_JSAMPLE = 9 to 12. (See "Library compile-time options", later.) The data format returned by the decompressor is the same in all details, except that colormapped output is supported. (Again, a JPEG file is never colormapped. But you can ask the decompressor to perform on-the-fly color quantization to deliver colormapped output.) If you request colormapped output then the returned data array contains a single JSAMPLE per pixel; its value is an index into a color map. The color map is represented as a 2-D JSAMPARRAY in which each row holds the values of one color component, that is, colormap[i][j] is the value of the i'th color component for pixel value (map index) j. Note that since the colormap indexes are stored in JSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE (ie, at most 256 colors for an 8-bit JPEG library). Compression details ------------------- Here we revisit the JPEG compression outline given in the overview. 1. Allocate and initialize a JPEG compression object. A JPEG compression object is a "struct jpeg_compress_struct". (It also has a bunch of subsidiary structures which are allocated via malloc(), but the application doesn't control those directly.) This struct can be just a local variable in the calling routine, if a single routine is going to execute the whole JPEG compression sequence. Otherwise it can be static or allocated from malloc(). You will also need a structure representing a JPEG error handler. The part of this that the library cares about is a "struct jpeg_error_mgr". If you are providing your own error handler, you'll typically want to embed the jpeg_error_mgr struct in a larger structure; this is discussed later under "Error handling". For now we'll assume you are just using the default error handler. The default error handler will print JPEG error/warning messages on stderr, and it will call exit() if a fatal error occurs. You must initialize the error handler structure, store a pointer to it into the JPEG object's "err" field, and then call jpeg_create_compress() to initialize the rest of the JPEG object. Typical code for this step, if you are using the default error handler, is struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; ... cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_create_compress allocates a small amount of memory, so it could fail if you are out of memory. In that case it will exit via the error handler; that's why the error handler must be initialized first. 2. Specify the destination for the compressed data (eg, a file). As previously mentioned, the JPEG library delivers compressed data to a "data destination" module. The library includes one data destination module which knows how to write to a stdio stream. You can use your own destination module if you want to do something else, as discussed later. If you use the standard destination module, you must open the target stdio stream beforehand. Typical code for this step looks like: FILE * outfile; ... if ((outfile = fopen(filename, "wb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); exit(1); } jpeg_stdio_dest(&cinfo, outfile); where the last line invokes the standard destination module. WARNING: it is critical that the binary compressed data be delivered to the output file unchanged. On non-Unix systems the stdio library may perform newline translation or otherwise corrupt binary data. To suppress this behavior, you may need to use a "b" option to fopen (as shown above), or use setmode() or another routine to put the stdio stream in binary mode. See cjpeg.c and djpeg.c for code that has been found to work on many systems. You can select the data destination after setting other parameters (step 3), if that's more convenient. You may not change the destination between calling jpeg_start_compress() and jpeg_finish_compress(). 3. Set parameters for compression, including image size & colorspace. You must supply information about the source image by setting the following fields in the JPEG object (cinfo structure): image_width Width of image, in pixels image_height Height of image, in pixels input_components Number of color channels (samples per pixel) in_color_space Color space of source image The image dimensions are, hopefully, obvious. JPEG supports image dimensions of 1 to 64K pixels in either direction. The input color space is typically RGB or grayscale, and input_components is 3 or 1 accordingly. (See "Special color spaces", later, for more info.) The in_color_space field must be assigned one of the J_COLOR_SPACE enum constants, typically JCS_RGB or JCS_GRAYSCALE. JPEG has a large number of compression parameters that determine how the image is encoded. Most applications don't need or want to know about all these parameters. You can set all the parameters to reasonable defaults by calling jpeg_set_defaults(); then, if there are particular values you want to change, you can do so after that. The "Compression parameter selection" section tells about all the parameters. You must set in_color_space correctly before calling jpeg_set_defaults(), because the defaults depend on the source image colorspace. However the other three source image parameters need not be valid until you call jpeg_start_compress(). There's no harm in calling jpeg_set_defaults() more than once, if that happens to be convenient. Typical code for a 24-bit RGB source image is cinfo.image_width = Width; /* image width and height, in pixels */ cinfo.image_height = Height; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults(&cinfo); /* Make optional parameter settings here */ 4. jpeg_start_compress(...); After you have established the data destination and set all the necessary source image info and other parameters, call jpeg_start_compress() to begin a compression cycle. This will initialize internal state, allocate working storage, and emit the first few bytes of the JPEG datastream header. Typical code: jpeg_start_compress(&cinfo, TRUE); The "TRUE" parameter ensures that a complete JPEG interchange datastream will be written. This is appropriate in most cases. If you think you might want to use an abbreviated datastream, read the section on abbreviated datastreams, below. Once you have called jpeg_start_compress(), you may not alter any JPEG parameters or other fields of the JPEG object until you have completed the compression cycle. 5. while (scan lines remain to be written) jpeg_write_scanlines(...); Now write all the required image data by calling jpeg_write_scanlines() one or more times. You can pass one or more scanlines in each call, up to the total image height. In most applications it is convenient to pass just one or a few scanlines at a time. The expected format for the passed data is discussed under "Data formats", above. Image data should be written in top-to-bottom scanline order. The JPEG spec contains some weasel wording about how top and bottom are application-defined terms (a curious interpretation of the English language...) but if you want your files to be compatible with everyone else's, you WILL use top-to-bottom order. If the source data must be read in bottom-to-top order, you can use the JPEG library's virtual array mechanism to invert the data efficiently. Examples of this can be found in the sample application cjpeg. The library maintains a count of the number of scanlines written so far in the next_scanline field of the JPEG object. Usually you can just use this variable as the loop counter, so that the loop test looks like "while (cinfo.next_scanline < cinfo.image_height)". Code for this step depends heavily on the way that you store the source data. example.c shows the following code for the case of a full-size 2-D source array containing 3-byte RGB pixels: JSAMPROW row_pointer[1]; /* pointer to a single row */ int row_stride; /* physical row width in buffer */ row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */ while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride]; jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_write_scanlines() returns the number of scanlines actually written. This will normally be equal to the number passed in, so you can usually ignore the return value. It is different in just two cases: * If you try to write more scanlines than the declared image height, the additional scanlines are ignored. * If you use a suspending data destination manager, output buffer overrun will cause the compressor to return before accepting all the passed lines. This feature is discussed under "I/O suspension", below. The normal stdio destination manager will NOT cause this to happen. In any case, the return value is the same as the change in the value of next_scanline. 6. jpeg_finish_compress(...); After all the image data has been written, call jpeg_finish_compress() to complete the compression cycle. This step is ESSENTIAL to ensure that the last bufferload of data is written to the data destination. jpeg_finish_compress() also releases working memory associated with the JPEG object. Typical code: jpeg_finish_compress(&cinfo); If using the stdio destination manager, don't forget to close the output stdio stream (if necessary) afterwards. If you have requested a multi-pass operating mode, such as Huffman code optimization, jpeg_finish_compress() will perform the additional passes using data buffered by the first pass. In this case jpeg_finish_compress() may take quite a while to complete. With the default compression parameters, this will not happen. It is an error to call jpeg_finish_compress() before writing the necessary total number of scanlines. If you wish to abort compression, call jpeg_abort() as discussed below. After completing a compression cycle, you may dispose of the JPEG object as discussed next, or you may use it to compress another image. In that case return to step 2, 3, or 4 as appropriate. If you do not change the destination manager, the new datastream will be written to the same target. If you do not change any JPEG parameters, the new datastream will be written with the same parameters as before. Note that you can change the input image dimensions freely between cycles, but if you change the input colorspace, you should call jpeg_set_defaults() to adjust for the new colorspace; and then you'll need to repeat all of step 3. 7. Release the JPEG compression object. When you are done with a JPEG compression object, destroy it by calling jpeg_destroy_compress(). This will free all subsidiary memory (regardless of the previous state of the object). Or you can call jpeg_destroy(), which works for either compression or decompression objects --- this may be more convenient if you are sharing code between compression and decompression cases. (Actually, these routines are equivalent except for the declared type of the passed pointer. To avoid gripes from ANSI C compilers, jpeg_destroy() should be passed a j_common_ptr.) If you allocated the jpeg_compress_struct structure from malloc(), freeing it is your responsibility --- jpeg_destroy() won't. Ditto for the error handler structure. Typical code: jpeg_destroy_compress(&cinfo); 8. Aborting. If you decide to abort a compression cycle before finishing, you can clean up in either of two ways: * If you don't need the JPEG object any more, just call jpeg_destroy_compress() or jpeg_destroy() to release memory. This is legitimate at any point after calling jpeg_create_compress() --- in fact, it's safe even if jpeg_create_compress() fails. * If you want to re-use the JPEG object, call jpeg_abort_compress(), or call jpeg_abort() which works on both compression and decompression objects. This will return the object to an idle state, releasing any working memory. jpeg_abort() is allowed at any time after successful object creation. Note that cleaning up the data destination, if required, is your responsibility; neither of these routines will call term_destination(). (See "Compressed data handling", below, for more about that.) jpeg_destroy() and jpeg_abort() are the only safe calls to make on a JPEG object that has reported an error by calling error_exit (see "Error handling" for more info). The internal state of such an object is likely to be out of whack. Either of these two routines will return the object to a known state. Decompression details --------------------- Here we revisit the JPEG decompression outline given in the overview. 1. Allocate and initialize a JPEG decompression object. This is just like initialization for compression, as discussed above, except that the object is a "struct jpeg_decompress_struct" and you call jpeg_create_decompress(). Error handling is exactly the same. Typical code: struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; ... cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); (Both here and in the IJG code, we usually use variable name "cinfo" for both compression and decompression objects.) 2. Specify the source of the compressed data (eg, a file). As previously mentioned, the JPEG library reads compressed data from a "data source" module. The library includes one data source module which knows how to read from a stdio stream. You can use your own source module if you want to do something else, as discussed later. If you use the standard source module, you must open the source stdio stream beforehand. Typical code for this step looks like: FILE * infile; ... if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); exit(1); } jpeg_stdio_src(&cinfo, infile); where the last line invokes the standard source module. WARNING: it is critical that the binary compressed data be read unchanged. On non-Unix systems the stdio library may perform newline translation or otherwise corrupt binary data. To suppress this behavior, you may need to use a "b" option to fopen (as shown above), or use setmode() or another routine to put the stdio stream in binary mode. See cjpeg.c and djpeg.c for code that has been found to work on many systems. You may not change the data source between calling jpeg_read_header() and jpeg_finish_decompress(). If you wish to read a series of JPEG images from a single source file, you should repeat the jpeg_read_header() to jpeg_finish_decompress() sequence without reinitializing either the JPEG object or the data source module; this prevents buffered input data from being discarded. 3. Call jpeg_read_header() to obtain image info. Typical code for this step is just jpeg_read_header(&cinfo, TRUE); This will read the source datastream header markers, up to the beginning of the compressed data proper. On return, the image dimensions and other info have been stored in the JPEG object. The application may wish to consult this information before selecting decompression parameters. More complex code is necessary if * A suspending data source is used --- in that case jpeg_read_header() may return before it has read all the header data. See "I/O suspension", below. The normal stdio source manager will NOT cause this to happen. * Abbreviated JPEG files are to be processed --- see the section on abbreviated datastreams. Standard applications that deal only in interchange JPEG files need not be concerned with this case either. It is permissible to stop at this point if you just wanted to find out the image dimensions and other header info for a JPEG file. In that case, call jpeg_destroy() when you are done with the JPEG object, or call jpeg_abort() to return it to an idle state before selecting a new data source and reading another header. 4. Set parameters for decompression. jpeg_read_header() sets appropriate default decompression parameters based on the properties of the image (in particular, its colorspace). However, you may well want to alter these defaults before beginning the decompression. For example, the default is to produce full color output from a color file. If you want colormapped output you must ask for it. Other options allow the returned image to be scaled and allow various speed/quality tradeoffs to be selected. "Decompression parameter selection", below, gives details. If the defaults are appropriate, nothing need be done at this step. Note that all default values are set by each call to jpeg_read_header(). If you reuse a decompression object, you cannot expect your parameter settings to be preserved across cycles, as you can for compression. You must set desired parameter values each time. 5. jpeg_start_decompress(...); Once the parameter values are satisfactory, call jpeg_start_decompress() to begin decompression. This will initialize internal state, allocate working memory, and prepare for returning data. Typical code is just jpeg_start_decompress(&cinfo); If you have requested a multi-pass operating mode, such as 2-pass color quantization, jpeg_start_decompress() will do everything needed before data output can begin. In this case jpeg_start_decompress() may take quite a while to complete. With a single-scan (non progressive) JPEG file and default decompression parameters, this will not happen; jpeg_start_decompress() will return quickly. After this call, the final output image dimensions, including any requested scaling, are available in the JPEG object; so is the selected colormap, if colormapped output has been requested. Useful fields include output_width image width and height, as scaled output_height out_color_components # of color components in out_color_space output_components # of color components returned per pixel colormap the selected colormap, if any actual_number_of_colors number of entries in colormap output_components is 1 (a colormap index) when quantizing colors; otherwise it equals out_color_components. It is the number of JSAMPLE values that will be emitted per pixel in the output arrays. Typically you will need to allocate data buffers to hold the incoming image. You will need output_width * output_components JSAMPLEs per scanline in your output buffer, and a total of output_height scanlines will be returned. Note: if you are using the JPEG library's internal memory manager to allocate data buffers (as djpeg does), then the manager's protocol requires that you request large buffers *before* calling jpeg_start_decompress(). This is a little tricky since the output_XXX fields are not normally valid then. You can make them valid by calling jpeg_calc_output_dimensions() after setting the relevant parameters (scaling, output color space, and quantization flag). 6. while (scan lines remain to be read) jpeg_read_scanlines(...); Now you can read the decompressed image data by calling jpeg_read_scanlines() one or more times. At each call, you pass in the maximum number of scanlines to be read (ie, the height of your working buffer); jpeg_read_scanlines() will return up to that many lines. The return value is the number of lines actually read. The format of the returned data is discussed under "Data formats", above. Don't forget that grayscale and color JPEGs will return different data formats! Image data is returned in top-to-bottom scanline order. If you must write out the image in bottom-to-top order, you can use the JPEG library's virtual array mechanism to invert the data efficiently. Examples of this can be found in the sample application djpeg. The library maintains a count of the number of scanlines returned so far in the output_scanline field of the JPEG object. Usually you can just use this variable as the loop counter, so that the loop test looks like "while (cinfo.output_scanline < cinfo.output_height)". (Note that the test should NOT be against image_height, unless you never use scaling. The image_height field is the height of the original unscaled image.) The return value always equals the change in the value of output_scanline. If you don't use a suspending data source, it is safe to assume that jpeg_read_scanlines() reads at least one scanline per call, until the bottom of the image has been reached. If you use a buffer larger than one scanline, it is NOT safe to assume that jpeg_read_scanlines() fills it. (The current implementation returns only a few scanlines per call, no matter how large a buffer you pass.) So you must always provide a loop that calls jpeg_read_scanlines() repeatedly until the whole image has been read. 7. jpeg_finish_decompress(...); After all the image data has been read, call jpeg_finish_decompress() to complete the decompression cycle. This causes working memory associated with the JPEG object to be released. Typical code: jpeg_finish_decompress(&cinfo); If using the stdio source manager, don't forget to close the source stdio stream if necessary. It is an error to call jpeg_finish_decompress() before reading the correct total number of scanlines. If you wish to abort decompression, call jpeg_abort() as discussed below. After completing a decompression cycle, you may dispose of the JPEG object as discussed next, or you may use it to decompress another image. In that case return to step 2 or 3 as appropriate. If you do not change the source manager, the next image will be read from the same source. 8. Release the JPEG decompression object. When you are done with a JPEG decompression object, destroy it by calling jpeg_destroy_decompress() or jpeg_destroy(). The previous discussion of destroying compression objects applies here too. Typical code: jpeg_destroy_decompress(&cinfo); 9. Aborting. You can abort a decompression cycle by calling jpeg_destroy_decompress() or jpeg_destroy() if you don't need the JPEG object any more, or jpeg_abort_decompress() or jpeg_abort() if you want to reuse the object. The previous discussion of aborting compression cycles applies here too. Mechanics of usage: include files, linking, etc ----------------------------------------------- Applications using the JPEG library should include the header file jpeglib.h to obtain declarations of data types and routines. Before including jpeglib.h, include system headers that define at least the typedefs FILE and size_t. On ANSI-conforming systems, including is sufficient; on older Unix systems, you may need to define size_t. If the application needs to refer to individual JPEG library error codes, also include jerror.h to define those symbols. jpeglib.h indirectly includes the files jconfig.h and jmorecfg.h. If you are installing the JPEG header files in a system directory, you will want to install all four files: jpeglib.h, jerror.h, jconfig.h, jmorecfg.h. The most convenient way to include the JPEG code into your executable program is to prepare a library file ("libjpeg.a", or a corresponding name on non-Unix machines) and reference it at your link step. If you use only half of the library (only compression or only decompression), only that much code will be included from the library, unless your linker is hopelessly brain-damaged. The supplied makefiles build libjpeg.a automatically (see install.txt). While you can build the JPEG library as a shared library if the whim strikes you, we don't really recommend it. The trouble with shared libraries is that at some point you'll probably try to substitute a new version of the library without recompiling the calling applications. That generally doesn't work because the parameter struct declarations usually change with each new version. In other words, the library's API is *not* guaranteed binary compatible across versions; we only try to ensure source-code compatibility. (In hindsight, it might have been smarter to hide the parameter structs from applications and introduce a ton of access functions instead. Too late now, however.) On some systems your application may need to set up a signal handler to ensure that temporary files are deleted if the program is interrupted. This is most critical if you are on MS-DOS and use the jmemdos.c memory manager back end; it will try to grab extended memory for temp files, and that space will NOT be freed automatically. See cjpeg.c or djpeg.c for an example signal handler. It may be worth pointing out that the core JPEG library does not actually require the stdio library: only the default source/destination managers and error handler need it. You can use the library in a stdio-less environment if you replace those modules and use jmemnobs.c (or another memory manager of your own devising). More info about the minimum system library requirements may be found in jinclude.h. ADVANCED FEATURES ================= Compression parameter selection ------------------------------- This section describes all the optional parameters you can set for JPEG compression, as well as the "helper" routines provided to assist in this task. Proper setting of some parameters requires detailed understanding of the JPEG standard; if you don't know what a parameter is for, it's best not to mess with it! See REFERENCES in the README file for pointers to more info about JPEG. It's a good idea to call jpeg_set_defaults() first, even if you plan to set all the parameters; that way your code is more likely to work with future JPEG libraries that have additional parameters. For the same reason, we recommend you use a helper routine where one is provided, in preference to twiddling cinfo fields directly. The helper routines are: jpeg_set_defaults (j_compress_ptr cinfo) This routine sets all JPEG parameters to reasonable defaults, using only the input image's color space (field in_color_space, which must already be set in cinfo). Many applications will only need to use this routine and perhaps jpeg_set_quality(). jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace) Sets the JPEG file's colorspace (field jpeg_color_space) as specified, and sets other color-space-dependent parameters appropriately. See "Special color spaces", below, before using this. A large number of parameters, including all per-component parameters, are set by this routine; if you want to twiddle individual parameters you should call jpeg_set_colorspace() before rather than after. jpeg_default_colorspace (j_compress_ptr cinfo) Selects an appropriate JPEG colorspace based on cinfo->in_color_space, and calls jpeg_set_colorspace(). This is actually a subroutine of jpeg_set_defaults(). It's broken out in case you want to change just the colorspace-dependent JPEG parameters. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline) Constructs JPEG quantization tables appropriate for the indicated quality setting. The quality value is expressed on the 0..100 scale recommended by IJG (cjpeg's "-quality" switch uses this routine). Note that the exact mapping from quality values to tables may change in future IJG releases as more is learned about DCT quantization. If the force_baseline parameter is TRUE, then the quantization table entries are constrained to the range 1..255 for full JPEG baseline compatibility. In the current implementation, this only makes a difference for quality settings below 25, and it effectively prevents very small/low quality files from being generated. The IJG decoder is capable of reading the non-baseline files generated at low quality settings when force_baseline is FALSE, but other decoders may not be. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor, boolean force_baseline) Same as jpeg_set_quality() except that the generated tables are the sample tables given in the JPEC spec section K.1, multiplied by the specified scale factor (which is expressed as a percentage; thus scale_factor = 100 reproduces the spec's tables). Note that larger scale factors give lower quality. This entry point is useful for conforming to the Adobe PostScript DCT conventions, but we do not recommend linear scaling as a user-visible quality scale otherwise. force_baseline again constrains the computed table entries to 1..255. int jpeg_quality_scaling (int quality) Converts a value on the IJG-recommended quality scale to a linear scaling percentage. Note that this routine may change or go away in future releases --- IJG may choose to adopt a scaling method that can't be expressed as a simple scalar multiplier, in which case the premise of this routine collapses. Caveat user. jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline) Set default quantization tables with linear q_scale_factor[] values (see below). jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl, const unsigned int *basic_table, int scale_factor, boolean force_baseline) Allows an arbitrary quantization table to be created. which_tbl indicates which table slot to fill. basic_table points to an array of 64 unsigned ints given in normal array order. These values are multiplied by scale_factor/100 and then clamped to the range 1..65535 (or to 1..255 if force_baseline is TRUE). CAUTION: prior to library version 6a, jpeg_add_quant_table expected the basic table to be given in JPEG zigzag order. If you need to write code that works with either older or newer versions of this routine, you must check the library version number. Something like "#if JPEG_LIB_VERSION >= 61" is the right test. jpeg_simple_progression (j_compress_ptr cinfo) Generates a default scan script for writing a progressive-JPEG file. This is the recommended method of creating a progressive file, unless you want to make a custom scan sequence. You must ensure that the JPEG color space is set correctly before calling this routine. Compression parameters (cinfo fields) include: boolean arith_code If TRUE, use arithmetic coding. If FALSE, use Huffman coding. int block_size Set DCT block size. All N from 1 to 16 are possible. Default is 8 (baseline format). Larger values produce higher compression, smaller values produce higher quality. An exact DCT stage is possible with 1 or 2. With the default quality of 75 and default Luminance qtable the DCT+Quantization stage is lossless for value 1. Note that values other than 8 require a SmartScale capable decoder, introduced with IJG JPEG 8. Setting the block_size parameter for compression works with version 8c and later. J_DCT_METHOD dct_method Selects the algorithm used for the DCT step. Choices are: JDCT_ISLOW: slow but accurate integer algorithm JDCT_IFAST: faster, less accurate integer method JDCT_FLOAT: floating-point method JDCT_DEFAULT: default method (normally JDCT_ISLOW) JDCT_FASTEST: fastest method (normally JDCT_IFAST) The FLOAT method is very slightly more accurate than the ISLOW method, but may give different results on different machines due to varying roundoff behavior. The integer methods should give the same results on all machines. On machines with sufficiently fast FP hardware, the floating-point method may also be the fastest. The IFAST method is considerably less accurate than the other two; its use is not recommended if high quality is a concern. JDCT_DEFAULT and JDCT_FASTEST are macros configurable by each installation. unsigned int scale_num, scale_denom Scale the image by the fraction scale_num/scale_denom. Default is 1/1, or no scaling. Currently, the supported scaling ratios are M/N with all N from 1 to 16, where M is the destination DCT size, which is 8 by default (see block_size parameter above). (The library design allows for arbitrary scaling ratios but this is not likely to be implemented any time soon.) J_COLOR_SPACE jpeg_color_space int num_components The JPEG color space and corresponding number of components; see "Special color spaces", below, for more info. We recommend using jpeg_set_colorspace() if you want to change these. J_COLOR_TRANSFORM color_transform Internal color transform identifier, writes LSE marker if nonzero (requires decoder with inverse color transform support, introduced with IJG JPEG 9). Two values are currently possible: JCT_NONE and JCT_SUBTRACT_GREEN. Set this value for lossless RGB application *before* calling jpeg_set_colorspace(), because entropy table assignment in jpeg_set_colorspace() depends on color_transform. boolean optimize_coding TRUE causes the compressor to compute optimal Huffman coding tables for the image. This requires an extra pass over the data and therefore costs a good deal of space and time. The default is FALSE, which tells the compressor to use the supplied or default Huffman tables. In most cases optimal tables save only a few percent of file size compared to the default tables. Note that when this is TRUE, you need not supply Huffman tables at all, and any you do supply will be overwritten. unsigned int restart_interval int restart_in_rows To emit restart markers in the JPEG file, set one of these nonzero. Set restart_interval to specify the exact interval in MCU blocks. Set restart_in_rows to specify the interval in MCU rows. (If restart_in_rows is not 0, then restart_interval is set after the image width in MCUs is computed.) Defaults are zero (no restarts). One restart marker per MCU row is often a good choice. NOTE: the overhead of restart markers is higher in grayscale JPEG files than in color files, and MUCH higher in progressive JPEGs. If you use restarts, you may want to use larger intervals in those cases. const jpeg_scan_info * scan_info int num_scans By default, scan_info is NULL; this causes the compressor to write a single-scan sequential JPEG file. If not NULL, scan_info points to an array of scan definition records of length num_scans. The compressor will then write a JPEG file having one scan for each scan definition record. This is used to generate noninterleaved or progressive JPEG files. The library checks that the scan array defines a valid JPEG scan sequence. (jpeg_simple_progression creates a suitable scan definition array for progressive JPEG.) This is discussed further under "Progressive JPEG support". boolean do_fancy_downsampling If TRUE, use direct DCT scaling with DCT size > 8 for downsampling of chroma components. If FALSE, use only DCT size <= 8 and simple separate downsampling. Default is TRUE. For better image stability in multiple generation compression cycles it is preferable that this value matches the corresponding do_fancy_upsampling value in decompression. int smoothing_factor If non-zero, the input image is smoothed; the value should be 1 for minimal smoothing to 100 for maximum smoothing. Consult jcsample.c for details of the smoothing algorithm. The default is zero. boolean write_JFIF_header If TRUE, a JFIF APP0 marker is emitted. jpeg_set_defaults() and jpeg_set_colorspace() set this TRUE if a JFIF-legal JPEG color space (ie, YCbCr or grayscale) is selected, otherwise FALSE. UINT8 JFIF_major_version UINT8 JFIF_minor_version The version number to be written into the JFIF marker. jpeg_set_defaults() initializes the version to 1.01 (major=minor=1). You should set it to 1.02 (major=1, minor=2) if you plan to write any JFIF 1.02 extension markers. UINT8 density_unit UINT16 X_density UINT16 Y_density The resolution information to be written into the JFIF marker; not used otherwise. density_unit may be 0 for unknown, 1 for dots/inch, or 2 for dots/cm. The default values are 0,1,1 indicating square pixels of unknown size. boolean write_Adobe_marker If TRUE, an Adobe APP14 marker is emitted. jpeg_set_defaults() and jpeg_set_colorspace() set this TRUE if JPEG color space RGB, CMYK, or YCCK is selected, otherwise FALSE. It is generally a bad idea to set both write_JFIF_header and write_Adobe_marker. In fact, you probably shouldn't change the default settings at all --- the default behavior ensures that the JPEG file's color space can be recognized by the decoder. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS] Pointers to coefficient quantization tables, one per table slot, or NULL if no table is defined for a slot. Usually these should be set via one of the above helper routines; jpeg_add_quant_table() is general enough to define any quantization table. The other routines will set up table slot 0 for luminance quality and table slot 1 for chrominance. int q_scale_factor[NUM_QUANT_TBLS] Linear quantization scaling factors (percentage, initialized 100) for use with jpeg_default_qtables(). See rdswitch.c and cjpeg.c for an example of usage. Note that the q_scale_factor[] fields are the "linear" scales, so you have to convert from user-defined ratings via jpeg_quality_scaling(). Here is an example code which corresponds to cjpeg -quality 90,70: jpeg_set_defaults(cinfo); /* Set luminance quality 90. */ cinfo->q_scale_factor[0] = jpeg_quality_scaling(90); /* Set chrominance quality 70. */ cinfo->q_scale_factor[1] = jpeg_quality_scaling(70); jpeg_default_qtables(cinfo, force_baseline); CAUTION: You must also set 1x1 subsampling for efficient separate color quality selection, since the default value used by library is 2x2: cinfo->comp_info[0].v_samp_factor = 1; cinfo->comp_info[0].h_samp_factor = 1; JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS] JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS] Pointers to Huffman coding tables, one per table slot, or NULL if no table is defined for a slot. Slots 0 and 1 are filled with the JPEG sample tables by jpeg_set_defaults(). If you need to allocate more table structures, jpeg_alloc_huff_table() may be used. Note that optimal Huffman tables can be computed for an image by setting optimize_coding, as discussed above; there's seldom any need to mess with providing your own Huffman tables. The actual dimensions of the JPEG image that will be written to the file are given by the following fields. These are computed from the input image dimensions and the compression parameters by jpeg_start_compress(). You can also call jpeg_calc_jpeg_dimensions() to obtain the values that will result from the current parameter settings. This can be useful if you are trying to pick a scaling ratio that will get close to a desired target size. JDIMENSION jpeg_width Actual dimensions of output image. JDIMENSION jpeg_height Per-component parameters are stored in the struct cinfo.comp_info[i] for component number i. Note that components here refer to components of the JPEG color space, *not* the source image color space. A suitably large comp_info[] array is allocated by jpeg_set_defaults(); if you choose not to use that routine, it's up to you to allocate the array. int component_id The one-byte identifier code to be recorded in the JPEG file for this component. For the standard color spaces, we recommend you leave the default values alone. int h_samp_factor int v_samp_factor Horizontal and vertical sampling factors for the component; must be 1..4 according to the JPEG standard. Note that larger sampling factors indicate a higher-resolution component; many people find this behavior quite unintuitive. The default values are 2,2 for luminance components and 1,1 for chrominance components, except for grayscale where 1,1 is used. int quant_tbl_no Quantization table number for component. The default value is 0 for luminance components and 1 for chrominance components. int dc_tbl_no int ac_tbl_no DC and AC entropy coding table numbers. The default values are 0 for luminance components and 1 for chrominance components. int component_index Must equal the component's index in comp_info[]. (Beginning in release v6, the compressor library will fill this in automatically; you don't have to.) Decompression parameter selection --------------------------------- Decompression parameter selection is somewhat simpler than compression parameter selection, since all of the JPEG internal parameters are recorded in the source file and need not be supplied by the application. (Unless you are working with abbreviated files, in which case see "Abbreviated datastreams", below.) Decompression parameters control the postprocessing done on the image to deliver it in a format suitable for the application's use. Many of the parameters control speed/quality tradeoffs, in which faster decompression may be obtained at the price of a poorer-quality image. The defaults select the highest quality (slowest) processing. The following fields in the JPEG object are set by jpeg_read_header() and may be useful to the application in choosing decompression parameters: JDIMENSION image_width Width and height of image JDIMENSION image_height int num_components Number of color components J_COLOR_SPACE jpeg_color_space Colorspace of image boolean saw_JFIF_marker TRUE if a JFIF APP0 marker was seen UINT8 JFIF_major_version Version information from JFIF marker UINT8 JFIF_minor_version UINT8 density_unit Resolution data from JFIF marker UINT16 X_density UINT16 Y_density boolean saw_Adobe_marker TRUE if an Adobe APP14 marker was seen UINT8 Adobe_transform Color transform code from Adobe marker The JPEG color space, unfortunately, is something of a guess since the JPEG standard proper does not provide a way to record it. In practice most files adhere to the JFIF or Adobe conventions, and the decoder will recognize these correctly. See "Special color spaces", below, for more info. The decompression parameters that determine the basic properties of the returned image are: J_COLOR_SPACE out_color_space Output color space. jpeg_read_header() sets an appropriate default based on jpeg_color_space; typically it will be RGB or grayscale. The application can change this field to request output in a different colorspace. For example, set it to JCS_GRAYSCALE to get grayscale output from a color file. (This is useful for previewing: grayscale output is faster than full color since the color components need not be processed.) Note that not all possible color space transforms are currently implemented; you may need to extend jdcolor.c if you want an unusual conversion. unsigned int scale_num, scale_denom Scale the image by the fraction scale_num/scale_denom. Currently, the supported scaling ratios are M/N with all M from 1 to 16, where N is the source DCT size, which is 8 for baseline JPEG. (The library design allows for arbitrary scaling ratios but this is not likely to be implemented any time soon.) The values are initialized by jpeg_read_header() with the source DCT size. For baseline JPEG this is 8/8. If you change only the scale_num value while leaving the other unchanged, then this specifies the DCT scaled size to be applied on the given input. For baseline JPEG this is equivalent to M/8 scaling, since the source DCT size for baseline JPEG is 8. Smaller scaling ratios permit significantly faster decoding since fewer pixels need be processed and a simpler IDCT method can be used. boolean quantize_colors If set TRUE, colormapped output will be delivered. Default is FALSE, meaning that full-color output will be delivered. The next three parameters are relevant only if quantize_colors is TRUE. int desired_number_of_colors Maximum number of colors to use in generating a library-supplied color map (the actual number of colors is returned in a different field). Default 256. Ignored when the application supplies its own color map. boolean two_pass_quantize If TRUE, an extra pass over the image is made to select a custom color map for the image. This usually looks a lot better than the one-size- fits-all colormap that is used otherwise. Default is TRUE. Ignored when the application supplies its own color map. J_DITHER_MODE dither_mode Selects color dithering method. Supported values are: JDITHER_NONE no dithering: fast, very low quality JDITHER_ORDERED ordered dither: moderate speed and quality JDITHER_FS Floyd-Steinberg dither: slow, high quality Default is JDITHER_FS. (At present, ordered dither is implemented only in the single-pass, standard-colormap case. If you ask for ordered dither when two_pass_quantize is TRUE or when you supply an external color map, you'll get F-S dithering.) When quantize_colors is TRUE, the target color map is described by the next two fields. colormap is set to NULL by jpeg_read_header(). The application can supply a color map by setting colormap non-NULL and setting actual_number_of_colors to the map size. Otherwise, jpeg_start_decompress() selects a suitable color map and sets these two fields itself. [Implementation restriction: at present, an externally supplied colormap is only accepted for 3-component output color spaces.] JSAMPARRAY colormap The color map, represented as a 2-D pixel array of out_color_components rows and actual_number_of_colors columns. Ignored if not quantizing. CAUTION: if the JPEG library creates its own colormap, the storage pointed to by this field is released by jpeg_finish_decompress(). Copy the colormap somewhere else first, if you want to save it. int actual_number_of_colors The number of colors in the color map. Additional decompression parameters that the application may set include: J_DCT_METHOD dct_method Selects the algorithm used for the DCT step. Choices are the same as described above for compression. boolean do_fancy_upsampling If TRUE, use direct DCT scaling with DCT size > 8 for upsampling of chroma components. If FALSE, use only DCT size <= 8 and simple separate upsampling. Default is TRUE. For better image stability in multiple generation compression cycles it is preferable that this value matches the corresponding do_fancy_downsampling value in compression. boolean do_block_smoothing If TRUE, interblock smoothing is applied in early stages of decoding progressive JPEG files; if FALSE, not. Default is TRUE. Early progression stages look "fuzzy" with smoothing, "blocky" without. In any case, block smoothing ceases to be applied after the first few AC coefficients are known to full accuracy, so it is relevant only when using buffered-image mode for progressive images. boolean enable_1pass_quant boolean enable_external_quant boolean enable_2pass_quant These are significant only in buffered-image mode, which is described in its own section below. The output image dimensions are given by the following fields. These are computed from the source image dimensions and the decompression parameters by jpeg_start_decompress(). You can also call jpeg_calc_output_dimensions() to obtain the values that will result from the current parameter settings. This can be useful if you are trying to pick a scaling ratio that will get close to a desired target size. It's also important if you are using the JPEG library's memory manager to allocate output buffer space, because you are supposed to request such buffers *before* jpeg_start_decompress(). JDIMENSION output_width Actual dimensions of output image. JDIMENSION output_height int out_color_components Number of color components in out_color_space. int output_components Number of color components returned. int rec_outbuf_height Recommended height of scanline buffer. When quantizing colors, output_components is 1, indicating a single color map index per pixel. Otherwise it equals out_color_components. The output arrays are required to be output_width * output_components JSAMPLEs wide. rec_outbuf_height is the recommended minimum height (in scanlines) of the buffer passed to jpeg_read_scanlines(). If the buffer is smaller, the library will still work, but time will be wasted due to unnecessary data copying. In high-quality modes, rec_outbuf_height is always 1, but some faster, lower-quality modes set it to larger values (typically 2 to 4). If you are going to ask for a high-speed processing mode, you may as well go to the trouble of honoring rec_outbuf_height so as to avoid data copying. (An output buffer larger than rec_outbuf_height lines is OK, but won't provide any material speed improvement over that height.) Special color spaces -------------------- The JPEG standard itself is "color blind" and doesn't specify any particular color space. It is customary to convert color data to a luminance/chrominance color space before compressing, since this permits greater compression. The existing JPEG file interchange format standards specify YCbCr or GRAYSCALE data (JFIF version 1), GRAYSCALE, RGB, YCbCr, CMYK, or YCCK (Adobe), or BG_RGB or BG_YCC (big gamut color spaces, JFIF version 2). For special applications such as multispectral images, other color spaces can be used, but it must be understood that such files will be unportable. The JPEG library can handle the most common colorspace conversions (namely RGB <=> YCbCr and CMYK <=> YCCK). It can also deal with data of an unknown color space, passing it through without conversion. If you deal extensively with an unusual color space, you can easily extend the library to understand additional color spaces and perform appropriate conversions. For compression, the source data's color space is specified by field in_color_space. This is transformed to the JPEG file's color space given by jpeg_color_space. jpeg_set_defaults() chooses a reasonable JPEG color space depending on in_color_space, but you can override this by calling jpeg_set_colorspace(). Of course you must select a supported transformation. jccolor.c currently supports the following transformations: RGB => YCbCr RGB => GRAYSCALE RGB => BG_YCC YCbCr => GRAYSCALE YCbCr => BG_YCC CMYK => YCCK plus the null transforms: GRAYSCALE => GRAYSCALE, RGB => RGB, BG_RGB => BG_RGB, YCbCr => YCbCr, BG_YCC => BG_YCC, CMYK => CMYK, YCCK => YCCK, and UNKNOWN => UNKNOWN. The file interchange format standards (JFIF and Adobe) specify APPn markers that indicate the color space of the JPEG file. It is important to ensure that these are written correctly, or omitted if the JPEG file's color space is not one of the ones supported by the interchange standards. jpeg_set_colorspace() will set the compression parameters to include or omit the APPn markers properly, so long as it is told the truth about the JPEG color space. For example, if you are writing some random 3-component color space without conversion, don't try to fake out the library by setting in_color_space and jpeg_color_space to JCS_YCbCr; use JCS_UNKNOWN. You may want to write an APPn marker of your own devising to identify the colorspace --- see "Special markers", below. When told that the color space is UNKNOWN, the library will default to using luminance-quality compression parameters for all color components. You may well want to change these parameters. See the source code for jpeg_set_colorspace(), in jcparam.c, for details. For decompression, the JPEG file's color space is given in jpeg_color_space, and this is transformed to the output color space out_color_space. jpeg_read_header's setting of jpeg_color_space can be relied on if the file conforms to JFIF or Adobe conventions, but otherwise it is no better than a guess. If you know the JPEG file's color space for certain, you can override jpeg_read_header's guess by setting jpeg_color_space. jpeg_read_header also selects a default output color space based on (its guess of) jpeg_color_space; set out_color_space to override this. Again, you must select a supported transformation. jdcolor.c currently supports YCbCr => RGB YCbCr => GRAYSCALE BG_YCC => RGB BG_YCC => GRAYSCALE RGB => GRAYSCALE GRAYSCALE => RGB YCCK => CMYK as well as the null transforms. (Since GRAYSCALE=>RGB is provided, an application can force grayscale JPEGs to look like color JPEGs if it only wants to handle one case.) The two-pass color quantizer, jquant2.c, is specialized to handle RGB data (it weights distances appropriately for RGB colors). You'll need to modify the code if you want to use it for non-RGB output color spaces. Note that jquant2.c is used to map to an application-supplied colormap as well as for the normal two-pass colormap selection process. CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG files: 0 represents 100% ink coverage, rather than 0% ink as you'd expect. This is arguably a bug in Photoshop, but if you need to work with Photoshop CMYK files, you will have to deal with it in your application. We cannot "fix" this in the library by inverting the data during the CMYK<=>YCCK transform, because that would break other applications, notably Ghostscript. Photoshop versions prior to 3.0 write EPS files containing JPEG-encoded CMYK data in the same inverted-YCCK representation used in bare JPEG files, but the surrounding PostScript code performs an inversion using the PS image operator. I am told that Photoshop 3.0 will write uninverted YCCK in EPS/JPEG files, and will omit the PS-level inversion. (But the data polarity used in bare JPEG files will not change in 3.0.) In either case, the JPEG library must not invert the data itself, or else Ghostscript would read these EPS files incorrectly. Error handling -------------- When the default error handler is used, any error detected inside the JPEG routines will cause a message to be printed on stderr, followed by exit(). You can supply your own error handling routines to override this behavior and to control the treatment of nonfatal warnings and trace/debug messages. The file example.c illustrates the most common case, which is to have the application regain control after an error rather than exiting. The JPEG library never writes any message directly; it always goes through the error handling routines. Three classes of messages are recognized: * Fatal errors: the library cannot continue. * Warnings: the library can continue, but the data is corrupt, and a damaged output image is likely to result. * Trace/informational messages. These come with a trace level indicating the importance of the message; you can control the verbosity of the program by adjusting the maximum trace level that will be displayed. You may, if you wish, simply replace the entire JPEG error handling module (jerror.c) with your own code. However, you can avoid code duplication by only replacing some of the routines depending on the behavior you need. This is accomplished by calling jpeg_std_error() as usual, but then overriding some of the method pointers in the jpeg_error_mgr struct, as illustrated by example.c. All of the error handling routines will receive a pointer to the JPEG object (a j_common_ptr which points to either a jpeg_compress_struct or a jpeg_decompress_struct; if you need to tell which, test the is_decompressor field). This struct includes a pointer to the error manager struct in its "err" field. Frequently, custom error handler routines will need to access additional data which is not known to the JPEG library or the standard error handler. The most convenient way to do this is to embed either the JPEG object or the jpeg_error_mgr struct in a larger structure that contains additional fields; then casting the passed pointer provides access to the additional fields. Again, see example.c for one way to do it. (Beginning with IJG version 6b, there is also a void pointer "client_data" in each JPEG object, which the application can also use to find related data. The library does not touch client_data at all.) The individual methods that you might wish to override are: error_exit (j_common_ptr cinfo) Receives control for a fatal error. Information sufficient to generate the error message has been stored in cinfo->err; call output_message to display it. Control must NOT return to the caller; generally this routine will exit() or longjmp() somewhere. Typically you would override this routine to get rid of the exit() default behavior. Note that if you continue processing, you should clean up the JPEG object with jpeg_abort() or jpeg_destroy(). output_message (j_common_ptr cinfo) Actual output of any JPEG message. Override this to send messages somewhere other than stderr. Note that this method does not know how to generate a message, only where to send it. format_message (j_common_ptr cinfo, char * buffer) Constructs a readable error message string based on the error info stored in cinfo->err. This method is called by output_message. Few applications should need to override this method. One possible reason for doing so is to implement dynamic switching of error message language. emit_message (j_common_ptr cinfo, int msg_level) Decide whether or not to emit a warning or trace message; if so, calls output_message. The main reason for overriding this method would be to abort on warnings. msg_level is -1 for warnings, 0 and up for trace messages. Only error_exit() and emit_message() are called from the rest of the JPEG library; the other two are internal to the error handler. The actual message texts are stored in an array of strings which is pointed to by the field err->jpeg_message_table. The messages are numbered from 0 to err->last_jpeg_message, and it is these code numbers that are used in the JPEG library code. You could replace the message texts (for instance, with messages in French or German) by changing the message table pointer. See jerror.h for the default texts. CAUTION: this table will almost certainly change or grow from one library version to the next. It may be useful for an application to add its own message texts that are handled by the same mechanism. The error handler supports a second "add-on" message table for this purpose. To define an addon table, set the pointer err->addon_message_table and the message numbers err->first_addon_message and err->last_addon_message. If you number the addon messages beginning at 1000 or so, you won't have to worry about conflicts with the library's built-in messages. See the sample applications cjpeg/djpeg for an example of using addon messages (the addon messages are defined in cderror.h). Actual invocation of the error handler is done via macros defined in jerror.h: ERREXITn(...) for fatal errors WARNMSn(...) for corrupt-data warnings TRACEMSn(...) for trace and informational messages. These macros store the message code and any additional parameters into the error handler struct, then invoke the error_exit() or emit_message() method. The variants of each macro are for varying numbers of additional parameters. The additional parameters are inserted into the generated message using standard printf() format codes. See jerror.h and jerror.c for further details. Compressed data handling (source and destination managers) ---------------------------------------------------------- The JPEG compression library sends its compressed data to a "destination manager" module. The default destination manager just writes the data to a memory buffer or to a stdio stream, but you can provide your own manager to do something else. Similarly, the decompression library calls a "source manager" to obtain the compressed data; you can provide your own source manager if you want the data to come from somewhere other than a memory buffer or a stdio stream. In both cases, compressed data is processed a bufferload at a time: the destination or source manager provides a work buffer, and the library invokes the manager only when the buffer is filled or emptied. (You could define a one-character buffer to force the manager to be invoked for each byte, but that would be rather inefficient.) The buffer's size and location are controlled by the manager, not by the library. For example, the memory source manager just makes the buffer pointer and length point to the original data in memory. In this case the buffer-reload procedure will be invoked only if the decompressor ran off the end of the datastream, which would indicate an erroneous datastream. The work buffer is defined as an array of datatype JOCTET, which is generally "char" or "unsigned char". On a machine where char is not exactly 8 bits wide, you must define JOCTET as a wider data type and then modify the data source and destination modules to transcribe the work arrays into 8-bit units on external storage. A data destination manager struct contains a pointer and count defining the next byte to write in the work buffer and the remaining free space: JOCTET * next_output_byte; /* => next byte to write in buffer */ size_t free_in_buffer; /* # of byte spaces remaining in buffer */ The library increments the pointer and decrements the count until the buffer is filled. The manager's empty_output_buffer method must reset the pointer and count. The manager is expected to remember the buffer's starting address and total size in private fields not visible to the library. A data destination manager provides three methods: init_destination (j_compress_ptr cinfo) Initialize destination. This is called by jpeg_start_compress() before any data is actually written. It must initialize next_output_byte and free_in_buffer. free_in_buffer must be initialized to a positive value. empty_output_buffer (j_compress_ptr cinfo) This is called whenever the buffer has filled (free_in_buffer reaches zero). In typical applications, it should write out the *entire* buffer (use the saved start address and buffer length; ignore the current state of next_output_byte and free_in_buffer). Then reset the pointer & count to the start of the buffer, and return TRUE indicating that the buffer has been dumped. free_in_buffer must be set to a positive value when TRUE is returned. A FALSE return should only be used when I/O suspension is desired (this operating mode is discussed in the next section). term_destination (j_compress_ptr cinfo) Terminate destination --- called by jpeg_finish_compress() after all data has been written. In most applications, this must flush any data remaining in the buffer. Use either next_output_byte or free_in_buffer to determine how much data is in the buffer. term_destination() is NOT called by jpeg_abort() or jpeg_destroy(). If you want the destination manager to be cleaned up during an abort, you must do it yourself. You will also need code to create a jpeg_destination_mgr struct, fill in its method pointers, and insert a pointer to the struct into the "dest" field of the JPEG compression object. This can be done in-line in your setup code if you like, but it's probably cleaner to provide a separate routine similar to the jpeg_stdio_dest() or jpeg_mem_dest() routines of the supplied destination managers. Decompression source managers follow a parallel design, but with some additional frammishes. The source manager struct contains a pointer and count defining the next byte to read from the work buffer and the number of bytes remaining: const JOCTET * next_input_byte; /* => next byte to read from buffer */ size_t bytes_in_buffer; /* # of bytes remaining in buffer */ The library increments the pointer and decrements the count until the buffer is emptied. The manager's fill_input_buffer method must reset the pointer and count. In most applications, the manager must remember the buffer's starting address and total size in private fields not visible to the library. A data source manager provides five methods: init_source (j_decompress_ptr cinfo) Initialize source. This is called by jpeg_read_header() before any data is actually read. Unlike init_destination(), it may leave bytes_in_buffer set to 0 (in which case a fill_input_buffer() call will occur immediately). fill_input_buffer (j_decompress_ptr cinfo) This is called whenever bytes_in_buffer has reached zero and more data is wanted. In typical applications, it should read fresh data into the buffer (ignoring the current state of next_input_byte and bytes_in_buffer), reset the pointer & count to the start of the buffer, and return TRUE indicating that the buffer has been reloaded. It is not necessary to fill the buffer entirely, only to obtain at least one more byte. bytes_in_buffer MUST be set to a positive value if TRUE is returned. A FALSE return should only be used when I/O suspension is desired (this mode is discussed in the next section). skip_input_data (j_decompress_ptr cinfo, long num_bytes) Skip num_bytes worth of data. The buffer pointer and count should be advanced over num_bytes input bytes, refilling the buffer as needed. This is used to skip over a potentially large amount of uninteresting data (such as an APPn marker). In some applications it may be possible to optimize away the reading of the skipped data, but it's not clear that being smart is worth much trouble; large skips are uncommon. bytes_in_buffer may be zero on return. A zero or negative skip count should be treated as a no-op. resync_to_restart (j_decompress_ptr cinfo, int desired) This routine is called only when the decompressor has failed to find a restart (RSTn) marker where one is expected. Its mission is to find a suitable point for resuming decompression. For most applications, we recommend that you just use the default resync procedure, jpeg_resync_to_restart(). However, if you are able to back up in the input data stream, or if you have a-priori knowledge about the likely location of restart markers, you may be able to do better. Read the read_restart_marker() and jpeg_resync_to_restart() routines in jdmarker.c if you think you'd like to implement your own resync procedure. term_source (j_decompress_ptr cinfo) Terminate source --- called by jpeg_finish_decompress() after all data has been read. Often a no-op. For both fill_input_buffer() and skip_input_data(), there is no such thing as an EOF return. If the end of the file has been reached, the routine has a choice of exiting via ERREXIT() or inserting fake data into the buffer. In most cases, generating a warning message and inserting a fake EOI marker is the best course of action --- this will allow the decompressor to output however much of the image is there. In pathological cases, the decompressor may swallow the EOI and again demand data ... just keep feeding it fake EOIs. jdatasrc.c illustrates the recommended error recovery behavior. term_source() is NOT called by jpeg_abort() or jpeg_destroy(). If you want the source manager to be cleaned up during an abort, you must do it yourself. You will also need code to create a jpeg_source_mgr struct, fill in its method pointers, and insert a pointer to the struct into the "src" field of the JPEG decompression object. This can be done in-line in your setup code if you like, but it's probably cleaner to provide a separate routine similar to the jpeg_stdio_src() or jpeg_mem_src() routines of the supplied source managers. For more information, consult the memory and stdio source and destination managers in jdatasrc.c and jdatadst.c. I/O suspension -------------- Some applications need to use the JPEG library as an incremental memory-to- memory filter: when the compressed data buffer is filled or emptied, they want control to return to the outer loop, rather than expecting that the buffer can be emptied or reloaded within the data source/destination manager subroutine. The library supports this need by providing an "I/O suspension" mode, which we describe in this section. The I/O suspension mode is not a panacea: nothing is guaranteed about the maximum amount of time spent in any one call to the library, so it will not eliminate response-time problems in single-threaded applications. If you need guaranteed response time, we suggest you "bite the bullet" and implement a real multi-tasking capability. To use I/O suspension, cooperation is needed between the calling application and the data source or destination manager; you will always need a custom source/destination manager. (Please read the previous section if you haven't already.) The basic idea is that the empty_output_buffer() or fill_input_buffer() routine is a no-op, merely returning FALSE to indicate that it has done nothing. Upon seeing this, the JPEG library suspends operation and returns to its caller. The surrounding application is responsible for emptying or refilling the work buffer before calling the JPEG library again. Compression suspension: For compression suspension, use an empty_output_buffer() routine that returns FALSE; typically it will not do anything else. This will cause the compressor to return to the caller of jpeg_write_scanlines(), with the return value indicating that not all the supplied scanlines have been accepted. The application must make more room in the output buffer, adjust the output buffer pointer/count appropriately, and then call jpeg_write_scanlines() again, pointing to the first unconsumed scanline. When forced to suspend, the compressor will backtrack to a convenient stopping point (usually the start of the current MCU); it will regenerate some output data when restarted. Therefore, although empty_output_buffer() is only called when the buffer is filled, you should NOT write out the entire buffer after a suspension. Write only the data up to the current position of next_output_byte/free_in_buffer. The data beyond that point will be regenerated after resumption. Because of the backtracking behavior, a good-size output buffer is essential for efficiency; you don't want the compressor to suspend often. (In fact, an overly small buffer could lead to infinite looping, if a single MCU required more data than would fit in the buffer.) We recommend a buffer of at least several Kbytes. You may want to insert explicit code to ensure that you don't call jpeg_write_scanlines() unless there is a reasonable amount of space in the output buffer; in other words, flush the buffer before trying to compress more data. The compressor does not allow suspension while it is trying to write JPEG markers at the beginning and end of the file. This means that: * At the beginning of a compression operation, there must be enough free space in the output buffer to hold the header markers (typically 600 or so bytes). The recommended buffer size is bigger than this anyway, so this is not a problem as long as you start with an empty buffer. However, this restriction might catch you if you insert large special markers, such as a JFIF thumbnail image, without flushing the buffer afterwards. * When you call jpeg_finish_compress(), there must be enough space in the output buffer to emit any buffered data and the final EOI marker. In the current implementation, half a dozen bytes should suffice for this, but for safety's sake we recommend ensuring that at least 100 bytes are free before calling jpeg_finish_compress(). A more significant restriction is that jpeg_finish_compress() cannot suspend. This means you cannot use suspension with multi-pass operating modes, namely Huffman code optimization and multiple-scan output. Those modes write the whole file during jpeg_finish_compress(), which will certainly result in buffer overrun. (Note that this restriction applies only to compression, not decompression. The decompressor supports input suspension in all of its operating modes.) Decompression suspension: For decompression suspension, use a fill_input_buffer() routine that simply returns FALSE (except perhaps during error recovery, as discussed below). This will cause the decompressor to return to its caller with an indication that suspension has occurred. This can happen at four places: * jpeg_read_header(): will return JPEG_SUSPENDED. * jpeg_start_decompress(): will return FALSE, rather than its usual TRUE. * jpeg_read_scanlines(): will return the number of scanlines already completed (possibly 0). * jpeg_finish_decompress(): will return FALSE, rather than its usual TRUE. The surrounding application must recognize these cases, load more data into the input buffer, and repeat the call. In the case of jpeg_read_scanlines(), increment the passed pointers past any scanlines successfully read. Just as with compression, the decompressor will typically backtrack to a convenient restart point before suspending. When fill_input_buffer() is called, next_input_byte/bytes_in_buffer point to the current restart point, which is where the decompressor will backtrack to if FALSE is returned. The data beyond that position must NOT be discarded if you suspend; it needs to be re-read upon resumption. In most implementations, you'll need to shift this data down to the start of your work buffer and then load more data after it. Again, this behavior means that a several-Kbyte work buffer is essential for decent performance; furthermore, you should load a reasonable amount of new data before resuming decompression. (If you loaded, say, only one new byte each time around, you could waste a LOT of cycles.) The skip_input_data() source manager routine requires special care in a suspension scenario. This routine is NOT granted the ability to suspend the decompressor; it can decrement bytes_in_buffer to zero, but no more. If the requested skip distance exceeds the amount of data currently in the input buffer, then skip_input_data() must set bytes_in_buffer to zero and record the additional skip distance somewhere else. The decompressor will immediately call fill_input_buffer(), which should return FALSE, which will cause a suspension return. The surrounding application must then arrange to discard the recorded number of bytes before it resumes loading the input buffer. (Yes, this design is rather baroque, but it avoids complexity in the far more common case where a non-suspending source manager is used.) If the input data has been exhausted, we recommend that you emit a warning and insert dummy EOI markers just as a non-suspending data source manager would do. This can be handled either in the surrounding application logic or within fill_input_buffer(); the latter is probably more efficient. If fill_input_buffer() knows that no more data is available, it can set the pointer/count to point to a dummy EOI marker and then return TRUE just as though it had read more data in a non-suspending situation. The decompressor does not attempt to suspend within standard JPEG markers; instead it will backtrack to the start of the marker and reprocess the whole marker next time. Hence the input buffer must be large enough to hold the longest standard marker in the file. Standard JPEG markers should normally not exceed a few hundred bytes each (DHT tables are typically the longest). We recommend at least a 2K buffer for performance reasons, which is much larger than any correct marker is likely to be. For robustness against damaged marker length counts, you may wish to insert a test in your application for the case that the input buffer is completely full and yet the decoder has suspended without consuming any data --- otherwise, if this situation did occur, it would lead to an endless loop. (The library can't provide this test since it has no idea whether "the buffer is full", or even whether there is a fixed-size input buffer.) The input buffer would need to be 64K to allow for arbitrary COM or APPn markers, but these are handled specially: they are either saved into allocated memory, or skipped over by calling skip_input_data(). In the former case, suspension is handled correctly, and in the latter case, the problem of buffer overrun is placed on skip_input_data's shoulders, as explained above. Note that if you provide your own marker handling routine for large markers, you should consider how to deal with buffer overflow. Multiple-buffer management: In some applications it is desirable to store the compressed data in a linked list of buffer areas, so as to avoid data copying. This can be handled by having empty_output_buffer() or fill_input_buffer() set the pointer and count to reference the next available buffer; FALSE is returned only if no more buffers are available. Although seemingly straightforward, there is a pitfall in this approach: the backtrack that occurs when FALSE is returned could back up into an earlier buffer. For example, when fill_input_buffer() is called, the current pointer & count indicate the backtrack restart point. Since fill_input_buffer() will set the pointer and count to refer to a new buffer, the restart position must be saved somewhere else. Suppose a second call to fill_input_buffer() occurs in the same library call, and no additional input data is available, so fill_input_buffer must return FALSE. If the JPEG library has not moved the pointer/count forward in the current buffer, then *the correct restart point is the saved position in the prior buffer*. Prior buffers may be discarded only after the library establishes a restart point within a later buffer. Similar remarks apply for output into a chain of buffers. The library will never attempt to backtrack over a skip_input_data() call, so any skipped data can be permanently discarded. You still have to deal with the case of skipping not-yet-received data, however. It's much simpler to use only a single buffer; when fill_input_buffer() is called, move any unconsumed data (beyond the current pointer/count) down to the beginning of this buffer and then load new data into the remaining buffer space. This approach requires a little more data copying but is far easier to get right. Progressive JPEG support ------------------------ Progressive JPEG rearranges the stored data into a series of scans of increasing quality. In situations where a JPEG file is transmitted across a slow communications link, a decoder can generate a low-quality image very quickly from the first scan, then gradually improve the displayed quality as more scans are received. The final image after all scans are complete is identical to that of a regular (sequential) JPEG file of the same quality setting. Progressive JPEG files are often slightly smaller than equivalent sequential JPEG files, but the possibility of incremental display is the main reason for using progressive JPEG. The IJG encoder library generates progressive JPEG files when given a suitable "scan script" defining how to divide the data into scans. Creation of progressive JPEG files is otherwise transparent to the encoder. Progressive JPEG files can also be read transparently by the decoder library. If the decoding application simply uses the library as defined above, it will receive a final decoded image without any indication that the file was progressive. Of course, this approach does not allow incremental display. To perform incremental display, an application needs to use the decoder library's "buffered-image" mode, in which it receives a decoded image multiple times. Each displayed scan requires about as much work to decode as a full JPEG image of the same size, so the decoder must be fairly fast in relation to the data transmission rate in order to make incremental display useful. However, it is possible to skip displaying the image and simply add the incoming bits to the decoder's coefficient buffer. This is fast because only Huffman decoding need be done, not IDCT, upsampling, colorspace conversion, etc. The IJG decoder library allows the application to switch dynamically between displaying the image and simply absorbing the incoming bits. A properly coded application can automatically adapt the number of display passes to suit the time available as the image is received. Also, a final higher-quality display cycle can be performed from the buffered data after the end of the file is reached. Progressive compression: To create a progressive JPEG file (or a multiple-scan sequential JPEG file), set the scan_info cinfo field to point to an array of scan descriptors, and perform compression as usual. Instead of constructing your own scan list, you can call the jpeg_simple_progression() helper routine to create a recommended progression sequence; this method should be used by all applications that don't want to get involved in the nitty-gritty of progressive scan sequence design. (If you want to provide user control of scan sequences, you may wish to borrow the scan script reading code found in rdswitch.c, so that you can read scan script files just like cjpeg's.) When scan_info is not NULL, the compression library will store DCT'd data into a buffer array as jpeg_write_scanlines() is called, and will emit all the requested scans during jpeg_finish_compress(). This implies that multiple-scan output cannot be created with a suspending data destination manager, since jpeg_finish_compress() does not support suspension. We should also note that the compressor currently forces Huffman optimization mode when creating a progressive JPEG file, because the default Huffman tables are unsuitable for progressive files. Progressive decompression: When buffered-image mode is not used, the decoder library will read all of a multi-scan file during jpeg_start_decompress(), so that it can provide a final decoded image. (Here "multi-scan" means either progressive or multi-scan sequential.) This makes multi-scan files transparent to the decoding application. However, existing applications that used suspending input with version 5 of the IJG library will need to be modified to check for a suspension return from jpeg_start_decompress(). To perform incremental display, an application must use the library's buffered-image mode. This is described in the next section. Buffered-image mode ------------------- In buffered-image mode, the library stores the partially decoded image in a coefficient buffer, from which it can be read out as many times as desired. This mode is typically used for incremental display of progressive JPEG files, but it can be used with any JPEG file. Each scan of a progressive JPEG file adds more data (more detail) to the buffered image. The application can display in lockstep with the source file (one display pass per input scan), or it can allow input processing to outrun display processing. By making input and display processing run independently, it is possible for the application to adapt progressive display to a wide range of data transmission rates. The basic control flow for buffered-image decoding is jpeg_create_decompress() set data source jpeg_read_header() set overall decompression parameters cinfo.buffered_image = TRUE; /* select buffered-image mode */ jpeg_start_decompress() for (each output pass) { adjust output decompression parameters if required jpeg_start_output() /* start a new output pass */ for (all scanlines in image) { jpeg_read_scanlines() display scanlines } jpeg_finish_output() /* terminate output pass */ } jpeg_finish_decompress() jpeg_destroy_decompress() This differs from ordinary unbuffered decoding in that there is an additional level of looping. The application can choose how many output passes to make and how to display each pass. The simplest approach to displaying progressive images is to do one display pass for each scan appearing in the input file. In this case the outer loop condition is typically while (! jpeg_input_complete(&cinfo)) and the start-output call should read jpeg_start_output(&cinfo, cinfo.input_scan_number); The second parameter to jpeg_start_output() indicates which scan of the input file is to be displayed; the scans are numbered starting at 1 for this purpose. (You can use a loop counter starting at 1 if you like, but using the library's input scan counter is easier.) The library automatically reads data as necessary to complete each requested scan, and jpeg_finish_output() advances to the next scan or end-of-image marker (hence input_scan_number will be incremented by the time control arrives back at jpeg_start_output()). With this technique, data is read from the input file only as needed, and input and output processing run in lockstep. After reading the final scan and reaching the end of the input file, the buffered image remains available; it can be read additional times by repeating the jpeg_start_output()/jpeg_read_scanlines()/jpeg_finish_output() sequence. For example, a useful technique is to use fast one-pass color quantization for display passes made while the image is arriving, followed by a final display pass using two-pass quantization for highest quality. This is done by changing the library parameters before the final output pass. Changing parameters between passes is discussed in detail below. In general the last scan of a progressive file cannot be recognized as such until after it is read, so a post-input display pass is the best approach if you want special processing in the final pass. When done with the image, be sure to call jpeg_finish_decompress() to release the buffered image (or just use jpeg_destroy_decompress()). If input data arrives faster than it can be displayed, the application can cause the library to decode input data in advance of what's needed to produce output. This is done by calling the routine jpeg_consume_input(). The return value is one of the following: JPEG_REACHED_SOS: reached an SOS marker (the start of a new scan) JPEG_REACHED_EOI: reached the EOI marker (end of image) JPEG_ROW_COMPLETED: completed reading one MCU row of compressed data JPEG_SCAN_COMPLETED: completed reading last MCU row of current scan JPEG_SUSPENDED: suspended before completing any of the above (JPEG_SUSPENDED can occur only if a suspending data source is used.) This routine can be called at any time after initializing the JPEG object. It reads some additional data and returns when one of the indicated significant events occurs. (If called after the EOI marker is reached, it will immediately return JPEG_REACHED_EOI without attempting to read more data.) The library's output processing will automatically call jpeg_consume_input() whenever the output processing overtakes the input; thus, simple lockstep display requires no direct calls to jpeg_consume_input(). But by adding calls to jpeg_consume_input(), you can absorb data in advance of what is being displayed. This has two benefits: * You can limit buildup of unprocessed data in your input buffer. * You can eliminate extra display passes by paying attention to the state of the library's input processing. The first of these benefits only requires interspersing calls to jpeg_consume_input() with your display operations and any other processing you may be doing. To avoid wasting cycles due to backtracking, it's best to call jpeg_consume_input() only after a hundred or so new bytes have arrived. This is discussed further under "I/O suspension", above. (Note: the JPEG library currently is not thread-safe. You must not call jpeg_consume_input() from one thread of control if a different library routine is working on the same JPEG object in another thread.) When input arrives fast enough that more than one new scan is available before you start a new output pass, you may as well skip the output pass corresponding to the completed scan. This occurs for free if you pass cinfo.input_scan_number as the target scan number to jpeg_start_output(). The input_scan_number field is simply the index of the scan currently being consumed by the input processor. You can ensure that this is up-to-date by emptying the input buffer just before calling jpeg_start_output(): call jpeg_consume_input() repeatedly until it returns JPEG_SUSPENDED or JPEG_REACHED_EOI. The target scan number passed to jpeg_start_output() is saved in the cinfo.output_scan_number field. The library's output processing calls jpeg_consume_input() whenever the current input scan number and row within that scan is less than or equal to the current output scan number and row. Thus, input processing can "get ahead" of the output processing but is not allowed to "fall behind". You can achieve several different effects by manipulating this interlock rule. For example, if you pass a target scan number greater than the current input scan number, the output processor will wait until that scan starts to arrive before producing any output. (To avoid an infinite loop, the target scan number is automatically reset to the last scan number when the end of image is reached. Thus, if you specify a large target scan number, the library will just absorb the entire input file and then perform an output pass. This is effectively the same as what jpeg_start_decompress() does when you don't select buffered-image mode.) When you pass a target scan number equal to the current input scan number, the image is displayed no faster than the current input scan arrives. The final possibility is to pass a target scan number less than the current input scan number; this disables the input/output interlock and causes the output processor to simply display whatever it finds in the image buffer, without waiting for input. (However, the library will not accept a target scan number less than one, so you can't avoid waiting for the first scan.) When data is arriving faster than the output display processing can advance through the image, jpeg_consume_input() will store data into the buffered image beyond the point at which the output processing is reading data out again. If the input arrives fast enough, it may "wrap around" the buffer to the point where the input is more than one whole scan ahead of the output. If the output processing simply proceeds through its display pass without paying attention to the input, the effect seen on-screen is that the lower part of the image is one or more scans better in quality than the upper part. Then, when the next output scan is started, you have a choice of what target scan number to use. The recommended choice is to use the current input scan number at that time, which implies that you've skipped the output scans corresponding to the input scans that were completed while you processed the previous output scan. In this way, the decoder automatically adapts its speed to the arriving data, by skipping output scans as necessary to keep up with the arriving data. When using this strategy, you'll want to be sure that you perform a final output pass after receiving all the data; otherwise your last display may not be full quality across the whole screen. So the right outer loop logic is something like this: do { absorb any waiting input by calling jpeg_consume_input() final_pass = jpeg_input_complete(&cinfo); adjust output decompression parameters if required jpeg_start_output(&cinfo, cinfo.input_scan_number); ... jpeg_finish_output() } while (! final_pass); rather than quitting as soon as jpeg_input_complete() returns TRUE. This arrangement makes it simple to use higher-quality decoding parameters for the final pass. But if you don't want to use special parameters for the final pass, the right loop logic is like this: for (;;) { absorb any waiting input by calling jpeg_consume_input() jpeg_start_output(&cinfo, cinfo.input_scan_number); ... jpeg_finish_output() if (jpeg_input_complete(&cinfo) && cinfo.input_scan_number == cinfo.output_scan_number) break; } In this case you don't need to know in advance whether an output pass is to be the last one, so it's not necessary to have reached EOF before starting the final output pass; rather, what you want to test is whether the output pass was performed in sync with the final input scan. This form of the loop will avoid an extra output pass whenever the decoder is able (or nearly able) to keep up with the incoming data. When the data transmission speed is high, you might begin a display pass, then find that much or all of the file has arrived before you can complete the pass. (You can detect this by noting the JPEG_REACHED_EOI return code from jpeg_consume_input(), or equivalently by testing jpeg_input_complete().) In this situation you may wish to abort the current display pass and start a new one using the newly arrived information. To do so, just call jpeg_finish_output() and then start a new pass with jpeg_start_output(). A variant strategy is to abort and restart display if more than one complete scan arrives during an output pass; this can be detected by noting JPEG_REACHED_SOS returns and/or examining cinfo.input_scan_number. This idea should be employed with caution, however, since the display process might never get to the bottom of the image before being aborted, resulting in the lower part of the screen being several passes worse than the upper. In most cases it's probably best to abort an output pass only if the whole file has arrived and you want to begin the final output pass immediately. When receiving data across a communication link, we recommend always using the current input scan number for the output target scan number; if a higher-quality final pass is to be done, it should be started (aborting any incomplete output pass) as soon as the end of file is received. However, many other strategies are possible. For example, the application can examine the parameters of the current input scan and decide whether to display it or not. If the scan contains only chroma data, one might choose not to use it as the target scan, expecting that the scan will be small and will arrive quickly. To skip to the next scan, call jpeg_consume_input() until it returns JPEG_REACHED_SOS or JPEG_REACHED_EOI. Or just use the next higher number as the target scan for jpeg_start_output(); but that method doesn't let you inspect the next scan's parameters before deciding to display it. In buffered-image mode, jpeg_start_decompress() never performs input and thus never suspends. An application that uses input suspension with buffered-image mode must be prepared for suspension returns from these routines: * jpeg_start_output() performs input only if you request 2-pass quantization and the target scan isn't fully read yet. (This is discussed below.) * jpeg_read_scanlines(), as always, returns the number of scanlines that it was able to produce before suspending. * jpeg_finish_output() will read any markers following the target scan, up to the end of the file or the SOS marker that begins another scan. (But it reads no input if jpeg_consume_input() has already reached the end of the file or a SOS marker beyond the target output scan.) * jpeg_finish_decompress() will read until the end of file, and thus can suspend if the end hasn't already been reached (as can be tested by calling jpeg_input_complete()). jpeg_start_output(), jpeg_finish_output(), and jpeg_finish_decompress() all return TRUE if they completed their tasks, FALSE if they had to suspend. In the event of a FALSE return, the application must load more input data and repeat the call. Applications that use non-suspending data sources need not check the return values of these three routines. It is possible to change decoding parameters between output passes in the buffered-image mode. The decoder library currently supports only very limited changes of parameters. ONLY THE FOLLOWING parameter changes are allowed after jpeg_start_decompress() is called: * dct_method can be changed before each call to jpeg_start_output(). For example, one could use a fast DCT method for early scans, changing to a higher quality method for the final scan. * dither_mode can be changed before each call to jpeg_start_output(); of course this has no impact if not using color quantization. Typically one would use ordered dither for initial passes, then switch to Floyd-Steinberg dither for the final pass. Caution: changing dither mode can cause more memory to be allocated by the library. Although the amount of memory involved is not large (a scanline or so), it may cause the initial max_memory_to_use specification to be exceeded, which in the worst case would result in an out-of-memory failure. * do_block_smoothing can be changed before each call to jpeg_start_output(). This setting is relevant only when decoding a progressive JPEG image. During the first DC-only scan, block smoothing provides a very "fuzzy" look instead of the very "blocky" look seen without it; which is better seems a matter of personal taste. But block smoothing is nearly always a win during later stages, especially when decoding a successive-approximation image: smoothing helps to hide the slight blockiness that otherwise shows up on smooth gradients until the lowest coefficient bits are sent. * Color quantization mode can be changed under the rules described below. You *cannot* change between full-color and quantized output (because that would alter the required I/O buffer sizes), but you can change which quantization method is used. When generating color-quantized output, changing quantization method is a very useful way of switching between high-speed and high-quality display. The library allows you to change among its three quantization methods: 1. Single-pass quantization to a fixed color cube. Selected by cinfo.two_pass_quantize = FALSE and cinfo.colormap = NULL. 2. Single-pass quantization to an application-supplied colormap. Selected by setting cinfo.colormap to point to the colormap (the value of two_pass_quantize is ignored); also set cinfo.actual_number_of_colors. 3. Two-pass quantization to a colormap chosen specifically for the image. Selected by cinfo.two_pass_quantize = TRUE and cinfo.colormap = NULL. (This is the default setting selected by jpeg_read_header, but it is probably NOT what you want for the first pass of progressive display!) These methods offer successively better quality and lesser speed. However, only the first method is available for quantizing in non-RGB color spaces. IMPORTANT: because the different quantizer methods have very different working-storage requirements, the library requires you to indicate which one(s) you intend to use before you call jpeg_start_decompress(). (If we did not require this, the max_memory_to_use setting would be a complete fiction.) You do this by setting one or more of these three cinfo fields to TRUE: enable_1pass_quant Fixed color cube colormap enable_external_quant Externally-supplied colormap enable_2pass_quant Two-pass custom colormap All three are initialized FALSE by jpeg_read_header(). But jpeg_start_decompress() automatically sets TRUE the one selected by the current two_pass_quantize and colormap settings, so you only need to set the enable flags for any other quantization methods you plan to change to later. After setting the enable flags correctly at jpeg_start_decompress() time, you can change to any enabled quantization method by setting two_pass_quantize and colormap properly just before calling jpeg_start_output(). The following special rules apply: 1. You must explicitly set cinfo.colormap to NULL when switching to 1-pass or 2-pass mode from a different mode, or when you want the 2-pass quantizer to be re-run to generate a new colormap. 2. To switch to an external colormap, or to change to a different external colormap than was used on the prior pass, you must call jpeg_new_colormap() after setting cinfo.colormap. NOTE: if you want to use the same colormap as was used in the prior pass, you should not do either of these things. This will save some nontrivial switchover costs. (These requirements exist because cinfo.colormap will always be non-NULL after completing a prior output pass, since both the 1-pass and 2-pass quantizers set it to point to their output colormaps. Thus you have to do one of these two things to notify the library that something has changed. Yup, it's a bit klugy, but it's necessary to do it this way for backwards compatibility.) Note that in buffered-image mode, the library generates any requested colormap during jpeg_start_output(), not during jpeg_start_decompress(). When using two-pass quantization, jpeg_start_output() makes a pass over the buffered image to determine the optimum color map; it therefore may take a significant amount of time, whereas ordinarily it does little work. The progress monitor hook is called during this pass, if defined. It is also important to realize that if the specified target scan number is greater than or equal to the current input scan number, jpeg_start_output() will attempt to consume input as it makes this pass. If you use a suspending data source, you need to check for a FALSE return from jpeg_start_output() under these conditions. The combination of 2-pass quantization and a not-yet-fully-read target scan is the only case in which jpeg_start_output() will consume input. Application authors who support buffered-image mode may be tempted to use it for all JPEG images, even single-scan ones. This will work, but it is inefficient: there is no need to create an image-sized coefficient buffer for single-scan images. Requesting buffered-image mode for such an image wastes memory. Worse, it can cost time on large images, since the buffered data has to be swapped out or written to a temporary file. If you are concerned about maximum performance on baseline JPEG files, you should use buffered-image mode only when the incoming file actually has multiple scans. This can be tested by calling jpeg_has_multiple_scans(), which will return a correct result at any time after jpeg_read_header() completes. It is also worth noting that when you use jpeg_consume_input() to let input processing get ahead of output processing, the resulting pattern of access to the coefficient buffer is quite nonsequential. It's best to use the memory manager jmemnobs.c if you can (ie, if you have enough real or virtual main memory). If not, at least make sure that max_memory_to_use is set as high as possible. If the JPEG memory manager has to use a temporary file, you will probably see a lot of disk traffic and poor performance. (This could be improved with additional work on the memory manager, but we haven't gotten around to it yet.) In some applications it may be convenient to use jpeg_consume_input() for all input processing, including reading the initial markers; that is, you may wish to call jpeg_consume_input() instead of jpeg_read_header() during startup. This works, but note that you must check for JPEG_REACHED_SOS and JPEG_REACHED_EOI return codes as the equivalent of jpeg_read_header's codes. Once the first SOS marker has been reached, you must call jpeg_start_decompress() before jpeg_consume_input() will consume more input; it'll just keep returning JPEG_REACHED_SOS until you do. If you read a tables-only file this way, jpeg_consume_input() will return JPEG_REACHED_EOI without ever returning JPEG_REACHED_SOS; be sure to check for this case. If this happens, the decompressor will not read any more input until you call jpeg_abort() to reset it. It is OK to call jpeg_consume_input() even when not using buffered-image mode, but in that case it's basically a no-op after the initial markers have been read: it will just return JPEG_SUSPENDED. Abbreviated datastreams and multiple images ------------------------------------------- A JPEG compression or decompression object can be reused to process multiple images. This saves a small amount of time per image by eliminating the "create" and "destroy" operations, but that isn't the real purpose of the feature. Rather, reuse of an object provides support for abbreviated JPEG datastreams. Object reuse can also simplify processing a series of images in a single input or output file. This section explains these features. A JPEG file normally contains several hundred bytes worth of quantization and Huffman tables. In a situation where many images will be stored or transmitted with identical tables, this may represent an annoying overhead. The JPEG standard therefore permits tables to be omitted. The standard defines three classes of JPEG datastreams: * "Interchange" datastreams contain an image and all tables needed to decode the image. These are the usual kind of JPEG file. * "Abbreviated image" datastreams contain an image, but are missing some or all of the tables needed to decode that image. * "Abbreviated table specification" (henceforth "tables-only") datastreams contain only table specifications. To decode an abbreviated image, it is necessary to load the missing table(s) into the decoder beforehand. This can be accomplished by reading a separate tables-only file. A variant scheme uses a series of images in which the first image is an interchange (complete) datastream, while subsequent ones are abbreviated and rely on the tables loaded by the first image. It is assumed that once the decoder has read a table, it will remember that table until a new definition for the same table number is encountered. It is the application designer's responsibility to figure out how to associate the correct tables with an abbreviated image. While abbreviated datastreams can be useful in a closed environment, their use is strongly discouraged in any situation where data exchange with other applications might be needed. Caveat designer. The JPEG library provides support for reading and writing any combination of tables-only datastreams and abbreviated images. In both compression and decompression objects, a quantization or Huffman table will be retained for the lifetime of the object, unless it is overwritten by a new table definition. To create abbreviated image datastreams, it is only necessary to tell the compressor not to emit some or all of the tables it is using. Each quantization and Huffman table struct contains a boolean field "sent_table", which normally is initialized to FALSE. For each table used by the image, the header-writing process emits the table and sets sent_table = TRUE unless it is already TRUE. (In normal usage, this prevents outputting the same table definition multiple times, as would otherwise occur because the chroma components typically share tables.) Thus, setting this field to TRUE before calling jpeg_start_compress() will prevent the table from being written at all. If you want to create a "pure" abbreviated image file containing no tables, just call "jpeg_suppress_tables(&cinfo, TRUE)" after constructing all the tables. If you want to emit some but not all tables, you'll need to set the individual sent_table fields directly. To create an abbreviated image, you must also call jpeg_start_compress() with a second parameter of FALSE, not TRUE. Otherwise jpeg_start_compress() will force all the sent_table fields to FALSE. (This is a safety feature to prevent abbreviated images from being created accidentally.) To create a tables-only file, perform the same parameter setup that you normally would, but instead of calling jpeg_start_compress() and so on, call jpeg_write_tables(&cinfo). This will write an abbreviated datastream containing only SOI, DQT and/or DHT markers, and EOI. All the quantization and Huffman tables that are currently defined in the compression object will be emitted unless their sent_tables flag is already TRUE, and then all the sent_tables flags will be set TRUE. A sure-fire way to create matching tables-only and abbreviated image files is to proceed as follows: create JPEG compression object set JPEG parameters set destination to tables-only file jpeg_write_tables(&cinfo); set destination to image file jpeg_start_compress(&cinfo, FALSE); write data... jpeg_finish_compress(&cinfo); Since the JPEG parameters are not altered between writing the table file and the abbreviated image file, the same tables are sure to be used. Of course, you can repeat the jpeg_start_compress() ... jpeg_finish_compress() sequence many times to produce many abbreviated image files matching the table file. You cannot suppress output of the computed Huffman tables when Huffman optimization is selected. (If you could, there'd be no way to decode the image...) Generally, you don't want to set optimize_coding = TRUE when you are trying to produce abbreviated files. In some cases you might want to compress an image using tables which are not stored in the application, but are defined in an interchange or tables-only file readable by the application. This can be done by setting up a JPEG decompression object to read the specification file, then copying the tables into your compression object. See jpeg_copy_critical_parameters() for an example of copying quantization tables. To read abbreviated image files, you simply need to load the proper tables into the decompression object before trying to read the abbreviated image. If the proper tables are stored in the application program, you can just allocate the table structs and fill in their contents directly. For example, to load a fixed quantization table into table slot "n": if (cinfo.quant_tbl_ptrs[n] == NULL) cinfo.quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) &cinfo); quant_ptr = cinfo.quant_tbl_ptrs[n]; /* quant_ptr is JQUANT_TBL* */ for (i = 0; i < 64; i++) { /* Qtable[] is desired quantization table, in natural array order */ quant_ptr->quantval[i] = Qtable[i]; } Code to load a fixed Huffman table is typically (for AC table "n"): if (cinfo.ac_huff_tbl_ptrs[n] == NULL) cinfo.ac_huff_tbl_ptrs[n] = jpeg_alloc_huff_table((j_common_ptr) &cinfo); huff_ptr = cinfo.ac_huff_tbl_ptrs[n]; /* huff_ptr is JHUFF_TBL* */ for (i = 1; i <= 16; i++) { /* counts[i] is number of Huffman codes of length i bits, i=1..16 */ huff_ptr->bits[i] = counts[i]; } for (i = 0; i < 256; i++) { /* symbols[] is the list of Huffman symbols, in code-length order */ huff_ptr->huffval[i] = symbols[i]; } (Note that trying to set cinfo.quant_tbl_ptrs[n] to point directly at a constant JQUANT_TBL object is not safe. If the incoming file happened to contain a quantization table definition, your master table would get overwritten! Instead allocate a working table copy and copy the master table into it, as illustrated above. Ditto for Huffman tables, of course.) You might want to read the tables from a tables-only file, rather than hard-wiring them into your application. The jpeg_read_header() call is sufficient to read a tables-only file. You must pass a second parameter of FALSE to indicate that you do not require an image to be present. Thus, the typical scenario is create JPEG decompression object set source to tables-only file jpeg_read_header(&cinfo, FALSE); set source to abbreviated image file jpeg_read_header(&cinfo, TRUE); set decompression parameters jpeg_start_decompress(&cinfo); read data... jpeg_finish_decompress(&cinfo); In some cases, you may want to read a file without knowing whether it contains an image or just tables. In that case, pass FALSE and check the return value from jpeg_read_header(): it will be JPEG_HEADER_OK if an image was found, JPEG_HEADER_TABLES_ONLY if only tables were found. (A third return value, JPEG_SUSPENDED, is possible when using a suspending data source manager.) Note that jpeg_read_header() will not complain if you read an abbreviated image for which you haven't loaded the missing tables; the missing-table check occurs later, in jpeg_start_decompress(). It is possible to read a series of images from a single source file by repeating the jpeg_read_header() ... jpeg_finish_decompress() sequence, without releasing/recreating the JPEG object or the data source module. (If you did reinitialize, any partial bufferload left in the data source buffer at the end of one image would be discarded, causing you to lose the start of the next image.) When you use this method, stored tables are automatically carried forward, so some of the images can be abbreviated images that depend on tables from earlier images. If you intend to write a series of images into a single destination file, you might want to make a specialized data destination module that doesn't flush the output buffer at term_destination() time. This would speed things up by some trifling amount. Of course, you'd need to remember to flush the buffer after the last image. You can make the later images be abbreviated ones by passing FALSE to jpeg_start_compress(). Special markers --------------- Some applications may need to insert or extract special data in the JPEG datastream. The JPEG standard provides marker types "COM" (comment) and "APP0" through "APP15" (application) to hold application-specific data. Unfortunately, the use of these markers is not specified by the standard. COM markers are fairly widely used to hold user-supplied text. The JFIF file format spec uses APP0 markers with specified initial strings to hold certain data. Adobe applications use APP14 markers beginning with the string "Adobe" for miscellaneous data. Other APPn markers are rarely seen, but might contain almost anything. If you wish to store user-supplied text, we recommend you use COM markers and place readable 7-bit ASCII text in them. Newline conventions are not standardized --- expect to find LF (Unix style), CR/LF (DOS style), or CR (Mac style). A robust COM reader should be able to cope with random binary garbage, including nulls, since some applications generate COM markers containing non-ASCII junk. (But yours should not be one of them.) For program-supplied data, use an APPn marker, and be sure to begin it with an identifying string so that you can tell whether the marker is actually yours. It's probably best to avoid using APP0 or APP14 for any private markers. (NOTE: the upcoming SPIFF standard will use APP8 markers; we recommend you not use APP8 markers for any private purposes, either.) Keep in mind that at most 65533 bytes can be put into one marker, but you can have as many markers as you like. By default, the IJG compression library will write a JFIF APP0 marker if the selected JPEG colorspace is grayscale or YCbCr, or an Adobe APP14 marker if the selected colorspace is RGB, CMYK, or YCCK. You can disable this, but we don't recommend it. The decompression library will recognize JFIF and Adobe markers and will set the JPEG colorspace properly when one is found. You can write special markers immediately following the datastream header by calling jpeg_write_marker() after jpeg_start_compress() and before the first call to jpeg_write_scanlines(). When you do this, the markers appear after the SOI and the JFIF APP0 and Adobe APP14 markers (if written), but before all else. Specify the marker type parameter as "JPEG_COM" for COM or "JPEG_APP0 + n" for APPn. (Actually, jpeg_write_marker will let you write any marker type, but we don't recommend writing any other kinds of marker.) For example, to write a user comment string pointed to by comment_text: jpeg_write_marker(cinfo, JPEG_COM, comment_text, strlen(comment_text)); If it's not convenient to store all the marker data in memory at once, you can instead call jpeg_write_m_header() followed by multiple calls to jpeg_write_m_byte(). If you do it this way, it's your responsibility to call jpeg_write_m_byte() exactly the number of times given in the length parameter to jpeg_write_m_header(). (This method lets you empty the output buffer partway through a marker, which might be important when using a suspending data destination module. In any case, if you are using a suspending destination, you should flush its buffer after inserting any special markers. See "I/O suspension".) Or, if you prefer to synthesize the marker byte sequence yourself, you can just cram it straight into the data destination module. If you are writing JFIF 1.02 extension markers (thumbnail images), don't forget to set cinfo.JFIF_minor_version = 2 so that the encoder will write the correct JFIF version number in the JFIF header marker. The library's default is to write version 1.01, but that's wrong if you insert any 1.02 extension markers. (We could probably get away with just defaulting to 1.02, but there used to be broken decoders that would complain about unknown minor version numbers. To reduce compatibility risks it's safest not to write 1.02 unless you are actually using 1.02 extensions.) When reading, two methods of handling special markers are available: 1. You can ask the library to save the contents of COM and/or APPn markers into memory, and then examine them at your leisure afterwards. 2. You can supply your own routine to process COM and/or APPn markers on-the-fly as they are read. The first method is simpler to use, especially if you are using a suspending data source; writing a marker processor that copes with input suspension is not easy (consider what happens if the marker is longer than your available input buffer). However, the second method conserves memory since the marker data need not be kept around after it's been processed. For either method, you'd normally set up marker handling after creating a decompression object and before calling jpeg_read_header(), because the markers of interest will typically be near the head of the file and so will be scanned by jpeg_read_header. Once you've established a marker handling method, it will be used for the life of that decompression object (potentially many datastreams), unless you change it. Marker handling is determined separately for COM markers and for each APPn marker code. To save the contents of special markers in memory, call jpeg_save_markers(cinfo, marker_code, length_limit) where marker_code is the marker type to save, JPEG_COM or JPEG_APP0+n. (To arrange to save all the special marker types, you need to call this routine 17 times, for COM and APP0-APP15.) If the incoming marker is longer than length_limit data bytes, only length_limit bytes will be saved; this parameter allows you to avoid chewing up memory when you only need to see the first few bytes of a potentially large marker. If you want to save all the data, set length_limit to 0xFFFF; that is enough since marker lengths are only 16 bits. As a special case, setting length_limit to 0 prevents that marker type from being saved at all. (That is the default behavior, in fact.) After jpeg_read_header() completes, you can examine the special markers by following the cinfo->marker_list pointer chain. All the special markers in the file appear in this list, in order of their occurrence in the file (but omitting any markers of types you didn't ask for). Both the original data length and the saved data length are recorded for each list entry; the latter will not exceed length_limit for the particular marker type. Note that these lengths exclude the marker length word, whereas the stored representation within the JPEG file includes it. (Hence the maximum data length is really only 65533.) It is possible that additional special markers appear in the file beyond the SOS marker at which jpeg_read_header stops; if so, the marker list will be extended during reading of the rest of the file. This is not expected to be common, however. If you are short on memory you may want to reset the length limit to zero for all marker types after finishing jpeg_read_header, to ensure that the max_memory_to_use setting cannot be exceeded due to addition of later markers. The marker list remains stored until you call jpeg_finish_decompress or jpeg_abort, at which point the memory is freed and the list is set to empty. (jpeg_destroy also releases the storage, of course.) Note that the library is internally interested in APP0 and APP14 markers; if you try to set a small nonzero length limit on these types, the library will silently force the length up to the minimum it wants. (But you can set a zero length limit to prevent them from being saved at all.) Also, in a 16-bit environment, the maximum length limit may be constrained to less than 65533 by malloc() limitations. It is therefore best not to assume that the effective length limit is exactly what you set it to be. If you want to supply your own marker-reading routine, you do it by calling jpeg_set_marker_processor(). A marker processor routine must have the signature boolean jpeg_marker_parser_method (j_decompress_ptr cinfo) Although the marker code is not explicitly passed, the routine can find it in cinfo->unread_marker. At the time of call, the marker proper has been read from the data source module. The processor routine is responsible for reading the marker length word and the remaining parameter bytes, if any. Return TRUE to indicate success. (FALSE should be returned only if you are using a suspending data source and it tells you to suspend. See the standard marker processors in jdmarker.c for appropriate coding methods if you need to use a suspending data source.) If you override the default APP0 or APP14 processors, it is up to you to recognize JFIF and Adobe markers if you want colorspace recognition to occur properly. We recommend copying and extending the default processors if you want to do that. (A better idea is to save these marker types for later examination by calling jpeg_save_markers(); that method doesn't interfere with the library's own processing of these markers.) jpeg_set_marker_processor() and jpeg_save_markers() are mutually exclusive --- if you call one it overrides any previous call to the other, for the particular marker type specified. A simple example of an external COM processor can be found in djpeg.c. Also, see jpegtran.c for an example of using jpeg_save_markers. Raw (downsampled) image data ---------------------------- Some applications need to supply already-downsampled image data to the JPEG compressor, or to receive raw downsampled data from the decompressor. The library supports this requirement by allowing the application to write or read raw data, bypassing the normal preprocessing or postprocessing steps. The interface is different from the standard one and is somewhat harder to use. If your interest is merely in bypassing color conversion, we recommend that you use the standard interface and simply set jpeg_color_space = in_color_space (or jpeg_color_space = out_color_space for decompression). The mechanism described in this section is necessary only to supply or receive downsampled image data, in which not all components have the same dimensions. To compress raw data, you must supply the data in the colorspace to be used in the JPEG file (please read the earlier section on Special color spaces) and downsampled to the sampling factors specified in the JPEG parameters. You must supply the data in the format used internally by the JPEG library, namely a JSAMPIMAGE array. This is an array of pointers to two-dimensional arrays, each of type JSAMPARRAY. Each 2-D array holds the values for one color component. This structure is necessary since the components are of different sizes. If the image dimensions are not a multiple of the MCU size, you must also pad the data correctly (usually, this is done by replicating the last column and/or row). The data must be padded to a multiple of a DCT block in each component: that is, each downsampled row must contain a multiple of block_size valid samples, and there must be a multiple of block_size sample rows for each component. (For applications such as conversion of digital TV images, the standard image size is usually a multiple of the DCT block size, so that no padding need actually be done.) The procedure for compression of raw data is basically the same as normal compression, except that you call jpeg_write_raw_data() in place of jpeg_write_scanlines(). Before calling jpeg_start_compress(), you must do the following: * Set cinfo->raw_data_in to TRUE. (It is set FALSE by jpeg_set_defaults().) This notifies the library that you will be supplying raw data. Furthermore, set cinfo->do_fancy_downsampling to FALSE if you want to use real downsampled data. (It is set TRUE by jpeg_set_defaults().) * Ensure jpeg_color_space is correct --- an explicit jpeg_set_colorspace() call is a good idea. Note that since color conversion is bypassed, in_color_space is ignored, except that jpeg_set_defaults() uses it to choose the default jpeg_color_space setting. * Ensure the sampling factors, cinfo->comp_info[i].h_samp_factor and cinfo->comp_info[i].v_samp_factor, are correct. Since these indicate the dimensions of the data you are supplying, it's wise to set them explicitly, rather than assuming the library's defaults are what you want. To pass raw data to the library, call jpeg_write_raw_data() in place of jpeg_write_scanlines(). The two routines work similarly except that jpeg_write_raw_data takes a JSAMPIMAGE data array rather than JSAMPARRAY. The scanlines count passed to and returned from jpeg_write_raw_data is measured in terms of the component with the largest v_samp_factor. jpeg_write_raw_data() processes one MCU row per call, which is to say v_samp_factor*block_size sample rows of each component. The passed num_lines value must be at least max_v_samp_factor*block_size, and the return value will be exactly that amount (or possibly some multiple of that amount, in future library versions). This is true even on the last call at the bottom of the image; don't forget to pad your data as necessary. The required dimensions of the supplied data can be computed for each component as cinfo->comp_info[i].width_in_blocks*block_size samples per row cinfo->comp_info[i].height_in_blocks*block_size rows in image after jpeg_start_compress() has initialized those fields. If the valid data is smaller than this, it must be padded appropriately. For some sampling factors and image sizes, additional dummy DCT blocks are inserted to make the image a multiple of the MCU dimensions. The library creates such dummy blocks itself; it does not read them from your supplied data. Therefore you need never pad by more than block_size samples. An example may help here. Assume 2h2v downsampling of YCbCr data, that is cinfo->comp_info[0].h_samp_factor = 2 for Y cinfo->comp_info[0].v_samp_factor = 2 cinfo->comp_info[1].h_samp_factor = 1 for Cb cinfo->comp_info[1].v_samp_factor = 1 cinfo->comp_info[2].h_samp_factor = 1 for Cr cinfo->comp_info[2].v_samp_factor = 1 and suppose that the nominal image dimensions (cinfo->image_width and cinfo->image_height) are 101x101 pixels. Then jpeg_start_compress() will compute downsampled_width = 101 and width_in_blocks = 13 for Y, downsampled_width = 51 and width_in_blocks = 7 for Cb and Cr (and the same for the height fields). You must pad the Y data to at least 13*8 = 104 columns and rows, the Cb/Cr data to at least 7*8 = 56 columns and rows. The MCU height is max_v_samp_factor = 2 DCT rows so you must pass at least 16 scanlines on each call to jpeg_write_raw_data(), which is to say 16 actual sample rows of Y and 8 each of Cb and Cr. A total of 7 MCU rows are needed, so you must pass a total of 7*16 = 112 "scanlines". The last DCT block row of Y data is dummy, so it doesn't matter what you pass for it in the data arrays, but the scanlines count must total up to 112 so that all of the Cb and Cr data gets passed. Output suspension is supported with raw-data compression: if the data destination module suspends, jpeg_write_raw_data() will return 0. In this case the same data rows must be passed again on the next call. Decompression with raw data output implies bypassing all postprocessing. You must deal with the color space and sampling factors present in the incoming file. If your application only handles, say, 2h1v YCbCr data, you must check for and fail on other color spaces or other sampling factors. The library will not convert to a different color space for you. To obtain raw data output, set cinfo->raw_data_out = TRUE before jpeg_start_decompress() (it is set FALSE by jpeg_read_header()). Be sure to verify that the color space and sampling factors are ones you can handle. Furthermore, set cinfo->do_fancy_upsampling = FALSE if you want to get real downsampled data (it is set TRUE by jpeg_read_header()). Then call jpeg_read_raw_data() in place of jpeg_read_scanlines(). The decompression process is otherwise the same as usual. jpeg_read_raw_data() returns one MCU row per call, and thus you must pass a buffer of at least max_v_samp_factor*block_size scanlines (scanline counting is the same as for raw-data compression). The buffer you pass must be large enough to hold the actual data plus padding to DCT-block boundaries. As with compression, any entirely dummy DCT blocks are not processed so you need not allocate space for them, but the total scanline count includes them. The above example of computing buffer dimensions for raw-data compression is equally valid for decompression. Input suspension is supported with raw-data decompression: if the data source module suspends, jpeg_read_raw_data() will return 0. You can also use buffered-image mode to read raw data in multiple passes. Really raw data: DCT coefficients --------------------------------- It is possible to read or write the contents of a JPEG file as raw DCT coefficients. This facility is mainly intended for use in lossless transcoding between different JPEG file formats. Other possible applications include lossless cropping of a JPEG image, lossless reassembly of a multi-strip or multi-tile TIFF/JPEG file into a single JPEG datastream, etc. To read the contents of a JPEG file as DCT coefficients, open the file and do jpeg_read_header() as usual. But instead of calling jpeg_start_decompress() and jpeg_read_scanlines(), call jpeg_read_coefficients(). This will read the entire image into a set of virtual coefficient-block arrays, one array per component. The return value is a pointer to an array of virtual-array descriptors. Each virtual array can be accessed directly using the JPEG memory manager's access_virt_barray method (see Memory management, below, and also read structure.txt's discussion of virtual array handling). Or, for simple transcoding to a different JPEG file format, the array list can just be handed directly to jpeg_write_coefficients(). Each block in the block arrays contains quantized coefficient values in normal array order (not JPEG zigzag order). The block arrays contain only DCT blocks containing real data; any entirely-dummy blocks added to fill out interleaved MCUs at the right or bottom edges of the image are discarded during reading and are not stored in the block arrays. (The size of each block array can be determined from the width_in_blocks and height_in_blocks fields of the component's comp_info entry.) This is also the data format expected by jpeg_write_coefficients(). When you are done using the virtual arrays, call jpeg_finish_decompress() to release the array storage and return the decompression object to an idle state; or just call jpeg_destroy() if you don't need to reuse the object. If you use a suspending data source, jpeg_read_coefficients() will return NULL if it is forced to suspend; a non-NULL return value indicates successful completion. You need not test for a NULL return value when using a non-suspending data source. It is also possible to call jpeg_read_coefficients() to obtain access to the decoder's coefficient arrays during a normal decode cycle in buffered-image mode. This frammish might be useful for progressively displaying an incoming image and then re-encoding it without loss. To do this, decode in buffered- image mode as discussed previously, then call jpeg_read_coefficients() after the last jpeg_finish_output() call. The arrays will be available for your use until you call jpeg_finish_decompress(). To write the contents of a JPEG file as DCT coefficients, you must provide the DCT coefficients stored in virtual block arrays. You can either pass block arrays read from an input JPEG file by jpeg_read_coefficients(), or allocate virtual arrays from the JPEG compression object and fill them yourself. In either case, jpeg_write_coefficients() is substituted for jpeg_start_compress() and jpeg_write_scanlines(). Thus the sequence is * Create compression object * Set all compression parameters as necessary * Request virtual arrays if needed * jpeg_write_coefficients() * jpeg_finish_compress() * Destroy or re-use compression object jpeg_write_coefficients() is passed a pointer to an array of virtual block array descriptors; the number of arrays is equal to cinfo.num_components. The virtual arrays need only have been requested, not realized, before jpeg_write_coefficients() is called. A side-effect of jpeg_write_coefficients() is to realize any virtual arrays that have been requested from the compression object's memory manager. Thus, when obtaining the virtual arrays from the compression object, you should fill the arrays after calling jpeg_write_coefficients(). The data is actually written out when you call jpeg_finish_compress(); jpeg_write_coefficients() only writes the file header. When writing raw DCT coefficients, it is crucial that the JPEG quantization tables and sampling factors match the way the data was encoded, or the resulting file will be invalid. For transcoding from an existing JPEG file, we recommend using jpeg_copy_critical_parameters(). This routine initializes all the compression parameters to default values (like jpeg_set_defaults()), then copies the critical information from a source decompression object. The decompression object should have just been used to read the entire JPEG input file --- that is, it should be awaiting jpeg_finish_decompress(). jpeg_write_coefficients() marks all tables stored in the compression object as needing to be written to the output file (thus, it acts like jpeg_start_compress(cinfo, TRUE)). This is for safety's sake, to avoid emitting abbreviated JPEG files by accident. If you really want to emit an abbreviated JPEG file, call jpeg_suppress_tables(), or set the tables' individual sent_table flags, between calling jpeg_write_coefficients() and jpeg_finish_compress(). Progress monitoring ------------------- Some applications may need to regain control from the JPEG library every so often. The typical use of this feature is to produce a percent-done bar or other progress display. (For a simple example, see cjpeg.c or djpeg.c.) Although you do get control back frequently during the data-transferring pass (the jpeg_read_scanlines or jpeg_write_scanlines loop), any additional passes will occur inside jpeg_finish_compress or jpeg_start_decompress; those routines may take a long time to execute, and you don't get control back until they are done. You can define a progress-monitor routine which will be called periodically by the library. No guarantees are made about how often this call will occur, so we don't recommend you use it for mouse tracking or anything like that. At present, a call will occur once per MCU row, scanline, or sample row group, whichever unit is convenient for the current processing mode; so the wider the image, the longer the time between calls. During the data transferring pass, only one call occurs per call of jpeg_read_scanlines or jpeg_write_scanlines, so don't pass a large number of scanlines at once if you want fine resolution in the progress count. (If you really need to use the callback mechanism for time-critical tasks like mouse tracking, you could insert additional calls inside some of the library's inner loops.) To establish a progress-monitor callback, create a struct jpeg_progress_mgr, fill in its progress_monitor field with a pointer to your callback routine, and set cinfo->progress to point to the struct. The callback will be called whenever cinfo->progress is non-NULL. (This pointer is set to NULL by jpeg_create_compress or jpeg_create_decompress; the library will not change it thereafter. So if you allocate dynamic storage for the progress struct, make sure it will live as long as the JPEG object does. Allocating from the JPEG memory manager with lifetime JPOOL_PERMANENT will work nicely.) You can use the same callback routine for both compression and decompression. The jpeg_progress_mgr struct contains four fields which are set by the library: long pass_counter; /* work units completed in this pass */ long pass_limit; /* total number of work units in this pass */ int completed_passes; /* passes completed so far */ int total_passes; /* total number of passes expected */ During any one pass, pass_counter increases from 0 up to (not including) pass_limit; the step size is usually but not necessarily 1. The pass_limit value may change from one pass to another. The expected total number of passes is in total_passes, and the number of passes already completed is in completed_passes. Thus the fraction of work completed may be estimated as completed_passes + (pass_counter/pass_limit) -------------------------------------------- total_passes ignoring the fact that the passes may not be equal amounts of work. When decompressing, pass_limit can even change within a pass, because it depends on the number of scans in the JPEG file, which isn't always known in advance. The computed fraction-of-work-done may jump suddenly (if the library discovers it has overestimated the number of scans) or even decrease (in the opposite case). It is not wise to put great faith in the work estimate. When using the decompressor's buffered-image mode, the progress monitor work estimate is likely to be completely unhelpful, because the library has no way to know how many output passes will be demanded of it. Currently, the library sets total_passes based on the assumption that there will be one more output pass if the input file end hasn't yet been read (jpeg_input_complete() isn't TRUE), but no more output passes if the file end has been reached when the output pass is started. This means that total_passes will rise as additional output passes are requested. If you have a way of determining the input file size, estimating progress based on the fraction of the file that's been read will probably be more useful than using the library's value. Memory management ----------------- This section covers some key facts about the JPEG library's built-in memory manager. For more info, please read structure.txt's section about the memory manager, and consult the source code if necessary. All memory and temporary file allocation within the library is done via the memory manager. If necessary, you can replace the "back end" of the memory manager to control allocation yourself (for example, if you don't want the library to use malloc() and free() for some reason). Some data is allocated "permanently" and will not be freed until the JPEG object is destroyed. Most data is allocated "per image" and is freed by jpeg_finish_compress, jpeg_finish_decompress, or jpeg_abort. You can call the memory manager yourself to allocate structures that will automatically be freed at these times. Typical code for this is ptr = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, size); Use JPOOL_PERMANENT to get storage that lasts as long as the JPEG object. Use alloc_large instead of alloc_small for anything bigger than a few Kbytes. There are also alloc_sarray and alloc_barray routines that automatically build 2-D sample or block arrays. The library's minimum space requirements to process an image depend on the image's width, but not on its height, because the library ordinarily works with "strip" buffers that are as wide as the image but just a few rows high. Some operating modes (eg, two-pass color quantization) require full-image buffers. Such buffers are treated as "virtual arrays": only the current strip need be in memory, and the rest can be swapped out to a temporary file. If you use the simplest memory manager back end (jmemnobs.c), then no temporary files are used; virtual arrays are simply malloc()'d. Images bigger than memory can be processed only if your system supports virtual memory. The other memory manager back ends support temporary files of various flavors and thus work in machines without virtual memory. They may also be useful on Unix machines if you need to process images that exceed available swap space. When using temporary files, the library will make the in-memory buffers for its virtual arrays just big enough to stay within a "maximum memory" setting. Your application can set this limit by setting cinfo->mem->max_memory_to_use after creating the JPEG object. (Of course, there is still a minimum size for the buffers, so the max-memory setting is effective only if it is bigger than the minimum space needed.) If you allocate any large structures yourself, you must allocate them before jpeg_start_compress() or jpeg_start_decompress() in order to have them counted against the max memory limit. Also keep in mind that space allocated with alloc_small() is ignored, on the assumption that it's too small to be worth worrying about; so a reasonable safety margin should be left when setting max_memory_to_use. If you use the jmemname.c or jmemdos.c memory manager back end, it is important to clean up the JPEG object properly to ensure that the temporary files get deleted. (This is especially crucial with jmemdos.c, where the "temporary files" may be extended-memory segments; if they are not freed, DOS will require a reboot to recover the memory.) Thus, with these memory managers, it's a good idea to provide a signal handler that will trap any early exit from your program. The handler should call either jpeg_abort() or jpeg_destroy() for any active JPEG objects. A handler is not needed with jmemnobs.c, and shouldn't be necessary with jmemansi.c or jmemmac.c either, since the C library is supposed to take care of deleting files made with tmpfile(). Memory usage ------------ Working memory requirements while performing compression or decompression depend on image dimensions, image characteristics (such as colorspace and JPEG process), and operating mode (application-selected options). As of v6b, the decompressor requires: 1. About 24K in more-or-less-fixed-size data. This varies a bit depending on operating mode and image characteristics (particularly color vs. grayscale), but it doesn't depend on image dimensions. 2. Strip buffers (of size proportional to the image width) for IDCT and upsampling results. The worst case for commonly used sampling factors is about 34 bytes * width in pixels for a color image. A grayscale image only needs about 8 bytes per pixel column. 3. A full-image DCT coefficient buffer is needed to decode a multi-scan JPEG file (including progressive JPEGs), or whenever you select buffered-image mode. This takes 2 bytes/coefficient. At typical 2x2 sampling, that's 3 bytes per pixel for a color image. Worst case (1x1 sampling) requires 6 bytes/pixel. For grayscale, figure 2 bytes/pixel. 4. To perform 2-pass color quantization, the decompressor also needs a 128K color lookup table and a full-image pixel buffer (3 bytes/pixel). This does not count any memory allocated by the application, such as a buffer to hold the final output image. The above figures are valid for 8-bit JPEG data precision and a machine with 32-bit ints. For 9-bit to 12-bit JPEG data, double the size of the strip buffers and quantization pixel buffer. The "fixed-size" data will be somewhat smaller with 16-bit ints, larger with 64-bit ints. Also, CMYK or other unusual color spaces will require different amounts of space. The full-image coefficient and pixel buffers, if needed at all, do not have to be fully RAM resident; you can have the library use temporary files instead when the total memory usage would exceed a limit you set. (But if your OS supports virtual memory, it's probably better to just use jmemnobs and let the OS do the swapping.) The compressor's memory requirements are similar, except that it has no need for color quantization. Also, it needs a full-image DCT coefficient buffer if Huffman-table optimization is asked for, even if progressive mode is not requested. If you need more detailed information about memory usage in a particular situation, you can enable the MEM_STATS code in jmemmgr.c. Library compile-time options ---------------------------- A number of compile-time options are available by modifying jmorecfg.h. The IJG code currently supports 8-bit to 12-bit sample data precision by defining BITS_IN_JSAMPLE as 8, 9, 10, 11, or 12. Note that a value larger than 8 causes JSAMPLE to be larger than a char, so it affects the surrounding application's image data. The sample applications cjpeg and djpeg can support deeper than 8-bit data only for PPM and GIF file formats; you must disable the other file formats to compile a 9-bit to 12-bit cjpeg or djpeg. (install.txt has more information about that.) Run-time selection and conversion of data precision are currently not supported and may be added later. Exception: The transcoding part (jpegtran) supports all settings in a single instance, since it operates on the level of DCT coefficients and not sample values. (If you need to include an 8-bit library and a 9-bit to 12-bit library for compression or decompression in a single application, you could probably do it by defining NEED_SHORT_EXTERNAL_NAMES for just one of the copies. You'd have to access the 8-bit and the 9-bit to 12-bit copies from separate application source files. This is untested ... if you try it, we'd like to hear whether it works!) Note that the standard Huffman tables are only valid for 8-bit data precision. If you selected more than 8-bit data precision, cjpeg uses arithmetic coding by default. The Huffman encoder normally uses entropy optimization to compute usable tables for higher precision. Otherwise, you'll have to supply different default Huffman tables. You may also want to supply your own DCT quantization tables; the existing quality-scaling code has been developed for 8-bit use, and probably doesn't generate especially good tables for 9-bit to 12-bit. The maximum number of components (color channels) in the image is determined by MAX_COMPONENTS. The JPEG standard allows up to 255 components, but we expect that few applications will need more than four or so. On machines with unusual data type sizes, you may be able to improve performance or reduce memory space by tweaking the various typedefs in jmorecfg.h. In particular, on some RISC CPUs, access to arrays of "short"s is quite slow; consider trading memory for speed by making JCOEF, INT16, and UINT16 be "int" or "unsigned int". UINT8 is also a candidate to become int. You probably don't want to make JSAMPLE be int unless you have lots of memory to burn. You can reduce the size of the library by compiling out various optional functions. To do this, undefine xxx_SUPPORTED symbols as necessary. You can also save a few K by not having text error messages in the library; the standard error message table occupies about 5Kb. This is particularly reasonable for embedded applications where there's no good way to display a message anyway. To do this, remove the creation of the message table (jpeg_std_message_table[]) from jerror.c, and alter format_message to do something reasonable without it. You could output the numeric value of the message code number, for example. If you do this, you can also save a couple more K by modifying the TRACEMSn() macros in jerror.h to expand to nothing; you don't need trace capability anyway, right? Portability considerations -------------------------- The JPEG library has been written to be extremely portable; the sample applications cjpeg and djpeg are slightly less so. This section summarizes the design goals in this area. (If you encounter any bugs that cause the library to be less portable than is claimed here, we'd appreciate hearing about them.) The code works fine on ANSI C, C++, and pre-ANSI C compilers, using any of the popular system include file setups, and some not-so-popular ones too. See install.txt for configuration procedures. The code is not dependent on the exact sizes of the C data types. As distributed, we make the assumptions that char is at least 8 bits wide short is at least 16 bits wide int is at least 16 bits wide long is at least 32 bits wide (These are the minimum requirements of the ANSI C standard.) Wider types will work fine, although memory may be used inefficiently if char is much larger than 8 bits or short is much bigger than 16 bits. The code should work equally well with 16- or 32-bit ints. In a system where these assumptions are not met, you may be able to make the code work by modifying the typedefs in jmorecfg.h. However, you will probably have difficulty if int is less than 16 bits wide, since references to plain int abound in the code. char can be either signed or unsigned, although the code runs faster if an unsigned char type is available. If char is wider than 8 bits, you will need to redefine JOCTET and/or provide custom data source/destination managers so that JOCTET represents exactly 8 bits of data on external storage. The JPEG library proper does not assume ASCII representation of characters. But some of the image file I/O modules in cjpeg/djpeg do have ASCII dependencies in file-header manipulation; so does cjpeg's select_file_type() routine. The JPEG library does not rely heavily on the C library. In particular, C stdio is used only by the data source/destination modules and the error handler, all of which are application-replaceable. (cjpeg/djpeg are more heavily dependent on stdio.) malloc and free are called only from the memory manager "back end" module, so you can use a different memory allocator by replacing that one file. The code generally assumes that C names must be unique in the first 15 characters. However, global function names can be made unique in the first 6 characters by defining NEED_SHORT_EXTERNAL_NAMES. More info about porting the code may be gleaned by reading jconfig.txt, jmorecfg.h, and jinclude.h. Notes for MS-DOS implementors ----------------------------- The IJG code is designed to work efficiently in 80x86 "small" or "medium" memory models (i.e., data pointers are 16 bits unless explicitly declared "far"; code pointers can be either size). You may be able to use small model to compile cjpeg or djpeg by itself, but you will probably have to use medium model for any larger application. This won't make much difference in performance. You *will* take a noticeable performance hit if you use a large-data memory model (perhaps 10%-25%), and you should avoid "huge" model if at all possible. The JPEG library typically needs 2Kb-3Kb of stack space. It will also malloc about 20K-30K of near heap space while executing (and lots of far heap, but that doesn't count in this calculation). This figure will vary depending on selected operating mode, and to a lesser extent on image size. There is also about 5Kb-6Kb of constant data which will be allocated in the near data segment (about 4Kb of this is the error message table). Thus you have perhaps 20K available for other modules' static data and near heap space before you need to go to a larger memory model. The C library's static data will account for several K of this, but that still leaves a good deal for your needs. (If you are tight on space, you could reduce the sizes of the I/O buffers allocated by jdatasrc.c and jdatadst.c, say from 4K to 1K. Another possibility is to move the error message table to far memory; this should be doable with only localized hacking on jerror.c.) About 2K of the near heap space is "permanent" memory that will not be released until you destroy the JPEG object. This is only an issue if you save a JPEG object between compression or decompression operations. Far data space may also be a tight resource when you are dealing with large images. The most memory-intensive case is decompression with two-pass color quantization, or single-pass quantization to an externally supplied color map. This requires a 128Kb color lookup table plus strip buffers amounting to about 40 bytes per column for typical sampling ratios (eg, about 25600 bytes for a 640-pixel-wide image). You may not be able to process wide images if you have large data structures of your own. Of course, all of these concerns vanish if you use a 32-bit flat-memory-model compiler, such as DJGPP or Watcom C. We highly recommend flat model if you can use it; the JPEG library is significantly faster in flat model. ================================================ FILE: tess-two/jni/libjpeg/ltmain.sh ================================================ #! /bin/sh ## DO NOT EDIT - This file generated from ./build-aux/ltmain.in ## by inline-source v2014-01-03.01 # libtool (GNU libtool) 2.4.6 # Provide generalized library-building support services. # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . PROGRAM=libtool PACKAGE=libtool VERSION=2.4.6 package_revision=2.4.6 ## ------ ## ## Usage. ## ## ------ ## # Run './libtool --help' for help with using this script from the # command line. ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # After configure completes, it has a better idea of some of the # shell tools we need than the defaults used by the functions shared # with bootstrap, so set those here where they can still be over- # ridden by the user, but otherwise take precedence. : ${AUTOCONF="autoconf"} : ${AUTOMAKE="automake"} ## -------------------------- ## ## Source external libraries. ## ## -------------------------- ## # Much of our low-level functionality needs to be sourced from external # libraries, which are installed to $pkgauxdir. # Set a version string for this script. scriptversion=2015-01-20.17; # UTC # General shell script boiler plate, and helper functions. # Written by Gary V. Vaughan, 2004 # Copyright (C) 2004-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # As a special exception to the GNU General Public License, if you distribute # this file as part of a program or library that is built using GNU Libtool, # you may include this file under the same distribution terms that you use # for the rest of that program. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # Evaluate this file near the top of your script to gain access to # the functions and variables defined here: # # . `echo "$0" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh # # If you need to override any of the default environment variable # settings, do that before evaluating this file. ## -------------------- ## ## Shell normalisation. ## ## -------------------- ## # Some shells need a little help to be as Bourne compatible as possible. # Before doing anything else, make sure all that help has been provided! DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi # NLS nuisances: We save the old values in case they are required later. _G_user_locale= _G_safe_locale= for _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test set = \"\${$_G_var+set}\"; then save_$_G_var=\$$_G_var $_G_var=C export $_G_var _G_user_locale=\"$_G_var=\\\$save_\$_G_var; \$_G_user_locale\" _G_safe_locale=\"$_G_var=C; \$_G_safe_locale\" fi" done # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Make sure IFS has a sensible default sp=' ' nl=' ' IFS="$sp $nl" # There are apparently some retarded systems that use ';' as a PATH separator! if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi ## ------------------------- ## ## Locate command utilities. ## ## ------------------------- ## # func_executable_p FILE # ---------------------- # Check that FILE is an executable regular file. func_executable_p () { test -f "$1" && test -x "$1" } # func_path_progs PROGS_LIST CHECK_FUNC [PATH] # -------------------------------------------- # Search for either a program that responds to --version with output # containing "GNU", or else returned by CHECK_FUNC otherwise, by # trying all the directories in PATH with each of the elements of # PROGS_LIST. # # CHECK_FUNC should accept the path to a candidate program, and # set $func_check_prog_result if it truncates its output less than # $_G_path_prog_max characters. func_path_progs () { _G_progs_list=$1 _G_check_func=$2 _G_PATH=${3-"$PATH"} _G_path_prog_max=0 _G_path_prog_found=false _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:} for _G_dir in $_G_PATH; do IFS=$_G_save_IFS test -z "$_G_dir" && _G_dir=. for _G_prog_name in $_G_progs_list; do for _exeext in '' .EXE; do _G_path_prog=$_G_dir/$_G_prog_name$_exeext func_executable_p "$_G_path_prog" || continue case `"$_G_path_prog" --version 2>&1` in *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;; *) $_G_check_func $_G_path_prog func_path_progs_result=$func_check_prog_result ;; esac $_G_path_prog_found && break 3 done done done IFS=$_G_save_IFS test -z "$func_path_progs_result" && { echo "no acceptable sed could be found in \$PATH" >&2 exit 1 } } # We want to be able to use the functions in this file before configure # has figured out where the best binaries are kept, which means we have # to search for them ourselves - except when the results are already set # where we skip the searches. # Unless the user overrides by setting SED, search the path for either GNU # sed, or the sed that truncates its output the least. test -z "$SED" && { _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for _G_i in 1 2 3 4 5 6 7; do _G_sed_script=$_G_sed_script$nl$_G_sed_script done echo "$_G_sed_script" 2>/dev/null | sed 99q >conftest.sed _G_sed_script= func_check_prog_sed () { _G_path_prog=$1 _G_count=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo '' >> conftest.nl "$_G_path_prog" -f conftest.sed conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "sed gsed" func_check_prog_sed $PATH:/usr/xpg4/bin rm -f conftest.sed SED=$func_path_progs_result } # Unless the user overrides by setting GREP, search the path for either GNU # grep, or the grep that truncates its output the least. test -z "$GREP" && { func_check_prog_grep () { _G_path_prog=$1 _G_count=0 _G_path_prog_max=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo 'GREP' >> conftest.nl "$_G_path_prog" -e 'GREP$' -e '-(cannot match)-' conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "grep ggrep" func_check_prog_grep $PATH:/usr/xpg4/bin GREP=$func_path_progs_result } ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # All uppercase variable names are used for environment variables. These # variables can be overridden by the user before calling a script that # uses them if a suitable command of that name is not already available # in the command search PATH. : ${CP="cp -f"} : ${ECHO="printf %s\n"} : ${EGREP="$GREP -E"} : ${FGREP="$GREP -F"} : ${LN_S="ln -s"} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} ## -------------------- ## ## Useful sed snippets. ## ## -------------------- ## sed_dirname='s|/[^/]*$||' sed_basename='s|^.*/||' # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='s|\([`"$\\]\)|\\\1|g' # Same as above, but do not quote variable references. sed_double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s|[].[^$\\*\/]|\\&|g' # Sed substitution that converts a w32 file name or path # that contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-'\' parameter expansions in output of sed_double_quote_subst that # were '\'-ed in input to the same. If an odd number of '\' preceded a # '$' in input to sed_double_quote_subst, that '$' was protected from # expansion. Since each input '\' is now two '\'s, look for any number # of runs of four '\'s followed by two '\'s and then a '$'. '\' that '$'. _G_bs='\\' _G_bs2='\\\\' _G_bs4='\\\\\\\\' _G_dollar='\$' sed_double_backslash="\ s/$_G_bs4/&\\ /g s/^$_G_bs2$_G_dollar/$_G_bs&/ s/\\([^$_G_bs]\\)$_G_bs2$_G_dollar/\\1$_G_bs2$_G_bs$_G_dollar/g s/\n//g" ## ----------------- ## ## Global variables. ## ## ----------------- ## # Except for the global variables explicitly listed below, the following # functions in the '^func_' namespace, and the '^require_' namespace # variables initialised in the 'Resource management' section, sourcing # this file will not pollute your global namespace with anything # else. There's no portable way to scope variables in Bourne shell # though, so actually running these functions will sometimes place # results into a variable named after the function, and often use # temporary variables in the '^_G_' namespace. If you are careful to # avoid using those namespaces casually in your sourcing script, things # should continue to work as you expect. And, of course, you can freely # overwrite any of the functions or variables defined here before # calling anything to customize them. EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. # Allow overriding, eg assuming that you follow the convention of # putting '$debug_cmd' at the start of all your functions, you can get # bash to show function call trace with: # # debug_cmd='eval echo "${FUNCNAME[0]} $*" >&2' bash your-script-name debug_cmd=${debug_cmd-":"} exit_cmd=: # By convention, finish your script with: # # exit $exit_status # # so that you can set exit_status to non-zero if you want to indicate # something went wrong during execution without actually bailing out at # the point of failure. exit_status=$EXIT_SUCCESS # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath=$0 # The name of this program. progname=`$ECHO "$progpath" |$SED "$sed_basename"` # Make sure we have an absolute progpath for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=`$ECHO "$progpath" |$SED "$sed_dirname"` progdir=`cd "$progdir" && pwd` progpath=$progdir/$progname ;; *) _G_IFS=$IFS IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS=$_G_IFS test -x "$progdir/$progname" && break done IFS=$_G_IFS test -n "$progdir" || progdir=`pwd` progpath=$progdir/$progname ;; esac ## ----------------- ## ## Standard options. ## ## ----------------- ## # The following options affect the operation of the functions defined # below, and should be set appropriately depending on run-time para- # meters passed on the command line. opt_dry_run=false opt_quiet=false opt_verbose=false # Categories 'all' and 'none' are always available. Append any others # you will pass as the first argument to func_warning from your own # code. warning_categories= # By default, display warnings according to 'opt_warning_types'. Set # 'warning_func' to ':' to elide all warnings, or func_fatal_error to # treat the next displayed warning as a fatal error. warning_func=func_warn_and_continue # Set to 'all' to display all warnings, 'none' to suppress all # warnings, or a space delimited list of some subset of # 'warning_categories' to display only the listed warnings. opt_warning_types=all ## -------------------- ## ## Resource management. ## ## -------------------- ## # This section contains definitions for functions that each ensure a # particular resource (a file, or a non-empty configuration variable for # example) is available, and if appropriate to extract default values # from pertinent package files. Call them using their associated # 'require_*' variable to ensure that they are executed, at most, once. # # It's entirely deliberate that calling these functions can set # variables that don't obey the namespace limitations obeyed by the rest # of this file, in order that that they be as useful as possible to # callers. # require_term_colors # ------------------- # Allow display of bold text on terminals that support it. require_term_colors=func_require_term_colors func_require_term_colors () { $debug_cmd test -t 1 && { # COLORTERM and USE_ANSI_COLORS environment variables take # precedence, because most terminfo databases neglect to describe # whether color sequences are supported. test -n "${COLORTERM+set}" && : ${USE_ANSI_COLORS="1"} if test 1 = "$USE_ANSI_COLORS"; then # Standard ANSI escape sequences tc_reset='' tc_bold=''; tc_standout='' tc_red=''; tc_green='' tc_blue=''; tc_cyan='' else # Otherwise trust the terminfo database after all. test -n "`tput sgr0 2>/dev/null`" && { tc_reset=`tput sgr0` test -n "`tput bold 2>/dev/null`" && tc_bold=`tput bold` tc_standout=$tc_bold test -n "`tput smso 2>/dev/null`" && tc_standout=`tput smso` test -n "`tput setaf 1 2>/dev/null`" && tc_red=`tput setaf 1` test -n "`tput setaf 2 2>/dev/null`" && tc_green=`tput setaf 2` test -n "`tput setaf 4 2>/dev/null`" && tc_blue=`tput setaf 4` test -n "`tput setaf 5 2>/dev/null`" && tc_cyan=`tput setaf 5` } fi } require_term_colors=: } ## ----------------- ## ## Function library. ## ## ----------------- ## # This section contains a variety of useful functions to call in your # scripts. Take note of the portable wrappers for features provided by # some modern shells, which will fall back to slower equivalents on # less featureful shells. # func_append VAR VALUE # --------------------- # Append VALUE onto the existing contents of VAR. # We should try to minimise forks, especially on Windows where they are # unreasonably slow, so skip the feature probes when bash or zsh are # being used: if test set = "${BASH_VERSION+set}${ZSH_VERSION+set}"; then : ${_G_HAVE_ARITH_OP="yes"} : ${_G_HAVE_XSI_OPS="yes"} # The += operator was introduced in bash 3.1 case $BASH_VERSION in [12].* | 3.0 | 3.0*) ;; *) : ${_G_HAVE_PLUSEQ_OP="yes"} ;; esac fi # _G_HAVE_PLUSEQ_OP # Can be empty, in which case the shell is probed, "yes" if += is # useable or anything else if it does not work. test -z "$_G_HAVE_PLUSEQ_OP" \ && (eval 'x=a; x+=" b"; test "a b" = "$x"') 2>/dev/null \ && _G_HAVE_PLUSEQ_OP=yes if test yes = "$_G_HAVE_PLUSEQ_OP" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_append () { $debug_cmd eval "$1+=\$2" }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_append () { $debug_cmd eval "$1=\$$1\$2" } fi # func_append_quoted VAR VALUE # ---------------------------- # Quote VALUE and append to the end of shell variable VAR, separated # by a space. if test yes = "$_G_HAVE_PLUSEQ_OP"; then eval 'func_append_quoted () { $debug_cmd func_quote_for_eval "$2" eval "$1+=\\ \$func_quote_for_eval_result" }' else func_append_quoted () { $debug_cmd func_quote_for_eval "$2" eval "$1=\$$1\\ \$func_quote_for_eval_result" } fi # func_append_uniq VAR VALUE # -------------------------- # Append unique VALUE onto the existing contents of VAR, assuming # entries are delimited by the first character of VALUE. For example: # # func_append_uniq options " --another-option option-argument" # # will only append to $options if " --another-option option-argument " # is not already present somewhere in $options already (note spaces at # each end implied by leading space in second argument). func_append_uniq () { $debug_cmd eval _G_current_value='`$ECHO $'$1'`' _G_delim=`expr "$2" : '\(.\)'` case $_G_delim$_G_current_value$_G_delim in *"$2$_G_delim"*) ;; *) func_append "$@" ;; esac } # func_arith TERM... # ------------------ # Set func_arith_result to the result of evaluating TERMs. test -z "$_G_HAVE_ARITH_OP" \ && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \ && _G_HAVE_ARITH_OP=yes if test yes = "$_G_HAVE_ARITH_OP"; then eval 'func_arith () { $debug_cmd func_arith_result=$(( $* )) }' else func_arith () { $debug_cmd func_arith_result=`expr "$@"` } fi # func_basename FILE # ------------------ # Set func_basename_result to FILE with everything up to and including # the last / stripped. if test yes = "$_G_HAVE_XSI_OPS"; then # If this shell supports suffix pattern removal, then use it to avoid # forking. Hide the definitions single quotes in case the shell chokes # on unsupported syntax... _b='func_basename_result=${1##*/}' _d='case $1 in */*) func_dirname_result=${1%/*}$2 ;; * ) func_dirname_result=$3 ;; esac' else # ...otherwise fall back to using sed. _b='func_basename_result=`$ECHO "$1" |$SED "$sed_basename"`' _d='func_dirname_result=`$ECHO "$1" |$SED "$sed_dirname"` if test "X$func_dirname_result" = "X$1"; then func_dirname_result=$3 else func_append func_dirname_result "$2" fi' fi eval 'func_basename () { $debug_cmd '"$_b"' }' # func_dirname FILE APPEND NONDIR_REPLACEMENT # ------------------------------------------- # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. eval 'func_dirname () { $debug_cmd '"$_d"' }' # func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT # -------------------------------------------------------- # Perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # For efficiency, we do not delegate to the functions above but instead # duplicate the functionality here. eval 'func_dirname_and_basename () { $debug_cmd '"$_b"' '"$_d"' }' # func_echo ARG... # ---------------- # Echo program name prefixed message. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname: $_G_line" done IFS=$func_echo_IFS } # func_echo_all ARG... # -------------------- # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_echo_infix_1 INFIX ARG... # ------------------------------ # Echo program name, followed by INFIX on the first line, with any # additional lines not showing INFIX. func_echo_infix_1 () { $debug_cmd $require_term_colors _G_infix=$1; shift _G_indent=$_G_infix _G_prefix="$progname: $_G_infix: " _G_message=$* # Strip color escape sequences before counting printable length for _G_tc in "$tc_reset" "$tc_bold" "$tc_standout" "$tc_red" "$tc_green" "$tc_blue" "$tc_cyan" do test -n "$_G_tc" && { _G_esc_tc=`$ECHO "$_G_tc" | $SED "$sed_make_literal_regex"` _G_indent=`$ECHO "$_G_indent" | $SED "s|$_G_esc_tc||g"` } done _G_indent="$progname: "`echo "$_G_indent" | $SED 's|.| |g'`" " ## exclude from sc_prohibit_nested_quotes func_echo_infix_1_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_infix_1_IFS $ECHO "$_G_prefix$tc_bold$_G_line$tc_reset" >&2 _G_prefix=$_G_indent done IFS=$func_echo_infix_1_IFS } # func_error ARG... # ----------------- # Echo program name prefixed message to standard error. func_error () { $debug_cmd $require_term_colors func_echo_infix_1 " $tc_standout${tc_red}error$tc_reset" "$*" >&2 } # func_fatal_error ARG... # ----------------------- # Echo program name prefixed message to standard error, and exit. func_fatal_error () { $debug_cmd func_error "$*" exit $EXIT_FAILURE } # func_grep EXPRESSION FILENAME # ----------------------------- # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $debug_cmd $GREP "$1" "$2" >/dev/null 2>&1 } # func_len STRING # --------------- # Set func_len_result to the length of STRING. STRING may not # start with a hyphen. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_len () { $debug_cmd func_len_result=${#1} }' else func_len () { $debug_cmd func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` } fi # func_mkdir_p DIRECTORY-PATH # --------------------------- # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { $debug_cmd _G_directory_path=$1 _G_dir_list= if test -n "$_G_directory_path" && test : != "$opt_dry_run"; then # Protect directory names starting with '-' case $_G_directory_path in -*) _G_directory_path=./$_G_directory_path ;; esac # While some portion of DIR does not yet exist... while test ! -d "$_G_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. _G_dir_list=$_G_directory_path:$_G_dir_list # If the last portion added has no slash in it, the list is done case $_G_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop _G_directory_path=`$ECHO "$_G_directory_path" | $SED -e "$sed_dirname"` done _G_dir_list=`$ECHO "$_G_dir_list" | $SED 's|:*$||'` func_mkdir_p_IFS=$IFS; IFS=: for _G_dir in $_G_dir_list; do IFS=$func_mkdir_p_IFS # mkdir can fail with a 'File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$_G_dir" 2>/dev/null || : done IFS=$func_mkdir_p_IFS # Bail out if we (or some other process) failed to create a directory. test -d "$_G_directory_path" || \ func_fatal_error "Failed to create '$1'" fi } # func_mktempdir [BASENAME] # ------------------------- # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, BASENAME is the basename for that directory. func_mktempdir () { $debug_cmd _G_template=${TMPDIR-/tmp}/${1-$progname} if test : = "$opt_dry_run"; then # Return a directory name, but don't create it in dry-run mode _G_tmpdir=$_G_template-$$ else # If mktemp works, use that first and foremost _G_tmpdir=`mktemp -d "$_G_template-XXXXXXXX" 2>/dev/null` if test ! -d "$_G_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race _G_tmpdir=$_G_template-${RANDOM-0}$$ func_mktempdir_umask=`umask` umask 0077 $MKDIR "$_G_tmpdir" umask $func_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$_G_tmpdir" || \ func_fatal_error "cannot create temporary directory '$_G_tmpdir'" fi $ECHO "$_G_tmpdir" } # func_normal_abspath PATH # ------------------------ # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. func_normal_abspath () { $debug_cmd # These SED scripts presuppose an absolute path with a trailing slash. _G_pathcar='s|^/\([^/]*\).*$|\1|' _G_pathcdr='s|^/[^/]*||' _G_removedotparts=':dotsl s|/\./|/|g t dotsl s|/\.$|/|' _G_collapseslashes='s|/\{1,\}|/|g' _G_finalslash='s|/*$|/|' # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_removedotparts" -e "$_G_collapseslashes" -e "$_G_finalslash"` while :; do # Processed it all yet? if test / = "$func_normal_abspath_tpath"; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result"; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_append func_normal_abspath_result "/$func_normal_abspath_tcomponent" ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_notquiet ARG... # -------------------- # Echo program name prefixed message only when not in quiet mode. func_notquiet () { $debug_cmd $opt_quiet || func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_relative_path SRCDIR DSTDIR # -------------------------------- # Set func_relative_path_result to the relative path from SRCDIR to DSTDIR. func_relative_path () { $debug_cmd func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=$func_dirname_result if test -z "$func_relative_path_tlibdir"; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test -n "$func_stripname_result"; then func_append func_relative_path_result "/$func_stripname_result" fi # Normalisation. If bindir is libdir, return '.' else relative path. if test -n "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result" func_relative_path_result=$func_stripname_result fi test -n "$func_relative_path_result" || func_relative_path_result=. : } # func_quote_for_eval ARG... # -------------------------- # Aesthetically quote ARGs to be evaled later. # This function returns two values: # i) func_quote_for_eval_result # double-quoted, suitable for a subsequent eval # ii) func_quote_for_eval_unquoted_result # has all characters that are still active within double # quotes backslashified. func_quote_for_eval () { $debug_cmd func_quote_for_eval_unquoted_result= func_quote_for_eval_result= while test 0 -lt $#; do case $1 in *[\\\`\"\$]*) _G_unquoted_arg=`printf '%s\n' "$1" |$SED "$sed_quote_subst"` ;; *) _G_unquoted_arg=$1 ;; esac if test -n "$func_quote_for_eval_unquoted_result"; then func_append func_quote_for_eval_unquoted_result " $_G_unquoted_arg" else func_append func_quote_for_eval_unquoted_result "$_G_unquoted_arg" fi case $_G_unquoted_arg in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and variable expansion # for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") _G_quoted_arg=\"$_G_unquoted_arg\" ;; *) _G_quoted_arg=$_G_unquoted_arg ;; esac if test -n "$func_quote_for_eval_result"; then func_append func_quote_for_eval_result " $_G_quoted_arg" else func_append func_quote_for_eval_result "$_G_quoted_arg" fi shift done } # func_quote_for_expand ARG # ------------------------- # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { $debug_cmd case $1 in *[\\\`\"]*) _G_arg=`$ECHO "$1" | $SED \ -e "$sed_double_quote_subst" -e "$sed_double_backslash"` ;; *) _G_arg=$1 ;; esac case $_G_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") _G_arg=\"$_G_arg\" ;; esac func_quote_for_expand_result=$_G_arg } # func_stripname PREFIX SUFFIX NAME # --------------------------------- # strip PREFIX and SUFFIX from NAME, and store in func_stripname_result. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_stripname () { $debug_cmd # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary variable first. func_stripname_result=$3 func_stripname_result=${func_stripname_result#"$1"} func_stripname_result=${func_stripname_result%"$2"} }' else func_stripname () { $debug_cmd case $2 in .*) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%\\\\$2\$%%"`;; *) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%$2\$%%"`;; esac } fi # func_show_eval CMD [FAIL_EXP] # ----------------------------- # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} func_quote_for_expand "$_G_cmd" eval "func_notquiet $func_quote_for_expand_result" $opt_dry_run || { eval "$_G_cmd" _G_status=$? if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_show_eval_locale CMD [FAIL_EXP] # ------------------------------------ # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} $opt_quiet || { func_quote_for_expand "$_G_cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || { eval "$_G_user_locale $_G_cmd" _G_status=$? eval "$_G_safe_locale" if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_tr_sh # ---------- # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { $debug_cmd case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED -e 's/^\([0-9]\)/_\1/' -e 's/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_verbose ARG... # ------------------- # Echo program name prefixed message in verbose mode only. func_verbose () { $debug_cmd $opt_verbose && func_echo "$*" : } # func_warn_and_continue ARG... # ----------------------------- # Echo program name prefixed warning message to standard error. func_warn_and_continue () { $debug_cmd $require_term_colors func_echo_infix_1 "${tc_red}warning$tc_reset" "$*" >&2 } # func_warning CATEGORY ARG... # ---------------------------- # Echo program name prefixed warning message to standard error. Warning # messages can be filtered according to CATEGORY, where this function # elides messages where CATEGORY is not listed in the global variable # 'opt_warning_types'. func_warning () { $debug_cmd # CATEGORY must be in the warning_categories list! case " $warning_categories " in *" $1 "*) ;; *) func_internal_error "invalid warning category '$1'" ;; esac _G_category=$1 shift case " $opt_warning_types " in *" $_G_category "*) $warning_func ${1+"$@"} ;; esac } # func_sort_ver VER1 VER2 # ----------------------- # 'sort -V' is not generally available. # Note this deviates from the version comparison in automake # in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a # but this should suffice as we won't be specifying old # version formats or redundant trailing .0 in bootstrap.conf. # If we did want full compatibility then we should probably # use m4_version_compare from autoconf. func_sort_ver () { $debug_cmd printf '%s\n%s\n' "$1" "$2" \ | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n } # func_lt_ver PREV CURR # --------------------- # Return true if PREV and CURR are in the correct order according to # func_sort_ver, otherwise false. Use it like this: # # func_lt_ver "$prev_ver" "$proposed_ver" || func_fatal_error "..." func_lt_ver () { $debug_cmd test "x$1" = x`func_sort_ver "$1" "$2" | $SED 1q` } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: #! /bin/sh # Set a version string for this script. scriptversion=2014-01-07.03; # UTC # A portable, pluggable option parser for Bourne shell. # Written by Gary V. Vaughan, 2010 # Copyright (C) 2010-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # This file is a library for parsing options in your shell scripts along # with assorted other useful supporting features that you can make use # of too. # # For the simplest scripts you might need only: # # #!/bin/sh # . relative/path/to/funclib.sh # . relative/path/to/options-parser # scriptversion=1.0 # func_options ${1+"$@"} # eval set dummy "$func_options_result"; shift # ...rest of your script... # # In order for the '--version' option to work, you will need to have a # suitably formatted comment like the one at the top of this file # starting with '# Written by ' and ending with '# warranty; '. # # For '-h' and '--help' to work, you will also need a one line # description of your script's purpose in a comment directly above the # '# Written by ' line, like the one at the top of this file. # # The default options also support '--debug', which will turn on shell # execution tracing (see the comment above debug_cmd below for another # use), and '--verbose' and the func_verbose function to allow your script # to display verbose messages only when your user has specified # '--verbose'. # # After sourcing this file, you can plug processing for additional # options by amending the variables from the 'Configuration' section # below, and following the instructions in the 'Option parsing' # section further down. ## -------------- ## ## Configuration. ## ## -------------- ## # You should override these variables in your script after sourcing this # file so that they reflect the customisations you have added to the # option parser. # The usage line for option parsing errors and the start of '-h' and # '--help' output messages. You can embed shell variables for delayed # expansion at the time the message is displayed, but you will need to # quote other shell meta-characters carefully to prevent them being # expanded when the contents are evaled. usage='$progpath [OPTION]...' # Short help message in response to '-h' and '--help'. Add to this or # override it after sourcing this library to reflect the full set of # options your script accepts. usage_message="\ --debug enable verbose shell tracing -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -v, --verbose verbosely report processing --version print version information and exit -h, --help print short or long help message and exit " # Additional text appended to 'usage_message' in response to '--help'. long_help_message=" Warning categories include: 'all' show all warnings 'none' turn off all the warnings 'error' warnings are treated as fatal errors" # Help message printed before fatal option parsing errors. fatal_help="Try '\$progname --help' for more information." ## ------------------------- ## ## Hook function management. ## ## ------------------------- ## # This section contains functions for adding, removing, and running hooks # to the main code. A hook is just a named list of of function, that can # be run in order later on. # func_hookable FUNC_NAME # ----------------------- # Declare that FUNC_NAME will run hooks added with # 'func_add_hook FUNC_NAME ...'. func_hookable () { $debug_cmd func_append hookable_fns " $1" } # func_add_hook FUNC_NAME HOOK_FUNC # --------------------------------- # Request that FUNC_NAME call HOOK_FUNC before it returns. FUNC_NAME must # first have been declared "hookable" by a call to 'func_hookable'. func_add_hook () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not accept hook functions." ;; esac eval func_append ${1}_hooks '" $2"' } # func_remove_hook FUNC_NAME HOOK_FUNC # ------------------------------------ # Remove HOOK_FUNC from the list of functions called by FUNC_NAME. func_remove_hook () { $debug_cmd eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`' } # func_run_hooks FUNC_NAME [ARG]... # --------------------------------- # Run all hook functions registered to FUNC_NAME. # It is assumed that the list of hook functions contains nothing more # than a whitespace-delimited list of legal shell function names, and # no effort is wasted trying to catch shell meta-characters or preserve # whitespace. func_run_hooks () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not support hook funcions.n" ;; esac eval _G_hook_fns=\$$1_hooks; shift for _G_hook in $_G_hook_fns; do eval $_G_hook '"$@"' # store returned options list back into positional # parameters for next 'cmd' execution. eval _G_hook_result=\$${_G_hook}_result eval set dummy "$_G_hook_result"; shift done func_quote_for_eval ${1+"$@"} func_run_hooks_result=$func_quote_for_eval_result } ## --------------- ## ## Option parsing. ## ## --------------- ## # In order to add your own option parsing hooks, you must accept the # full positional parameter list in your hook function, remove any # options that you action, and then pass back the remaining unprocessed # options in '_result', escaped suitably for # 'eval'. Like this: # # my_options_prep () # { # $debug_cmd # # # Extend the existing usage message. # usage_message=$usage_message' # -s, --silent don'\''t print informational messages # ' # # func_quote_for_eval ${1+"$@"} # my_options_prep_result=$func_quote_for_eval_result # } # func_add_hook func_options_prep my_options_prep # # # my_silent_option () # { # $debug_cmd # # # Note that for efficiency, we parse as many options as we can # # recognise in a loop before passing the remainder back to the # # caller on the first unrecognised argument we encounter. # while test $# -gt 0; do # opt=$1; shift # case $opt in # --silent|-s) opt_silent=: ;; # # Separate non-argument short options: # -s*) func_split_short_opt "$_G_opt" # set dummy "$func_split_short_opt_name" \ # "-$func_split_short_opt_arg" ${1+"$@"} # shift # ;; # *) set dummy "$_G_opt" "$*"; shift; break ;; # esac # done # # func_quote_for_eval ${1+"$@"} # my_silent_option_result=$func_quote_for_eval_result # } # func_add_hook func_parse_options my_silent_option # # # my_option_validation () # { # $debug_cmd # # $opt_silent && $opt_verbose && func_fatal_help "\ # '--silent' and '--verbose' options are mutually exclusive." # # func_quote_for_eval ${1+"$@"} # my_option_validation_result=$func_quote_for_eval_result # } # func_add_hook func_validate_options my_option_validation # # You'll alse need to manually amend $usage_message to reflect the extra # options you parse. It's preferable to append if you can, so that # multiple option parsing hooks can be added safely. # func_options [ARG]... # --------------------- # All the functions called inside func_options are hookable. See the # individual implementations for details. func_hookable func_options func_options () { $debug_cmd func_options_prep ${1+"$@"} eval func_parse_options \ ${func_options_prep_result+"$func_options_prep_result"} eval func_validate_options \ ${func_parse_options_result+"$func_parse_options_result"} eval func_run_hooks func_options \ ${func_validate_options_result+"$func_validate_options_result"} # save modified positional parameters for caller func_options_result=$func_run_hooks_result } # func_options_prep [ARG]... # -------------------------- # All initialisations required before starting the option parse loop. # Note that when calling hook functions, we pass through the list of # positional parameters. If a hook function modifies that list, and # needs to propogate that back to rest of this script, then the complete # modified list must be put in 'func_run_hooks_result' before # returning. func_hookable func_options_prep func_options_prep () { $debug_cmd # Option defaults: opt_verbose=false opt_warning_types= func_run_hooks func_options_prep ${1+"$@"} # save modified positional parameters for caller func_options_prep_result=$func_run_hooks_result } # func_parse_options [ARG]... # --------------------------- # The main option parsing loop. func_hookable func_parse_options func_parse_options () { $debug_cmd func_parse_options_result= # this just eases exit handling while test $# -gt 0; do # Defer to hook functions for initial option parsing, so they # get priority in the event of reusing an option name. func_run_hooks func_parse_options ${1+"$@"} # Adjust func_parse_options positional parameters to match eval set dummy "$func_run_hooks_result"; shift # Break out of the loop if we already parsed every option. test $# -gt 0 || break _G_opt=$1 shift case $_G_opt in --debug|-x) debug_cmd='set -x' func_echo "enabling shell trace mode" $debug_cmd ;; --no-warnings|--no-warning|--no-warn) set dummy --warnings none ${1+"$@"} shift ;; --warnings|--warning|-W) test $# = 0 && func_missing_arg $_G_opt && break case " $warning_categories $1" in *" $1 "*) # trailing space prevents matching last $1 above func_append_uniq opt_warning_types " $1" ;; *all) opt_warning_types=$warning_categories ;; *none) opt_warning_types=none warning_func=: ;; *error) opt_warning_types=$warning_categories warning_func=func_fatal_error ;; *) func_fatal_error \ "unsupported warning category: '$1'" ;; esac shift ;; --verbose|-v) opt_verbose=: ;; --version) func_version ;; -\?|-h) func_usage ;; --help) func_help ;; # Separate optargs to long options (plugins may need this): --*=*) func_split_equals "$_G_opt" set dummy "$func_split_equals_lhs" \ "$func_split_equals_rhs" ${1+"$@"} shift ;; # Separate optargs to short options: -W*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "$func_split_short_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-v*|-x*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognised option: '$_G_opt'" ;; *) set dummy "$_G_opt" ${1+"$@"}; shift; break ;; esac done # save modified positional parameters for caller func_quote_for_eval ${1+"$@"} func_parse_options_result=$func_quote_for_eval_result } # func_validate_options [ARG]... # ------------------------------ # Perform any sanity checks on option settings and/or unconsumed # arguments. func_hookable func_validate_options func_validate_options () { $debug_cmd # Display all warnings if -W was not given. test -n "$opt_warning_types" || opt_warning_types=" $warning_categories" func_run_hooks func_validate_options ${1+"$@"} # Bail if the options were screwed! $exit_cmd $EXIT_FAILURE # save modified positional parameters for caller func_validate_options_result=$func_run_hooks_result } ## ----------------- ## ## Helper functions. ## ## ----------------- ## # This section contains the helper functions used by the rest of the # hookable option parser framework in ascii-betical order. # func_fatal_help ARG... # ---------------------- # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { $debug_cmd eval \$ECHO \""Usage: $usage"\" eval \$ECHO \""$fatal_help"\" func_error ${1+"$@"} exit $EXIT_FAILURE } # func_help # --------- # Echo long help message to standard output and exit. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message" exit 0 } # func_missing_arg ARGNAME # ------------------------ # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $debug_cmd func_error "Missing argument for '$1'." exit_cmd=exit } # func_split_equals STRING # ------------------------ # Set func_split_equals_lhs and func_split_equals_rhs shell variables after # splitting STRING at the '=' sign. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_equals () { $debug_cmd func_split_equals_lhs=${1%%=*} func_split_equals_rhs=${1#*=} test "x$func_split_equals_lhs" = "x$1" \ && func_split_equals_rhs= }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_equals () { $debug_cmd func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'` func_split_equals_rhs= test "x$func_split_equals_lhs" = "x$1" \ || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'` } fi #func_split_equals # func_split_short_opt SHORTOPT # ----------------------------- # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_short_opt () { $debug_cmd func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"} }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_short_opt () { $debug_cmd func_split_short_opt_name=`expr "x$1" : 'x-\(.\)'` func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'` } fi #func_split_short_opt # func_usage # ---------- # Echo short help message to standard output and exit. func_usage () { $debug_cmd func_usage_message $ECHO "Run '$progname --help |${PAGER-more}' for full usage" exit 0 } # func_usage_message # ------------------ # Echo short help message to standard output. func_usage_message () { $debug_cmd eval \$ECHO \""Usage: $usage"\" echo $SED -n 's|^# || /^Written by/{ x;p;x } h /^Written by/q' < "$progpath" echo eval \$ECHO \""$usage_message"\" } # func_version # ------------ # Echo version message to standard output and exit. func_version () { $debug_cmd printf '%s\n' "$progname $scriptversion" $SED -n ' /(C)/!b go :more /\./!{ N s|\n# | | b more } :go /^# Written by /,/# warranty; / { s|^# || s|^# *$|| s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2| p } /^# Written by / { s|^# || p } /^warranty; /q' < "$progpath" exit $? } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: # Set a version string. scriptversion='(GNU libtool) 2.4.6' # func_echo ARG... # ---------------- # Libtool also displays the current mode in messages, so override # funclib.sh func_echo with this custom definition. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line" done IFS=$func_echo_IFS } # func_warning ARG... # ------------------- # Libtool warnings are not categorized, so override funclib.sh # func_warning with this simpler definition. func_warning () { $debug_cmd $warning_func ${1+"$@"} } ## ---------------- ## ## Options parsing. ## ## ---------------- ## # Hook in the functions to make sure our own options are parsed during # the option parsing loop. usage='$progpath [OPTION]... [MODE-ARG]...' # Short help message in response to '-h'. usage_message="Options: --config show all configuration variables --debug enable verbose shell tracing -n, --dry-run display commands without modifying any files --features display basic configuration information and exit --mode=MODE use operation mode MODE --no-warnings equivalent to '-Wnone' --preserve-dup-deps don't remove duplicate dependency libraries --quiet, --silent don't print informational messages --tag=TAG use configuration variables from tag TAG -v, --verbose print more informational messages than default --version print version information -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -h, --help, --help-all print short, long, or detailed help message " # Additional text appended to 'usage_message' in response to '--help'. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message MODE must be one of the following: clean remove files from the build directory compile compile a source file into a libtool object execute automatically set library path, then run a program finish complete the installation of libtool libraries install install libraries or executables link create a library or an executable uninstall remove libraries from an installed directory MODE-ARGS vary depending on the MODE. When passed as first option, '--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that. Try '$progname --help --mode=MODE' for a more detailed description of MODE. When reporting a bug, please describe a test case to reproduce it and include the following information: host-triplet: $host shell: $SHELL compiler: $LTCC compiler flags: $LTCFLAGS linker: $LD (gnu? $with_gnu_ld) version: $progname (GNU libtool) 2.4.6 automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` Report bugs to . GNU libtool home page: . General help using GNU software: ." exit 0 } # func_lo2o OBJECT-NAME # --------------------- # Transform OBJECT-NAME from a '.lo' suffix to the platform specific # object suffix. lo2o=s/\\.lo\$/.$objext/ o2lo=s/\\.$objext\$/.lo/ if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_lo2o () { case $1 in *.lo) func_lo2o_result=${1%.lo}.$objext ;; * ) func_lo2o_result=$1 ;; esac }' # func_xform LIBOBJ-OR-SOURCE # --------------------------- # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise) # suffix to a '.lo' libtool-object suffix. eval 'func_xform () { func_xform_result=${1%.*}.lo }' else # ...otherwise fall back to using sed. func_lo2o () { func_lo2o_result=`$ECHO "$1" | $SED "$lo2o"` } func_xform () { func_xform_result=`$ECHO "$1" | $SED 's|\.[^.]*$|.lo|'` } fi # func_fatal_configuration ARG... # ------------------------------- # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func__fatal_error ${1+"$@"} \ "See the $PACKAGE documentation for more information." \ "Fatal configuration error." } # func_config # ----------- # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # ------------- # Display the features supported by this script. func_features () { echo "host: $host" if test yes = "$build_libtool_libs"; then echo "enable shared libraries" else echo "disable shared libraries" fi if test yes = "$build_old_libs"; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag TAGNAME # ----------------------- # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname=$1 re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf=/$re_begincf/,/$re_endcf/p # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # ------------------------ # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # libtool_options_prep [ARG]... # ----------------------------- # Preparation for options parsed by libtool. libtool_options_prep () { $debug_mode # Option defaults: opt_config=false opt_dlopen= opt_dry_run=false opt_help=false opt_mode= opt_preserve_dup_deps=false opt_quiet=false nonopt= preserve_args= # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Pass back the list of options. func_quote_for_eval ${1+"$@"} libtool_options_prep_result=$func_quote_for_eval_result } func_add_hook func_options_prep libtool_options_prep # libtool_parse_options [ARG]... # --------------------------------- # Provide handling for libtool specific options. libtool_parse_options () { $debug_cmd # Perform our own loop to consume as many options as possible in # each iteration. while test $# -gt 0; do _G_opt=$1 shift case $_G_opt in --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) func_config ;; --dlopen|-dlopen) opt_dlopen="${opt_dlopen+$opt_dlopen }$1" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) func_features ;; --finish) set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $_G_opt && break opt_mode=$1 case $1 in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $_G_opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_quiet=false func_append preserve_args " $_G_opt" ;; --no-warnings|--no-warning|--no-warn) opt_warning=false func_append preserve_args " $_G_opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $_G_opt" ;; --silent|--quiet) opt_quiet=: opt_verbose=false func_append preserve_args " $_G_opt" ;; --tag) test $# = 0 && func_missing_arg $_G_opt && break opt_tag=$1 func_append preserve_args " $_G_opt $1" func_enable_tag "$1" shift ;; --verbose|-v) opt_quiet=false opt_verbose=: func_append preserve_args " $_G_opt" ;; # An option not handled by this hook function: *) set dummy "$_G_opt" ${1+"$@"}; shift; break ;; esac done # save modified positional parameters for caller func_quote_for_eval ${1+"$@"} libtool_parse_options_result=$func_quote_for_eval_result } func_add_hook func_parse_options libtool_parse_options # libtool_validate_options [ARG]... # --------------------------------- # Perform any sanity checks on option settings and/or unconsumed # arguments. libtool_validate_options () { # save first non-option argument if test 0 -lt $#; then nonopt=$1 shift fi # preserve --debug test : = "$debug_cmd" || func_append preserve_args " --debug" case $host in # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452 # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788 *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match test yes != "$build_libtool_libs" \ && test yes != "$build_old_libs" \ && func_fatal_configuration "not configured to build any kind of library" # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test execute != "$opt_mode"; then func_error "unrecognized option '-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help=$help help="Try '$progname --help --mode=$opt_mode' for more information." } # Pass back the unparsed argument list func_quote_for_eval ${1+"$@"} libtool_validate_options_result=$func_quote_for_eval_result } func_add_hook func_validate_options libtool_validate_options # Process options as early as possible so that --help and --version # can return quickly. func_options ${1+"$@"} eval set dummy "$func_options_result"; shift ## ----------- ## ## Main. ## ## ----------- ## magic='%%%MAGIC variable%%%' magic_exe='%%%MAGIC EXE variable%%%' # Global variables. extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # func_generated_by_libtool # True iff stdin has been generated by Libtool. This function is only # a basic sanity check; it will hardly flush out determined imposters. func_generated_by_libtool_p () { $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null | func_generated_by_libtool_p } # func_lalib_unsafe_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if 'file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case $lalib_p_line in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test yes = "$lalib_p" } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { test -f "$1" && $lt_truncate_bin < "$1" 2>/dev/null | func_generated_by_libtool_p } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $debug_cmd save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # 'FILE.' does not work on cygwin managed mounts. func_source () { $debug_cmd case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case $lt_sysroot:$1 in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result='='$func_stripname_result ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $debug_cmd if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with '--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=$1 if test yes = "$build_libtool_libs"; then write_lobj=\'$2\' else write_lobj=none fi if test yes = "$build_old_libs"; then write_oldobj=\'$3\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "$func_convert_core_file_wine_to_w32_tmp"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $debug_cmd # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result= if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result"; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $debug_cmd if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $debug_cmd # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $debug_cmd if test -z "$2" && test -n "$1"; then func_error "Could not determine host file name corresponding to" func_error " '$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result=$1 fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $debug_cmd if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " '$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result=$3 fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $debug_cmd case $4 in $1 ) func_to_host_path_result=$3$func_to_host_path_result ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via '$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $debug_cmd $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $debug_cmd case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result=$1 } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result=$func_convert_core_msys_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result=$func_convert_core_file_wine_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via '$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $debug_cmd if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd=func_convert_path_$func_stripname_result fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $debug_cmd func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result=$1 } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_msys_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_path_wine_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_dll_def_p FILE # True iff FILE is a Windows DLL '.def' file. # Keep in sync with _LT_DLL_DEF_P in libtool.m4 func_dll_def_p () { $debug_cmd func_dll_def_p_tmp=`$SED -n \ -e 's/^[ ]*//' \ -e '/^\(;.*\)*$/d' \ -e 's/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p' \ -e q \ "$1"` test DEF = "$func_dll_def_p_tmp" } # func_mode_compile arg... func_mode_compile () { $debug_cmd # Get the compilation command and the source file. base_compile= srcfile=$nonopt # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg=$arg arg_mode=normal ;; target ) libobj=$arg arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify '-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs=$IFS; IFS=, for arg in $args; do IFS=$save_ifs func_append_quoted lastarg "$arg" done IFS=$save_ifs func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg=$srcfile srcfile=$arg ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with '-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj=$func_basename_result } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from '$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test yes = "$build_libtool_libs" \ || func_fatal_configuration "cannot build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name '$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname=$func_basename_result xdir=$func_dirname_result lobj=$xdir$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test yes = "$build_old_libs"; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test no = "$pic_mode" && test pass_all != "$deplibs_check_method"; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test no = "$compiler_c_o"; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.$objext lockfile=$output_obj.lock else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test yes = "$need_locks"; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test warn = "$need_locks"; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test yes = "$build_libtool_libs"; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test no != "$pic_mode"; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test yes = "$suppress_opt"; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test yes = "$build_old_libs"; then if test yes != "$pic_mode"; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test yes = "$compiler_c_o"; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test no != "$need_locks"; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test compile = "$opt_mode" && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a '.o' file suitable for static linking -static only build a '.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a 'standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix '.c' with the library object suffix, '.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to '-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the '--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the 'install' or 'cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE '-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE use a list of object files found in FILE to specify objects -os2dllname NAME force a short DLL name on OS/2 (no effect on other OSes) -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with '-') are ignored. Every other argument is treated as a filename. Files ending in '.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in '.la', then a libtool library is created, only library objects ('.lo' files) may be specified, and '-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created using 'ar' and 'ranlib', or on Windows using 'lib'. If OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode '$opt_mode'" ;; esac echo $ECHO "Try '$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test : = "$opt_help"; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | $SED -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | $SED '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $debug_cmd # The first argument is the command name. cmd=$nonopt test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "'$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "'$file' was not linked with '-export-dynamic'" continue fi func_dirname "$file" "" "." dir=$func_dirname_result if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find '$dlname' in '$dir' or '$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir=$func_dirname_result ;; *) func_warning "'-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir=$absdir # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic=$magic # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file=$progdir/$program elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file=$progdir/$program fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if $opt_dry_run; then # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS else if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd=\$cmd$args fi } test execute = "$opt_mode" && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $debug_cmd libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "'$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument '$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and '=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do $SED -e "$sysroot_cmd s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_quiet && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the '-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the '$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the '$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the '$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to '/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test finish = "$opt_mode" && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $debug_cmd # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$SHELL" = "$nonopt" || test /bin/sh = "$nonopt" || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" func_append install_prog "$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=false stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=: ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test X-m = "X$prev" && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" func_append install_prog " $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi func_append install_shared_prog " $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the '$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" func_append install_shared_prog " -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=: if $isdir; then destdir=$dest destname= else func_dirname_and_basename "$dest" "" "." destdir=$func_dirname_result destname=$func_basename_result # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "'$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "'$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir=$func_dirname_result func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install '$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking '$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname=$1 shift srcname=$realname test -n "$relink_command" && srcname=${realname}T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme=$stripme case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme= ;; esac ;; os2*) case $realname in *_dll.a) tstripme= ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try 'ln -sf' first, because the 'ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib=$destdir/$realname func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name=$func_basename_result instname=$dir/${name}i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest=$destfile destfile= ;; *) func_fatal_help "cannot copy a libtool object to '$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test yes = "$build_old_libs"; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext= case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=.exe fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script '$wrapper'" finalize=: for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile=$libdir/`$ECHO "$lib" | $SED 's%^.*/%%g'` if test -n "$libdir" && test ! -f "$libfile"; then func_warning "'$lib' has not been installed in '$libdir'" finalize=false fi done relink_command= func_source "$wrapper" outputname= if test no = "$fast_install" && test -n "$relink_command"; then $opt_dry_run || { if $finalize; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file=$func_basename_result outputname=$tmpdir/$file # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_quiet || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink '$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file=$outputname else func_warning "cannot relink '$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name=$func_basename_result # Set up the ranlib parameters. oldlib=$destdir/$name func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run '$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL "$progpath" $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test install = "$opt_mode" && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $debug_cmd my_outputname=$1 my_originator=$2 my_pic_p=${3-false} my_prefix=`$ECHO "$my_originator" | $SED 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms=${my_outputname}S.c else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist=$output_objdir/$my_outputname.nm func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* External symbol declarations for the compiler. */\ " if test yes = "$dlself"; then func_verbose "generating symbol list for '$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from '$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols=$output_objdir/$outputname.exp $opt_dry_run || { $RM $export_symbols eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "$SED -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from '$dlprefile'" func_basename "$dlprefile" name=$func_basename_result case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename= if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname"; then func_basename "$dlprefile_dlname" dlprefile_dlbasename=$func_basename_result else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename"; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi func_show_eval '$RM "${nlist}I"' if test -n "$global_symbol_to_import"; then eval "$global_symbol_to_import"' < "$nlist"S > "$nlist"I' fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[];\ " if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ static void lt_syminit(void) { LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols; for (; symbol->name; ++symbol) {" $SED 's/.*/ if (STREQ (symbol->name, \"&\")) symbol->address = (void *) \&&;/' < "$nlist"I >> "$output_objdir/$my_dlsyms" echo >> "$output_objdir/$my_dlsyms" "\ } }" fi echo >> "$output_objdir/$my_dlsyms" "\ LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = { {\"$my_originator\", (void *) 0}," if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ {\"@INIT@\", (void *) <_syminit}," fi case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) $my_pic_p && pic_flag_for_symtable=" $pic_flag" ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T" "${nlist}I"' # Transform the symbol file into the correct name. symfileobj=$output_objdir/${my_outputname}S.$objext case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for '$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $debug_cmd win32_libid_type=unknown win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then case $nm_interface in "MS dumpbin") if func_cygming_ms_implib_p "$1" || func_cygming_gnu_implib_p "$1" then win32_nmres=import else win32_nmres= fi ;; *) func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s|.*|import| p q } }'` ;; esac case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $debug_cmd sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $debug_cmd match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive that possess that section. Heuristic: eliminate # all those that have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $debug_cmd if func_cygming_gnu_implib_p "$1"; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1"; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result= fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $debug_cmd f_ex_an_ar_dir=$1; shift f_ex_an_ar_oldlib=$1 if test yes = "$lock_old_archive_extraction"; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test yes = "$lock_old_archive_extraction"; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $debug_cmd my_gentop=$1; shift my_oldlibs=${1+"$@"} my_oldobjs= my_xlib= my_xabs= my_xdir= for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs=$my_xlib ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib=$func_basename_result my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir=$my_gentop/$my_xlib_u func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` func_basename "$darwin_archive" darwin_base_archive=$func_basename_result darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches; do func_mkdir_p "unfat-$$/$darwin_base_archive-$darwin_arch" $LIPO -thin $darwin_arch -output "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" "$darwin_archive" cd "unfat-$$/$darwin_base_archive-$darwin_arch" func_extract_an_archive "`pwd`" "$darwin_base_archive" cd "$darwin_curdir" $RM "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$sed_basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result=$my_oldobjs } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory where it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ that is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options that match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"$outputname:$output:\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"$outputname:$output:\$LINENO: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test yes = "$fast_install"; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | $SED 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else \$ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: '\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* declarations of non-ANSI functions */ #if defined __MINGW32__ # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined __CYGWIN__ # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined other_platform || defined ... */ #endif /* portability defines, excluding path handling macros */ #if defined _MSC_VER # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC #elif defined __MINGW32__ # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined __CYGWIN__ # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined other platforms ... */ #endif #if defined PATH_MAX # define LT_PATHMAX PATH_MAX #elif defined MAXPATHLEN # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \ defined __OS2__ # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free (stale); stale = 0; } \ } while (0) #if defined LT_DEBUGWRAPPER static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; size_t tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined HAVE_DOS_BASED_FILE_SYSTEM if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined HAVE_DOS_BASED_FILE_SYSTEM } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = (size_t) (q - p); p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (STREQ (str, pat)) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else size_t len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { size_t orig_value_len = strlen (orig_value); size_t add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ size_t len = strlen (new_value); while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[--len] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $debug_cmd case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_suncc_cstd_abi # !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!! # Several compiler flags select an ABI that is incompatible with the # Cstd library. Avoid specifying it if any are in CXXFLAGS. func_suncc_cstd_abi () { $debug_cmd case " $compile_command " in *" -compat=g "*|*\ -std=c++[0-9][0-9]\ *|*" -library=stdcxx4 "*|*" -library=stlport4 "*) suncc_use_cstd_abi=no ;; *) suncc_use_cstd_abi=yes ;; esac } # func_mode_link arg... func_mode_link () { $debug_cmd case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # what system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll that has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= os2dllname= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=false prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module=$wl-single_module func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test yes != "$build_libtool_libs" \ && func_fatal_configuration "cannot build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test yes = "$build_libtool_libs" && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg=$1 shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir=$arg prev= continue ;; dlfiles|dlprefiles) $preload || { # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=: } case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test no = "$dlself"; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test dlprefiles = "$prev"; then dlself=yes elif test dlfiles = "$prev" && test yes != "$dlopen_self"; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test dlfiles = "$prev"; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols=$arg test -f "$arg" \ || func_fatal_error "symbol file '$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex=$arg prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir=$arg prev= continue ;; mllvm) # Clang does not use LLVM to link, so we can simply discard any # '-mllvm $arg' options when doing the link step. prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result if test none != "$pic_object"; then # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object fi # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file '$arg' does not exist" fi arg=$save_arg prev= continue ;; os2dllname) os2dllname=$arg prev= continue ;; precious_regex) precious_files_regex=$arg prev= continue ;; release) release=-$arg prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test rpath = "$prev"; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds=$arg prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg=$arg case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "'-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test X-export-symbols = "X$arg"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between '-L' and '$1'" else func_fatal_error "need path for '-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of '$dir'" dir=$absdir ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test X-lc = "X$arg" || test X-lm = "X$arg"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test X-lc = "X$arg" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc due to us having libc/libc_r. test X-lc = "X$arg" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test X-lc = "X$arg" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test X-lc = "X$arg" && continue ;; esac elif test X-lc_r = "X$arg"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -mllvm) prev=mllvm continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module=$wl-multi_module continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "'-no-install' is ignored for $host" func_warning "assuming '-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -os2dllname) prev=os2dllname continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_for_eval "$flag" func_append arg " $func_quote_for_eval_result" func_append compiler_flags " $func_quote_for_eval_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_for_eval "$flag" func_append arg " $wl$func_quote_for_eval_result" func_append compiler_flags " $wl$func_quote_for_eval_result" func_append linker_flags " $func_quote_for_eval_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # -fstack-protector* stack protector flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization # -stdlib=* select c++ std lib with clang -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; -Z*) if test os2 = "`expr $host : '.*\(os2\)'`"; then # OS/2 uses -Zxxx to specify OS/2-specific options compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case $arg in -Zlinker | -Zstack) prev=xcompiler ;; esac continue else # Otherwise treat like 'Some other compiler flag' below func_quote_for_eval "$arg" arg=$func_quote_for_eval_result fi ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result test none = "$pic_object" || { # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object } # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test dlfiles = "$prev"; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test dlprefiles = "$prev"; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg=$func_quote_for_eval_result ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the '$prevarg' option requires an argument" if test yes = "$export_dynamic" && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname=$func_basename_result libobjs_save=$libobjs if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\$$shlibpath_var\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" # Definition is injected by LT_CONFIG during libtool generation. func_munge_path_list sys_lib_dlsearch_path "$LT_SYS_LIBRARY_PATH" func_dirname "$output" "/" "" output_objdir=$func_dirname_result$objdir func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test lib = "$linkmode"; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can '-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=false newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test lib,link = "$linkmode,$pass"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs=$tmp_deplibs fi if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass"; then libs=$deplibs deplibs= fi if test prog = "$linkmode"; then case $pass in dlopen) libs=$dlfiles ;; dlpreopen) libs=$dlprefiles ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test lib,dlpreopen = "$linkmode,$pass"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs=$dlprefiles fi if test dlopen = "$pass"; then # Collect dlpreopened libraries save_deplibs=$deplibs deplibs= fi for deplib in $libs; do lib= found=false case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test lib != "$linkmode" && test prog != "$linkmode"; then func_warning "'-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test lib = "$linkmode"; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib=$searchdir/lib$name$search_ext if test -f "$lib"; then if test .la = "$search_ext"; then found=: else found=false fi break 2 fi done done if $found; then # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll=$l done if test "X$ll" = "X$old_library"; then # only static version available found=false func_dirname "$lib" "" "." ladir=$func_dirname_result lib=$ladir/$old_library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi else # deplib doesn't seem to be a libtool library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi ;; # -l *.ltframework) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test conv = "$pass" && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi if test scan = "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "'-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test link = "$pass"; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=false case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=: fi ;; pass_all) valid_a_lib=: ;; esac if $valid_a_lib; then echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" else echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." fi ;; esac continue ;; prog) if test link != "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test conv = "$pass"; then deplibs="$deplib $deplibs" elif test prog = "$linkmode"; then if test dlpreopen = "$pass" || test yes != "$dlopen_support" || test no = "$build_libtool_libs"; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=: continue ;; esac # case $deplib $found || test -f "$lib" \ || func_fatal_error "cannot find the library '$lib' or unhandled argument '$deplib'" # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "'$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir=$func_dirname_result dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass" || { test prog != "$linkmode" && test lib != "$linkmode"; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test conv = "$pass"; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for '$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" elif test prog != "$linkmode" && test lib != "$linkmode"; then func_fatal_error "'$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test yes = "$prefer_static_libs" || test built,no = "$prefer_static_libs,$installed"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib=$l done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for '$lib'" fi # This library was specified with -dlopen. if test dlopen = "$pass"; then test -z "$libdir" \ && func_fatal_error "cannot -dlopen a convenience library: '$lib'" if test -z "$dlname" || test yes != "$dlopen_support" || test no = "$build_libtool_libs" then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir=$ladir ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of '$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir=$ladir fi ;; esac func_basename "$lib" laname=$func_basename_result # Find the relevant object directory and library name. if test yes = "$installed"; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library '$lib' was moved." dir=$ladir absdir=$abs_ladir libdir=$abs_ladir else dir=$lt_sysroot$libdir absdir=$lt_sysroot$libdir fi test yes = "$hardcode_automatic" && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir=$ladir absdir=$abs_ladir # Remove this search path later func_append notinst_path " $abs_ladir" else dir=$ladir/$objdir absdir=$abs_ladir/$objdir # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test dlpreopen = "$pass"; then if test -z "$libdir" && test prog = "$linkmode"; then func_fatal_error "only libraries may -dlpreopen a convenience library: '$lib'" fi case $host in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test lib = "$linkmode"; then deplibs="$dir/$old_library $deplibs" elif test prog,link = "$linkmode,$pass"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test prog = "$linkmode" && test link != "$pass"; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=false if test no != "$link_all_deplibs" || test -z "$library_names" || test no = "$build_libtool_libs"; then linkalldeplibs=: fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if $linkalldeplibs; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test prog,link = "$linkmode,$pass"; then if test -n "$library_names" && { { test no = "$prefer_static_libs" || test built,yes = "$prefer_static_libs,$installed"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath"; then # Make sure the rpath contains only unique directories. case $temp_rpath: in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if $alldeplibs && { test pass_all = "$deplibs_check_method" || { test yes = "$build_libtool_libs" && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test built = "$use_static_libs" && test yes = "$installed"; then use_static_libs=no fi if test -n "$library_names" && { test no = "$use_static_libs" || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc* | *os2*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test no = "$installed"; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule= for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule=$dlpremoduletest break fi done if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then echo if test prog = "$linkmode"; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test lib = "$linkmode" && test yes = "$hardcode_into_libs"; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname=$1 shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname=$dlname elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc* | *os2*) func_arith $current - $age major=$func_arith_result versuffix=-$major ;; esac eval soname=\"$soname_spec\" else soname=$realname fi # Make a new name for the extract_expsyms_cmds to use soroot=$soname func_basename "$soroot" soname=$func_basename_result func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from '$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for '$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test prog = "$linkmode" || test relink != "$opt_mode"; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test no = "$hardcode_direct"; then add=$dir/$linklib case $host in *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;; *-*-sysv4*uw2*) add_dir=-L$dir ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir=-L$dir ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we cannot # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library"; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add=$dir/$old_library fi elif test -n "$old_library"; then add=$dir/$old_library fi fi esac elif test no = "$hardcode_minus_L"; then case $host in *-*-sunos*) add_shlibpath=$dir ;; esac add_dir=-L$dir add=-l$name elif test no = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; relink) if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$dir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$absdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name elif test yes = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; *) lib_linked=no ;; esac if test yes != "$lib_linked"; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test prog = "$linkmode"; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test yes != "$hardcode_direct" && test yes != "$hardcode_minus_L" && test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test prog = "$linkmode" || test relink = "$opt_mode"; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$libdir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$libdir add=-l$name elif test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add=-l$name elif test yes = "$hardcode_automatic"; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib"; then add=$inst_prefix_dir$libdir/$linklib else add=$libdir/$linklib fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir=-L$libdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name fi if test prog = "$linkmode"; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test prog = "$linkmode"; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test unsupported != "$hardcode_direct"; then test -n "$old_library" && linklib=$old_library compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test yes = "$build_libtool_libs"; then # Not a shared library if test pass_all != "$deplibs_check_method"; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system cannot link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test yes = "$module"; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test lib = "$linkmode"; then if test -n "$dependency_libs" && { test yes != "$hardcode_into_libs" || test yes = "$build_old_libs" || test yes = "$link_static"; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs=$temp_deplibs fi func_append newlib_search_path " $absdir" # Link against this library test no = "$link_static" && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test no != "$link_all_deplibs"; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path=$deplib ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir=$dir ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of '$dir'" absdir=$dir fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`$SED -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names"; then for tmp in $deplibrary_names; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl"; then depdepl=$absdir/$objdir/$depdepl darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`$OTOOL64 -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " $wl-dylib_file $wl$darwin_install_name:$depdepl" func_append linker_flags " -dylib_file $darwin_install_name:$depdepl" path= fi fi ;; *) path=-L$absdir/$objdir ;; esac else eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "'$deplib' seems to be moved" path=-L$absdir fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test link = "$pass"; then if test prog = "$linkmode"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs=$newdependency_libs if test dlpreopen = "$pass"; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test dlopen != "$pass"; then test conv = "$pass" || { # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= } if test prog,link = "$linkmode,$pass"; then vars="compile_deplibs finalize_deplibs" else vars=deplibs fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Add Sun CC postdeps if required: test CXX = "$tagname" && { case $host_os in linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; solaris*) func_cc_basename "$CC" case $func_cc_basename_result in CC* | sunCC*) func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; esac } # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i= ;; esac if test -n "$i"; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test prog = "$linkmode"; then dlfiles=$newdlfiles fi if test prog = "$linkmode" || test lib = "$linkmode"; then dlprefiles=$newdlprefiles fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "'-R' is ignored for archives" test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "'-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "'-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs=$output func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form 'libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test no = "$module" \ && func_fatal_help "libtool library '$output' must begin with 'lib'" if test no != "$need_lib_prefix"; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test pass_all != "$deplibs_check_method"; then func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test no = "$dlself" \ || func_warning "'-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test 1 -lt "$#" \ && func_warning "ignoring multiple '-rpath's for a libtool library" install_libdir=$1 oldlibs= if test -z "$rpath"; then if test yes = "$build_libtool_libs"; then # Building a libtool convenience library. # Some compilers have problems with a '.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "'-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs=$IFS; IFS=: set dummy $vinfo 0 0 0 shift IFS=$save_ifs test -n "$7" && \ func_fatal_help "too many parameters to '-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major=$1 number_minor=$2 number_revision=$3 # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # that has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|freebsd-elf|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_revision ;; freebsd-aout|qnx|sunos) current=$number_major revision=$number_minor age=0 ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_minor lt_irix_increment=no ;; esac ;; no) current=$1 revision=$2 age=$3 ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT '$current' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION '$revision' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE '$age' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE '$age' is greater than the current interface number '$current'" func_fatal_error "'$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" # On Darwin other compilers case $CC in nagfor*) verstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" ;; *) verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; esac ;; freebsd-aout) major=.$current versuffix=.$current.$revision ;; freebsd-elf) func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; irix | nonstopux) if test no = "$lt_irix_increment"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring=$verstring_prefix$major.$revision # Add in all the interfaces that we are compatible with. loop=$revision while test 0 -ne "$loop"; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring_prefix$major.$iface:$verstring done # Before this point, $major must not contain '.'. major=.$major versuffix=$major.$revision ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=.$current.$age.$revision verstring=$current.$age.$revision # Add in all the interfaces that we are compatible with. loop=$age while test 0 -ne "$loop"; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring:$iface.0 done # Make executables depend on our current version. func_append verstring ":$current.0" ;; qnx) major=.$current versuffix=.$current ;; sco) major=.$current versuffix=.$current ;; sunos) major=.$current versuffix=.$current.$revision ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 file systems. func_arith $current - $age major=$func_arith_result versuffix=-$major ;; *) func_fatal_configuration "unknown library version type '$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring=0.0 ;; esac if test no = "$need_version"; then versuffix= else versuffix=.0.0 fi fi # Remove version info from name if versioning should be avoided if test yes,no = "$avoid_version,$need_version"; then major= versuffix= verstring= fi # Check to see if the archive will have undefined symbols. if test yes = "$allow_undefined"; then if test unsupported = "$allow_undefined_flag"; then if test yes = "$build_old_libs"; then func_warning "undefined symbols not allowed in $host shared libraries; building static only" build_libtool_libs=no else func_fatal_error "can't build $host shared library unless -no-undefined is specified" fi fi else # Don't allow undefined symbols. allow_undefined_flag=$no_undefined_flag fi fi func_generate_dlsyms "$libname" "$libname" : func_append libobjs " $symfileobj" test " " = "$libobjs" && libobjs= if test relink != "$opt_mode"; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*) if test -n "$precious_files_regex"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test yes = "$build_old_libs" && test convenience != "$build_libtool_libs"; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test yes != "$hardcode_into_libs" || test yes = "$build_old_libs"; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles=$dlfiles dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles=$dlprefiles dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test yes = "$build_libtool_libs"; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test yes = "$build_libtool_need_lc"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release= versuffix= major= newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib=$potent_lib while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | $SED 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib=$potliblink;; *) potlib=`$ECHO "$potlib" | $SED 's|[^/]*$||'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib= ;; esac fi if test -n "$a_deplib"; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib=$potent_lib # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs= tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test yes = "$allow_libtool_libs_with_static_runtimes"; then for i in $predeps $postdeps; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s|$i||"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test none = "$deplibs_check_method"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test yes = "$droppeddeps"; then if test yes = "$module"; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test no = "$allow_undefined"; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs=$new_libs # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test yes = "$build_libtool_libs"; then # Remove $wl instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test yes = "$hardcode_into_libs"; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath=$finalize_rpath test relink = "$opt_mode" || rpath=$compile_rpath$rpath for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath=$finalize_shlibpath test relink = "$opt_mode" || shlibpath=$compile_shlibpath$shlibpath if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname=$1 shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname=$realname fi if test -z "$dlname"; then dlname=$soname fi lib=$output_objdir/$realname linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols=$output_objdir/$libname.uexp func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile func_dll_def_p "$export_symbols" || { # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols=$export_symbols export_symbols= always_export_symbols=yes } fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test yes = "$always_export_symbols" || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs=$IFS; IFS='~' for cmd1 in $cmds; do IFS=$save_ifs # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test yes = "$try_normal_branch" \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=$output_objdir/$output_la.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS=$save_ifs if test -n "$export_symbols_regex" && test : != "$skipped_export"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test : != "$skipped_export" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs=$tmp_deplibs if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test yes = "$compiler_needs_object" && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test yes = "$thread_safe" && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test : != "$skipped_export" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then output=$output_objdir/$output_la.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then output=$output_objdir/$output_la.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test yes = "$compiler_needs_object"; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-$k.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test -z "$objlist" || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test 1 -eq "$k"; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-$k.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-$k.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi ${skipped_export-false} && { func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi } test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs=$IFS; IFS='~' for cmd in $concat_cmds; do IFS=$save_ifs $opt_quiet || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi ${skipped_export-false} && { if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi } libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs=$IFS; IFS='~' for cmd in $cmds; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs $opt_quiet || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs # Restore the uninstalled library and exit if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test yes = "$module" || test yes = "$export_dynamic"; then # On all known operating systems, these are identical. dlname=$soname fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "'-R' is ignored for objects" test -n "$vinfo" && \ func_warning "'-version-info' is ignored for objects" test -n "$release" && \ func_warning "'-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object '$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj=$output ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # if reload_cmds runs $LD directly, get rid of -Wl from # whole_archive_flag_spec and hope we can get by with turning comma # into space. case $reload_cmds in *\$LD[\ \$]*) wl= ;; esac if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" test -n "$wl" || tmp_whole_archive_flags=`$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` reload_conv_objs=$reload_objs\ $tmp_whole_archive_flags else gentop=$output_objdir/${obj}x func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test yes = "$build_libtool_libs" || libobjs=$non_pic_objects # Create the old-style object. reload_objs=$objs$old_deplibs' '`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; /\.lib$/d; $lo2o" | $NL2SP`' '$reload_conv_objs output=$obj func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi test yes = "$build_libtool_libs" || { if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS } if test -n "$pic_flag" || test default != "$pic_mode"; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output=$libobj func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "'-version-info' is ignored for programs" test -n "$release" && \ func_warning "'-release' is ignored for programs" $preload \ && test unknown,unknown,unknown = "$dlopen_support,$dlopen_self,$dlopen_self_static" \ && func_warning "'LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test CXX = "$tagname"; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " $wl-bind_at_load" func_append finalize_command " $wl-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs=$new_libs func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath=$rpath rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath=$rpath if test -n "$libobjs" && test yes = "$build_old_libs"; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" false # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=: case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=false ;; *cygwin* | *mingw* ) test yes = "$build_libtool_libs" || wrappers_required=false ;; *) if test no = "$need_relink" || test yes != "$build_libtool_libs"; then wrappers_required=false fi ;; esac $wrappers_required || { # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command=$compile_command$compile_rpath # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.$objext"; then func_show_eval '$RM "$output_objdir/${outputname}S.$objext"' fi exit $exit_status } if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test yes = "$no_install"; then # We don't need to create a wrapper script. link_command=$compile_var$compile_command$compile_rpath # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi case $hardcode_action,$fast_install in relink,*) # Fast installation is not supported link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath func_warning "this platform does not like uninstalled shared libraries" func_warning "'$output' will be relinked during installation" ;; *,yes) link_command=$finalize_var$compile_command$finalize_rpath relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` ;; *,no) link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath ;; *,needless) link_command=$finalize_var$compile_command$finalize_rpath relink_command= ;; esac # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource=$output_path/$objdir/lt-$output_name.c cwrapper=$output_path/$output_name.exe $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host"; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do case $build_libtool_libs in convenience) oldobjs="$libobjs_save $symfileobj" addlibs=$convenience build_libtool_libs=no ;; module) oldobjs=$libobjs_save addlibs=$old_convenience build_libtool_libs=no ;; *) oldobjs="$old_deplibs $non_pic_objects" $preload && test -f "$symfileobj" \ && func_append oldobjs " $symfileobj" addlibs=$old_convenience ;; esac if test -n "$addlibs"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test yes = "$build_libtool_libs"; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase=$func_basename_result case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj"; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test -z "$oldobjs"; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test yes = "$build_old_libs" && old_library=$libname.$libext func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL \"$progpath\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test yes = "$hardcode_automatic"; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test yes = "$installed"; then if test -z "$install_libdir"; then break fi output=$output_objdir/${outputname}i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name=$func_basename_result func_resolve_sysroot "$deplib" eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs=$newdependency_libs newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles=$newdlprefiles else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles=$newdlprefiles fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test -n "$bindir"; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result/$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that cannot go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test no,yes = "$installed,$need_relink"; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } if test link = "$opt_mode" || test relink = "$opt_mode"; then func_mode_link ${1+"$@"} fi # func_mode_uninstall arg... func_mode_uninstall () { $debug_cmd RM=$nonopt files= rmforce=false exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic for arg do case $arg in -f) func_append RM " $arg"; rmforce=: ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir=$func_dirname_result if test . = "$dir"; then odir=$objdir else odir=$dir/$objdir fi func_basename "$file" name=$func_basename_result test uninstall = "$opt_mode" && odir=$dir # Remember odir for removal later, being careful to avoid duplicates if test clean = "$opt_mode"; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif $rmforce; then continue fi rmfiles=$file case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case $opt_mode in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" '$rmforce || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" '$rmforce || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test none != "$pic_object"; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test none != "$non_pic_object"; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test clean = "$opt_mode"; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.$objext" if test yes = "$fast_install" && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name"; then func_append rmfiles " $odir/lt-$noexename.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the $objdir's in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } if test uninstall = "$opt_mode" || test clean = "$opt_mode"; then func_mode_uninstall ${1+"$@"} fi test -z "$opt_mode" && { help=$generic_help func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode '$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # where we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: ================================================ FILE: tess-two/jni/libjpeg/makcjpeg.st ================================================ ; Project file for Independent JPEG Group's software ; ; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C. ; Thanks to Frank Moehle, B. Setzepfandt, and Guido Vollbeding. ; ; To use this file, rename it to cjpeg.prj. ; If you are using Turbo C, change filenames beginning with "pc..." to "tc..." ; Read installation instructions before trying to make the program! ; ; ; * * * Output file * * * cjpeg.ttp ; ; * * * COMPILER OPTIONS * * * .C[-P] ; absolute calls .C[-M] ; and no string merging, folks .C[-w-cln] ; no "constant is long" warnings .C[-w-par] ; no "parameter xxxx unused" .C[-w-rch] ; no "unreachable code" .C[-wsig] ; warn if significant digits may be lost = ; * * * * List of modules * * * * pcstart.o cjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,jversion.h) cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdswitch.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdppm.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdgif.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdtarga.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdbmp.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdrle.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) libjpeg.lib ; built by libjpeg.prj pcfltlib.lib ; floating point library ; the float library can be omitted if you've turned off DCT_FLOAT_SUPPORTED pcstdlib.lib ; standard library pcextlib.lib ; extended library ================================================ FILE: tess-two/jni/libjpeg/makdjpeg.st ================================================ ; Project file for Independent JPEG Group's software ; ; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C. ; Thanks to Frank Moehle, B. Setzepfandt, and Guido Vollbeding. ; ; To use this file, rename it to djpeg.prj. ; If you are using Turbo C, change filenames beginning with "pc..." to "tc..." ; Read installation instructions before trying to make the program! ; ; ; * * * Output file * * * djpeg.ttp ; ; * * * COMPILER OPTIONS * * * .C[-P] ; absolute calls .C[-M] ; and no string merging, folks .C[-w-cln] ; no "constant is long" warnings .C[-w-par] ; no "parameter xxxx unused" .C[-w-rch] ; no "unreachable code" .C[-wsig] ; warn if significant digits may be lost = ; * * * * List of modules * * * * pcstart.o djpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,jversion.h) cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdcolmap.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) wrppm.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) wrgif.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) wrtarga.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) wrbmp.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) wrrle.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) libjpeg.lib ; built by libjpeg.prj pcfltlib.lib ; floating point library ; the float library can be omitted if you've turned off DCT_FLOAT_SUPPORTED pcstdlib.lib ; standard library pcextlib.lib ; extended library ================================================ FILE: tess-two/jni/libjpeg/makeadsw.vc6 ================================================ Microsoft Developer Studio Workspace File, Format Version 6.00 # WARNUNG: DIESE ARBEITSBEREICHSDATEI DARF NICHT BEARBEITET ODER GELSCHT WERDEN! ############################################################################### Project: "cjpeg"=".\cjpeg.dsp" - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "djpeg"=".\djpeg.dsp" - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "jpegtran"=".\jpegtran.dsp" - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "rdjpgcom"=".\rdjpgcom.dsp" - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "wrjpgcom"=".\wrjpgcom.dsp" - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Global: Package=<5> {{{ }}} Package=<3> {{{ }}} ############################################################################### ================================================ FILE: tess-two/jni/libjpeg/makeasln.v10 ================================================ Microsoft Visual Studio Solution File, Format Version 11.00 # Visual C++ Express 2010 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cjpeg", "cjpeg.vcxproj", "{2E7FAAD9-2F58-4BDE-81F2-1D6D3FB8BF57}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "djpeg", "djpeg.vcxproj", "{11043137-B453-4DFA-9010-4D2B9DC1545C}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jpegtran", "jpegtran.vcxproj", "{025BAC50-51B5-4FFE-BC47-3F920BB4047E}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rdjpgcom", "rdjpgcom.vcxproj", "{C81513DB-78DC-46BC-BC98-82E745203976}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "wrjpgcom", "wrjpgcom.vcxproj", "{B57065D4-DDDA-4668-BAF5-2D49270C973C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2E7FAAD9-2F58-4BDE-81F2-1D6D3FB8BF57}.Release|Win32.ActiveCfg = Release|Win32 {2E7FAAD9-2F58-4BDE-81F2-1D6D3FB8BF57}.Release|Win32.Build.0 = Release|Win32 {11043137-B453-4DFA-9010-4D2B9DC1545C}.Release|Win32.ActiveCfg = Release|Win32 {11043137-B453-4DFA-9010-4D2B9DC1545C}.Release|Win32.Build.0 = Release|Win32 {025BAC50-51B5-4FFE-BC47-3F920BB4047E}.Release|Win32.ActiveCfg = Release|Win32 {025BAC50-51B5-4FFE-BC47-3F920BB4047E}.Release|Win32.Build.0 = Release|Win32 {C81513DB-78DC-46BC-BC98-82E745203976}.Release|Win32.ActiveCfg = Release|Win32 {C81513DB-78DC-46BC-BC98-82E745203976}.Release|Win32.Build.0 = Release|Win32 {B57065D4-DDDA-4668-BAF5-2D49270C973C}.Release|Win32.ActiveCfg = Release|Win32 {B57065D4-DDDA-4668-BAF5-2D49270C973C}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: tess-two/jni/libjpeg/makecdep.vc6 ================================================ # Microsoft Developer Studio erstellte Abhngigkeitsdatei, einbezogen von cjpeg.mak .\cdjpeg.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\cjpeg.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ ".\jversion.h"\ .\rdbmp.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\rdgif.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\rdppm.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\rdrle.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\rdswitch.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\rdtarga.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ ================================================ FILE: tess-two/jni/libjpeg/makecdsp.vc6 ================================================ # Microsoft Developer Studio Project File - Name="cjpeg" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** NICHT BEARBEITEN ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=cjpeg - Win32 !MESSAGE Dies ist kein gltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE !MESSAGE verwenden Sie den Befehl "Makefile exportieren" und fhren Sie den Befehl !MESSAGE !MESSAGE NMAKE /f "cjpeg.mak". !MESSAGE !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "cjpeg.mak" CFG="cjpeg - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "cjpeg - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir ".\cjpeg\Release" # PROP BASE Intermediate_Dir ".\cjpeg\Release" # PROP BASE Target_Dir ".\cjpeg" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir ".\cjpeg\Release" # PROP Intermediate_Dir ".\cjpeg\Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir ".\cjpeg" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c # ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /FD /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # Begin Target # Name "cjpeg - Win32" # Begin Group "Quellcodedateien" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;for;f90" # Begin Source File SOURCE=.\cdjpeg.c # End Source File # Begin Source File SOURCE=.\cjpeg.c # End Source File # Begin Source File SOURCE=.\rdbmp.c # End Source File # Begin Source File SOURCE=.\rdgif.c # End Source File # Begin Source File SOURCE=.\rdppm.c # End Source File # Begin Source File SOURCE=.\rdrle.c # End Source File # Begin Source File SOURCE=.\rdswitch.c # End Source File # Begin Source File SOURCE=.\rdtarga.c # End Source File # End Group # Begin Group "Header-Dateien" # PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" # Begin Source File SOURCE=.\cderror.h # End Source File # Begin Source File SOURCE=.\cdjpeg.h # End Source File # Begin Source File SOURCE=.\jconfig.h # End Source File # Begin Source File SOURCE=.\jerror.h # End Source File # Begin Source File SOURCE=.\jinclude.h # End Source File # Begin Source File SOURCE=.\jmorecfg.h # End Source File # Begin Source File SOURCE=.\jpeglib.h # End Source File # Begin Source File SOURCE=.\jversion.h # End Source File # End Group # Begin Group "Ressourcendateien" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" # End Group # End Target # End Project ================================================ FILE: tess-two/jni/libjpeg/makecfil.v10 ================================================ {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files ================================================ FILE: tess-two/jni/libjpeg/makecmak.vc6 ================================================ # Microsoft Developer Studio Generated NMAKE File, Based on cjpeg.dsp !IF "$(CFG)" == "" CFG=cjpeg - Win32 !MESSAGE Keine Konfiguration angegeben. cjpeg - Win32 wird als Standard verwendet. !ENDIF !IF "$(CFG)" != "cjpeg - Win32" !MESSAGE Ungltige Konfiguration "$(CFG)" angegeben. !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "cjpeg.mak" CFG="cjpeg - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "cjpeg - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE !ERROR Eine ungltige Konfiguration wurde angegeben. !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF CPP=cl.exe RSC=rc.exe OUTDIR=.\cjpeg\Release INTDIR=.\cjpeg\Release # Begin Custom Macros OutDir=.\cjpeg\Release # End Custom Macros ALL : "$(OUTDIR)\cjpeg.exe" CLEAN : -@erase "$(INTDIR)\cdjpeg.obj" -@erase "$(INTDIR)\cjpeg.obj" -@erase "$(INTDIR)\rdbmp.obj" -@erase "$(INTDIR)\rdgif.obj" -@erase "$(INTDIR)\rdppm.obj" -@erase "$(INTDIR)\rdrle.obj" -@erase "$(INTDIR)\rdswitch.obj" -@erase "$(INTDIR)\rdtarga.obj" -@erase "$(INTDIR)\vc60.idb" -@erase "$(OUTDIR)\cjpeg.exe" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" BSC32=bscmake.exe BSC32_FLAGS=/nologo /o"$(OUTDIR)\cjpeg.bsc" BSC32_SBRS= \ LINK32=link.exe LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no /pdb:"$(OUTDIR)\cjpeg.pdb" /machine:I386 /out:"$(OUTDIR)\cjpeg.exe" LINK32_OBJS= \ "$(INTDIR)\cdjpeg.obj" \ "$(INTDIR)\cjpeg.obj" \ "$(INTDIR)\rdbmp.obj" \ "$(INTDIR)\rdgif.obj" \ "$(INTDIR)\rdppm.obj" \ "$(INTDIR)\rdrle.obj" \ "$(INTDIR)\rdswitch.obj" \ "$(INTDIR)\rdtarga.obj" "$(OUTDIR)\cjpeg.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) $(LINK32) @<< $(LINK32_FLAGS) $(LINK32_OBJS) << CPP_PROJ=/nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /Fp"$(INTDIR)\cjpeg.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << !IF "$(NO_EXTERNAL_DEPS)" != "1" !IF EXISTS("cjpeg.dep") !INCLUDE "cjpeg.dep" !ELSE !MESSAGE Warning: cannot find "cjpeg.dep" !ENDIF !ENDIF !IF "$(CFG)" == "cjpeg - Win32" SOURCE=.\cdjpeg.c "$(INTDIR)\cdjpeg.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\cjpeg.c "$(INTDIR)\cjpeg.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdbmp.c "$(INTDIR)\rdbmp.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdgif.c "$(INTDIR)\rdgif.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdppm.c "$(INTDIR)\rdppm.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdrle.c "$(INTDIR)\rdrle.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdswitch.c "$(INTDIR)\rdswitch.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdtarga.c "$(INTDIR)\rdtarga.obj" : $(SOURCE) "$(INTDIR)" !ENDIF ================================================ FILE: tess-two/jni/libjpeg/makecvcx.v10 ================================================ Release Win32 {2E7FAAD9-2F58-4BDE-81F2-1D6D3FB8BF57} Win32Proj cjpeg Application false true Unicode false $(ProjectName)\$(Configuration)\ $(ProjectName)\$(Configuration)\ Level3 NotUsing Full true false WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS true true 4996 Console true true true Release\jpeg.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies) ================================================ FILE: tess-two/jni/libjpeg/makeddep.vc6 ================================================ # Microsoft Developer Studio erstellte Abhngigkeitsdatei, einbezogen von djpeg.mak .\cdjpeg.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\djpeg.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ ".\jversion.h"\ .\rdcolmap.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\wrbmp.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\wrgif.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\wrppm.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\wrrle.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\wrtarga.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ ================================================ FILE: tess-two/jni/libjpeg/makeddsp.vc6 ================================================ # Microsoft Developer Studio Project File - Name="djpeg" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** NICHT BEARBEITEN ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=djpeg - Win32 !MESSAGE Dies ist kein gltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE !MESSAGE verwenden Sie den Befehl "Makefile exportieren" und fhren Sie den Befehl !MESSAGE !MESSAGE NMAKE /f "djpeg.mak". !MESSAGE !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "djpeg.mak" CFG="djpeg - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "djpeg - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir ".\djpeg\Release" # PROP BASE Intermediate_Dir ".\djpeg\Release" # PROP BASE Target_Dir ".\djpeg" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir ".\djpeg\Release" # PROP Intermediate_Dir ".\djpeg\Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir ".\djpeg" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c # ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /FD /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # Begin Target # Name "djpeg - Win32" # Begin Group "Quellcodedateien" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;for;f90" # Begin Source File SOURCE=.\cdjpeg.c # End Source File # Begin Source File SOURCE=.\djpeg.c # End Source File # Begin Source File SOURCE=.\rdcolmap.c # End Source File # Begin Source File SOURCE=.\wrbmp.c # End Source File # Begin Source File SOURCE=.\wrgif.c # End Source File # Begin Source File SOURCE=.\wrppm.c # End Source File # Begin Source File SOURCE=.\wrrle.c # End Source File # Begin Source File SOURCE=.\wrtarga.c # End Source File # End Group # Begin Group "Header-Dateien" # PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" # Begin Source File SOURCE=.\cderror.h # End Source File # Begin Source File SOURCE=.\cdjpeg.h # End Source File # Begin Source File SOURCE=.\jconfig.h # End Source File # Begin Source File SOURCE=.\jerror.h # End Source File # Begin Source File SOURCE=.\jinclude.h # End Source File # Begin Source File SOURCE=.\jmorecfg.h # End Source File # Begin Source File SOURCE=.\jpeglib.h # End Source File # Begin Source File SOURCE=.\jversion.h # End Source File # End Group # Begin Group "Ressourcendateien" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" # End Group # End Target # End Project ================================================ FILE: tess-two/jni/libjpeg/makedfil.v10 ================================================ {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files ================================================ FILE: tess-two/jni/libjpeg/makedmak.vc6 ================================================ # Microsoft Developer Studio Generated NMAKE File, Based on djpeg.dsp !IF "$(CFG)" == "" CFG=djpeg - Win32 !MESSAGE Keine Konfiguration angegeben. djpeg - Win32 wird als Standard verwendet. !ENDIF !IF "$(CFG)" != "djpeg - Win32" !MESSAGE Ungltige Konfiguration "$(CFG)" angegeben. !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "djpeg.mak" CFG="djpeg - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "djpeg - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE !ERROR Eine ungltige Konfiguration wurde angegeben. !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF CPP=cl.exe RSC=rc.exe OUTDIR=.\djpeg\Release INTDIR=.\djpeg\Release # Begin Custom Macros OutDir=.\djpeg\Release # End Custom Macros ALL : "$(OUTDIR)\djpeg.exe" CLEAN : -@erase "$(INTDIR)\cdjpeg.obj" -@erase "$(INTDIR)\djpeg.obj" -@erase "$(INTDIR)\rdcolmap.obj" -@erase "$(INTDIR)\vc60.idb" -@erase "$(INTDIR)\wrbmp.obj" -@erase "$(INTDIR)\wrgif.obj" -@erase "$(INTDIR)\wrppm.obj" -@erase "$(INTDIR)\wrrle.obj" -@erase "$(INTDIR)\wrtarga.obj" -@erase "$(OUTDIR)\djpeg.exe" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" BSC32=bscmake.exe BSC32_FLAGS=/nologo /o"$(OUTDIR)\djpeg.bsc" BSC32_SBRS= \ LINK32=link.exe LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no /pdb:"$(OUTDIR)\djpeg.pdb" /machine:I386 /out:"$(OUTDIR)\djpeg.exe" LINK32_OBJS= \ "$(INTDIR)\cdjpeg.obj" \ "$(INTDIR)\djpeg.obj" \ "$(INTDIR)\rdcolmap.obj" \ "$(INTDIR)\wrbmp.obj" \ "$(INTDIR)\wrgif.obj" \ "$(INTDIR)\wrppm.obj" \ "$(INTDIR)\wrrle.obj" \ "$(INTDIR)\wrtarga.obj" "$(OUTDIR)\djpeg.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) $(LINK32) @<< $(LINK32_FLAGS) $(LINK32_OBJS) << CPP_PROJ=/nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /Fp"$(INTDIR)\djpeg.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << !IF "$(NO_EXTERNAL_DEPS)" != "1" !IF EXISTS("djpeg.dep") !INCLUDE "djpeg.dep" !ELSE !MESSAGE Warning: cannot find "djpeg.dep" !ENDIF !ENDIF !IF "$(CFG)" == "djpeg - Win32" SOURCE=.\cdjpeg.c "$(INTDIR)\cdjpeg.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\djpeg.c "$(INTDIR)\djpeg.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdcolmap.c "$(INTDIR)\rdcolmap.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\wrbmp.c "$(INTDIR)\wrbmp.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\wrgif.c "$(INTDIR)\wrgif.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\wrppm.c "$(INTDIR)\wrppm.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\wrrle.c "$(INTDIR)\wrrle.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\wrtarga.c "$(INTDIR)\wrtarga.obj" : $(SOURCE) "$(INTDIR)" !ENDIF ================================================ FILE: tess-two/jni/libjpeg/makedvcx.v10 ================================================ Release Win32 {11043137-B453-4DFA-9010-4D2B9DC1545C} Win32Proj djpeg Application false true Unicode false $(ProjectName)\$(Configuration)\ $(ProjectName)\$(Configuration)\ Level3 NotUsing Full true false WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS true true 4996 Console true true true Release\jpeg.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies) ================================================ FILE: tess-two/jni/libjpeg/makefile.ansi ================================================ # Makefile for Independent JPEG Group's software # This makefile is suitable for Unix-like systems with ANSI-capable compilers. # If you have a non-ANSI compiler, makefile.unix is a better starting point. # Read installation instructions before saying "make" !! # The name of your C compiler: CC= cc # You may need to adjust these cc options: CFLAGS= -O # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via -D switches here. # Link-time cc options: LDFLAGS= # To link any special libraries, add the necessary -l commands here. LDLIBS= # Put here the object file name for the correct system-dependent memory # manager file. For Unix this is usually jmemnobs.o, but you may want # to use jmemansi.o or jmemname.o if you have limited swap space. SYSDEPMEM= jmemnobs.o # miscellaneous OS-dependent stuff # linker LN= $(CC) # file deletion command RM= rm -f # library (.a) file creation command AR= ar rc # second step in .a creation (use "touch" if not needed) AR2= ranlib # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.o jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.o jcapistd.o jcarith.o jctrans.o jcparam.o \ jdatadst.o jcinit.o jcmaster.o jcmarker.o jcmainct.o jcprepct.o \ jccoefct.o jccolor.o jcsample.o jchuff.o jcdctmgr.o jfdctfst.o \ jfdctflt.o jfdctint.o # decompression library object files DLIBOBJECTS= jdapimin.o jdapistd.o jdarith.o jdtrans.o jdatasrc.o \ jdmaster.o jdinput.o jdmarker.o jdhuff.o jdmainct.o \ jdcoefct.o jdpostct.o jddctmgr.o jidctfst.o jidctflt.o \ jidctint.o jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o # These objectfiles are included in libjpeg.a LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \ cdjpeg.o DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \ cdjpeg.o TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o all: libjpeg.a cjpeg djpeg jpegtran rdjpgcom wrjpgcom libjpeg.a: $(LIBOBJECTS) $(RM) libjpeg.a $(AR) libjpeg.a $(LIBOBJECTS) $(AR2) libjpeg.a cjpeg: $(COBJECTS) libjpeg.a $(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.a $(LDLIBS) djpeg: $(DOBJECTS) libjpeg.a $(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.a $(LDLIBS) jpegtran: $(TROBJECTS) libjpeg.a $(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.a $(LDLIBS) rdjpgcom: rdjpgcom.o $(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.o $(LDLIBS) wrjpgcom: wrjpgcom.o $(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.o $(LDLIBS) jconfig.h: jconfig.txt echo You must prepare a system-dependent jconfig.h file. echo Please read the installation directions in install.txt. exit 1 clean: $(RM) *.o cjpeg djpeg jpegtran libjpeg.a rdjpgcom wrjpgcom $(RM) core testout* test: cjpeg djpeg jpegtran $(RM) testout* ./djpeg -dct int -ppm -outfile testout.ppm testorig.jpg ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg ./cjpeg -dct int -outfile testout.jpg testimg.ppm ./djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm ./jpegtran -outfile testoutt.jpg testprog.jpg cmp testimg.ppm testout.ppm cmp testimg.bmp testout.bmp cmp testimg.jpg testout.jpg cmp testimg.ppm testoutp.ppm cmp testimgp.jpg testoutp.jpg cmp testorig.jpg testoutt.jpg jaricom.o: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.o: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.o: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h ================================================ FILE: tess-two/jni/libjpeg/makefile.b32 ================================================ # Makefile for Independent JPEG Group's software # This makefile is suitable for Borland C on MS-DOS. # It works with Borland C++ 32-bit for DOS, revision 5.0 or later. # Thanks to Tom Wright and Ge' Weijers (original DOS) and # Joe Slater for adding 32-bit additions (needed for Borland # revision 5.5). # Read installation instructions before saying "make" !! # The name of your C compiler: CC= bcc32 # You may need to adjust these cc options: CFLAGS= -O2 -w-par -w-stu -w-ccc -w-rch -w-aus # -w-par suppresses warnings about unused function parameters # -w-stu suppresses warnings about incomplete structures # -w-ccc suppresses warnings about compile-time-constant conditions # -w-rch suppresses warnings about unreachable code # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via -D switches here. # Link-time cc options: LDFLAGS= # -lc case-significant link # Put here the object file name for the correct system-dependent memory # manager file. # SYSDEPMEMLIB must list the same files with "+" signs for the librarian. SYSDEPMEM= jmemnobs.obj SYSDEPMEMLIB= +jmemnobs.obj # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.obj jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.obj jcapistd.obj jcarith.obj jctrans.obj jcparam.obj \ jdatadst.obj jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj \ jcprepct.obj jccoefct.obj jccolor.obj jcsample.obj jchuff.obj \ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj # decompression library object files DLIBOBJECTS= jdapimin.obj jdapistd.obj jdarith.obj jdtrans.obj jdatasrc.obj \ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdmainct.obj \ jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj jidctflt.obj \ jidctint.obj jdsample.obj jdcolor.obj jquant1.obj jquant2.obj \ jdmerge.obj # These objectfiles are included in libjpeg.lib LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \ rdswitch.obj cdjpeg.obj DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \ rdcolmap.obj cdjpeg.obj TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe libjpeg.lib: $(LIBOBJECTS) - del libjpeg.lib tlib libjpeg.lib /E /C @&&| +jcapimin.obj +jcapistd.obj +jcarith.obj +jctrans.obj +jcparam.obj & +jdatadst.obj +jcinit.obj +jcmaster.obj +jcmarker.obj +jcmainct.obj & +jcprepct.obj +jccoefct.obj +jccolor.obj +jcsample.obj +jchuff.obj & +jcdctmgr.obj +jfdctfst.obj +jfdctflt.obj +jfdctint.obj +jdapimin.obj & +jdapistd.obj +jdarith.obj +jdtrans.obj +jdatasrc.obj +jdmaster.obj & +jdinput.obj +jdmarker.obj +jdhuff.obj +jdmainct.obj +jdcoefct.obj & +jdpostct.obj +jddctmgr.obj +jidctfst.obj +jidctflt.obj +jidctint.obj & +jdsample.obj +jdcolor.obj +jquant1.obj +jquant2.obj +jdmerge.obj & +jaricom.obj +jcomapi.obj +jutils.obj +jerror.obj +jmemmgr.obj & $(SYSDEPMEMLIB) | cjpeg.exe: $(COBJECTS) libjpeg.lib $(CC) $(LDFLAGS) -ecjpeg.exe $(COBJECTS) libjpeg.lib djpeg.exe: $(DOBJECTS) libjpeg.lib $(CC) $(LDFLAGS) -edjpeg.exe $(DOBJECTS) libjpeg.lib jpegtran.exe: $(TROBJECTS) libjpeg.lib $(CC) $(LDFLAGS) -ejpegtran.exe $(TROBJECTS) libjpeg.lib rdjpgcom.exe: rdjpgcom.c $(CC) $(CFLAGS) rdjpgcom.c wrjpgcom.exe: wrjpgcom.c $(CC) $(CFLAGS) wrjpgcom.c # This "{}" syntax allows Borland Make to "batch" source files. # In this way, each run of the compiler can build many modules. .c.obj: $(CC) $(CFLAGS) -c{ $<} jconfig.h: jconfig.txt echo You must prepare a system-dependent jconfig.h file. echo Please read the installation directions in install.txt. exit 1 clean: - del *.obj - del libjpeg.lib - del cjpeg.exe - del djpeg.exe - del jpegtran.exe - del rdjpgcom.exe - del wrjpgcom.exe - del testout*.* test: cjpeg.exe djpeg.exe jpegtran.exe - del testout*.* djpeg -dct int -ppm -outfile testout.ppm testorig.jpg djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg cjpeg -dct int -outfile testout.jpg testimg.ppm djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm jpegtran -outfile testoutt.jpg testprog.jpg echo n > n.tmp comp testimg.ppm testout.ppm < n.tmp comp testimg.bmp testout.bmp < n.tmp comp testimg.jpg testout.jpg < n.tmp comp testimg.ppm testoutp.ppm < n.tmp comp testimgp.jpg testoutp.jpg < n.tmp comp testorig.jpg testoutt.jpg < n.tmp del n.tmp jaricom.obj: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.obj: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.obj: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jmemdosa.obj: jmemdosa.asm tasm /mx jmemdosa.asm ================================================ FILE: tess-two/jni/libjpeg/makefile.bcc ================================================ # Makefile for Independent JPEG Group's software # This makefile is suitable for Borland C on MS-DOS or OS/2. # It works with Borland C++ for DOS, revision 3.0 or later, # and has been tested with Borland C++ for OS/2. # Watch out for optimization bugs in the OS/2 compilers --- see notes below! # Thanks to Tom Wright and Ge' Weijers (original DOS) and # Ken Porter (OS/2) for this file. # Read installation instructions before saying "make" !! # Are we under DOS or OS/2? !if !$d(DOS) && !$d(OS2) !if $d(__OS2__) OS2=1 !else DOS=1 !endif !endif # The name of your C compiler: CC= bcc # You may need to adjust these cc options: !if $d(DOS) CFLAGS= -O2 -mm -w-par -w-stu -w-ccc -w-rch !else CFLAGS= -O1 -w-par -w-stu -w-ccc -w-rch !endif # -O2 enables full code optimization (for pre-3.0 Borland C++, use -O -G -Z). # -O2 is buggy in Borland OS/2 C++ revision 2.0, so use -O1 there for now. # If you have Borland OS/2 C++ revision 1.0, use -O or no optimization at all. # -mm selects medium memory model (near data, far code pointers; DOS only!) # -w-par suppresses warnings about unused function parameters # -w-stu suppresses warnings about incomplete structures # -w-ccc suppresses warnings about compile-time-constant conditions # -w-rch suppresses warnings about unreachable code # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via -D switches here. # Link-time cc options: !if $d(DOS) LDFLAGS= -mm # memory model option here must match CFLAGS! !else LDFLAGS= # -lai full-screen app # -lc case-significant link !endif # Put here the object file name for the correct system-dependent memory # manager file. # For DOS, we recommend jmemdos.c and jmemdosa.asm. # For OS/2, we recommend jmemnobs.c (flat memory!) # SYSDEPMEMLIB must list the same files with "+" signs for the librarian. !if $d(DOS) SYSDEPMEM= jmemdos.obj jmemdosa.obj SYSDEPMEMLIB= +jmemdos.obj +jmemdosa.obj !else SYSDEPMEM= jmemnobs.obj SYSDEPMEMLIB= +jmemnobs.obj !endif # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.obj jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.obj jcapistd.obj jcarith.obj jctrans.obj jcparam.obj \ jdatadst.obj jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj \ jcprepct.obj jccoefct.obj jccolor.obj jcsample.obj jchuff.obj \ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj # decompression library object files DLIBOBJECTS= jdapimin.obj jdapistd.obj jdarith.obj jdtrans.obj jdatasrc.obj \ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdmainct.obj \ jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj jidctflt.obj \ jidctint.obj jdsample.obj jdcolor.obj jquant1.obj jquant2.obj \ jdmerge.obj # These objectfiles are included in libjpeg.lib LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \ rdswitch.obj cdjpeg.obj DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \ rdcolmap.obj cdjpeg.obj TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe libjpeg.lib: $(LIBOBJECTS) - del libjpeg.lib tlib libjpeg.lib /E /C @&&| +jcapimin.obj +jcapistd.obj +jcarith.obj +jctrans.obj +jcparam.obj & +jdatadst.obj +jcinit.obj +jcmaster.obj +jcmarker.obj +jcmainct.obj & +jcprepct.obj +jccoefct.obj +jccolor.obj +jcsample.obj +jchuff.obj & +jcdctmgr.obj +jfdctfst.obj +jfdctflt.obj +jfdctint.obj +jdapimin.obj & +jdapistd.obj +jdarith.obj +jdtrans.obj +jdatasrc.obj +jdmaster.obj & +jdinput.obj +jdmarker.obj +jdhuff.obj +jdmainct.obj +jdcoefct.obj & +jdpostct.obj +jddctmgr.obj +jidctfst.obj +jidctflt.obj +jidctint.obj & +jdsample.obj +jdcolor.obj +jquant1.obj +jquant2.obj +jdmerge.obj & +jaricom.obj +jcomapi.obj +jutils.obj +jerror.obj +jmemmgr.obj & $(SYSDEPMEMLIB) | cjpeg.exe: $(COBJECTS) libjpeg.lib $(CC) $(LDFLAGS) -ecjpeg.exe $(COBJECTS) libjpeg.lib djpeg.exe: $(DOBJECTS) libjpeg.lib $(CC) $(LDFLAGS) -edjpeg.exe $(DOBJECTS) libjpeg.lib jpegtran.exe: $(TROBJECTS) libjpeg.lib $(CC) $(LDFLAGS) -ejpegtran.exe $(TROBJECTS) libjpeg.lib rdjpgcom.exe: rdjpgcom.c !if $d(DOS) $(CC) -ms -O rdjpgcom.c !else $(CC) $(CFLAGS) rdjpgcom.c !endif # On DOS, wrjpgcom needs large model so it can malloc a 64K chunk wrjpgcom.exe: wrjpgcom.c !if $d(DOS) $(CC) -ml -O wrjpgcom.c !else $(CC) $(CFLAGS) wrjpgcom.c !endif # This "{}" syntax allows Borland Make to "batch" source files. # In this way, each run of the compiler can build many modules. .c.obj: $(CC) $(CFLAGS) -c{ $<} jconfig.h: jconfig.txt echo You must prepare a system-dependent jconfig.h file. echo Please read the installation directions in install.txt. exit 1 clean: - del *.obj - del libjpeg.lib - del cjpeg.exe - del djpeg.exe - del jpegtran.exe - del rdjpgcom.exe - del wrjpgcom.exe - del testout*.* test: cjpeg.exe djpeg.exe jpegtran.exe - del testout*.* djpeg -dct int -ppm -outfile testout.ppm testorig.jpg djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg cjpeg -dct int -outfile testout.jpg testimg.ppm djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm jpegtran -outfile testoutt.jpg testprog.jpg !if $d(DOS) fc /b testimg.ppm testout.ppm fc /b testimg.bmp testout.bmp fc /b testimg.jpg testout.jpg fc /b testimg.ppm testoutp.ppm fc /b testimgp.jpg testoutp.jpg fc /b testorig.jpg testoutt.jpg !else echo n > n.tmp comp testimg.ppm testout.ppm < n.tmp comp testimg.bmp testout.bmp < n.tmp comp testimg.jpg testout.jpg < n.tmp comp testimg.ppm testoutp.ppm < n.tmp comp testimgp.jpg testoutp.jpg < n.tmp comp testorig.jpg testoutt.jpg < n.tmp del n.tmp !endif jaricom.obj: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.obj: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.obj: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jmemdosa.obj: jmemdosa.asm tasm /mx jmemdosa.asm ================================================ FILE: tess-two/jni/libjpeg/makefile.dj ================================================ # Makefile for Independent JPEG Group's software # This makefile is for DJGPP (Delorie's GNU C port on MS-DOS), v2.0 or later. # Thanks to Frank J. Donahoe for this version. # Read installation instructions before saying "make" !! # The name of your C compiler: CC= gcc # You may need to adjust these cc options: CFLAGS= -O2 -Wall -I. # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via -D switches here. # Link-time cc options: LDFLAGS= -s # To link any special libraries, add the necessary -l commands here. LDLIBS= # Put here the object file name for the correct system-dependent memory # manager file. For DJGPP this is usually jmemnobs.o, but you could # use jmemname.o if you want to use named temp files instead of swap space. SYSDEPMEM= jmemnobs.o # miscellaneous OS-dependent stuff # linker LN= $(CC) # file deletion command RM= del # library (.a) file creation command AR= ar rc # second step in .a creation (use "touch" if not needed) AR2= ranlib # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.o jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.o jcapistd.o jcarith.o jctrans.o jcparam.o \ jdatadst.o jcinit.o jcmaster.o jcmarker.o jcmainct.o jcprepct.o \ jccoefct.o jccolor.o jcsample.o jchuff.o jcdctmgr.o jfdctfst.o \ jfdctflt.o jfdctint.o # decompression library object files DLIBOBJECTS= jdapimin.o jdapistd.o jdarith.o jdtrans.o jdatasrc.o \ jdmaster.o jdinput.o jdmarker.o jdhuff.o jdmainct.o \ jdcoefct.o jdpostct.o jddctmgr.o jidctfst.o jidctflt.o \ jidctint.o jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o # These objectfiles are included in libjpeg.a LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \ cdjpeg.o DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \ cdjpeg.o TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o all: libjpeg.a cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe libjpeg.a: $(LIBOBJECTS) $(RM) libjpeg.a $(AR) libjpeg.a $(LIBOBJECTS) $(AR2) libjpeg.a cjpeg.exe: $(COBJECTS) libjpeg.a $(LN) $(LDFLAGS) -o cjpeg.exe $(COBJECTS) libjpeg.a $(LDLIBS) djpeg.exe: $(DOBJECTS) libjpeg.a $(LN) $(LDFLAGS) -o djpeg.exe $(DOBJECTS) libjpeg.a $(LDLIBS) jpegtran.exe: $(TROBJECTS) libjpeg.a $(LN) $(LDFLAGS) -o jpegtran.exe $(TROBJECTS) libjpeg.a $(LDLIBS) rdjpgcom.exe: rdjpgcom.o $(LN) $(LDFLAGS) -o rdjpgcom.exe rdjpgcom.o $(LDLIBS) wrjpgcom.exe: wrjpgcom.o $(LN) $(LDFLAGS) -o wrjpgcom.exe wrjpgcom.o $(LDLIBS) jconfig.h: jconfig.txt echo You must prepare a system-dependent jconfig.h file. echo Please read the installation directions in install.txt. exit 1 clean: $(RM) *.o $(RM) cjpeg.exe $(RM) djpeg.exe $(RM) jpegtran.exe $(RM) rdjpgcom.exe $(RM) wrjpgcom.exe $(RM) libjpeg.a $(RM) testout*.* test: cjpeg.exe djpeg.exe jpegtran.exe $(RM) testout*.* ./djpeg -dct int -ppm -outfile testout.ppm testorig.jpg ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg ./cjpeg -dct int -outfile testout.jpg testimg.ppm ./djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm ./jpegtran -outfile testoutt.jpg testprog.jpg fc /b testimg.ppm testout.ppm fc /b testimg.bmp testout.bmp fc /b testimg.jpg testout.jpg fc /b testimg.ppm testoutp.ppm fc /b testimgp.jpg testoutp.jpg fc /b testorig.jpg testoutt.jpg jaricom.o: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.o: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.o: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h ================================================ FILE: tess-two/jni/libjpeg/makefile.manx ================================================ # Makefile for Independent JPEG Group's software # This makefile is for Amiga systems using Manx Aztec C ver 5.x. # Thanks to D.J. James (djjames@cup.portal.com) for this version. # Read installation instructions before saying "make" !! # The name of your C compiler: CC= cc # You may need to adjust these cc options: # Uncomment for generic 68000 code (will work on any Amiga) ARCHFLAGS= -sn # Uncomment for 68020/68030 code (faster, but won't run on 68000 CPU) #ARCHFLAGS= -c2 CFLAGS= -MC -MD $(ARCHFLAGS) -spfam -r4 # Link-time cc options: LDFLAGS= -g # To link any special libraries, add the necessary -l commands here. LDLIBS= -lml -lcl # Put here the object file name for the correct system-dependent memory # manager file. For Amiga we recommend jmemname.o. SYSDEPMEM= jmemname.o # miscellaneous OS-dependent stuff # linker LN= ln # file deletion command RM= delete quiet # library (.lib) file creation command AR= lb # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.o jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.o jcapistd.o jcarith.o jctrans.o jcparam.o \ jdatadst.o jcinit.o jcmaster.o jcmarker.o jcmainct.o jcprepct.o \ jccoefct.o jccolor.o jcsample.o jchuff.o jcdctmgr.o jfdctfst.o \ jfdctflt.o jfdctint.o # decompression library object files DLIBOBJECTS= jdapimin.o jdapistd.o jdarith.o jdtrans.o jdatasrc.o \ jdmaster.o jdinput.o jdmarker.o jdhuff.o jdmainct.o \ jdcoefct.o jdpostct.o jddctmgr.o jidctfst.o jidctflt.o \ jidctint.o jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o # These objectfiles are included in libjpeg.lib LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \ cdjpeg.o DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \ cdjpeg.o TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o all: libjpeg.lib cjpeg djpeg jpegtran rdjpgcom wrjpgcom libjpeg.lib: $(LIBOBJECTS) -$(RM) libjpeg.lib $(AR) libjpeg.lib $(LIBOBJECTS) cjpeg: $(COBJECTS) libjpeg.lib $(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.lib $(LDLIBS) djpeg: $(DOBJECTS) libjpeg.lib $(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.lib $(LDLIBS) jpegtran: $(TROBJECTS) libjpeg.lib $(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.lib $(LDLIBS) rdjpgcom: rdjpgcom.o $(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.o $(LDLIBS) wrjpgcom: wrjpgcom.o $(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.o $(LDLIBS) jconfig.h: jconfig.txt echo You must prepare a system-dependent jconfig.h file. echo Please read the installation directions in install.txt. exit 1 clean: -$(RM) *.o cjpeg djpeg jpegtran libjpeg.lib rdjpgcom wrjpgcom -$(RM) core testout*.* test: cjpeg djpeg jpegtran -$(RM) testout*.* djpeg -dct int -ppm -outfile testout.ppm testorig.jpg djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg cjpeg -dct int -outfile testout.jpg testimg.ppm djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm jpegtran -outfile testoutt.jpg testprog.jpg cmp testimg.ppm testout.ppm cmp testimg.bmp testout.bmp cmp testimg.jpg testout.jpg cmp testimg.ppm testoutp.ppm cmp testimgp.jpg testoutp.jpg cmp testorig.jpg testoutt.jpg jaricom.o: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.o: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.o: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h ================================================ FILE: tess-two/jni/libjpeg/makefile.mc6 ================================================ # Makefile for Independent JPEG Group's software # This makefile is for Microsoft C for MS-DOS, version 6.00A and up. # Use NMAKE, not Microsoft's brain-damaged MAKE. # Thanks to Alan Wright and Chris Turner of Olivetti Research Ltd. # Read installation instructions before saying "nmake" !! # You may need to adjust these compiler options: CFLAGS = -AM -Oecigt -Gs -W3 # -AM medium memory model (or use -AS for small model, if you remove features) # -Oecigt -Gs maximum safe optimisation (-Ol has bugs in MSC 6.00A) # -W3 warning level 3 # You might also want to add -G2 if you have an 80286, etc. # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via -D switches here. # Jan-Herman Buining suggests the following switches for MS C 8.0 and a 486: # CFLAGS = /AM /f- /FPi87 /G3 /Gs /Gy /Ob1 /Oc /Oe /Og /Oi /Ol /On /Oo /Ot \ # /OV4 /W3 # except for jquant1.c, which must be compiled with /Oo- to avoid a compiler # crash. # Ingar Steinsland suggests the following switches when building # a 16-bit Windows DLL: # CFLAGS = -ALw -Gsw -Zpe -W3 -O2 -Zi -Zd # Put here the object file name for the correct system-dependent memory # manager file. For DOS, we recommend jmemdos.c and jmemdosa.asm. # (But not for Windows; see install.txt if you use this makefile for Windows.) SYSDEPMEM= jmemdos.obj jmemdosa.obj # SYSDEPMEMLIB must list the same files with "+" signs for the librarian. SYSDEPMEMLIB= +jmemdos.obj +jmemdosa.obj # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.obj jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.obj jcapistd.obj jcarith.obj jctrans.obj jcparam.obj \ jdatadst.obj jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj \ jcprepct.obj jccoefct.obj jccolor.obj jcsample.obj jchuff.obj \ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj # decompression library object files DLIBOBJECTS= jdapimin.obj jdapistd.obj jdarith.obj jdtrans.obj jdatasrc.obj \ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdmainct.obj \ jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj jidctflt.obj \ jidctint.obj jdsample.obj jdcolor.obj jquant1.obj jquant2.obj \ jdmerge.obj # These objectfiles are included in libjpeg.lib LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \ rdswitch.obj cdjpeg.obj DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \ rdcolmap.obj cdjpeg.obj TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj # need linker response file because file list > 128 chars RFILE = libjpeg.ans all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe libjpeg.lib: $(LIBOBJECTS) $(RFILE) del libjpeg.lib lib @$(RFILE) # linker response file for building libjpeg.lib $(RFILE) : makefile del $(RFILE) echo libjpeg.lib >$(RFILE) # silly want-to-create-it prompt: echo y >>$(RFILE) echo +jcapimin.obj +jcapistd.obj +jcarith.obj +jctrans.obj & >>$(RFILE) echo +jcparam.obj +jdatadst.obj +jcinit.obj +jcmaster.obj & >>$(RFILE) echo +jcmarker.obj +jcmainct.obj +jcprepct.obj & >>$(RFILE) echo +jccoefct.obj +jccolor.obj +jcsample.obj +jchuff.obj & >>$(RFILE) echo +jcdctmgr.obj +jfdctfst.obj +jfdctflt.obj & >>$(RFILE) echo +jfdctint.obj +jdapimin.obj +jdapistd.obj & >>$(RFILE) echo +jdarith.obj +jdtrans.obj +jdatasrc.obj +jdmaster.obj & >>$(RFILE) echo +jdinput.obj +jdmarker.obj +jdhuff.obj +jdmainct.obj & >>$(RFILE) echo +jdcoefct.obj +jdpostct.obj +jddctmgr.obj & >>$(RFILE) echo +jidctfst.obj +jidctflt.obj +jidctint.obj & >>$(RFILE) echo +jdsample.obj +jdcolor.obj +jquant1.obj & >>$(RFILE) echo +jquant2.obj +jdmerge.obj +jaricom.obj +jcomapi.obj & >>$(RFILE) echo +jutils.obj +jerror.obj +jmemmgr.obj & >>$(RFILE) echo $(SYSDEPMEMLIB) ; >>$(RFILE) cjpeg.exe: $(COBJECTS) libjpeg.lib echo $(COBJECTS) >cjpeg.lst link /STACK:4096 /EXEPACK @cjpeg.lst, cjpeg.exe, , libjpeg.lib, ; del cjpeg.lst djpeg.exe: $(DOBJECTS) libjpeg.lib echo $(DOBJECTS) >djpeg.lst link /STACK:4096 /EXEPACK @djpeg.lst, djpeg.exe, , libjpeg.lib, ; del djpeg.lst jpegtran.exe: $(TROBJECTS) libjpeg.lib link /STACK:4096 /EXEPACK $(TROBJECTS), jpegtran.exe, , libjpeg.lib, ; rdjpgcom.exe: rdjpgcom.c $(CC) -AS -O -W3 rdjpgcom.c # wrjpgcom needs large model so it can malloc a 64K chunk wrjpgcom.exe: wrjpgcom.c $(CC) -AL -O -W3 wrjpgcom.c jconfig.h: jconfig.txt echo You must prepare a system-dependent jconfig.h file. echo Please read the installation directions in install.txt. exit 1 clean: del *.obj del libjpeg.lib del cjpeg.exe del djpeg.exe del jpegtran.exe del rdjpgcom.exe del wrjpgcom.exe del testout*.* test: cjpeg.exe djpeg.exe jpegtran.exe del testout*.* djpeg -dct int -ppm -outfile testout.ppm testorig.jpg djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg cjpeg -dct int -outfile testout.jpg testimg.ppm djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm jpegtran -outfile testoutt.jpg testprog.jpg fc /b testimg.ppm testout.ppm fc /b testimg.bmp testout.bmp fc /b testimg.jpg testout.jpg fc /b testimg.ppm testoutp.ppm fc /b testimgp.jpg testoutp.jpg fc /b testorig.jpg testoutt.jpg jaricom.obj: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.obj: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.obj: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jmemdosa.obj : jmemdosa.asm masm /mx $*; ================================================ FILE: tess-two/jni/libjpeg/makefile.mms ================================================ # Makefile for Independent JPEG Group's software # This makefile is for use with MMS on Digital VMS systems. # Thanks to Rick Dyson (dyson@iowasp.physics.uiowa.edu) # and Tim Bell (tbell@netcom.com) for their help. # Read installation instructions before saying "MMS" !! # You may need to adjust these cc options: CFLAGS= $(CFLAGS) /NoDebug /Optimize # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via /Define switches here. .ifdef ALPHA OPT= .else OPT= ,Sys$Disk:[]MAKVMS.OPT/Option .endif # Put here the object file name for the correct system-dependent memory # manager file. For Unix this is usually jmemnobs.o, but you may want # to use jmemansi.o or jmemname.o if you have limited swap space. SYSDEPMEM= jmemnobs.obj # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.obj jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.obj jcapistd.obj jcarith.obj jctrans.obj jcparam.obj \ jdatadst.obj jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj \ jcprepct.obj jccoefct.obj jccolor.obj jcsample.obj jchuff.obj \ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj # decompression library object files DLIBOBJECTS= jdapimin.obj jdapistd.obj jdarith.obj jdtrans.obj jdatasrc.obj \ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdmainct.obj \ jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj jidctflt.obj \ jidctint.obj jdsample.obj jdcolor.obj jquant1.obj jquant2.obj \ jdmerge.obj # These objectfiles are included in libjpeg.olb LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \ rdswitch.obj cdjpeg.obj DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \ rdcolmap.obj cdjpeg.obj TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj # objectfile lists with commas --- what a crock COBJLIST= cjpeg.obj,rdppm.obj,rdgif.obj,rdtarga.obj,rdrle.obj,rdbmp.obj,\ rdswitch.obj,cdjpeg.obj DOBJLIST= djpeg.obj,wrppm.obj,wrgif.obj,wrtarga.obj,wrrle.obj,wrbmp.obj,\ rdcolmap.obj,cdjpeg.obj TROBJLIST= jpegtran.obj,rdswitch.obj,cdjpeg.obj,transupp.obj LIBOBJLIST= jaricom.obj,jcapimin.obj,jcapistd.obj,jcarith.obj,jctrans.obj,\ jcparam.obj,jdatadst.obj,jcinit.obj,jcmaster.obj,jcmarker.obj,\ jcmainct.obj,jcprepct.obj,jccoefct.obj,jccolor.obj,jcsample.obj,\ jchuff.obj,jcdctmgr.obj,jfdctfst.obj,jfdctflt.obj,jfdctint.obj,\ jdapimin.obj,jdapistd.obj,jdarith.obj,jdtrans.obj,jdatasrc.obj,\ jdmaster.obj,jdinput.obj,jdmarker.obj,jdhuff.obj,jdmainct.obj,\ jdcoefct.obj,jdpostct.obj,jddctmgr.obj,jidctfst.obj,jidctflt.obj,\ jidctint.obj,jdsample.obj,jdcolor.obj,jquant1.obj,jquant2.obj,\ jdmerge.obj,jcomapi.obj,jutils.obj,jerror.obj,jmemmgr.obj,$(SYSDEPMEM) .first @- Define /NoLog Sys Sys$Library ALL : libjpeg.olb cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe @ Continue libjpeg.olb : $(LIBOBJECTS) Library /Create libjpeg.olb $(LIBOBJLIST) cjpeg.exe : $(COBJECTS) libjpeg.olb $(LINK) $(LFLAGS) /Executable = cjpeg.exe $(COBJLIST),libjpeg.olb/Library$(OPT) djpeg.exe : $(DOBJECTS) libjpeg.olb $(LINK) $(LFLAGS) /Executable = djpeg.exe $(DOBJLIST),libjpeg.olb/Library$(OPT) jpegtran.exe : $(TROBJECTS) libjpeg.olb $(LINK) $(LFLAGS) /Executable = jpegtran.exe $(TROBJLIST),libjpeg.olb/Library$(OPT) rdjpgcom.exe : rdjpgcom.obj $(LINK) $(LFLAGS) /Executable = rdjpgcom.exe rdjpgcom.obj$(OPT) wrjpgcom.exe : wrjpgcom.obj $(LINK) $(LFLAGS) /Executable = wrjpgcom.exe wrjpgcom.obj$(OPT) jconfig.h : jconfig.vms @- Copy jconfig.vms jconfig.h clean : @- Set Protection = Owner:RWED *.*;-1 @- Set Protection = Owner:RWED *.OBJ - Purge /NoLog /NoConfirm *.* - Delete /NoLog /NoConfirm *.OBJ; test : cjpeg.exe djpeg.exe jpegtran.exe mcr sys$disk:[]djpeg -dct int -ppm -outfile testout.ppm testorig.jpg mcr sys$disk:[]djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg mcr sys$disk:[]cjpeg -dct int -outfile testout.jpg testimg.ppm mcr sys$disk:[]djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg mcr sys$disk:[]cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm mcr sys$disk:[]jpegtran -outfile testoutt.jpg testprog.jpg - Backup /Compare/Log testimg.ppm testout.ppm - Backup /Compare/Log testimg.bmp testout.bmp - Backup /Compare/Log testimg.jpg testout.jpg - Backup /Compare/Log testimg.ppm testoutp.ppm - Backup /Compare/Log testimgp.jpg testoutp.jpg - Backup /Compare/Log testorig.jpg testoutt.jpg jaricom.obj : jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.obj : jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.obj : jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.obj : jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.obj : jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.obj : jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.obj : jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.obj : jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.obj : jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.obj : jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.obj : jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.obj : jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.obj : jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.obj : jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.obj : jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.obj : jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.obj : jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.obj : jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.obj : jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.obj : jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.obj : jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.obj : jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.obj : jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.obj : jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.obj : jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.obj : jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.obj : jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.obj : jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.obj : jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.obj : jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.obj : jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.obj : jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.obj : jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.obj : jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.obj : jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.obj : jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.obj : jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.obj : jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.obj : jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.obj : jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.obj : jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.obj : jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.obj : jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.obj : jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.obj : jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.obj : jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.obj : jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.obj : jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.obj : jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.obj : jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.obj : cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.obj : djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.obj : jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.obj : rdjpgcom.c jinclude.h jconfig.h wrjpgcom.obj : wrjpgcom.c jinclude.h jconfig.h cdjpeg.obj : cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.obj : rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.obj : rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.obj : transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.obj : rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.obj : wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.obj : rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.obj : wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.obj : rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.obj : wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.obj : rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.obj : wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.obj : rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.obj : wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h ================================================ FILE: tess-two/jni/libjpeg/makefile.sas ================================================ # Makefile for Independent JPEG Group's software # This makefile is for Amiga systems using SAS C 6.0 and up. # Thanks to Ed Hanway, Mark Rinfret, and Jim Zepeda. # Read installation instructions before saying "make" !! # The name of your C compiler: CC= sc # You may need to adjust these cc options: # Uncomment the following lines for generic 680x0 version ARCHFLAGS= cpu=any SUFFIX= # Uncomment the following lines for 68030-only version #ARCHFLAGS= cpu=68030 #SUFFIX=.030 CFLAGS= nostackcheck data=near parms=register optimize $(ARCHFLAGS) \ ignore=104 ignore=304 ignore=306 # ignore=104 disables warnings for mismatched const qualifiers # ignore=304 disables warnings for variables being optimized out # ignore=306 disables warnings for the inlining of functions # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via define switches here. # Link-time cc options: LDFLAGS= SC SD ND BATCH # To link any special libraries, add the necessary commands here. LDLIBS= LIB:scm.lib LIB:sc.lib # Put here the object file name for the correct system-dependent memory # manager file. For Amiga we recommend jmemname.o. SYSDEPMEM= jmemname.o # miscellaneous OS-dependent stuff # linker LN= slink # file deletion command RM= delete quiet # library (.lib) file creation command AR= oml # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.o jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.o jcapistd.o jcarith.o jctrans.o jcparam.o \ jdatadst.o jcinit.o jcmaster.o jcmarker.o jcmainct.o jcprepct.o \ jccoefct.o jccolor.o jcsample.o jchuff.o jcdctmgr.o jfdctfst.o \ jfdctflt.o jfdctint.o # decompression library object files DLIBOBJECTS= jdapimin.o jdapistd.o jdarith.o jdtrans.o jdatasrc.o \ jdmaster.o jdinput.o jdmarker.o jdhuff.o jdmainct.o \ jdcoefct.o jdpostct.o jddctmgr.o jidctfst.o jidctflt.o \ jidctint.o jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o # These objectfiles are included in libjpeg.lib LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \ cdjpeg.o DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \ cdjpeg.o TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o all: libjpeg.lib cjpeg$(SUFFIX) djpeg$(SUFFIX) jpegtran$(SUFFIX) rdjpgcom$(SUFFIX) wrjpgcom$(SUFFIX) # note: do several AR steps to avoid command line length limitations libjpeg.lib: $(LIBOBJECTS) -$(RM) libjpeg.lib $(AR) libjpeg.lib r $(CLIBOBJECTS) $(AR) libjpeg.lib r $(DLIBOBJECTS) $(AR) libjpeg.lib r $(COMOBJECTS) cjpeg$(SUFFIX): $(COBJECTS) libjpeg.lib $(LN) # You may want to adjust these compiler options: CFLAGS= $(cflags) $(cdebug) $(cvars) -I. # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via -D switches here. # Link-time options: LDFLAGS= $(ldebug) $(conlflags) # To link any special libraries, add the necessary commands here. LDLIBS= $(conlibs) # Put here the object file name for the correct system-dependent memory # manager file. For NT we suggest jmemnobs.obj, which expects the OS to # provide adequate virtual memory. SYSDEPMEM= jmemnobs.obj # miscellaneous OS-dependent stuff # file deletion command RM= del # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \ jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \ wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \ coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 \ makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc \ makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 \ makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 \ makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 \ makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 \ makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 \ makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 \ makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac \ makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx \ makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \ jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp \ missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \ testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.obj jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.obj jcapistd.obj jcarith.obj jctrans.obj jcparam.obj \ jdatadst.obj jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj \ jcprepct.obj jccoefct.obj jccolor.obj jcsample.obj jchuff.obj \ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj # decompression library object files DLIBOBJECTS= jdapimin.obj jdapistd.obj jdarith.obj jdtrans.obj jdatasrc.obj \ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdmainct.obj \ jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj jidctflt.obj \ jidctint.obj jdsample.obj jdcolor.obj jquant1.obj jquant2.obj \ jdmerge.obj # These objectfiles are included in libjpeg.lib LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \ rdswitch.obj cdjpeg.obj DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \ rdcolmap.obj cdjpeg.obj TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj # Template command for compiling .c to .obj .c.obj: $(cc) $(CFLAGS) $*.c all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe libjpeg.lib: $(LIBOBJECTS) $(RM) libjpeg.lib lib -out:libjpeg.lib $(LIBOBJECTS) cjpeg.exe: $(COBJECTS) libjpeg.lib $(link) $(LDFLAGS) -out:cjpeg.exe $(COBJECTS) libjpeg.lib $(LDLIBS) djpeg.exe: $(DOBJECTS) libjpeg.lib $(link) $(LDFLAGS) -out:djpeg.exe $(DOBJECTS) libjpeg.lib $(LDLIBS) jpegtran.exe: $(TROBJECTS) libjpeg.lib $(link) $(LDFLAGS) -out:jpegtran.exe $(TROBJECTS) libjpeg.lib $(LDLIBS) rdjpgcom.exe: rdjpgcom.obj $(link) $(LDFLAGS) -out:rdjpgcom.exe rdjpgcom.obj $(LDLIBS) wrjpgcom.exe: wrjpgcom.obj $(link) $(LDFLAGS) -out:wrjpgcom.exe wrjpgcom.obj $(LDLIBS) clean: $(RM) *.obj *.exe libjpeg.lib $(RM) testout* setup-vc6: ren jconfig.vc jconfig.h ren makejdsw.vc6 jpeg.dsw ren makeadsw.vc6 apps.dsw ren makejmak.vc6 jpeg.mak ren makejdep.vc6 jpeg.dep ren makejdsp.vc6 jpeg.dsp ren makecmak.vc6 cjpeg.mak ren makecdep.vc6 cjpeg.dep ren makecdsp.vc6 cjpeg.dsp ren makedmak.vc6 djpeg.mak ren makeddep.vc6 djpeg.dep ren makeddsp.vc6 djpeg.dsp ren maketmak.vc6 jpegtran.mak ren maketdep.vc6 jpegtran.dep ren maketdsp.vc6 jpegtran.dsp ren makermak.vc6 rdjpgcom.mak ren makerdep.vc6 rdjpgcom.dep ren makerdsp.vc6 rdjpgcom.dsp ren makewmak.vc6 wrjpgcom.mak ren makewdep.vc6 wrjpgcom.dep ren makewdsp.vc6 wrjpgcom.dsp setup-v10: ren jconfig.vc jconfig.h ren makejsln.v10 jpeg.sln ren makeasln.v10 apps.sln ren makejvcx.v10 jpeg.vcxproj ren makejfil.v10 jpeg.vcxproj.filters ren makecvcx.v10 cjpeg.vcxproj ren makecfil.v10 cjpeg.vcxproj.filters ren makedvcx.v10 djpeg.vcxproj ren makedfil.v10 djpeg.vcxproj.filters ren maketvcx.v10 jpegtran.vcxproj ren maketfil.v10 jpegtran.vcxproj.filters ren makervcx.v10 rdjpgcom.vcxproj ren makerfil.v10 rdjpgcom.vcxproj.filters ren makewvcx.v10 wrjpgcom.vcxproj ren makewfil.v10 wrjpgcom.vcxproj.filters test: IF EXIST testout* $(RM) testout* .\djpeg -dct int -ppm -outfile testout.ppm testorig.jpg .\djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg .\cjpeg -dct int -outfile testout.jpg testimg.ppm .\djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg .\cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm .\jpegtran -outfile testoutt.jpg testprog.jpg fc /b testimg.ppm testout.ppm fc /b testimg.bmp testout.bmp fc /b testimg.jpg testout.jpg fc /b testimg.ppm testoutp.ppm fc /b testimgp.jpg testoutp.jpg fc /b testorig.jpg testoutt.jpg test-build: IF EXIST testout* $(RM) testout* .\djpeg\Release\djpeg -dct int -ppm -outfile testout.ppm testorig.jpg .\djpeg\Release\djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg .\cjpeg\Release\cjpeg -dct int -outfile testout.jpg testimg.ppm .\djpeg\Release\djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg .\cjpeg\Release\cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm .\jpegtran\Release\jpegtran -outfile testoutt.jpg testprog.jpg fc /b testimg.ppm testout.ppm fc /b testimg.bmp testout.bmp fc /b testimg.jpg testout.jpg fc /b testimg.ppm testoutp.ppm fc /b testimgp.jpg testoutp.jpg fc /b testorig.jpg testoutt.jpg jaricom.obj: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.obj: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.obj: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h ================================================ FILE: tess-two/jni/libjpeg/makefile.vms ================================================ $! Makefile for Independent JPEG Group's software $! $! This is a command procedure for Digital VMS systems that do not have MMS. $! It builds the JPEG software by brute force, recompiling everything whether $! or not it is necessary. It then runs the basic self-test. $! Thanks to Rick Dyson (dyson@iowasp.physics.uiowa.edu) $! and Tim Bell (tbell@netcom.com) for their help. $! $! Read installation instructions before running this!! $! $ If F$Mode () .eqs. "INTERACTIVE" $ Then $ VERIFY = F$Verify (0) $ Else $ VERIFY = F$Verify (1) $ EndIf $ On Control_Y Then GoTo End $ On Error Then GoTo End $ $ If F$GetSyi ("HW_MODEL") .gt. 1023 $ Then $ OPT = "" $ Else $ OPT = ",Sys$Disk:[]makvms.opt/Option" $ EndIf $ $ DoCompile := CC /NoDebug /Optimize /NoList $! $ DoCompile jaricom.c $ DoCompile jcapimin.c $ DoCompile jcapistd.c $ DoCompile jcarith.c $ DoCompile jctrans.c $ DoCompile jcparam.c $ DoCompile jdatadst.c $ DoCompile jcinit.c $ DoCompile jcmaster.c $ DoCompile jcmarker.c $ DoCompile jcmainct.c $ DoCompile jcprepct.c $ DoCompile jccoefct.c $ DoCompile jccolor.c $ DoCompile jcsample.c $ DoCompile jchuff.c $ DoCompile jcdctmgr.c $ DoCompile jfdctfst.c $ DoCompile jfdctflt.c $ DoCompile jfdctint.c $ DoCompile jdapimin.c $ DoCompile jdapistd.c $ DoCompile jdarith.c $ DoCompile jdtrans.c $ DoCompile jdatasrc.c $ DoCompile jdmaster.c $ DoCompile jdinput.c $ DoCompile jdmarker.c $ DoCompile jdhuff.c $ DoCompile jdmainct.c $ DoCompile jdcoefct.c $ DoCompile jdpostct.c $ DoCompile jddctmgr.c $ DoCompile jidctfst.c $ DoCompile jidctflt.c $ DoCompile jidctint.c $ DoCompile jdsample.c $ DoCompile jdcolor.c $ DoCompile jquant1.c $ DoCompile jquant2.c $ DoCompile jdmerge.c $ DoCompile jcomapi.c $ DoCompile jutils.c $ DoCompile jerror.c $ DoCompile jmemmgr.c $ DoCompile jmemnobs.c $! $ Library /Create libjpeg.olb jaricom.obj,jcapimin.obj,jcapistd.obj, - jcarith.obj,jctrans.obj,jcparam.obj,jdatadst.obj,jcinit.obj, - jcmaster.obj,jcmarker.obj,jcmainct.obj,jcprepct.obj,jccoefct.obj, - jccolor.obj,jcsample.obj,jchuff.obj,jcdctmgr.obj,jfdctfst.obj, - jfdctflt.obj,jfdctint.obj,jdapimin.obj,jdapistd.obj,jdarith.obj, - jdtrans.obj,jdatasrc.obj,jdmaster.obj,jdinput.obj,jdmarker.obj, - jdhuff.obj,jdmainct.obj,jdcoefct.obj,jdpostct.obj,jddctmgr.obj, - jidctfst.obj,jidctflt.obj,jidctint.obj,jdsample.obj,jdcolor.obj, - jquant1.obj,jquant2.obj,jdmerge.obj,jcomapi.obj,jutils.obj, - jerror.obj,jmemmgr.obj,jmemnobs.obj $! $ DoCompile cjpeg.c $ DoCompile rdppm.c $ DoCompile rdgif.c $ DoCompile rdtarga.c $ DoCompile rdrle.c $ DoCompile rdbmp.c $ DoCompile rdswitch.c $ DoCompile cdjpeg.c $! $ Link /NoMap /Executable = cjpeg.exe cjpeg.obj,rdppm.obj,rdgif.obj, - rdtarga.obj,rdrle.obj,rdbmp.obj,rdswitch.obj,cdjpeg.obj,libjpeg.olb/Library'OPT' $! $ DoCompile djpeg.c $ DoCompile wrppm.c $ DoCompile wrgif.c $ DoCompile wrtarga.c $ DoCompile wrrle.c $ DoCompile wrbmp.c $ DoCompile rdcolmap.c $ DoCompile cdjpeg.c $! $ Link /NoMap /Executable = djpeg.exe djpeg.obj,wrppm.obj,wrgif.obj, - wrtarga.obj,wrrle.obj,wrbmp.obj,rdcolmap.obj,cdjpeg.obj,libjpeg.olb/Library'OPT' $! $ DoCompile jpegtran.c $ DoCompile rdswitch.c $ DoCompile cdjpeg.c $ DoCompile transupp.c $! $ Link /NoMap /Executable = jpegtran.exe jpegtran.obj,rdswitch.obj, - cdjpeg.obj,transupp.obj,libjpeg.olb/Library'OPT' $! $ DoCompile rdjpgcom.c $ Link /NoMap /Executable = rdjpgcom.exe rdjpgcom.obj'OPT' $! $ DoCompile wrjpgcom.c $ Link /NoMap /Executable = wrjpgcom.exe wrjpgcom.obj'OPT' $! $! Run the self-test $! $ mcr sys$disk:[]djpeg -dct int -ppm -outfile testout.ppm testorig.jpg $ mcr sys$disk:[]djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg $ mcr sys$disk:[]cjpeg -dct int -outfile testout.jpg testimg.ppm $ mcr sys$disk:[]djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg $ mcr sys$disk:[]cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm $ mcr sys$disk:[]jpegtran -outfile testoutt.jpg testprog.jpg $ Backup /Compare/Log testimg.ppm testout.ppm $ Backup /Compare/Log testimg.bmp testout.bmp $ Backup /Compare/Log testimg.jpg testout.jpg $ Backup /Compare/Log testimg.ppm testoutp.ppm $ Backup /Compare/Log testimgp.jpg testoutp.jpg $ Backup /Compare/Log testorig.jpg testoutt.jpg $! $End: $ If Verify Then Set Verify $ Exit ================================================ FILE: tess-two/jni/libjpeg/makefile.wat ================================================ # Makefile for Independent JPEG Group's software # This makefile is suitable for Watcom C/C++ 10.0 on MS-DOS (using # dos4g extender), OS/2, and Windows NT console mode. # Thanks to Janos Haide, jhaide@btrvtech.com. # Read installation instructions before saying "wmake" !! # Uncomment line for desired system SYSTEM=DOS #SYSTEM=OS2 #SYSTEM=NT # The name of your C compiler: CC= wcl386 # You may need to adjust these cc options: CFLAGS= -4r -ort -wx -zq -bt=$(SYSTEM) # Caution: avoid -ol or -ox; these generate bad code with 10.0 or 10.0a. # Generally, we recommend defining any configuration symbols in jconfig.h, # NOT via -D switches here. # Link-time cc options: !ifeq SYSTEM DOS LDFLAGS= -zq -l=dos4g !else ifeq SYSTEM OS2 LDFLAGS= -zq -l=os2v2 !else ifeq SYSTEM NT LDFLAGS= -zq -l=nt !endif # Put here the object file name for the correct system-dependent memory # manager file. jmemnobs should work fine for dos4g or OS/2 environment. SYSDEPMEM= jmemnobs.obj # End of configurable options. # source files: JPEG library proper LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c & jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c & jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c & jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c & jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c & jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c & jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c & jquant2.c jutils.c jmemmgr.c # memmgr back ends: compile only one of these into a working library SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c & rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c & rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) # files included by source files INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h & jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h # documentation, test, and support files DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 & wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt & coderules.txt filelist.txt change.log MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.b32 & makefile.bcc makefile.mc6 makefile.dj makefile.wat makefile.vc & makejdsw.vc6 makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 & makecdep.vc6 makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 & makedmak.vc6 maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 & makerdsp.vc6 makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 & makejsln.v10 makeasln.v10 makejvcx.v10 makejfil.v10 makecvcx.v10 & makecfil.v10 makedvcx.v10 makedfil.v10 maketvcx.v10 maketfil.v10 & makervcx.v10 makerfil.v10 makewvcx.v10 makewfil.v10 makeproj.mac & makcjpeg.st makdjpeg.st makljpeg.st maktjpeg.st makefile.manx & makefile.sas makefile.mms makefile.vms makvms.opt CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat & jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas & jconfig.vms CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp & missing ar-lib OTHERFILES= jconfig.txt ckconfig.c jmemdosa.asm libjpeg.map TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg & testimgp.jpg DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) & $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES) # library object files common to compression and decompression COMOBJECTS= jaricom.obj jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM) # compression library object files CLIBOBJECTS= jcapimin.obj jcapistd.obj jcarith.obj jctrans.obj jcparam.obj & jdatadst.obj jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj & jcprepct.obj jccoefct.obj jccolor.obj jcsample.obj jchuff.obj & jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj # decompression library object files DLIBOBJECTS= jdapimin.obj jdapistd.obj jdarith.obj jdtrans.obj jdatasrc.obj & jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdmainct.obj & jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj jidctflt.obj & jidctint.obj jdsample.obj jdcolor.obj jquant1.obj jquant2.obj & jdmerge.obj # These objectfiles are included in libjpeg.lib LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) # object files for sample applications (excluding library files) COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj & rdswitch.obj cdjpeg.obj DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj & rdcolmap.obj cdjpeg.obj TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe libjpeg.lib: $(LIBOBJECTS) - del libjpeg.lib * wlib -n libjpeg.lib $(LIBOBJECTS) cjpeg.exe: $(COBJECTS) libjpeg.lib $(CC) $(LDFLAGS) $(COBJECTS) libjpeg.lib djpeg.exe: $(DOBJECTS) libjpeg.lib $(CC) $(LDFLAGS) $(DOBJECTS) libjpeg.lib jpegtran.exe: $(TROBJECTS) libjpeg.lib $(CC) $(LDFLAGS) $(TROBJECTS) libjpeg.lib rdjpgcom.exe: rdjpgcom.c $(CC) $(CFLAGS) $(LDFLAGS) rdjpgcom.c wrjpgcom.exe: wrjpgcom.c $(CC) $(CFLAGS) $(LDFLAGS) wrjpgcom.c .c.obj: $(CC) $(CFLAGS) -c $< jconfig.h: jconfig.txt echo You must prepare a system-dependent jconfig.h file. echo Please read the installation directions in install.txt. exit 1 clean: .SYMBOLIC - del *.obj - del libjpeg.lib - del cjpeg.exe - del djpeg.exe - del jpegtran.exe - del rdjpgcom.exe - del wrjpgcom.exe - del testout*.* test: cjpeg.exe djpeg.exe jpegtran.exe .SYMBOLIC - del testout*.* djpeg -dct int -ppm -outfile testout.ppm testorig.jpg djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg cjpeg -dct int -outfile testout.jpg testimg.ppm djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm jpegtran -outfile testoutt.jpg testprog.jpg !ifeq SYSTEM DOS fc /b testimg.ppm testout.ppm fc /b testimg.bmp testout.bmp fc /b testimg.jpg testout.jpg fc /b testimg.ppm testoutp.ppm fc /b testimgp.jpg testoutp.jpg fc /b testorig.jpg testoutt.jpg !else echo n > n.tmp comp testimg.ppm testout.ppm < n.tmp comp testimg.bmp testout.bmp < n.tmp comp testimg.jpg testout.jpg < n.tmp comp testimg.ppm testoutp.ppm < n.tmp comp testimgp.jpg testoutp.jpg < n.tmp comp testorig.jpg testoutt.jpg < n.tmp del n.tmp !endif jaricom.obj: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcarith.obj: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdarith.obj: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h ================================================ FILE: tess-two/jni/libjpeg/makejdep.vc6 ================================================ # Microsoft Developer Studio erstellte Abhngigkeitsdatei, einbezogen von jpeg.mak .\jaricom.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcapimin.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcapistd.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcarith.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jccoefct.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jccolor.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcdctmgr.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jchuff.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcinit.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcmainct.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcmarker.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcmaster.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcomapi.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcparam.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcprepct.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jcsample.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jctrans.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdapimin.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdapistd.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdarith.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdatadst.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\jdatasrc.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\jdcoefct.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdcolor.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jddctmgr.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdhuff.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdinput.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdmainct.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdmarker.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdmaster.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdmerge.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdpostct.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdsample.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jdtrans.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jerror.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ ".\jversion.h"\ .\jfdctflt.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jfdctfst.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jfdctint.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jidctflt.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jidctfst.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jidctint.c : \ ".\jconfig.h"\ ".\jdct.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jmemmgr.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmemsys.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jmemnobs.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmemsys.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jquant1.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jquant2.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ .\jutils.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ ================================================ FILE: tess-two/jni/libjpeg/makejdsp.vc6 ================================================ # Microsoft Developer Studio Project File - Name="jpeg" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** NICHT BEARBEITEN ** # TARGTYPE "Win32 (x86) Static Library" 0x0104 CFG=jpeg - Win32 !MESSAGE Dies ist kein gltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE !MESSAGE verwenden Sie den Befehl "Makefile exportieren" und fhren Sie den Befehl !MESSAGE !MESSAGE NMAKE /f "jpeg.mak". !MESSAGE !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "jpeg.mak" CFG="jpeg - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "jpeg - Win32" (basierend auf "Win32 (x86) Static Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir ".\Release" # PROP BASE Intermediate_Dir ".\Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir ".\Release" # PROP Intermediate_Dir ".\Release" # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c # ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c # ADD BASE RSC /l 0x407 # ADD RSC /l 0x407 BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LIB32=link.exe -lib # ADD BASE LIB32 /nologo # ADD LIB32 /nologo # Begin Target # Name "jpeg - Win32" # Begin Group "Quellcodedateien" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;for;f90" # Begin Source File SOURCE=.\jaricom.c # End Source File # Begin Source File SOURCE=.\jcapimin.c # End Source File # Begin Source File SOURCE=.\jcapistd.c # End Source File # Begin Source File SOURCE=.\jcarith.c # End Source File # Begin Source File SOURCE=.\jccoefct.c # End Source File # Begin Source File SOURCE=.\jccolor.c # End Source File # Begin Source File SOURCE=.\jcdctmgr.c # End Source File # Begin Source File SOURCE=.\jchuff.c # End Source File # Begin Source File SOURCE=.\jcinit.c # End Source File # Begin Source File SOURCE=.\jcmainct.c # End Source File # Begin Source File SOURCE=.\jcmarker.c # End Source File # Begin Source File SOURCE=.\jcmaster.c # End Source File # Begin Source File SOURCE=.\jcomapi.c # End Source File # Begin Source File SOURCE=.\jcparam.c # End Source File # Begin Source File SOURCE=.\jcprepct.c # End Source File # Begin Source File SOURCE=.\jcsample.c # End Source File # Begin Source File SOURCE=.\jctrans.c # End Source File # Begin Source File SOURCE=.\jdapimin.c # End Source File # Begin Source File SOURCE=.\jdapistd.c # End Source File # Begin Source File SOURCE=.\jdarith.c # End Source File # Begin Source File SOURCE=.\jdatadst.c # End Source File # Begin Source File SOURCE=.\jdatasrc.c # End Source File # Begin Source File SOURCE=.\jdcoefct.c # End Source File # Begin Source File SOURCE=.\jdcolor.c # End Source File # Begin Source File SOURCE=.\jddctmgr.c # End Source File # Begin Source File SOURCE=.\jdhuff.c # End Source File # Begin Source File SOURCE=.\jdinput.c # End Source File # Begin Source File SOURCE=.\jdmainct.c # End Source File # Begin Source File SOURCE=.\jdmarker.c # End Source File # Begin Source File SOURCE=.\jdmaster.c # End Source File # Begin Source File SOURCE=.\jdmerge.c # End Source File # Begin Source File SOURCE=.\jdpostct.c # End Source File # Begin Source File SOURCE=.\jdsample.c # End Source File # Begin Source File SOURCE=.\jdtrans.c # End Source File # Begin Source File SOURCE=.\jerror.c # End Source File # Begin Source File SOURCE=.\jfdctflt.c # End Source File # Begin Source File SOURCE=.\jfdctfst.c # End Source File # Begin Source File SOURCE=.\jfdctint.c # End Source File # Begin Source File SOURCE=.\jidctflt.c # End Source File # Begin Source File SOURCE=.\jidctfst.c # End Source File # Begin Source File SOURCE=.\jidctint.c # End Source File # Begin Source File SOURCE=.\jmemmgr.c # End Source File # Begin Source File SOURCE=.\jmemnobs.c # End Source File # Begin Source File SOURCE=.\jquant1.c # End Source File # Begin Source File SOURCE=.\jquant2.c # End Source File # Begin Source File SOURCE=.\jutils.c # End Source File # End Group # Begin Group "Header-Dateien" # PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" # Begin Source File SOURCE=.\jconfig.h # End Source File # Begin Source File SOURCE=.\jdct.h # End Source File # Begin Source File SOURCE=.\jerror.h # End Source File # Begin Source File SOURCE=.\jinclude.h # End Source File # Begin Source File SOURCE=.\jmemsys.h # End Source File # Begin Source File SOURCE=.\jmorecfg.h # End Source File # Begin Source File SOURCE=.\jpegint.h # End Source File # Begin Source File SOURCE=.\jpeglib.h # End Source File # Begin Source File SOURCE=.\jversion.h # End Source File # End Group # Begin Group "Ressourcendateien" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" # End Group # End Target # End Project ================================================ FILE: tess-two/jni/libjpeg/makejdsw.vc6 ================================================ Microsoft Developer Studio Workspace File, Format Version 6.00 # WARNUNG: DIESE ARBEITSBEREICHSDATEI DARF NICHT BEARBEITET ODER GELSCHT WERDEN! ############################################################################### Project: "jpeg"=".\jpeg.dsp" - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Global: Package=<5> {{{ }}} Package=<3> {{{ }}} ############################################################################### ================================================ FILE: tess-two/jni/libjpeg/makejfil.v10 ================================================ {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files ================================================ FILE: tess-two/jni/libjpeg/makejmak.vc6 ================================================ # Microsoft Developer Studio Generated NMAKE File, Based on jpeg.dsp !IF "$(CFG)" == "" CFG=jpeg - Win32 !MESSAGE Keine Konfiguration angegeben. jpeg - Win32 wird als Standard verwendet. !ENDIF !IF "$(CFG)" != "jpeg - Win32" !MESSAGE Ungltige Konfiguration "$(CFG)" angegeben. !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "jpeg.mak" CFG="jpeg - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "jpeg - Win32" (basierend auf "Win32 (x86) Static Library") !MESSAGE !ERROR Eine ungltige Konfiguration wurde angegeben. !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF OUTDIR=.\Release INTDIR=.\Release # Begin Custom Macros OutDir=.\Release # End Custom Macros ALL : "$(OUTDIR)\jpeg.lib" CLEAN : -@erase "$(INTDIR)\jaricom.obj" -@erase "$(INTDIR)\jcapimin.obj" -@erase "$(INTDIR)\jcapistd.obj" -@erase "$(INTDIR)\jcarith.obj" -@erase "$(INTDIR)\jccoefct.obj" -@erase "$(INTDIR)\jccolor.obj" -@erase "$(INTDIR)\jcdctmgr.obj" -@erase "$(INTDIR)\jchuff.obj" -@erase "$(INTDIR)\jcinit.obj" -@erase "$(INTDIR)\jcmainct.obj" -@erase "$(INTDIR)\jcmarker.obj" -@erase "$(INTDIR)\jcmaster.obj" -@erase "$(INTDIR)\jcomapi.obj" -@erase "$(INTDIR)\jcparam.obj" -@erase "$(INTDIR)\jcprepct.obj" -@erase "$(INTDIR)\jcsample.obj" -@erase "$(INTDIR)\jctrans.obj" -@erase "$(INTDIR)\jdapimin.obj" -@erase "$(INTDIR)\jdapistd.obj" -@erase "$(INTDIR)\jdarith.obj" -@erase "$(INTDIR)\jdatadst.obj" -@erase "$(INTDIR)\jdatasrc.obj" -@erase "$(INTDIR)\jdcoefct.obj" -@erase "$(INTDIR)\jdcolor.obj" -@erase "$(INTDIR)\jddctmgr.obj" -@erase "$(INTDIR)\jdhuff.obj" -@erase "$(INTDIR)\jdinput.obj" -@erase "$(INTDIR)\jdmainct.obj" -@erase "$(INTDIR)\jdmarker.obj" -@erase "$(INTDIR)\jdmaster.obj" -@erase "$(INTDIR)\jdmerge.obj" -@erase "$(INTDIR)\jdpostct.obj" -@erase "$(INTDIR)\jdsample.obj" -@erase "$(INTDIR)\jdtrans.obj" -@erase "$(INTDIR)\jerror.obj" -@erase "$(INTDIR)\jfdctflt.obj" -@erase "$(INTDIR)\jfdctfst.obj" -@erase "$(INTDIR)\jfdctint.obj" -@erase "$(INTDIR)\jidctflt.obj" -@erase "$(INTDIR)\jidctfst.obj" -@erase "$(INTDIR)\jidctint.obj" -@erase "$(INTDIR)\jmemmgr.obj" -@erase "$(INTDIR)\jmemnobs.obj" -@erase "$(INTDIR)\jquant1.obj" -@erase "$(INTDIR)\jquant2.obj" -@erase "$(INTDIR)\jutils.obj" -@erase "$(INTDIR)\vc60.idb" -@erase "$(OUTDIR)\jpeg.lib" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" CPP=cl.exe CPP_PROJ=/nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /Fp"$(INTDIR)\jpeg.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << RSC=rc.exe BSC32=bscmake.exe BSC32_FLAGS=/nologo /o"$(OUTDIR)\jpeg.bsc" BSC32_SBRS= \ LIB32=link.exe -lib LIB32_FLAGS=/nologo /out:"$(OUTDIR)\jpeg.lib" LIB32_OBJS= \ "$(INTDIR)\jaricom.obj" \ "$(INTDIR)\jcapimin.obj" \ "$(INTDIR)\jcapistd.obj" \ "$(INTDIR)\jcarith.obj" \ "$(INTDIR)\jccoefct.obj" \ "$(INTDIR)\jccolor.obj" \ "$(INTDIR)\jcdctmgr.obj" \ "$(INTDIR)\jchuff.obj" \ "$(INTDIR)\jcinit.obj" \ "$(INTDIR)\jcmainct.obj" \ "$(INTDIR)\jcmarker.obj" \ "$(INTDIR)\jcmaster.obj" \ "$(INTDIR)\jcomapi.obj" \ "$(INTDIR)\jcparam.obj" \ "$(INTDIR)\jcprepct.obj" \ "$(INTDIR)\jcsample.obj" \ "$(INTDIR)\jctrans.obj" \ "$(INTDIR)\jdapimin.obj" \ "$(INTDIR)\jdapistd.obj" \ "$(INTDIR)\jdarith.obj" \ "$(INTDIR)\jdatadst.obj" \ "$(INTDIR)\jdatasrc.obj" \ "$(INTDIR)\jdcoefct.obj" \ "$(INTDIR)\jdcolor.obj" \ "$(INTDIR)\jddctmgr.obj" \ "$(INTDIR)\jdhuff.obj" \ "$(INTDIR)\jdinput.obj" \ "$(INTDIR)\jdmainct.obj" \ "$(INTDIR)\jdmarker.obj" \ "$(INTDIR)\jdmaster.obj" \ "$(INTDIR)\jdmerge.obj" \ "$(INTDIR)\jdpostct.obj" \ "$(INTDIR)\jdsample.obj" \ "$(INTDIR)\jdtrans.obj" \ "$(INTDIR)\jerror.obj" \ "$(INTDIR)\jfdctflt.obj" \ "$(INTDIR)\jfdctfst.obj" \ "$(INTDIR)\jfdctint.obj" \ "$(INTDIR)\jidctflt.obj" \ "$(INTDIR)\jidctfst.obj" \ "$(INTDIR)\jidctint.obj" \ "$(INTDIR)\jmemmgr.obj" \ "$(INTDIR)\jmemnobs.obj" \ "$(INTDIR)\jquant1.obj" \ "$(INTDIR)\jquant2.obj" \ "$(INTDIR)\jutils.obj" "$(OUTDIR)\jpeg.lib" : "$(OUTDIR)" $(DEF_FILE) $(LIB32_OBJS) $(LIB32) @<< $(LIB32_FLAGS) $(DEF_FLAGS) $(LIB32_OBJS) << !IF "$(NO_EXTERNAL_DEPS)" != "1" !IF EXISTS("jpeg.dep") !INCLUDE "jpeg.dep" !ELSE !MESSAGE Warning: cannot find "jpeg.dep" !ENDIF !ENDIF !IF "$(CFG)" == "jpeg - Win32" SOURCE=.\jaricom.c "$(INTDIR)\jaricom.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcapimin.c "$(INTDIR)\jcapimin.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcapistd.c "$(INTDIR)\jcapistd.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcarith.c "$(INTDIR)\jcarith.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jccoefct.c "$(INTDIR)\jccoefct.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jccolor.c "$(INTDIR)\jccolor.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcdctmgr.c "$(INTDIR)\jcdctmgr.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jchuff.c "$(INTDIR)\jchuff.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcinit.c "$(INTDIR)\jcinit.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcmainct.c "$(INTDIR)\jcmainct.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcmarker.c "$(INTDIR)\jcmarker.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcmaster.c "$(INTDIR)\jcmaster.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcomapi.c "$(INTDIR)\jcomapi.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcparam.c "$(INTDIR)\jcparam.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcprepct.c "$(INTDIR)\jcprepct.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jcsample.c "$(INTDIR)\jcsample.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jctrans.c "$(INTDIR)\jctrans.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdapimin.c "$(INTDIR)\jdapimin.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdapistd.c "$(INTDIR)\jdapistd.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdarith.c "$(INTDIR)\jdarith.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdatadst.c "$(INTDIR)\jdatadst.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdatasrc.c "$(INTDIR)\jdatasrc.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdcoefct.c "$(INTDIR)\jdcoefct.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdcolor.c "$(INTDIR)\jdcolor.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jddctmgr.c "$(INTDIR)\jddctmgr.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdhuff.c "$(INTDIR)\jdhuff.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdinput.c "$(INTDIR)\jdinput.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdmainct.c "$(INTDIR)\jdmainct.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdmarker.c "$(INTDIR)\jdmarker.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdmaster.c "$(INTDIR)\jdmaster.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdmerge.c "$(INTDIR)\jdmerge.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdpostct.c "$(INTDIR)\jdpostct.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdsample.c "$(INTDIR)\jdsample.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jdtrans.c "$(INTDIR)\jdtrans.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jerror.c "$(INTDIR)\jerror.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jfdctflt.c "$(INTDIR)\jfdctflt.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jfdctfst.c "$(INTDIR)\jfdctfst.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jfdctint.c "$(INTDIR)\jfdctint.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jidctflt.c "$(INTDIR)\jidctflt.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jidctfst.c "$(INTDIR)\jidctfst.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jidctint.c "$(INTDIR)\jidctint.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jmemmgr.c "$(INTDIR)\jmemmgr.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jmemnobs.c "$(INTDIR)\jmemnobs.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jquant1.c "$(INTDIR)\jquant1.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jquant2.c "$(INTDIR)\jquant2.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jutils.c "$(INTDIR)\jutils.obj" : $(SOURCE) "$(INTDIR)" !ENDIF ================================================ FILE: tess-two/jni/libjpeg/makejsln.v10 ================================================ Microsoft Visual Studio Solution File, Format Version 11.00 # Visual C++ Express 2010 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jpeg", "jpeg.vcxproj", "{019DBD2A-273D-4BA4-BF86-B5EFE2ED76B1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {019DBD2A-273D-4BA4-BF86-B5EFE2ED76B1}.Release|Win32.ActiveCfg = Release|Win32 {019DBD2A-273D-4BA4-BF86-B5EFE2ED76B1}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: tess-two/jni/libjpeg/makejvcx.v10 ================================================ Release Win32 Disabled false {019DBD2A-273D-4BA4-BF86-B5EFE2ED76B1} Win32Proj jpeg StaticLibrary false true Unicode Level3 NotUsing Full true false WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS true true Windows true true true ================================================ FILE: tess-two/jni/libjpeg/makeproj.mac ================================================ -- -- makeproj.mac -- -- This AppleScript builds Code Warrior PRO Release 2 project files for the -- libjpeg library as well as the test programs 'cjpeg', 'djpeg', 'jpegtran'. -- (We'd distribute real project files, except they're not text -- and would create maintenance headaches.) -- -- The script then compiles and links the library and the test programs. -- NOTE: if you haven't already created a 'jconfig.h' file, the script -- automatically copies 'jconfig.mac' to 'jconfig.h'. -- -- To use this script, you must have AppleScript 1.1 or later installed -- and a suitable AppleScript editor like Script Editor or Script Debugger -- (http://www.latenightsw.com). Open this file with your AppleScript -- editor and execute the "run" command to build the projects. -- -- Thanks to Dan Sears and Don Agro for this script. -- Questions about this script can be addressed to dogpark@interlog.com -- on run choose folder with prompt ">>> Select IJG source folder <<<" set ijg_folder to result choose folder with prompt ">>> Select MetroWerks folder <<<" set cw_folder to result -- if jconfig.h doesn't already exist, copy jconfig.mac tell application "Finder" if not (exists file "jconfig.h" of ijg_folder) then duplicate {file "jconfig.mac" of folder ijg_folder} select file "jconfig.mac copy" of folder ijg_folder set name of selection to "jconfig.h" end if end tell tell application "CodeWarrior IDE 2.1" with timeout of 10000 seconds -- create libjpeg project activate Create Project (ijg_folder as string) & "libjpeg.proj" Set Preferences of panel "Target Settings" to {Target Name:"libjpeg"} Set Preferences of panel "PPC Project" to {File Name:"libjpeg"} Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"} Set Preferences of panel "PPC Project" to {Project Type:library} Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true} Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true} Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC} Set Preferences of panel "PPC Linker" to {Generate SYM File:false} Add Files (ijg_folder as string) & "jaricom.c" To Segment 1 Add Files (ijg_folder as string) & "jcapimin.c" To Segment 1 Add Files (ijg_folder as string) & "jcapistd.c" To Segment 1 Add Files (ijg_folder as string) & "jcarith.c" To Segment 1 Add Files (ijg_folder as string) & "jctrans.c" To Segment 1 Add Files (ijg_folder as string) & "jcparam.c" To Segment 1 Add Files (ijg_folder as string) & "jdatadst.c" To Segment 1 Add Files (ijg_folder as string) & "jcinit.c" To Segment 1 Add Files (ijg_folder as string) & "jcmaster.c" To Segment 1 Add Files (ijg_folder as string) & "jcmarker.c" To Segment 1 Add Files (ijg_folder as string) & "jcmainct.c" To Segment 1 Add Files (ijg_folder as string) & "jcprepct.c" To Segment 1 Add Files (ijg_folder as string) & "jccoefct.c" To Segment 1 Add Files (ijg_folder as string) & "jccolor.c" To Segment 1 Add Files (ijg_folder as string) & "jcsample.c" To Segment 1 Add Files (ijg_folder as string) & "jchuff.c" To Segment 1 Add Files (ijg_folder as string) & "jcdctmgr.c" To Segment 1 Add Files (ijg_folder as string) & "jfdctfst.c" To Segment 1 Add Files (ijg_folder as string) & "jfdctflt.c" To Segment 1 Add Files (ijg_folder as string) & "jfdctint.c" To Segment 1 Add Files (ijg_folder as string) & "jdapimin.c" To Segment 1 Add Files (ijg_folder as string) & "jdapistd.c" To Segment 1 Add Files (ijg_folder as string) & "jdarith.c" To Segment 1 Add Files (ijg_folder as string) & "jdtrans.c" To Segment 1 Add Files (ijg_folder as string) & "jdatasrc.c" To Segment 1 Add Files (ijg_folder as string) & "jdmaster.c" To Segment 1 Add Files (ijg_folder as string) & "jdinput.c" To Segment 1 Add Files (ijg_folder as string) & "jdmarker.c" To Segment 1 Add Files (ijg_folder as string) & "jdhuff.c" To Segment 1 Add Files (ijg_folder as string) & "jdmainct.c" To Segment 1 Add Files (ijg_folder as string) & "jdcoefct.c" To Segment 1 Add Files (ijg_folder as string) & "jdpostct.c" To Segment 1 Add Files (ijg_folder as string) & "jddctmgr.c" To Segment 1 Add Files (ijg_folder as string) & "jidctfst.c" To Segment 1 Add Files (ijg_folder as string) & "jidctflt.c" To Segment 1 Add Files (ijg_folder as string) & "jidctint.c" To Segment 1 Add Files (ijg_folder as string) & "jdsample.c" To Segment 1 Add Files (ijg_folder as string) & "jdcolor.c" To Segment 1 Add Files (ijg_folder as string) & "jquant1.c" To Segment 1 Add Files (ijg_folder as string) & "jquant2.c" To Segment 1 Add Files (ijg_folder as string) & "jdmerge.c" To Segment 1 Add Files (ijg_folder as string) & "jcomapi.c" To Segment 1 Add Files (ijg_folder as string) & "jutils.c" To Segment 1 Add Files (ijg_folder as string) & "jerror.c" To Segment 1 Add Files (ijg_folder as string) & "jmemmgr.c" To Segment 1 Add Files (ijg_folder as string) & "jmemmac.c" To Segment 1 -- compile and link the library Make Project Close Project -- create cjpeg project activate Create Project (ijg_folder as string) & "cjpeg.proj" Set Preferences of panel "Target Settings" to {Target Name:"cjpeg"} Set Preferences of panel "PPC Project" to {File Name:"cjpeg"} Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"} Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true} Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true} Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC} Set Preferences of panel "PPC Linker" to {Generate SYM File:false} Add Files (ijg_folder as string) & "cjpeg.c" To Segment 1 Add Files (ijg_folder as string) & "rdppm.c" To Segment 1 Add Files (ijg_folder as string) & "rdgif.c" To Segment 1 Add Files (ijg_folder as string) & "rdtarga.c" To Segment 1 Add Files (ijg_folder as string) & "rdrle.c" To Segment 1 Add Files (ijg_folder as string) & "rdbmp.c" To Segment 1 Add Files (ijg_folder as string) & "rdswitch.c" To Segment 1 Add Files (ijg_folder as string) & "cdjpeg.c" To Segment 1 Add Files (ijg_folder as string) & "libjpeg" To Segment 2 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL C.PPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL SIOUX.PPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:Runtime:Runtime PPC:MSL RuntimePPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:InterfaceLib" To Segment 4 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:MathLib" To Segment 4 -- compile and link cjpeg Make Project Close Project -- create djpeg project activate Create Project (ijg_folder as string) & "djpeg.proj" Set Preferences of panel "Target Settings" to {Target Name:"djpeg"} Set Preferences of panel "PPC Project" to {File Name:"djpeg"} Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"} Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true} Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true} Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC} Set Preferences of panel "PPC Linker" to {Generate SYM File:false} Add Files (ijg_folder as string) & "djpeg.c" To Segment 1 Add Files (ijg_folder as string) & "wrppm.c" To Segment 1 Add Files (ijg_folder as string) & "wrgif.c" To Segment 1 Add Files (ijg_folder as string) & "wrtarga.c" To Segment 1 Add Files (ijg_folder as string) & "wrrle.c" To Segment 1 Add Files (ijg_folder as string) & "wrbmp.c" To Segment 1 Add Files (ijg_folder as string) & "rdcolmap.c" To Segment 1 Add Files (ijg_folder as string) & "cdjpeg.c" To Segment 1 Add Files (ijg_folder as string) & "libjpeg" To Segment 2 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL C.PPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL SIOUX.PPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:Runtime:Runtime PPC:MSL RuntimePPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:InterfaceLib" To Segment 4 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:MathLib" To Segment 4 -- compile and link djpeg Make Project Close Project -- create jpegtran project activate Create Project (ijg_folder as string) & "jpegtran.proj" Set Preferences of panel "Target Settings" to {Target Name:"jpegtran"} Set Preferences of panel "PPC Project" to {File Name:"jpegtran"} Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"} Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true} Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true} Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC} Set Preferences of panel "PPC Linker" to {Generate SYM File:false} Add Files (ijg_folder as string) & "jpegtran.c" To Segment 1 Add Files (ijg_folder as string) & "rdswitch.c" To Segment 1 Add Files (ijg_folder as string) & "cdjpeg.c" To Segment 1 Add Files (ijg_folder as string) & "transupp.c" To Segment 1 Add Files (ijg_folder as string) & "libjpeg" To Segment 2 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL C.PPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL SIOUX.PPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:Runtime:Runtime PPC:MSL RuntimePPC.Lib" To Segment 3 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:InterfaceLib" To Segment 4 Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:MathLib" To Segment 4 -- compile and link jpegtran Make Project Close Project quit end timeout end tell end run ================================================ FILE: tess-two/jni/libjpeg/makerdep.vc6 ================================================ # Microsoft Developer Studio erstellte Abhngigkeitsdatei, einbezogen von rdjpgcom.mak .\rdjpgcom.c : \ ".\jconfig.h"\ ".\jinclude.h"\ ================================================ FILE: tess-two/jni/libjpeg/makerdsp.vc6 ================================================ # Microsoft Developer Studio Project File - Name="rdjpgcom" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** NICHT BEARBEITEN ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=rdjpgcom - Win32 !MESSAGE Dies ist kein gltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE !MESSAGE verwenden Sie den Befehl "Makefile exportieren" und fhren Sie den Befehl !MESSAGE !MESSAGE NMAKE /f "rdjpgcom.mak". !MESSAGE !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "rdjpgcom.mak" CFG="rdjpgcom - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "rdjpgcom - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir ".\rdjpgcom\Release" # PROP BASE Intermediate_Dir ".\rdjpgcom\Release" # PROP BASE Target_Dir ".\rdjpgcom" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir ".\rdjpgcom\Release" # PROP Intermediate_Dir ".\rdjpgcom\Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir ".\rdjpgcom" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c # ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /FD /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # Begin Target # Name "rdjpgcom - Win32" # Begin Group "Quellcodedateien" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;for;f90" # Begin Source File SOURCE=.\rdjpgcom.c # End Source File # End Group # Begin Group "Header-Dateien" # PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" # Begin Source File SOURCE=.\jconfig.h # End Source File # Begin Source File SOURCE=.\jinclude.h # End Source File # End Group # Begin Group "Ressourcendateien" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" # End Group # End Target # End Project ================================================ FILE: tess-two/jni/libjpeg/makerfil.v10 ================================================ {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Source Files ================================================ FILE: tess-two/jni/libjpeg/makermak.vc6 ================================================ # Microsoft Developer Studio Generated NMAKE File, Based on rdjpgcom.dsp !IF "$(CFG)" == "" CFG=rdjpgcom - Win32 !MESSAGE Keine Konfiguration angegeben. rdjpgcom - Win32 wird als Standard verwendet. !ENDIF !IF "$(CFG)" != "rdjpgcom - Win32" !MESSAGE Ungltige Konfiguration "$(CFG)" angegeben. !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "rdjpgcom.mak" CFG="rdjpgcom - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "rdjpgcom - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE !ERROR Eine ungltige Konfiguration wurde angegeben. !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF CPP=cl.exe RSC=rc.exe OUTDIR=.\rdjpgcom\Release INTDIR=.\rdjpgcom\Release # Begin Custom Macros OutDir=.\rdjpgcom\Release # End Custom Macros ALL : "$(OUTDIR)\rdjpgcom.exe" CLEAN : -@erase "$(INTDIR)\rdjpgcom.obj" -@erase "$(INTDIR)\vc60.idb" -@erase "$(OUTDIR)\rdjpgcom.exe" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" BSC32=bscmake.exe BSC32_FLAGS=/nologo /o"$(OUTDIR)\rdjpgcom.bsc" BSC32_SBRS= \ LINK32=link.exe LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no /pdb:"$(OUTDIR)\rdjpgcom.pdb" /machine:I386 /out:"$(OUTDIR)\rdjpgcom.exe" LINK32_OBJS= \ "$(INTDIR)\rdjpgcom.obj" "$(OUTDIR)\rdjpgcom.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) $(LINK32) @<< $(LINK32_FLAGS) $(LINK32_OBJS) << CPP_PROJ=/nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /Fp"$(INTDIR)\rdjpgcom.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << !IF "$(NO_EXTERNAL_DEPS)" != "1" !IF EXISTS("rdjpgcom.dep") !INCLUDE "rdjpgcom.dep" !ELSE !MESSAGE Warning: cannot find "rdjpgcom.dep" !ENDIF !ENDIF !IF "$(CFG)" == "rdjpgcom - Win32" SOURCE=.\rdjpgcom.c "$(INTDIR)\rdjpgcom.obj" : $(SOURCE) "$(INTDIR)" !ENDIF ================================================ FILE: tess-two/jni/libjpeg/makervcx.v10 ================================================ Release Win32 {C81513DB-78DC-46BC-BC98-82E745203976} Win32Proj rdjpgcom Application false true Unicode false $(ProjectName)\$(Configuration)\ $(ProjectName)\$(Configuration)\ Level3 NotUsing Full true false WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS true true 4996 Console true true true ================================================ FILE: tess-two/jni/libjpeg/maketdep.vc6 ================================================ # Microsoft Developer Studio erstellte Abhngigkeitsdatei, einbezogen von jpegtran.mak .\cdjpeg.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\jpegtran.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ ".\jversion.h"\ ".\transupp.h"\ .\rdswitch.c : \ ".\cderror.h"\ ".\cdjpeg.h"\ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpeglib.h"\ .\transupp.c : \ ".\jconfig.h"\ ".\jerror.h"\ ".\jinclude.h"\ ".\jmorecfg.h"\ ".\jpegint.h"\ ".\jpeglib.h"\ ".\transupp.h"\ ================================================ FILE: tess-two/jni/libjpeg/maketdsp.vc6 ================================================ # Microsoft Developer Studio Project File - Name="jpegtran" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** NICHT BEARBEITEN ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=jpegtran - Win32 !MESSAGE Dies ist kein gltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE !MESSAGE verwenden Sie den Befehl "Makefile exportieren" und fhren Sie den Befehl !MESSAGE !MESSAGE NMAKE /f "jpegtran.mak". !MESSAGE !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "jpegtran.mak" CFG="jpegtran - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "jpegtran - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir ".\jpegtran\Release" # PROP BASE Intermediate_Dir ".\jpegtran\Release" # PROP BASE Target_Dir ".\jpegtran" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir ".\jpegtran\Release" # PROP Intermediate_Dir ".\jpegtran\Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir ".\jpegtran" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c # ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /FD /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # Begin Target # Name "jpegtran - Win32" # Begin Group "Quellcodedateien" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;for;f90" # Begin Source File SOURCE=.\cdjpeg.c # End Source File # Begin Source File SOURCE=.\jpegtran.c # End Source File # Begin Source File SOURCE=.\rdswitch.c # End Source File # Begin Source File SOURCE=.\transupp.c # End Source File # End Group # Begin Group "Header-Dateien" # PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" # Begin Source File SOURCE=.\cderror.h # End Source File # Begin Source File SOURCE=.\cdjpeg.h # End Source File # Begin Source File SOURCE=.\jconfig.h # End Source File # Begin Source File SOURCE=.\jerror.h # End Source File # Begin Source File SOURCE=.\jinclude.h # End Source File # Begin Source File SOURCE=.\jmorecfg.h # End Source File # Begin Source File SOURCE=.\jpegint.h # End Source File # Begin Source File SOURCE=.\jpeglib.h # End Source File # Begin Source File SOURCE=.\jversion.h # End Source File # Begin Source File SOURCE=.\transupp.h # End Source File # End Group # Begin Group "Ressourcendateien" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" # End Group # End Target # End Project ================================================ FILE: tess-two/jni/libjpeg/maketfil.v10 ================================================ {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files ================================================ FILE: tess-two/jni/libjpeg/maketmak.vc6 ================================================ # Microsoft Developer Studio Generated NMAKE File, Based on jpegtran.dsp !IF "$(CFG)" == "" CFG=jpegtran - Win32 !MESSAGE Keine Konfiguration angegeben. jpegtran - Win32 wird als Standard verwendet. !ENDIF !IF "$(CFG)" != "jpegtran - Win32" !MESSAGE Ungltige Konfiguration "$(CFG)" angegeben. !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "jpegtran.mak" CFG="jpegtran - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "jpegtran - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE !ERROR Eine ungltige Konfiguration wurde angegeben. !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF CPP=cl.exe RSC=rc.exe OUTDIR=.\jpegtran\Release INTDIR=.\jpegtran\Release # Begin Custom Macros OutDir=.\jpegtran\Release # End Custom Macros ALL : "$(OUTDIR)\jpegtran.exe" CLEAN : -@erase "$(INTDIR)\cdjpeg.obj" -@erase "$(INTDIR)\jpegtran.obj" -@erase "$(INTDIR)\rdswitch.obj" -@erase "$(INTDIR)\transupp.obj" -@erase "$(INTDIR)\vc60.idb" -@erase "$(OUTDIR)\jpegtran.exe" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" BSC32=bscmake.exe BSC32_FLAGS=/nologo /o"$(OUTDIR)\jpegtran.bsc" BSC32_SBRS= \ LINK32=link.exe LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no /pdb:"$(OUTDIR)\jpegtran.pdb" /machine:I386 /out:"$(OUTDIR)\jpegtran.exe" LINK32_OBJS= \ "$(INTDIR)\cdjpeg.obj" \ "$(INTDIR)\jpegtran.obj" \ "$(INTDIR)\rdswitch.obj" \ "$(INTDIR)\transupp.obj" "$(OUTDIR)\jpegtran.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) $(LINK32) @<< $(LINK32_FLAGS) $(LINK32_OBJS) << CPP_PROJ=/nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /Fp"$(INTDIR)\jpegtran.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << !IF "$(NO_EXTERNAL_DEPS)" != "1" !IF EXISTS("jpegtran.dep") !INCLUDE "jpegtran.dep" !ELSE !MESSAGE Warning: cannot find "jpegtran.dep" !ENDIF !ENDIF !IF "$(CFG)" == "jpegtran - Win32" SOURCE=.\cdjpeg.c "$(INTDIR)\cdjpeg.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\jpegtran.c "$(INTDIR)\jpegtran.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\rdswitch.c "$(INTDIR)\rdswitch.obj" : $(SOURCE) "$(INTDIR)" SOURCE=.\transupp.c "$(INTDIR)\transupp.obj" : $(SOURCE) "$(INTDIR)" !ENDIF ================================================ FILE: tess-two/jni/libjpeg/maketvcx.v10 ================================================ Release Win32 {025BAC50-51B5-4FFE-BC47-3F920BB4047E} Win32Proj jpegtran Application false true Unicode false $(ProjectName)\$(Configuration)\ $(ProjectName)\$(Configuration)\ Level3 NotUsing Full true false WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS true true 4996 Console true true true Release\jpeg.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies) ================================================ FILE: tess-two/jni/libjpeg/makewdep.vc6 ================================================ # Microsoft Developer Studio erstellte Abhngigkeitsdatei, einbezogen von wrjpgcom.mak .\wrjpgcom.c : \ ".\jconfig.h"\ ".\jinclude.h"\ ================================================ FILE: tess-two/jni/libjpeg/makewdsp.vc6 ================================================ # Microsoft Developer Studio Project File - Name="wrjpgcom" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** NICHT BEARBEITEN ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=wrjpgcom - Win32 !MESSAGE Dies ist kein gltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE !MESSAGE verwenden Sie den Befehl "Makefile exportieren" und fhren Sie den Befehl !MESSAGE !MESSAGE NMAKE /f "wrjpgcom.mak". !MESSAGE !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "wrjpgcom.mak" CFG="wrjpgcom - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "wrjpgcom - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir ".\wrjpgcom\Release" # PROP BASE Intermediate_Dir ".\wrjpgcom\Release" # PROP BASE Target_Dir ".\wrjpgcom" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir ".\wrjpgcom\Release" # PROP Intermediate_Dir ".\wrjpgcom\Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir ".\wrjpgcom" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c # ADD CPP /nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /FD /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 # Begin Target # Name "wrjpgcom - Win32" # Begin Group "Quellcodedateien" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;for;f90" # Begin Source File SOURCE=.\wrjpgcom.c # End Source File # End Group # Begin Group "Header-Dateien" # PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" # Begin Source File SOURCE=.\jconfig.h # End Source File # Begin Source File SOURCE=.\jinclude.h # End Source File # End Group # Begin Group "Ressourcendateien" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" # End Group # End Target # End Project ================================================ FILE: tess-two/jni/libjpeg/makewfil.v10 ================================================ {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Source Files ================================================ FILE: tess-two/jni/libjpeg/makewmak.vc6 ================================================ # Microsoft Developer Studio Generated NMAKE File, Based on wrjpgcom.dsp !IF "$(CFG)" == "" CFG=wrjpgcom - Win32 !MESSAGE Keine Konfiguration angegeben. wrjpgcom - Win32 wird als Standard verwendet. !ENDIF !IF "$(CFG)" != "wrjpgcom - Win32" !MESSAGE Ungltige Konfiguration "$(CFG)" angegeben. !MESSAGE Sie knnen beim Ausfhren von NMAKE eine Konfiguration angeben !MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel: !MESSAGE !MESSAGE NMAKE /f "wrjpgcom.mak" CFG="wrjpgcom - Win32" !MESSAGE !MESSAGE Fr die Konfiguration stehen zur Auswahl: !MESSAGE !MESSAGE "wrjpgcom - Win32" (basierend auf "Win32 (x86) Console Application") !MESSAGE !ERROR Eine ungltige Konfiguration wurde angegeben. !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF CPP=cl.exe RSC=rc.exe OUTDIR=.\wrjpgcom\Release INTDIR=.\wrjpgcom\Release # Begin Custom Macros OutDir=.\wrjpgcom\Release # End Custom Macros ALL : "$(OUTDIR)\wrjpgcom.exe" CLEAN : -@erase "$(INTDIR)\vc60.idb" -@erase "$(INTDIR)\wrjpgcom.obj" -@erase "$(OUTDIR)\wrjpgcom.exe" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" BSC32=bscmake.exe BSC32_FLAGS=/nologo /o"$(OUTDIR)\wrjpgcom.bsc" BSC32_SBRS= \ LINK32=link.exe LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no /pdb:"$(OUTDIR)\wrjpgcom.pdb" /machine:I386 /out:"$(OUTDIR)\wrjpgcom.exe" LINK32_OBJS= \ "$(INTDIR)\wrjpgcom.obj" "$(OUTDIR)\wrjpgcom.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) $(LINK32) @<< $(LINK32_FLAGS) $(LINK32_OBJS) << CPP_PROJ=/nologo /G6 /MT /W3 /GX /Ox /Oa /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /Fp"$(INTDIR)\wrjpgcom.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) $< << !IF "$(NO_EXTERNAL_DEPS)" != "1" !IF EXISTS("wrjpgcom.dep") !INCLUDE "wrjpgcom.dep" !ELSE !MESSAGE Warning: cannot find "wrjpgcom.dep" !ENDIF !ENDIF !IF "$(CFG)" == "wrjpgcom - Win32" SOURCE=.\wrjpgcom.c "$(INTDIR)\wrjpgcom.obj" : $(SOURCE) "$(INTDIR)" !ENDIF ================================================ FILE: tess-two/jni/libjpeg/makewvcx.v10 ================================================ Release Win32 {B57065D4-DDDA-4668-BAF5-2D49270C973C} Win32Proj wrjpgcom Application false true Unicode false $(ProjectName)\$(Configuration)\ $(ProjectName)\$(Configuration)\ Level3 NotUsing Full true false WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS true true 4996 Console true true true ================================================ FILE: tess-two/jni/libjpeg/makljpeg.st ================================================ ; Project file for Independent JPEG Group's software ; ; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C. ; Thanks to Frank Moehle, B. Setzepfandt, and Guido Vollbeding. ; ; To use this file, rename it to libjpeg.prj. ; Read installation instructions before trying to make the program! ; ; ; * * * Output file * * * libjpeg.lib ; ; * * * COMPILER OPTIONS * * * .C[-P] ; absolute calls .C[-M] ; and no string merging, folks .C[-w-cln] ; no "constant is long" warnings .C[-w-par] ; no "parameter xxxx unused" .C[-w-rch] ; no "unreachable code" .C[-wsig] ; warn if significant digits may be lost .L[-J] ; link new Obj-format (so we get a library) = ; * * * * List of modules * * * * jaricom.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcapimin.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcapistd.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcarith.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jccoefct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jccolor.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcdctmgr.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jchuff.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcinit.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcmainct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcmarker.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcmaster.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcomapi.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcparam.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcprepct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jcsample.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jctrans.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdapimin.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdapistd.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdarith.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdatadst.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h) jdatasrc.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h) jdcoefct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdcolor.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jddctmgr.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jdhuff.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdinput.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdmainct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdmarker.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdmaster.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdmerge.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdpostct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdsample.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jdtrans.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jerror.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jversion.h,jerror.h) jfdctflt.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jfdctfst.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jfdctint.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jidctflt.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jidctfst.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jidctint.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h) jquant1.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jquant2.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jutils.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h) jmemmgr.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jmemsys.h) jmemansi.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jmemsys.h) ================================================ FILE: tess-two/jni/libjpeg/maktjpeg.st ================================================ ; Project file for Independent JPEG Group's software ; ; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C. ; Thanks to Frank Moehle, B. Setzepfandt, and Guido Vollbeding. ; ; To use this file, rename it to jpegtran.prj. ; If you are using Turbo C, change filenames beginning with "pc..." to "tc..." ; Read installation instructions before trying to make the program! ; ; ; * * * Output file * * * jpegtran.ttp ; ; * * * COMPILER OPTIONS * * * .C[-P] ; absolute calls .C[-M] ; and no string merging, folks .C[-w-cln] ; no "constant is long" warnings .C[-w-par] ; no "parameter xxxx unused" .C[-w-rch] ; no "unreachable code" .C[-wsig] ; warn if significant digits may be lost = ; * * * * List of modules * * * * pcstart.o jpegtran.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,transupp.h,jversion.h) cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdswitch.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) transupp.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,transupp.h) libjpeg.lib ; built by libjpeg.prj pcstdlib.lib ; standard library pcextlib.lib ; extended library ================================================ FILE: tess-two/jni/libjpeg/makvms.opt ================================================ ! A pointer to the VAX/VMS C Run-Time Shareable Library. ! This file is needed by makefile.mms and makefile.vms, ! but only for the older VAX C compiler. DEC C does not need it. Sys$Library:VAXCRTL.EXE /Share ================================================ FILE: tess-two/jni/libjpeg/missing ================================================ #! /bin/sh # Common wrapper for a few potentially missing GNU programs. scriptversion=2013-10-28.13; # UTC # Copyright (C) 1996-2014 Free Software Foundation, Inc. # Originally written by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try '$0 --help' for more information" exit 1 fi case $1 in --is-lightweight) # Used by our autoconf macros to check whether the available missing # script is modern enough. exit 0 ;; --run) # Back-compat with the calling convention used by older automake. shift ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due to PROGRAM being missing or too old. Options: -h, --help display this help and exit -v, --version output version information and exit Supported PROGRAM values: aclocal autoconf autoheader autom4te automake makeinfo bison yacc flex lex help2man Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and 'g' are ignored when checking the name. Send bug reports to ." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: unknown '$1' option" echo 1>&2 "Try '$0 --help' for more information" exit 1 ;; esac # Run the given program, remember its exit status. "$@"; st=$? # If it succeeded, we are done. test $st -eq 0 && exit 0 # Also exit now if we it failed (or wasn't found), and '--version' was # passed; such an option is passed most likely to detect whether the # program is present and works. case $2 in --version|--help) exit $st;; esac # Exit code 63 means version mismatch. This often happens when the user # tries to use an ancient version of a tool on a file that requires a # minimum version. if test $st -eq 63; then msg="probably too old" elif test $st -eq 127; then # Program was missing. msg="missing on your system" else # Program was found and executed, but failed. Give up. exit $st fi perl_URL=http://www.perl.org/ flex_URL=http://flex.sourceforge.net/ gnu_software_URL=http://www.gnu.org/software program_details () { case $1 in aclocal|automake) echo "The '$1' program is part of the GNU Automake package:" echo "<$gnu_software_URL/automake>" echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/autoconf>" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; autoconf|autom4te|autoheader) echo "The '$1' program is part of the GNU Autoconf package:" echo "<$gnu_software_URL/autoconf/>" echo "It also requires GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; esac } give_advice () { # Normalize program name to check for. normalized_program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` printf '%s\n' "'$1' is $msg." configure_deps="'configure.ac' or m4 files included by 'configure.ac'" case $normalized_program in autoconf*) echo "You should only need it if you modified 'configure.ac'," echo "or m4 files included by it." program_details 'autoconf' ;; autoheader*) echo "You should only need it if you modified 'acconfig.h' or" echo "$configure_deps." program_details 'autoheader' ;; automake*) echo "You should only need it if you modified 'Makefile.am' or" echo "$configure_deps." program_details 'automake' ;; aclocal*) echo "You should only need it if you modified 'acinclude.m4' or" echo "$configure_deps." program_details 'aclocal' ;; autom4te*) echo "You might have modified some maintainer files that require" echo "the 'autom4te' program to be rebuilt." program_details 'autom4te' ;; bison*|yacc*) echo "You should only need it if you modified a '.y' file." echo "You may want to install the GNU Bison package:" echo "<$gnu_software_URL/bison/>" ;; lex*|flex*) echo "You should only need it if you modified a '.l' file." echo "You may want to install the Fast Lexical Analyzer package:" echo "<$flex_URL>" ;; help2man*) echo "You should only need it if you modified a dependency" \ "of a man page." echo "You may want to install the GNU Help2man package:" echo "<$gnu_software_URL/help2man/>" ;; makeinfo*) echo "You should only need it if you modified a '.texi' file, or" echo "any other file indirectly affecting the aspect of the manual." echo "You might want to install the Texinfo package:" echo "<$gnu_software_URL/texinfo/>" echo "The spurious makeinfo call might also be the consequence of" echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might" echo "want to install GNU make:" echo "<$gnu_software_URL/make/>" ;; *) echo "You might have modified some files without having the proper" echo "tools for further handling them. Check the 'README' file, it" echo "often tells you about the needed prerequisites for installing" echo "this package. You may also peek at any GNU archive site, in" echo "case some other package contains this missing '$1' program." ;; esac } give_advice "$1" | sed -e '1s/^/WARNING: /' \ -e '2,$s/^/ /' >&2 # Propagate the correct exit status (expected to be 127 for a program # not found, 63 for a program that failed due to version mismatch). exit $st # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: ================================================ FILE: tess-two/jni/libjpeg/rdbmp.c ================================================ /* * rdbmp.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2009-2010 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to read input images in Microsoft "BMP" * format (MS Windows 3.x, OS/2 1.x, and OS/2 2.x flavors). * Currently, only 8-bit and 24-bit images are supported, not 1-bit or * 4-bit (feeding such low-depth images into JPEG would be silly anyway). * Also, we don't support RLE-compressed files. * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume input from * an ordinary stdio stream. They further assume that reading begins * at the start of the file; start_input may need work if the * user interface has already read some data (e.g., to determine that * the file is indeed BMP format). * * This code contributed by James Arthur Boucher. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef BMP_SUPPORTED /* Macros to deal with unsigned chars as efficiently as compiler allows */ #ifdef HAVE_UNSIGNED_CHAR typedef unsigned char U_CHAR; #define UCH(x) ((int) (x)) #else /* !HAVE_UNSIGNED_CHAR */ #ifdef CHAR_IS_UNSIGNED typedef char U_CHAR; #define UCH(x) ((int) (x)) #else typedef char U_CHAR; #define UCH(x) ((int) (x) & 0xFF) #endif #endif /* HAVE_UNSIGNED_CHAR */ #define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len))) /* Private version of data source object */ typedef struct _bmp_source_struct * bmp_source_ptr; typedef struct _bmp_source_struct { struct cjpeg_source_struct pub; /* public fields */ j_compress_ptr cinfo; /* back link saves passing separate parm */ JSAMPARRAY colormap; /* BMP colormap (converted to my format) */ jvirt_sarray_ptr whole_image; /* Needed to reverse row order */ JDIMENSION source_row; /* Current source row number */ JDIMENSION row_width; /* Physical width of scanlines in file */ int bits_per_pixel; /* remembers 8- or 24-bit format */ } bmp_source_struct; LOCAL(int) read_byte (bmp_source_ptr sinfo) /* Read next byte from BMP file */ { register FILE *infile = sinfo->pub.input_file; register int c; if ((c = getc(infile)) == EOF) ERREXIT(sinfo->cinfo, JERR_INPUT_EOF); return c; } LOCAL(void) read_colormap (bmp_source_ptr sinfo, int cmaplen, int mapentrysize) /* Read the colormap from a BMP file */ { int i; switch (mapentrysize) { case 3: /* BGR format (occurs in OS/2 files) */ for (i = 0; i < cmaplen; i++) { sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo); sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo); sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo); } break; case 4: /* BGR0 format (occurs in MS Windows files) */ for (i = 0; i < cmaplen; i++) { sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo); sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo); sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo); (void) read_byte(sinfo); } break; default: ERREXIT(sinfo->cinfo, JERR_BMP_BADCMAP); break; } } /* * Read one row of pixels. * The image has been read into the whole_image array, but is otherwise * unprocessed. We must read it out in top-to-bottom row order, and if * it is an 8-bit image, we must expand colormapped pixels to 24bit format. */ METHODDEF(JDIMENSION) get_8bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 8-bit colormap indexes */ { bmp_source_ptr source = (bmp_source_ptr) sinfo; register JSAMPARRAY colormap = source->colormap; JSAMPARRAY image_ptr; register int t; register JSAMPROW inptr, outptr; register JDIMENSION col; /* Fetch next row from virtual array */ source->source_row--; image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->whole_image, source->source_row, (JDIMENSION) 1, FALSE); /* Expand the colormap indexes to real data */ inptr = image_ptr[0]; outptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { t = GETJSAMPLE(*inptr++); *outptr++ = colormap[0][t]; /* can omit GETJSAMPLE() safely */ *outptr++ = colormap[1][t]; *outptr++ = colormap[2][t]; } return 1; } METHODDEF(JDIMENSION) get_24bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 24-bit pixels */ { bmp_source_ptr source = (bmp_source_ptr) sinfo; JSAMPARRAY image_ptr; register JSAMPROW inptr, outptr; register JDIMENSION col; /* Fetch next row from virtual array */ source->source_row--; image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->whole_image, source->source_row, (JDIMENSION) 1, FALSE); /* Transfer data. Note source values are in BGR order * (even though Microsoft's own documents say the opposite). */ inptr = image_ptr[0]; outptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { outptr[2] = *inptr++; /* can omit GETJSAMPLE() safely */ outptr[1] = *inptr++; outptr[0] = *inptr++; outptr += 3; } return 1; } METHODDEF(JDIMENSION) get_32bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 32-bit pixels */ { bmp_source_ptr source = (bmp_source_ptr) sinfo; JSAMPARRAY image_ptr; register JSAMPROW inptr, outptr; register JDIMENSION col; /* Fetch next row from virtual array */ source->source_row--; image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->whole_image, source->source_row, (JDIMENSION) 1, FALSE); /* Transfer data. Note source values are in BGR order * (even though Microsoft's own documents say the opposite). */ inptr = image_ptr[0]; outptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { outptr[2] = *inptr++; /* can omit GETJSAMPLE() safely */ outptr[1] = *inptr++; outptr[0] = *inptr++; inptr++; /* skip the 4th byte (Alpha channel) */ outptr += 3; } return 1; } /* * This method loads the image into whole_image during the first call on * get_pixel_rows. The get_pixel_rows pointer is then adjusted to call * get_8bit_row, get_24bit_row, or get_32bit_row on subsequent calls. */ METHODDEF(JDIMENSION) preload_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { bmp_source_ptr source = (bmp_source_ptr) sinfo; register FILE *infile = source->pub.input_file; register int c; register JSAMPROW out_ptr; JSAMPARRAY image_ptr; JDIMENSION row, col; cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; /* Read the data into a virtual array in input-file row order. */ for (row = 0; row < cinfo->image_height; row++) { if (progress != NULL) { progress->pub.pass_counter = (long) row; progress->pub.pass_limit = (long) cinfo->image_height; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->whole_image, row, (JDIMENSION) 1, TRUE); out_ptr = image_ptr[0]; for (col = source->row_width; col > 0; col--) { /* inline copy of read_byte() for speed */ if ((c = getc(infile)) == EOF) ERREXIT(cinfo, JERR_INPUT_EOF); *out_ptr++ = (JSAMPLE) c; } } if (progress != NULL) progress->completed_extra_passes++; /* Set up to read from the virtual array in top-to-bottom order */ switch (source->bits_per_pixel) { case 8: source->pub.get_pixel_rows = get_8bit_row; break; case 24: source->pub.get_pixel_rows = get_24bit_row; break; case 32: source->pub.get_pixel_rows = get_32bit_row; break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); } source->source_row = cinfo->image_height; /* And read the first row */ return (*source->pub.get_pixel_rows) (cinfo, sinfo); } /* * Read the file header; return image size and component count. */ METHODDEF(void) start_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { bmp_source_ptr source = (bmp_source_ptr) sinfo; U_CHAR bmpfileheader[14]; U_CHAR bmpinfoheader[64]; #define GET_2B(array,offset) ((unsigned int) UCH(array[offset]) + \ (((unsigned int) UCH(array[offset+1])) << 8)) #define GET_4B(array,offset) ((INT32) UCH(array[offset]) + \ (((INT32) UCH(array[offset+1])) << 8) + \ (((INT32) UCH(array[offset+2])) << 16) + \ (((INT32) UCH(array[offset+3])) << 24)) INT32 bfOffBits; INT32 headerSize; INT32 biWidth; INT32 biHeight; unsigned int biPlanes; INT32 biCompression; INT32 biXPelsPerMeter,biYPelsPerMeter; INT32 biClrUsed = 0; int mapentrysize = 0; /* 0 indicates no colormap */ INT32 bPad; JDIMENSION row_width; /* Read and verify the bitmap file header */ if (! ReadOK(source->pub.input_file, bmpfileheader, 14)) ERREXIT(cinfo, JERR_INPUT_EOF); if (GET_2B(bmpfileheader,0) != 0x4D42) /* 'BM' */ ERREXIT(cinfo, JERR_BMP_NOT); bfOffBits = (INT32) GET_4B(bmpfileheader,10); /* We ignore the remaining fileheader fields */ /* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows), * or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which. */ if (! ReadOK(source->pub.input_file, bmpinfoheader, 4)) ERREXIT(cinfo, JERR_INPUT_EOF); headerSize = (INT32) GET_4B(bmpinfoheader,0); if (headerSize < 12 || headerSize > 64) ERREXIT(cinfo, JERR_BMP_BADHEADER); if (! ReadOK(source->pub.input_file, bmpinfoheader+4, headerSize-4)) ERREXIT(cinfo, JERR_INPUT_EOF); switch ((int) headerSize) { case 12: /* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */ biWidth = (INT32) GET_2B(bmpinfoheader,4); biHeight = (INT32) GET_2B(bmpinfoheader,6); biPlanes = GET_2B(bmpinfoheader,8); source->bits_per_pixel = (int) GET_2B(bmpinfoheader,10); switch (source->bits_per_pixel) { case 8: /* colormapped image */ mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */ TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, (int) biWidth, (int) biHeight); break; case 24: /* RGB image */ TRACEMS2(cinfo, 1, JTRC_BMP_OS2, (int) biWidth, (int) biHeight); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); break; } break; case 40: case 64: /* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */ /* or OS/2 2.x header, which has additional fields that we ignore */ biWidth = GET_4B(bmpinfoheader,4); biHeight = GET_4B(bmpinfoheader,8); biPlanes = GET_2B(bmpinfoheader,12); source->bits_per_pixel = (int) GET_2B(bmpinfoheader,14); biCompression = GET_4B(bmpinfoheader,16); biXPelsPerMeter = GET_4B(bmpinfoheader,24); biYPelsPerMeter = GET_4B(bmpinfoheader,28); biClrUsed = GET_4B(bmpinfoheader,32); /* biSizeImage, biClrImportant fields are ignored */ switch (source->bits_per_pixel) { case 8: /* colormapped image */ mapentrysize = 4; /* Windows uses RGBQUAD colormap */ TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, (int) biWidth, (int) biHeight); break; case 24: /* RGB image */ TRACEMS2(cinfo, 1, JTRC_BMP, (int) biWidth, (int) biHeight); break; case 32: /* RGB image + Alpha channel */ TRACEMS2(cinfo, 1, JTRC_BMP, (int) biWidth, (int) biHeight); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); break; } if (biCompression != 0) ERREXIT(cinfo, JERR_BMP_COMPRESSED); if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) { /* Set JFIF density parameters from the BMP data */ cinfo->X_density = (UINT16) (biXPelsPerMeter/100); /* 100 cm per meter */ cinfo->Y_density = (UINT16) (biYPelsPerMeter/100); cinfo->density_unit = 2; /* dots/cm */ } break; default: ERREXIT(cinfo, JERR_BMP_BADHEADER); return; } if (biWidth <= 0 || biHeight <= 0) ERREXIT(cinfo, JERR_BMP_EMPTY); if (biPlanes != 1) ERREXIT(cinfo, JERR_BMP_BADPLANES); /* Compute distance to bitmap data --- will adjust for colormap below */ bPad = bfOffBits - (headerSize + 14); /* Read the colormap, if any */ if (mapentrysize > 0) { if (biClrUsed <= 0) biClrUsed = 256; /* assume it's 256 */ else if (biClrUsed > 256) ERREXIT(cinfo, JERR_BMP_BADCMAP); /* Allocate space to store the colormap */ source->colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) biClrUsed, (JDIMENSION) 3); /* and read it from the file */ read_colormap(source, (int) biClrUsed, mapentrysize); /* account for size of colormap */ bPad -= biClrUsed * mapentrysize; } /* Skip any remaining pad bytes */ if (bPad < 0) /* incorrect bfOffBits value? */ ERREXIT(cinfo, JERR_BMP_BADHEADER); while (--bPad >= 0) { (void) read_byte(source); } /* Compute row width in file, including padding to 4-byte boundary */ if (source->bits_per_pixel == 24) row_width = (JDIMENSION) (biWidth * 3); else if (source->bits_per_pixel == 32) row_width = (JDIMENSION) (biWidth * 4); else row_width = (JDIMENSION) biWidth; while ((row_width & 3) != 0) row_width++; source->row_width = row_width; /* Allocate space for inversion array, prepare for preload pass */ source->whole_image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, row_width, (JDIMENSION) biHeight, (JDIMENSION) 1); source->pub.get_pixel_rows = preload_image; if (cinfo->progress != NULL) { cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; progress->total_extra_passes++; /* count file input as separate pass */ } /* Allocate one-row buffer for returned data */ source->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) (biWidth * 3), (JDIMENSION) 1); source->pub.buffer_height = 1; cinfo->in_color_space = JCS_RGB; cinfo->input_components = 3; cinfo->data_precision = 8; cinfo->image_width = (JDIMENSION) biWidth; cinfo->image_height = (JDIMENSION) biHeight; } /* * Finish up at the end of the file. */ METHODDEF(void) finish_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { /* no work */ } /* * The module selection routine for BMP format input. */ GLOBAL(cjpeg_source_ptr) jinit_read_bmp (j_compress_ptr cinfo) { bmp_source_ptr source; /* Create module interface object */ source = (bmp_source_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(bmp_source_struct)); source->cinfo = cinfo; /* make back link for subroutines */ /* Fill in method ptrs, except get_pixel_rows which start_input sets */ source->pub.start_input = start_input_bmp; source->pub.finish_input = finish_input_bmp; return (cjpeg_source_ptr) source; } #endif /* BMP_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/rdcolmap.c ================================================ /* * rdcolmap.c * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file implements djpeg's "-map file" switch. It reads a source image * and constructs a colormap to be supplied to the JPEG decompressor. * * Currently, these file formats are supported for the map file: * GIF: the contents of the GIF's global colormap are used. * PPM (either text or raw flavor): the entire file is read and * each unique pixel value is entered in the map. * Note that reading a large PPM file will be horrendously slow. * Typically, a PPM-format map file should contain just one pixel * of each desired color. Such a file can be extracted from an * ordinary image PPM file with ppmtomap(1). * * Rescaling a PPM that has a maxval unequal to MAXJSAMPLE is not * currently implemented. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */ /* Portions of this code are based on the PBMPLUS library, which is: ** ** Copyright (C) 1988 by Jef Poskanzer. ** ** 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. */ /* * Add a (potentially) new color to the color map. */ LOCAL(void) add_map_entry (j_decompress_ptr cinfo, int R, int G, int B) { JSAMPROW colormap0 = cinfo->colormap[0]; JSAMPROW colormap1 = cinfo->colormap[1]; JSAMPROW colormap2 = cinfo->colormap[2]; int ncolors = cinfo->actual_number_of_colors; int index; /* Check for duplicate color. */ for (index = 0; index < ncolors; index++) { if (GETJSAMPLE(colormap0[index]) == R && GETJSAMPLE(colormap1[index]) == G && GETJSAMPLE(colormap2[index]) == B) return; /* color is already in map */ } /* Check for map overflow. */ if (ncolors >= (MAXJSAMPLE+1)) ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, (MAXJSAMPLE+1)); /* OK, add color to map. */ colormap0[ncolors] = (JSAMPLE) R; colormap1[ncolors] = (JSAMPLE) G; colormap2[ncolors] = (JSAMPLE) B; cinfo->actual_number_of_colors++; } /* * Extract color map from a GIF file. */ LOCAL(void) read_gif_map (j_decompress_ptr cinfo, FILE * infile) { int header[13]; int i, colormaplen; int R, G, B; /* Initial 'G' has already been read by read_color_map */ /* Read the rest of the GIF header and logical screen descriptor */ for (i = 1; i < 13; i++) { if ((header[i] = getc(infile)) == EOF) ERREXIT(cinfo, JERR_BAD_CMAP_FILE); } /* Verify GIF Header */ if (header[1] != 'I' || header[2] != 'F') ERREXIT(cinfo, JERR_BAD_CMAP_FILE); /* There must be a global color map. */ if ((header[10] & 0x80) == 0) ERREXIT(cinfo, JERR_BAD_CMAP_FILE); /* OK, fetch it. */ colormaplen = 2 << (header[10] & 0x07); for (i = 0; i < colormaplen; i++) { R = getc(infile); G = getc(infile); B = getc(infile); if (R == EOF || G == EOF || B == EOF) ERREXIT(cinfo, JERR_BAD_CMAP_FILE); add_map_entry(cinfo, R << (BITS_IN_JSAMPLE-8), G << (BITS_IN_JSAMPLE-8), B << (BITS_IN_JSAMPLE-8)); } } /* Support routines for reading PPM */ LOCAL(int) pbm_getc (FILE * infile) /* Read next char, skipping over any comments */ /* A comment/newline sequence is returned as a newline */ { register int ch; ch = getc(infile); if (ch == '#') { do { ch = getc(infile); } while (ch != '\n' && ch != EOF); } return ch; } LOCAL(unsigned int) read_pbm_integer (j_decompress_ptr cinfo, FILE * infile) /* Read an unsigned decimal integer from the PPM file */ /* Swallows one trailing character after the integer */ /* Note that on a 16-bit-int machine, only values up to 64k can be read. */ /* This should not be a problem in practice. */ { register int ch; register unsigned int val; /* Skip any leading whitespace */ do { ch = pbm_getc(infile); if (ch == EOF) ERREXIT(cinfo, JERR_BAD_CMAP_FILE); } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'); if (ch < '0' || ch > '9') ERREXIT(cinfo, JERR_BAD_CMAP_FILE); val = ch - '0'; while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') { val *= 10; val += ch - '0'; } return val; } /* * Extract color map from a PPM file. */ LOCAL(void) read_ppm_map (j_decompress_ptr cinfo, FILE * infile) { int c; unsigned int w, h, maxval, row, col; int R, G, B; /* Initial 'P' has already been read by read_color_map */ c = getc(infile); /* save format discriminator for a sec */ /* while we fetch the remaining header info */ w = read_pbm_integer(cinfo, infile); h = read_pbm_integer(cinfo, infile); maxval = read_pbm_integer(cinfo, infile); if (w <= 0 || h <= 0 || maxval <= 0) /* error check */ ERREXIT(cinfo, JERR_BAD_CMAP_FILE); /* For now, we don't support rescaling from an unusual maxval. */ if (maxval != (unsigned int) MAXJSAMPLE) ERREXIT(cinfo, JERR_BAD_CMAP_FILE); switch (c) { case '3': /* it's a text-format PPM file */ for (row = 0; row < h; row++) { for (col = 0; col < w; col++) { R = read_pbm_integer(cinfo, infile); G = read_pbm_integer(cinfo, infile); B = read_pbm_integer(cinfo, infile); add_map_entry(cinfo, R, G, B); } } break; case '6': /* it's a raw-format PPM file */ for (row = 0; row < h; row++) { for (col = 0; col < w; col++) { R = getc(infile); G = getc(infile); B = getc(infile); if (R == EOF || G == EOF || B == EOF) ERREXIT(cinfo, JERR_BAD_CMAP_FILE); add_map_entry(cinfo, R, G, B); } } break; default: ERREXIT(cinfo, JERR_BAD_CMAP_FILE); break; } } /* * Main entry point from djpeg.c. * Input: opened input file (from file name argument on command line). * Output: colormap and actual_number_of_colors fields are set in cinfo. */ GLOBAL(void) read_color_map (j_decompress_ptr cinfo, FILE * infile) { /* Allocate space for a color map of maximum supported size. */ cinfo->colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) (MAXJSAMPLE+1), (JDIMENSION) 3); cinfo->actual_number_of_colors = 0; /* initialize map to empty */ /* Read first byte to determine file format */ switch (getc(infile)) { case 'G': read_gif_map(cinfo, infile); break; case 'P': read_ppm_map(cinfo, infile); break; default: ERREXIT(cinfo, JERR_BAD_CMAP_FILE); break; } } #endif /* QUANT_2PASS_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/rdgif.c ================================================ /* * rdgif.c * * Copyright (C) 1991-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to read input images in GIF format. * ***************************************************************************** * NOTE: to avoid entanglements with Unisys' patent on LZW compression, * * the ability to read GIF files has been removed from the IJG distribution. * * Sorry about that. * ***************************************************************************** * * We are required to state that * "The Graphics Interchange Format(c) is the Copyright property of * CompuServe Incorporated. GIF(sm) is a Service Mark property of * CompuServe Incorporated." */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef GIF_SUPPORTED /* * The module selection routine for GIF format input. */ GLOBAL(cjpeg_source_ptr) jinit_read_gif (j_compress_ptr cinfo) { fprintf(stderr, "GIF input is unsupported for legal reasons. Sorry.\n"); exit(EXIT_FAILURE); return NULL; /* keep compiler happy */ } #endif /* GIF_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/rdjpgcom.1 ================================================ .TH RDJPGCOM 1 "13 September 2013" .SH NAME rdjpgcom \- display text comments from a JPEG file .SH SYNOPSIS .B rdjpgcom [ .B \-raw ] [ .B \-verbose ] [ .I filename ] .LP .SH DESCRIPTION .LP .B rdjpgcom reads the named JPEG/JFIF file, or the standard input if no file is named, and prints any text comments found in the file on the standard output. .PP The JPEG standard allows "comment" (COM) blocks to occur within a JPEG file. Although the standard doesn't actually define what COM blocks are for, they are widely used to hold user-supplied text strings. This lets you add annotations, titles, index terms, etc to your JPEG files, and later retrieve them as text. COM blocks do not interfere with the image stored in the JPEG file. The maximum size of a COM block is 64K, but you can have as many of them as you like in one JPEG file. .SH OPTIONS .TP .B \-raw Normally .B rdjpgcom escapes non-printable characters in comments, for security reasons. This option avoids that. .PP .B \-verbose Causes .B rdjpgcom to also display the JPEG image dimensions. .PP Switch names may be abbreviated, and are not case sensitive. .SH HINTS .B rdjpgcom does not depend on the IJG JPEG library. Its source code is intended as an illustration of the minimum amount of code required to parse a JPEG file header correctly. .PP In .B \-verbose mode, .B rdjpgcom will also attempt to print the contents of any "APP12" markers as text. Some digital cameras produce APP12 markers containing useful textual information. If you like, you can modify the source code to print other APPn marker types as well. .SH SEE ALSO .BR cjpeg (1), .BR djpeg (1), .BR jpegtran (1), .BR wrjpgcom (1) .SH AUTHOR Independent JPEG Group ================================================ FILE: tess-two/jni/libjpeg/rdjpgcom.c ================================================ /* * rdjpgcom.c * * Copyright (C) 1994-1997, Thomas G. Lane. * Modified 2009 by Bill Allombert, Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a very simple stand-alone application that displays * the text in COM (comment) markers in a JFIF file. * This may be useful as an example of the minimum logic needed to parse * JPEG markers. */ #define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */ #include "jinclude.h" /* get auto-config symbols, */ #ifdef HAVE_LOCALE_H #include /* Bill Allombert: use locale for isprint */ #endif #include /* to declare isupper(), tolower() */ #ifdef USE_SETMODE #include /* to declare setmode()'s parameter macros */ /* If you have setmode() but not , just delete this line: */ #include /* to declare setmode() */ #endif #ifdef USE_CCOMMAND /* command-line reader for Macintosh */ #ifdef __MWERKS__ #include /* Metrowerks needs this */ #include /* ... and this */ #endif #ifdef THINK_C #include /* Think declares it here */ #endif #endif #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */ #define READ_BINARY "r" #else #ifdef VMS /* VMS is very nonstandard */ #define READ_BINARY "rb", "ctx=stm" #else /* standard ANSI-compliant case */ #define READ_BINARY "rb" #endif #endif #ifndef EXIT_FAILURE /* define exit() codes if not provided */ #define EXIT_FAILURE 1 #endif #ifndef EXIT_SUCCESS #ifdef VMS #define EXIT_SUCCESS 1 /* VMS is very nonstandard */ #else #define EXIT_SUCCESS 0 #endif #endif /* * These macros are used to read the input file. * To reuse this code in another application, you might need to change these. */ static FILE * infile; /* input JPEG file */ /* Return next input byte, or EOF if no more */ #define NEXTBYTE() getc(infile) /* Error exit handler */ #define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE)) /* Read one byte, testing for EOF */ static int read_1_byte (void) { int c; c = NEXTBYTE(); if (c == EOF) ERREXIT("Premature EOF in JPEG file"); return c; } /* Read 2 bytes, convert to unsigned int */ /* All 2-byte quantities in JPEG markers are MSB first */ static unsigned int read_2_bytes (void) { int c1, c2; c1 = NEXTBYTE(); if (c1 == EOF) ERREXIT("Premature EOF in JPEG file"); c2 = NEXTBYTE(); if (c2 == EOF) ERREXIT("Premature EOF in JPEG file"); return (((unsigned int) c1) << 8) + ((unsigned int) c2); } /* * JPEG markers consist of one or more 0xFF bytes, followed by a marker * code byte (which is not an FF). Here are the marker codes of interest * in this program. (See jdmarker.c for a more complete list.) */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */ #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_APP0 0xE0 /* Application-specific marker, type N */ #define M_APP12 0xEC /* (we don't bother to list all 16 APPn's) */ #define M_COM 0xFE /* COMment */ /* * Find the next JPEG marker and return its marker code. * We expect at least one FF byte, possibly more if the compressor used FFs * to pad the file. * There could also be non-FF garbage between markers. The treatment of such * garbage is unspecified; we choose to skip over it but emit a warning msg. * NB: this routine must not be used after seeing SOS marker, since it will * not deal correctly with FF/00 sequences in the compressed image data... */ static int next_marker (void) { int c; int discarded_bytes = 0; /* Find 0xFF byte; count and skip any non-FFs. */ c = read_1_byte(); while (c != 0xFF) { discarded_bytes++; c = read_1_byte(); } /* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs * are legal as pad bytes, so don't count them in discarded_bytes. */ do { c = read_1_byte(); } while (c == 0xFF); if (discarded_bytes != 0) { fprintf(stderr, "Warning: garbage data found in JPEG file\n"); } return c; } /* * Read the initial marker, which should be SOI. * For a JFIF file, the first two bytes of the file should be literally * 0xFF M_SOI. To be more general, we could use next_marker, but if the * input file weren't actually JPEG at all, next_marker might read the whole * file and then return a misleading error message... */ static int first_marker (void) { int c1, c2; c1 = NEXTBYTE(); c2 = NEXTBYTE(); if (c1 != 0xFF || c2 != M_SOI) ERREXIT("Not a JPEG file"); return c2; } /* * Most types of marker are followed by a variable-length parameter segment. * This routine skips over the parameters for any marker we don't otherwise * want to process. * Note that we MUST skip the parameter segment explicitly in order not to * be fooled by 0xFF bytes that might appear within the parameter segment; * such bytes do NOT introduce new markers. */ static void skip_variable (void) /* Skip over an unknown or uninteresting variable-length marker */ { unsigned int length; /* Get the marker parameter length count */ length = read_2_bytes(); /* Length includes itself, so must be at least 2 */ if (length < 2) ERREXIT("Erroneous JPEG marker length"); length -= 2; /* Skip over the remaining bytes */ while (length > 0) { (void) read_1_byte(); length--; } } /* * Process a COM marker. * We want to print out the marker contents as legible text; * we must guard against non-text junk and varying newline representations. */ static void process_COM (int raw) { unsigned int length; int ch; int lastch = 0; /* Bill Allombert: set locale properly for isprint */ #ifdef HAVE_LOCALE_H setlocale(LC_CTYPE, ""); #endif /* Get the marker parameter length count */ length = read_2_bytes(); /* Length includes itself, so must be at least 2 */ if (length < 2) ERREXIT("Erroneous JPEG marker length"); length -= 2; while (length > 0) { ch = read_1_byte(); if (raw) { putc(ch, stdout); /* Emit the character in a readable form. * Nonprintables are converted to \nnn form, * while \ is converted to \\. * Newlines in CR, CR/LF, or LF form will be printed as one newline. */ } else if (ch == '\r') { printf("\n"); } else if (ch == '\n') { if (lastch != '\r') printf("\n"); } else if (ch == '\\') { printf("\\\\"); } else if (isprint(ch)) { putc(ch, stdout); } else { printf("\\%03o", ch); } lastch = ch; length--; } printf("\n"); /* Bill Allombert: revert to C locale */ #ifdef HAVE_LOCALE_H setlocale(LC_CTYPE, "C"); #endif } /* * Process a SOFn marker. * This code is only needed if you want to know the image dimensions... */ static void process_SOFn (int marker) { unsigned int length; unsigned int image_height, image_width; int data_precision, num_components; const char * process; int ci; length = read_2_bytes(); /* usual parameter length count */ data_precision = read_1_byte(); image_height = read_2_bytes(); image_width = read_2_bytes(); num_components = read_1_byte(); switch (marker) { case M_SOF0: process = "Baseline"; break; case M_SOF1: process = "Extended sequential"; break; case M_SOF2: process = "Progressive"; break; case M_SOF3: process = "Lossless"; break; case M_SOF5: process = "Differential sequential"; break; case M_SOF6: process = "Differential progressive"; break; case M_SOF7: process = "Differential lossless"; break; case M_SOF9: process = "Extended sequential, arithmetic coding"; break; case M_SOF10: process = "Progressive, arithmetic coding"; break; case M_SOF11: process = "Lossless, arithmetic coding"; break; case M_SOF13: process = "Differential sequential, arithmetic coding"; break; case M_SOF14: process = "Differential progressive, arithmetic coding"; break; case M_SOF15: process = "Differential lossless, arithmetic coding"; break; default: process = "Unknown"; break; } printf("JPEG image is %uw * %uh, %d color components, %d bits per sample\n", image_width, image_height, num_components, data_precision); printf("JPEG process: %s\n", process); if (length != (unsigned int) (8 + num_components * 3)) ERREXIT("Bogus SOF marker length"); for (ci = 0; ci < num_components; ci++) { (void) read_1_byte(); /* Component ID code */ (void) read_1_byte(); /* H, V sampling factors */ (void) read_1_byte(); /* Quantization table number */ } } /* * Parse the marker stream until SOS or EOI is seen; * display any COM markers. * While the companion program wrjpgcom will always insert COM markers before * SOFn, other implementations might not, so we scan to SOS before stopping. * If we were only interested in the image dimensions, we would stop at SOFn. * (Conversely, if we only cared about COM markers, there would be no need * for special code to handle SOFn; we could treat it like other markers.) */ static int scan_JPEG_header (int verbose, int raw) { int marker; /* Expect SOI at start of file */ if (first_marker() != M_SOI) ERREXIT("Expected SOI marker first"); /* Scan miscellaneous markers until we reach SOS. */ for (;;) { marker = next_marker(); switch (marker) { /* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be, * treated as SOFn. C4 in particular is actually DHT. */ case M_SOF0: /* Baseline */ case M_SOF1: /* Extended sequential, Huffman */ case M_SOF2: /* Progressive, Huffman */ case M_SOF3: /* Lossless, Huffman */ case M_SOF5: /* Differential sequential, Huffman */ case M_SOF6: /* Differential progressive, Huffman */ case M_SOF7: /* Differential lossless, Huffman */ case M_SOF9: /* Extended sequential, arithmetic */ case M_SOF10: /* Progressive, arithmetic */ case M_SOF11: /* Lossless, arithmetic */ case M_SOF13: /* Differential sequential, arithmetic */ case M_SOF14: /* Differential progressive, arithmetic */ case M_SOF15: /* Differential lossless, arithmetic */ if (verbose) process_SOFn(marker); else skip_variable(); break; case M_SOS: /* stop before hitting compressed data */ return marker; case M_EOI: /* in case it's a tables-only JPEG stream */ return marker; case M_COM: process_COM(raw); break; case M_APP12: /* Some digital camera makers put useful textual information into * APP12 markers, so we print those out too when in -verbose mode. */ if (verbose) { printf("APP12 contains:\n"); process_COM(raw); } else skip_variable(); break; default: /* Anything else just gets skipped */ skip_variable(); /* we assume it has a parameter count... */ break; } } /* end loop */ } /* Command line parsing code */ static const char * progname; /* program name for error messages */ static void usage (void) /* complain about bad command line */ { fprintf(stderr, "rdjpgcom displays any textual comments in a JPEG file.\n"); fprintf(stderr, "Usage: %s [switches] [inputfile]\n", progname); fprintf(stderr, "Switches (names may be abbreviated):\n"); fprintf(stderr, " -raw Display non-printable characters in comments (unsafe)\n"); fprintf(stderr, " -verbose Also display dimensions of JPEG image\n"); exit(EXIT_FAILURE); } static int keymatch (char * arg, const char * keyword, int minchars) /* Case-insensitive matching of (possibly abbreviated) keyword switches. */ /* keyword is the constant keyword (must be lower case already), */ /* minchars is length of minimum legal abbreviation. */ { register int ca, ck; register int nmatched = 0; while ((ca = *arg++) != '\0') { if ((ck = *keyword++) == '\0') return 0; /* arg longer than keyword, no good */ if (isupper(ca)) /* force arg to lcase (assume ck is already) */ ca = tolower(ca); if (ca != ck) return 0; /* no good */ nmatched++; /* count matched characters */ } /* reached end of argument; fail if it's too short for unique abbrev */ if (nmatched < minchars) return 0; return 1; /* A-OK */ } /* * The main program. */ int main (int argc, char **argv) { int argn; char * arg; int verbose = 0, raw = 0; /* On Mac, fetch a command line. */ #ifdef USE_CCOMMAND argc = ccommand(&argv); #endif progname = argv[0]; if (progname == NULL || progname[0] == 0) progname = "rdjpgcom"; /* in case C library doesn't provide it */ /* Parse switches, if any */ for (argn = 1; argn < argc; argn++) { arg = argv[argn]; if (arg[0] != '-') break; /* not switch, must be file name */ arg++; /* advance over '-' */ if (keymatch(arg, "verbose", 1)) { verbose++; } else if (keymatch(arg, "raw", 1)) { raw = 1; } else usage(); } /* Open the input file. */ /* Unix style: expect zero or one file name */ if (argn < argc-1) { fprintf(stderr, "%s: only one input file\n", progname); usage(); } if (argn < argc) { if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]); exit(EXIT_FAILURE); } } else { /* default input file is stdin */ #ifdef USE_SETMODE /* need to hack file mode? */ setmode(fileno(stdin), O_BINARY); #endif #ifdef USE_FDOPEN /* need to re-open in binary mode? */ if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open stdin\n", progname); exit(EXIT_FAILURE); } #else infile = stdin; #endif } /* Scan the JPEG headers. */ (void) scan_JPEG_header(verbose, raw); /* All done. */ exit(EXIT_SUCCESS); return 0; /* suppress no-return-value warnings */ } ================================================ FILE: tess-two/jni/libjpeg/rdppm.c ================================================ /* * rdppm.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2009 by Bill Allombert, Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to read input images in PPM/PGM format. * The extended 2-byte-per-sample raw PPM/PGM formats are supported. * The PBMPLUS library is NOT required to compile this software * (but it is highly useful as a set of PPM image manipulation programs). * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume input from * an ordinary stdio stream. They further assume that reading begins * at the start of the file; start_input may need work if the * user interface has already read some data (e.g., to determine that * the file is indeed PPM format). */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef PPM_SUPPORTED /* Portions of this code are based on the PBMPLUS library, which is: ** ** Copyright (C) 1988 by Jef Poskanzer. ** ** 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. */ /* Macros to deal with unsigned chars as efficiently as compiler allows */ #ifdef HAVE_UNSIGNED_CHAR typedef unsigned char U_CHAR; #define UCH(x) ((int) (x)) #else /* !HAVE_UNSIGNED_CHAR */ #ifdef CHAR_IS_UNSIGNED typedef char U_CHAR; #define UCH(x) ((int) (x)) #else typedef char U_CHAR; #define UCH(x) ((int) (x) & 0xFF) #endif #endif /* HAVE_UNSIGNED_CHAR */ #define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len))) /* * On most systems, reading individual bytes with getc() is drastically less * efficient than buffering a row at a time with fread(). On PCs, we must * allocate the buffer in near data space, because we are assuming small-data * memory model, wherein fread() can't reach far memory. If you need to * process very wide images on a PC, you might have to compile in large-memory * model, or else replace fread() with a getc() loop --- which will be much * slower. */ /* Private version of data source object */ typedef struct { struct cjpeg_source_struct pub; /* public fields */ U_CHAR *iobuffer; /* non-FAR pointer to I/O buffer */ JSAMPROW pixrow; /* FAR pointer to same */ size_t buffer_width; /* width of I/O buffer */ JSAMPLE *rescale; /* => maxval-remapping array, or NULL */ } ppm_source_struct; typedef ppm_source_struct * ppm_source_ptr; LOCAL(int) pbm_getc (FILE * infile) /* Read next char, skipping over any comments */ /* A comment/newline sequence is returned as a newline */ { register int ch; ch = getc(infile); if (ch == '#') { do { ch = getc(infile); } while (ch != '\n' && ch != EOF); } return ch; } LOCAL(unsigned int) read_pbm_integer (j_compress_ptr cinfo, FILE * infile) /* Read an unsigned decimal integer from the PPM file */ /* Swallows one trailing character after the integer */ /* Note that on a 16-bit-int machine, only values up to 64k can be read. */ /* This should not be a problem in practice. */ { register int ch; register unsigned int val; /* Skip any leading whitespace */ do { ch = pbm_getc(infile); if (ch == EOF) ERREXIT(cinfo, JERR_INPUT_EOF); } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'); if (ch < '0' || ch > '9') ERREXIT(cinfo, JERR_PPM_NONNUMERIC); val = ch - '0'; while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') { val *= 10; val += ch - '0'; } return val; } /* * Read one row of pixels. * * We provide several different versions depending on input file format. * In all cases, input is scaled to the size of JSAMPLE. * * A really fast path is provided for reading byte/sample raw files with * maxval = MAXJSAMPLE, which is the normal case for 8-bit data. */ METHODDEF(JDIMENSION) get_text_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading text-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; FILE * infile = source->pub.input_file; register JSAMPROW ptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; ptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { *ptr++ = rescale[read_pbm_integer(cinfo, infile)]; } return 1; } METHODDEF(JDIMENSION) get_text_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading text-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; FILE * infile = source->pub.input_file; register JSAMPROW ptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; ptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { *ptr++ = rescale[read_pbm_integer(cinfo, infile)]; *ptr++ = rescale[read_pbm_integer(cinfo, infile)]; *ptr++ = rescale[read_pbm_integer(cinfo, infile)]; } return 1; } METHODDEF(JDIMENSION) get_scaled_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-byte-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; register JSAMPROW ptr; register U_CHAR * bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { *ptr++ = rescale[UCH(*bufferptr++)]; } return 1; } METHODDEF(JDIMENSION) get_scaled_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-byte-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; register JSAMPROW ptr; register U_CHAR * bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { *ptr++ = rescale[UCH(*bufferptr++)]; *ptr++ = rescale[UCH(*bufferptr++)]; *ptr++ = rescale[UCH(*bufferptr++)]; } return 1; } METHODDEF(JDIMENSION) get_raw_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-byte-format files with maxval = MAXJSAMPLE. * In this case we just read right into the JSAMPLE buffer! * Note that same code works for PPM and PGM files. */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); return 1; } METHODDEF(JDIMENSION) get_word_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; register JSAMPROW ptr; register U_CHAR * bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); *ptr++ = rescale[temp]; } return 1; } METHODDEF(JDIMENSION) get_word_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; register JSAMPROW ptr; register U_CHAR * bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); *ptr++ = rescale[temp]; } return 1; } /* * Read the file header; return image size and component count. */ METHODDEF(void) start_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { ppm_source_ptr source = (ppm_source_ptr) sinfo; int c; unsigned int w, h, maxval; boolean need_iobuffer, use_raw_buffer, need_rescale; if (getc(source->pub.input_file) != 'P') ERREXIT(cinfo, JERR_PPM_NOT); c = getc(source->pub.input_file); /* subformat discriminator character */ /* detect unsupported variants (ie, PBM) before trying to read header */ switch (c) { case '2': /* it's a text-format PGM file */ case '3': /* it's a text-format PPM file */ case '5': /* it's a raw-format PGM file */ case '6': /* it's a raw-format PPM file */ break; default: ERREXIT(cinfo, JERR_PPM_NOT); break; } /* fetch the remaining header info */ w = read_pbm_integer(cinfo, source->pub.input_file); h = read_pbm_integer(cinfo, source->pub.input_file); maxval = read_pbm_integer(cinfo, source->pub.input_file); if (w <= 0 || h <= 0 || maxval <= 0) /* error check */ ERREXIT(cinfo, JERR_PPM_NOT); cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */ cinfo->image_width = (JDIMENSION) w; cinfo->image_height = (JDIMENSION) h; /* initialize flags to most common settings */ need_iobuffer = TRUE; /* do we need an I/O buffer? */ use_raw_buffer = FALSE; /* do we map input buffer onto I/O buffer? */ need_rescale = TRUE; /* do we need a rescale array? */ switch (c) { case '2': /* it's a text-format PGM file */ cinfo->input_components = 1; cinfo->in_color_space = JCS_GRAYSCALE; TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h); source->pub.get_pixel_rows = get_text_gray_row; need_iobuffer = FALSE; break; case '3': /* it's a text-format PPM file */ cinfo->input_components = 3; cinfo->in_color_space = JCS_RGB; TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h); source->pub.get_pixel_rows = get_text_rgb_row; need_iobuffer = FALSE; break; case '5': /* it's a raw-format PGM file */ cinfo->input_components = 1; cinfo->in_color_space = JCS_GRAYSCALE; TRACEMS2(cinfo, 1, JTRC_PGM, w, h); if (maxval > 255) { source->pub.get_pixel_rows = get_word_gray_row; } else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) { source->pub.get_pixel_rows = get_raw_row; use_raw_buffer = TRUE; need_rescale = FALSE; } else { source->pub.get_pixel_rows = get_scaled_gray_row; } break; case '6': /* it's a raw-format PPM file */ cinfo->input_components = 3; cinfo->in_color_space = JCS_RGB; TRACEMS2(cinfo, 1, JTRC_PPM, w, h); if (maxval > 255) { source->pub.get_pixel_rows = get_word_rgb_row; } else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) { source->pub.get_pixel_rows = get_raw_row; use_raw_buffer = TRUE; need_rescale = FALSE; } else { source->pub.get_pixel_rows = get_scaled_rgb_row; } break; } /* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */ if (need_iobuffer) { source->buffer_width = (size_t) w * cinfo->input_components * ((maxval<=255) ? SIZEOF(U_CHAR) : (2*SIZEOF(U_CHAR))); source->iobuffer = (U_CHAR *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, source->buffer_width); } /* Create compressor input buffer. */ if (use_raw_buffer) { /* For unscaled raw-input case, we can just map it onto the I/O buffer. */ /* Synthesize a JSAMPARRAY pointer structure */ /* Cast here implies near->far pointer conversion on PCs */ source->pixrow = (JSAMPROW) source->iobuffer; source->pub.buffer = & source->pixrow; source->pub.buffer_height = 1; } else { /* Need to translate anyway, so make a separate sample buffer. */ source->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) w * cinfo->input_components, (JDIMENSION) 1); source->pub.buffer_height = 1; } /* Compute the rescaling array if required. */ if (need_rescale) { INT32 val, half_maxval; /* On 16-bit-int machines we have to be careful of maxval = 65535 */ source->rescale = (JSAMPLE *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (size_t) (((long) maxval + 1L) * SIZEOF(JSAMPLE))); half_maxval = maxval / 2; for (val = 0; val <= (INT32) maxval; val++) { /* The multiplication here must be done in 32 bits to avoid overflow */ source->rescale[val] = (JSAMPLE) ((val*MAXJSAMPLE + half_maxval)/maxval); } } } /* * Finish up at the end of the file. */ METHODDEF(void) finish_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { /* no work */ } /* * The module selection routine for PPM format input. */ GLOBAL(cjpeg_source_ptr) jinit_read_ppm (j_compress_ptr cinfo) { ppm_source_ptr source; /* Create module interface object */ source = (ppm_source_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(ppm_source_struct)); /* Fill in method ptrs, except get_pixel_rows which start_input sets */ source->pub.start_input = start_input_ppm; source->pub.finish_input = finish_input_ppm; return (cjpeg_source_ptr) source; } #endif /* PPM_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/rdrle.c ================================================ /* * rdrle.c * * Copyright (C) 1991-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to read input images in Utah RLE format. * The Utah Raster Toolkit library is required (version 3.1 or later). * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume input from * an ordinary stdio stream. They further assume that reading begins * at the start of the file; start_input may need work if the * user interface has already read some data (e.g., to determine that * the file is indeed RLE format). * * Based on code contributed by Mike Lijewski, * with updates from Robert Hutchinson. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef RLE_SUPPORTED /* rle.h is provided by the Utah Raster Toolkit. */ #include /* * We assume that JSAMPLE has the same representation as rle_pixel, * to wit, "unsigned char". Hence we can't cope with 12- or 16-bit samples. */ #if BITS_IN_JSAMPLE != 8 Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */ #endif /* * We support the following types of RLE files: * * GRAYSCALE - 8 bits, no colormap * MAPPEDGRAY - 8 bits, 1 channel colomap * PSEUDOCOLOR - 8 bits, 3 channel colormap * TRUECOLOR - 24 bits, 3 channel colormap * DIRECTCOLOR - 24 bits, no colormap * * For now, we ignore any alpha channel in the image. */ typedef enum { GRAYSCALE, MAPPEDGRAY, PSEUDOCOLOR, TRUECOLOR, DIRECTCOLOR } rle_kind; /* * Since RLE stores scanlines bottom-to-top, we have to invert the image * to conform to JPEG's top-to-bottom order. To do this, we read the * incoming image into a virtual array on the first get_pixel_rows call, * then fetch the required row from the virtual array on subsequent calls. */ typedef struct _rle_source_struct * rle_source_ptr; typedef struct _rle_source_struct { struct cjpeg_source_struct pub; /* public fields */ rle_kind visual; /* actual type of input file */ jvirt_sarray_ptr image; /* virtual array to hold the image */ JDIMENSION row; /* current row # in the virtual array */ rle_hdr header; /* Input file information */ rle_pixel** rle_row; /* holds a row returned by rle_getrow() */ } rle_source_struct; /* * Read the file header; return image size and component count. */ METHODDEF(void) start_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { rle_source_ptr source = (rle_source_ptr) sinfo; JDIMENSION width, height; #ifdef PROGRESS_REPORT cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; #endif /* Use RLE library routine to get the header info */ source->header = *rle_hdr_init(NULL); source->header.rle_file = source->pub.input_file; switch (rle_get_setup(&(source->header))) { case RLE_SUCCESS: /* A-OK */ break; case RLE_NOT_RLE: ERREXIT(cinfo, JERR_RLE_NOT); break; case RLE_NO_SPACE: ERREXIT(cinfo, JERR_RLE_MEM); break; case RLE_EMPTY: ERREXIT(cinfo, JERR_RLE_EMPTY); break; case RLE_EOF: ERREXIT(cinfo, JERR_RLE_EOF); break; default: ERREXIT(cinfo, JERR_RLE_BADERROR); break; } /* Figure out what we have, set private vars and return values accordingly */ width = source->header.xmax - source->header.xmin + 1; height = source->header.ymax - source->header.ymin + 1; source->header.xmin = 0; /* realign horizontally */ source->header.xmax = width-1; cinfo->image_width = width; cinfo->image_height = height; cinfo->data_precision = 8; /* we can only handle 8 bit data */ if (source->header.ncolors == 1 && source->header.ncmap == 0) { source->visual = GRAYSCALE; TRACEMS2(cinfo, 1, JTRC_RLE_GRAY, width, height); } else if (source->header.ncolors == 1 && source->header.ncmap == 1) { source->visual = MAPPEDGRAY; TRACEMS3(cinfo, 1, JTRC_RLE_MAPGRAY, width, height, 1 << source->header.cmaplen); } else if (source->header.ncolors == 1 && source->header.ncmap == 3) { source->visual = PSEUDOCOLOR; TRACEMS3(cinfo, 1, JTRC_RLE_MAPPED, width, height, 1 << source->header.cmaplen); } else if (source->header.ncolors == 3 && source->header.ncmap == 3) { source->visual = TRUECOLOR; TRACEMS3(cinfo, 1, JTRC_RLE_FULLMAP, width, height, 1 << source->header.cmaplen); } else if (source->header.ncolors == 3 && source->header.ncmap == 0) { source->visual = DIRECTCOLOR; TRACEMS2(cinfo, 1, JTRC_RLE, width, height); } else ERREXIT(cinfo, JERR_RLE_UNSUPPORTED); if (source->visual == GRAYSCALE || source->visual == MAPPEDGRAY) { cinfo->in_color_space = JCS_GRAYSCALE; cinfo->input_components = 1; } else { cinfo->in_color_space = JCS_RGB; cinfo->input_components = 3; } /* * A place to hold each scanline while it's converted. * (GRAYSCALE scanlines don't need converting) */ if (source->visual != GRAYSCALE) { source->rle_row = (rle_pixel**) (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) width, (JDIMENSION) cinfo->input_components); } /* request a virtual array to hold the image */ source->image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, (JDIMENSION) (width * source->header.ncolors), (JDIMENSION) height, (JDIMENSION) 1); #ifdef PROGRESS_REPORT if (progress != NULL) { /* count file input as separate pass */ progress->total_extra_passes++; } #endif source->pub.buffer_height = 1; } /* * Read one row of pixels. * Called only after load_image has read the image into the virtual array. * Used for GRAYSCALE, MAPPEDGRAY, TRUECOLOR, and DIRECTCOLOR images. */ METHODDEF(JDIMENSION) get_rle_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { rle_source_ptr source = (rle_source_ptr) sinfo; source->row--; source->pub.buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE); return 1; } /* * Read one row of pixels. * Called only after load_image has read the image into the virtual array. * Used for PSEUDOCOLOR images. */ METHODDEF(JDIMENSION) get_pseudocolor_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { rle_source_ptr source = (rle_source_ptr) sinfo; JSAMPROW src_row, dest_row; JDIMENSION col; rle_map *colormap; int val; colormap = source->header.cmap; dest_row = source->pub.buffer[0]; source->row--; src_row = * (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE); for (col = cinfo->image_width; col > 0; col--) { val = GETJSAMPLE(*src_row++); *dest_row++ = (JSAMPLE) (colormap[val ] >> 8); *dest_row++ = (JSAMPLE) (colormap[val + 256] >> 8); *dest_row++ = (JSAMPLE) (colormap[val + 512] >> 8); } return 1; } /* * Load the image into a virtual array. We have to do this because RLE * files start at the lower left while the JPEG standard has them starting * in the upper left. This is called the first time we want to get a row * of input. What we do is load the RLE data into the array and then call * the appropriate routine to read one row from the array. Before returning, * we set source->pub.get_pixel_rows so that subsequent calls go straight to * the appropriate row-reading routine. */ METHODDEF(JDIMENSION) load_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { rle_source_ptr source = (rle_source_ptr) sinfo; JDIMENSION row, col; JSAMPROW scanline, red_ptr, green_ptr, blue_ptr; rle_pixel **rle_row; rle_map *colormap; char channel; #ifdef PROGRESS_REPORT cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; #endif colormap = source->header.cmap; rle_row = source->rle_row; /* Read the RLE data into our virtual array. * We assume here that (a) rle_pixel is represented the same as JSAMPLE, * and (b) we are not on a machine where FAR pointers differ from regular. */ RLE_CLR_BIT(source->header, RLE_ALPHA); /* don't read the alpha channel */ #ifdef PROGRESS_REPORT if (progress != NULL) { progress->pub.pass_limit = cinfo->image_height; progress->pub.pass_counter = 0; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } #endif switch (source->visual) { case GRAYSCALE: case PSEUDOCOLOR: for (row = 0; row < cinfo->image_height; row++) { rle_row = (rle_pixel **) (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE); rle_getrow(&source->header, rle_row); #ifdef PROGRESS_REPORT if (progress != NULL) { progress->pub.pass_counter++; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } #endif } break; case MAPPEDGRAY: case TRUECOLOR: for (row = 0; row < cinfo->image_height; row++) { scanline = * (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE); rle_row = source->rle_row; rle_getrow(&source->header, rle_row); for (col = 0; col < cinfo->image_width; col++) { for (channel = 0; channel < source->header.ncolors; channel++) { *scanline++ = (JSAMPLE) (colormap[GETJSAMPLE(rle_row[channel][col]) + 256 * channel] >> 8); } } #ifdef PROGRESS_REPORT if (progress != NULL) { progress->pub.pass_counter++; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } #endif } break; case DIRECTCOLOR: for (row = 0; row < cinfo->image_height; row++) { scanline = * (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE); rle_getrow(&source->header, rle_row); red_ptr = rle_row[0]; green_ptr = rle_row[1]; blue_ptr = rle_row[2]; for (col = cinfo->image_width; col > 0; col--) { *scanline++ = *red_ptr++; *scanline++ = *green_ptr++; *scanline++ = *blue_ptr++; } #ifdef PROGRESS_REPORT if (progress != NULL) { progress->pub.pass_counter++; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } #endif } } #ifdef PROGRESS_REPORT if (progress != NULL) progress->completed_extra_passes++; #endif /* Set up to call proper row-extraction routine in future */ if (source->visual == PSEUDOCOLOR) { source->pub.buffer = source->rle_row; source->pub.get_pixel_rows = get_pseudocolor_row; } else { source->pub.get_pixel_rows = get_rle_row; } source->row = cinfo->image_height; /* And fetch the topmost (bottommost) row */ return (*source->pub.get_pixel_rows) (cinfo, sinfo); } /* * Finish up at the end of the file. */ METHODDEF(void) finish_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { /* no work */ } /* * The module selection routine for RLE format input. */ GLOBAL(cjpeg_source_ptr) jinit_read_rle (j_compress_ptr cinfo) { rle_source_ptr source; /* Create module interface object */ source = (rle_source_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(rle_source_struct)); /* Fill in method ptrs */ source->pub.start_input = start_input_rle; source->pub.finish_input = finish_input_rle; source->pub.get_pixel_rows = load_image; return (cjpeg_source_ptr) source; } #endif /* RLE_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/rdswitch.c ================================================ /* * rdswitch.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2003-2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to process some of cjpeg's more complicated * command-line switches. Switches processed here are: * -qtables file Read quantization tables from text file * -scans file Read scan script from text file * -quality N[,N,...] Set quality ratings * -qslots N[,N,...] Set component quantization table selectors * -sample HxV[,HxV,...] Set component sampling factors */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #include /* to declare isdigit(), isspace() */ LOCAL(int) text_getc (FILE * file) /* Read next char, skipping over any comments (# to end of line) */ /* A comment/newline sequence is returned as a newline */ { register int ch; ch = getc(file); if (ch == '#') { do { ch = getc(file); } while (ch != '\n' && ch != EOF); } return ch; } LOCAL(boolean) read_text_integer (FILE * file, long * result, int * termchar) /* Read an unsigned decimal integer from a file, store it in result */ /* Reads one trailing character after the integer; returns it in termchar */ { register int ch; register long val; /* Skip any leading whitespace, detect EOF */ do { ch = text_getc(file); if (ch == EOF) { *termchar = ch; return FALSE; } } while (isspace(ch)); if (! isdigit(ch)) { *termchar = ch; return FALSE; } val = ch - '0'; while ((ch = text_getc(file)) != EOF) { if (! isdigit(ch)) break; val *= 10; val += ch - '0'; } *result = val; *termchar = ch; return TRUE; } GLOBAL(boolean) read_quant_tables (j_compress_ptr cinfo, char * filename, boolean force_baseline) /* Read a set of quantization tables from the specified file. * The file is plain ASCII text: decimal numbers with whitespace between. * Comments preceded by '#' may be included in the file. * There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values. * The tables are implicitly numbered 0,1,etc. * NOTE: does not affect the qslots mapping, which will default to selecting * table 0 for luminance (or primary) components, 1 for chrominance components. * You must use -qslots if you want a different component->table mapping. */ { FILE * fp; int tblno, i, termchar; long val; unsigned int table[DCTSIZE2]; if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Can't open table file %s\n", filename); return FALSE; } tblno = 0; while (read_text_integer(fp, &val, &termchar)) { /* read 1st element of table */ if (tblno >= NUM_QUANT_TBLS) { fprintf(stderr, "Too many tables in file %s\n", filename); fclose(fp); return FALSE; } table[0] = (unsigned int) val; for (i = 1; i < DCTSIZE2; i++) { if (! read_text_integer(fp, &val, &termchar)) { fprintf(stderr, "Invalid table data in file %s\n", filename); fclose(fp); return FALSE; } table[i] = (unsigned int) val; } jpeg_add_quant_table(cinfo, tblno, table, cinfo->q_scale_factor[tblno], force_baseline); tblno++; } if (termchar != EOF) { fprintf(stderr, "Non-numeric data in file %s\n", filename); fclose(fp); return FALSE; } fclose(fp); return TRUE; } #ifdef C_MULTISCAN_FILES_SUPPORTED LOCAL(boolean) read_scan_integer (FILE * file, long * result, int * termchar) /* Variant of read_text_integer that always looks for a non-space termchar; * this simplifies parsing of punctuation in scan scripts. */ { register int ch; if (! read_text_integer(file, result, termchar)) return FALSE; ch = *termchar; while (ch != EOF && isspace(ch)) ch = text_getc(file); if (isdigit(ch)) { /* oops, put it back */ if (ungetc(ch, file) == EOF) return FALSE; ch = ' '; } else { /* Any separators other than ';' and ':' are ignored; * this allows user to insert commas, etc, if desired. */ if (ch != EOF && ch != ';' && ch != ':') ch = ' '; } *termchar = ch; return TRUE; } GLOBAL(boolean) read_scan_script (j_compress_ptr cinfo, char * filename) /* Read a scan script from the specified text file. * Each entry in the file defines one scan to be emitted. * Entries are separated by semicolons ';'. * An entry contains one to four component indexes, * optionally followed by a colon ':' and four progressive-JPEG parameters. * The component indexes denote which component(s) are to be transmitted * in the current scan. The first component has index 0. * Sequential JPEG is used if the progressive-JPEG parameters are omitted. * The file is free format text: any whitespace may appear between numbers * and the ':' and ';' punctuation marks. Also, other punctuation (such * as commas or dashes) can be placed between numbers if desired. * Comments preceded by '#' may be included in the file. * Note: we do very little validity checking here; * jcmaster.c will validate the script parameters. */ { FILE * fp; int scanno, ncomps, termchar; long val; jpeg_scan_info * scanptr; #define MAX_SCANS 100 /* quite arbitrary limit */ jpeg_scan_info scans[MAX_SCANS]; if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Can't open scan definition file %s\n", filename); return FALSE; } scanptr = scans; scanno = 0; while (read_scan_integer(fp, &val, &termchar)) { if (scanno >= MAX_SCANS) { fprintf(stderr, "Too many scans defined in file %s\n", filename); fclose(fp); return FALSE; } scanptr->component_index[0] = (int) val; ncomps = 1; while (termchar == ' ') { if (ncomps >= MAX_COMPS_IN_SCAN) { fprintf(stderr, "Too many components in one scan in file %s\n", filename); fclose(fp); return FALSE; } if (! read_scan_integer(fp, &val, &termchar)) goto bogus; scanptr->component_index[ncomps] = (int) val; ncomps++; } scanptr->comps_in_scan = ncomps; if (termchar == ':') { if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ') goto bogus; scanptr->Ss = (int) val; if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ') goto bogus; scanptr->Se = (int) val; if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ') goto bogus; scanptr->Ah = (int) val; if (! read_scan_integer(fp, &val, &termchar)) goto bogus; scanptr->Al = (int) val; } else { /* set non-progressive parameters */ scanptr->Ss = 0; scanptr->Se = DCTSIZE2-1; scanptr->Ah = 0; scanptr->Al = 0; } if (termchar != ';' && termchar != EOF) { bogus: fprintf(stderr, "Invalid scan entry format in file %s\n", filename); fclose(fp); return FALSE; } scanptr++, scanno++; } if (termchar != EOF) { fprintf(stderr, "Non-numeric data in file %s\n", filename); fclose(fp); return FALSE; } if (scanno > 0) { /* Stash completed scan list in cinfo structure. * NOTE: for cjpeg's use, JPOOL_IMAGE is the right lifetime for this data, * but if you want to compress multiple images you'd want JPOOL_PERMANENT. */ scanptr = (jpeg_scan_info *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, scanno * SIZEOF(jpeg_scan_info)); MEMCOPY(scanptr, scans, scanno * SIZEOF(jpeg_scan_info)); cinfo->scan_info = scanptr; cinfo->num_scans = scanno; } fclose(fp); return TRUE; } #endif /* C_MULTISCAN_FILES_SUPPORTED */ GLOBAL(boolean) set_quality_ratings (j_compress_ptr cinfo, char *arg, boolean force_baseline) /* Process a quality-ratings parameter string, of the form * N[,N,...] * If there are more q-table slots than parameters, the last value is replicated. */ { int val = 75; /* default value */ int tblno; char ch; for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) { if (*arg) { ch = ','; /* if not set by sscanf, will be ',' */ if (sscanf(arg, "%d%c", &val, &ch) < 1) return FALSE; if (ch != ',') /* syntax check */ return FALSE; /* Convert user 0-100 rating to percentage scaling */ cinfo->q_scale_factor[tblno] = jpeg_quality_scaling(val); while (*arg && *arg++ != ',') /* advance to next segment of arg string */ ; } else { /* reached end of parameter, set remaining factors to last value */ cinfo->q_scale_factor[tblno] = jpeg_quality_scaling(val); } } jpeg_default_qtables(cinfo, force_baseline); return TRUE; } GLOBAL(boolean) set_quant_slots (j_compress_ptr cinfo, char *arg) /* Process a quantization-table-selectors parameter string, of the form * N[,N,...] * If there are more components than parameters, the last value is replicated. */ { int val = 0; /* default table # */ int ci; char ch; for (ci = 0; ci < MAX_COMPONENTS; ci++) { if (*arg) { ch = ','; /* if not set by sscanf, will be ',' */ if (sscanf(arg, "%d%c", &val, &ch) < 1) return FALSE; if (ch != ',') /* syntax check */ return FALSE; if (val < 0 || val >= NUM_QUANT_TBLS) { fprintf(stderr, "JPEG quantization tables are numbered 0..%d\n", NUM_QUANT_TBLS-1); return FALSE; } cinfo->comp_info[ci].quant_tbl_no = val; while (*arg && *arg++ != ',') /* advance to next segment of arg string */ ; } else { /* reached end of parameter, set remaining components to last table */ cinfo->comp_info[ci].quant_tbl_no = val; } } return TRUE; } GLOBAL(boolean) set_sample_factors (j_compress_ptr cinfo, char *arg) /* Process a sample-factors parameter string, of the form * HxV[,HxV,...] * If there are more components than parameters, "1x1" is assumed for the rest. */ { int ci, val1, val2; char ch1, ch2; for (ci = 0; ci < MAX_COMPONENTS; ci++) { if (*arg) { ch2 = ','; /* if not set by sscanf, will be ',' */ if (sscanf(arg, "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3) return FALSE; if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */ return FALSE; if (val1 <= 0 || val1 > MAX_SAMP_FACTOR || val2 <= 0 || val2 > MAX_SAMP_FACTOR) { fprintf(stderr, "JPEG sampling factors must be 1..%d\n", MAX_SAMP_FACTOR); return FALSE; } cinfo->comp_info[ci].h_samp_factor = val1; cinfo->comp_info[ci].v_samp_factor = val2; while (*arg && *arg++ != ',') /* advance to next segment of arg string */ ; } else { /* 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; } } return TRUE; } ================================================ FILE: tess-two/jni/libjpeg/rdtarga.c ================================================ /* * rdtarga.c * * Copyright (C) 1991-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to read input images in Targa format. * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume input from * an ordinary stdio stream. They further assume that reading begins * at the start of the file; start_input may need work if the * user interface has already read some data (e.g., to determine that * the file is indeed Targa format). * * Based on code contributed by Lee Daniel Crocker. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef TARGA_SUPPORTED /* Macros to deal with unsigned chars as efficiently as compiler allows */ #ifdef HAVE_UNSIGNED_CHAR typedef unsigned char U_CHAR; #define UCH(x) ((int) (x)) #else /* !HAVE_UNSIGNED_CHAR */ #ifdef CHAR_IS_UNSIGNED typedef char U_CHAR; #define UCH(x) ((int) (x)) #else typedef char U_CHAR; #define UCH(x) ((int) (x) & 0xFF) #endif #endif /* HAVE_UNSIGNED_CHAR */ #define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len))) /* Private version of data source object */ typedef struct _tga_source_struct * tga_source_ptr; typedef struct _tga_source_struct { struct cjpeg_source_struct pub; /* public fields */ j_compress_ptr cinfo; /* back link saves passing separate parm */ JSAMPARRAY colormap; /* Targa colormap (converted to my format) */ jvirt_sarray_ptr whole_image; /* Needed if funny input row order */ JDIMENSION current_row; /* Current logical row number to read */ /* Pointer to routine to extract next Targa pixel from input file */ JMETHOD(void, read_pixel, (tga_source_ptr sinfo)); /* Result of read_pixel is delivered here: */ U_CHAR tga_pixel[4]; int pixel_size; /* Bytes per Targa pixel (1 to 4) */ /* State info for reading RLE-coded pixels; both counts must be init to 0 */ int block_count; /* # of pixels remaining in RLE block */ int dup_pixel_count; /* # of times to duplicate previous pixel */ /* This saves the correct pixel-row-expansion method for preload_image */ JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)); } tga_source_struct; /* For expanding 5-bit pixel values to 8-bit with best rounding */ static const UINT8 c5to8bits[32] = { 0, 8, 16, 25, 33, 41, 49, 58, 66, 74, 82, 90, 99, 107, 115, 123, 132, 140, 148, 156, 165, 173, 181, 189, 197, 206, 214, 222, 230, 239, 247, 255 }; LOCAL(int) read_byte (tga_source_ptr sinfo) /* Read next byte from Targa file */ { register FILE *infile = sinfo->pub.input_file; register int c; if ((c = getc(infile)) == EOF) ERREXIT(sinfo->cinfo, JERR_INPUT_EOF); return c; } LOCAL(void) read_colormap (tga_source_ptr sinfo, int cmaplen, int mapentrysize) /* Read the colormap from a Targa file */ { int i; /* Presently only handles 24-bit BGR format */ if (mapentrysize != 24) ERREXIT(sinfo->cinfo, JERR_TGA_BADCMAP); for (i = 0; i < cmaplen; i++) { sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo); sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo); sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo); } } /* * read_pixel methods: get a single pixel from Targa file into tga_pixel[] */ METHODDEF(void) read_non_rle_pixel (tga_source_ptr sinfo) /* Read one Targa pixel from the input file; no RLE expansion */ { register FILE *infile = sinfo->pub.input_file; register int i; for (i = 0; i < sinfo->pixel_size; i++) { sinfo->tga_pixel[i] = (U_CHAR) getc(infile); } } METHODDEF(void) read_rle_pixel (tga_source_ptr sinfo) /* Read one Targa pixel from the input file, expanding RLE data as needed */ { register FILE *infile = sinfo->pub.input_file; register int i; /* Duplicate previously read pixel? */ if (sinfo->dup_pixel_count > 0) { sinfo->dup_pixel_count--; return; } /* Time to read RLE block header? */ if (--sinfo->block_count < 0) { /* decrement pixels remaining in block */ i = read_byte(sinfo); if (i & 0x80) { /* Start of duplicate-pixel block? */ sinfo->dup_pixel_count = i & 0x7F; /* number of dups after this one */ sinfo->block_count = 0; /* then read new block header */ } else { sinfo->block_count = i & 0x7F; /* number of pixels after this one */ } } /* Read next pixel */ for (i = 0; i < sinfo->pixel_size; i++) { sinfo->tga_pixel[i] = (U_CHAR) getc(infile); } } /* * Read one row of pixels. * * We provide several different versions depending on input file format. */ METHODDEF(JDIMENSION) get_8bit_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 8-bit grayscale pixels */ { tga_source_ptr source = (tga_source_ptr) sinfo; register JSAMPROW ptr; register JDIMENSION col; ptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { (*source->read_pixel) (source); /* Load next pixel into tga_pixel */ *ptr++ = (JSAMPLE) UCH(source->tga_pixel[0]); } return 1; } METHODDEF(JDIMENSION) get_8bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 8-bit colormap indexes */ { tga_source_ptr source = (tga_source_ptr) sinfo; register int t; register JSAMPROW ptr; register JDIMENSION col; register JSAMPARRAY colormap = source->colormap; ptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { (*source->read_pixel) (source); /* Load next pixel into tga_pixel */ t = UCH(source->tga_pixel[0]); *ptr++ = colormap[0][t]; *ptr++ = colormap[1][t]; *ptr++ = colormap[2][t]; } return 1; } METHODDEF(JDIMENSION) get_16bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 16-bit pixels */ { tga_source_ptr source = (tga_source_ptr) sinfo; register int t; register JSAMPROW ptr; register JDIMENSION col; ptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { (*source->read_pixel) (source); /* Load next pixel into tga_pixel */ t = UCH(source->tga_pixel[0]); t += UCH(source->tga_pixel[1]) << 8; /* We expand 5 bit data to 8 bit sample width. * The format of the 16-bit (LSB first) input word is * xRRRRRGGGGGBBBBB */ ptr[2] = (JSAMPLE) c5to8bits[t & 0x1F]; t >>= 5; ptr[1] = (JSAMPLE) c5to8bits[t & 0x1F]; t >>= 5; ptr[0] = (JSAMPLE) c5to8bits[t & 0x1F]; ptr += 3; } return 1; } METHODDEF(JDIMENSION) get_24bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 24-bit pixels */ { tga_source_ptr source = (tga_source_ptr) sinfo; register JSAMPROW ptr; register JDIMENSION col; ptr = source->pub.buffer[0]; for (col = cinfo->image_width; col > 0; col--) { (*source->read_pixel) (source); /* Load next pixel into tga_pixel */ *ptr++ = (JSAMPLE) UCH(source->tga_pixel[2]); /* change BGR to RGB order */ *ptr++ = (JSAMPLE) UCH(source->tga_pixel[1]); *ptr++ = (JSAMPLE) UCH(source->tga_pixel[0]); } return 1; } /* * Targa also defines a 32-bit pixel format with order B,G,R,A. * We presently ignore the attribute byte, so the code for reading * these pixels is identical to the 24-bit routine above. * This works because the actual pixel length is only known to read_pixel. */ #define get_32bit_row get_24bit_row /* * This method is for re-reading the input data in standard top-down * row order. The entire image has already been read into whole_image * with proper conversion of pixel format, but it's in a funny row order. */ METHODDEF(JDIMENSION) get_memory_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { tga_source_ptr source = (tga_source_ptr) sinfo; JDIMENSION source_row; /* Compute row of source that maps to current_row of normal order */ /* For now, assume image is bottom-up and not interlaced. */ /* NEEDS WORK to support interlaced images! */ source_row = cinfo->image_height - source->current_row - 1; /* Fetch that row from virtual array */ source->pub.buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->whole_image, source_row, (JDIMENSION) 1, FALSE); source->current_row++; return 1; } /* * This method loads the image into whole_image during the first call on * get_pixel_rows. The get_pixel_rows pointer is then adjusted to call * get_memory_row on subsequent calls. */ METHODDEF(JDIMENSION) preload_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { tga_source_ptr source = (tga_source_ptr) sinfo; JDIMENSION row; cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; /* Read the data into a virtual array in input-file row order. */ for (row = 0; row < cinfo->image_height; row++) { if (progress != NULL) { progress->pub.pass_counter = (long) row; progress->pub.pass_limit = (long) cinfo->image_height; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } source->pub.buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, source->whole_image, row, (JDIMENSION) 1, TRUE); (*source->get_pixel_rows) (cinfo, sinfo); } if (progress != NULL) progress->completed_extra_passes++; /* Set up to read from the virtual array in unscrambled order */ source->pub.get_pixel_rows = get_memory_row; source->current_row = 0; /* And read the first row */ return get_memory_row(cinfo, sinfo); } /* * Read the file header; return image size and component count. */ METHODDEF(void) start_input_tga (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { tga_source_ptr source = (tga_source_ptr) sinfo; U_CHAR targaheader[18]; int idlen, cmaptype, subtype, flags, interlace_type, components; unsigned int width, height, maplen; boolean is_bottom_up; #define GET_2B(offset) ((unsigned int) UCH(targaheader[offset]) + \ (((unsigned int) UCH(targaheader[offset+1])) << 8)) if (! ReadOK(source->pub.input_file, targaheader, 18)) ERREXIT(cinfo, JERR_INPUT_EOF); /* Pretend "15-bit" pixels are 16-bit --- we ignore attribute bit anyway */ if (targaheader[16] == 15) targaheader[16] = 16; idlen = UCH(targaheader[0]); cmaptype = UCH(targaheader[1]); subtype = UCH(targaheader[2]); maplen = GET_2B(5); width = GET_2B(12); height = GET_2B(14); source->pixel_size = UCH(targaheader[16]) >> 3; flags = UCH(targaheader[17]); /* Image Descriptor byte */ is_bottom_up = ((flags & 0x20) == 0); /* bit 5 set => top-down */ interlace_type = flags >> 6; /* bits 6/7 are interlace code */ if (cmaptype > 1 || /* cmaptype must be 0 or 1 */ source->pixel_size < 1 || source->pixel_size > 4 || (UCH(targaheader[16]) & 7) != 0 || /* bits/pixel must be multiple of 8 */ interlace_type != 0) /* currently don't allow interlaced image */ ERREXIT(cinfo, JERR_TGA_BADPARMS); if (subtype > 8) { /* It's an RLE-coded file */ source->read_pixel = read_rle_pixel; source->block_count = source->dup_pixel_count = 0; subtype -= 8; } else { /* Non-RLE file */ source->read_pixel = read_non_rle_pixel; } /* Now should have subtype 1, 2, or 3 */ components = 3; /* until proven different */ cinfo->in_color_space = JCS_RGB; switch (subtype) { case 1: /* Colormapped image */ if (source->pixel_size == 1 && cmaptype == 1) source->get_pixel_rows = get_8bit_row; else ERREXIT(cinfo, JERR_TGA_BADPARMS); TRACEMS2(cinfo, 1, JTRC_TGA_MAPPED, width, height); break; case 2: /* RGB image */ switch (source->pixel_size) { case 2: source->get_pixel_rows = get_16bit_row; break; case 3: source->get_pixel_rows = get_24bit_row; break; case 4: source->get_pixel_rows = get_32bit_row; break; default: ERREXIT(cinfo, JERR_TGA_BADPARMS); break; } TRACEMS2(cinfo, 1, JTRC_TGA, width, height); break; case 3: /* Grayscale image */ components = 1; cinfo->in_color_space = JCS_GRAYSCALE; if (source->pixel_size == 1) source->get_pixel_rows = get_8bit_gray_row; else ERREXIT(cinfo, JERR_TGA_BADPARMS); TRACEMS2(cinfo, 1, JTRC_TGA_GRAY, width, height); break; default: ERREXIT(cinfo, JERR_TGA_BADPARMS); break; } if (is_bottom_up) { /* Create a virtual array to buffer the upside-down image. */ source->whole_image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, (JDIMENSION) width * components, (JDIMENSION) height, (JDIMENSION) 1); if (cinfo->progress != NULL) { cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; progress->total_extra_passes++; /* count file input as separate pass */ } /* source->pub.buffer will point to the virtual array. */ source->pub.buffer_height = 1; /* in case anyone looks at it */ source->pub.get_pixel_rows = preload_image; } else { /* Don't need a virtual array, but do need a one-row input buffer. */ source->whole_image = NULL; source->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) width * components, (JDIMENSION) 1); source->pub.buffer_height = 1; source->pub.get_pixel_rows = source->get_pixel_rows; } while (idlen--) /* Throw away ID field */ (void) read_byte(source); if (maplen > 0) { if (maplen > 256 || GET_2B(3) != 0) ERREXIT(cinfo, JERR_TGA_BADCMAP); /* Allocate space to store the colormap */ source->colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) maplen, (JDIMENSION) 3); /* and read it from the file */ read_colormap(source, (int) maplen, UCH(targaheader[7])); } else { if (cmaptype) /* but you promised a cmap! */ ERREXIT(cinfo, JERR_TGA_BADPARMS); source->colormap = NULL; } cinfo->input_components = components; cinfo->data_precision = 8; cinfo->image_width = width; cinfo->image_height = height; } /* * Finish up at the end of the file. */ METHODDEF(void) finish_input_tga (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { /* no work */ } /* * The module selection routine for Targa format input. */ GLOBAL(cjpeg_source_ptr) jinit_read_targa (j_compress_ptr cinfo) { tga_source_ptr source; /* Create module interface object */ source = (tga_source_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(tga_source_struct)); source->cinfo = cinfo; /* make back link for subroutines */ /* Fill in method ptrs, except get_pixel_rows which start_input sets */ source->pub.start_input = start_input_tga; source->pub.finish_input = finish_input_tga; return (cjpeg_source_ptr) source; } #endif /* TARGA_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/structure.txt ================================================ IJG JPEG LIBRARY: SYSTEM ARCHITECTURE Copyright (C) 1991-2013, Thomas G. Lane, Guido Vollbeding. This file is part of the Independent JPEG Group's software. For conditions of distribution and use, see the accompanying README file. This file provides an overview of the architecture of the IJG JPEG software; that is, the functions of the various modules in the system and the interfaces between modules. For more precise details about any data structure or calling convention, see the include files and comments in the source code. We assume that the reader is already somewhat familiar with the JPEG standard. The README file includes references for learning about JPEG. The file libjpeg.txt describes the library from the viewpoint of an application programmer using the library; it's best to read that file before this one. Also, the file coderules.txt describes the coding style conventions we use. In this document, JPEG-specific terminology follows the JPEG standard: A "component" means a color channel, e.g., Red or Luminance. A "sample" is a single component value (i.e., one number in the image data). A "coefficient" is a frequency coefficient (a DCT transform output number). A "block" is an array of samples or coefficients. An "MCU" (minimum coded unit) is an interleaved set of blocks of size determined by the sampling factors, or a single block in a noninterleaved scan. We do not use the terms "pixel" and "sample" interchangeably. When we say pixel, we mean an element of the full-size image, while a sample is an element of the downsampled image. Thus the number of samples may vary across components while the number of pixels does not. (This terminology is not used rigorously throughout the code, but it is used in places where confusion would otherwise result.) *** System features *** The IJG distribution contains two parts: * A subroutine library for JPEG compression and decompression. * cjpeg/djpeg, two sample applications that use the library to transform JFIF JPEG files to and from several other image formats. cjpeg/djpeg are of no great intellectual complexity: they merely add a simple command-line user interface and I/O routines for several uncompressed image formats. This document concentrates on the library itself. We desire the library to be capable of supporting all JPEG baseline, extended sequential, and progressive DCT processes. The library does not support the hierarchical or lossless processes defined in the standard. Within these limits, any set of compression parameters allowed by the JPEG spec should be readable for decompression. (We can be more restrictive about what formats we can generate.) Although the system design allows for all parameter values, some uncommon settings are not yet implemented and may never be; nonintegral sampling ratios are the prime example. Furthermore, we treat 8-bit vs. 12-bit data precision as a compile-time switch, not a run-time option, because most machines can store 8-bit pixels much more compactly than 12-bit. By itself, the library handles only interchange JPEG datastreams --- in particular the widely used JFIF file format. The library can be used by surrounding code to process interchange or abbreviated JPEG datastreams that are embedded in more complex file formats. (For example, libtiff uses this library to implement JPEG compression within the TIFF file format.) The library includes a substantial amount of code that is not covered by the JPEG standard but is necessary for typical applications of JPEG. These functions preprocess the image before JPEG compression or postprocess it after decompression. They include colorspace conversion, downsampling/upsampling, and color quantization. This code can be omitted if not needed. A wide range of quality vs. speed tradeoffs are possible in JPEG processing, and even more so in decompression postprocessing. The decompression library provides multiple implementations that cover most of the useful tradeoffs, ranging from very-high-quality down to fast-preview operation. On the compression side we have generally not provided low-quality choices, since compression is normally less time-critical. It should be understood that the low-quality modes may not meet the JPEG standard's accuracy requirements; nonetheless, they are useful for viewers. *** Portability issues *** Portability is an essential requirement for the library. The key portability issues that show up at the level of system architecture are: 1. Memory usage. We want the code to be able to run on PC-class machines with limited memory. Images should therefore be processed sequentially (in strips), to avoid holding the whole image in memory at once. Where a full-image buffer is necessary, we should be able to use either virtual memory or temporary files. 2. Near/far pointer distinction. To run efficiently on 80x86 machines, the code should distinguish "small" objects (kept in near data space) from "large" ones (kept in far data space). This is an annoying restriction, but fortunately it does not impact code quality for less brain-damaged machines, and the source code clutter turns out to be minimal with sufficient use of pointer typedefs. 3. Data precision. We assume that "char" is at least 8 bits, "short" and "int" at least 16, "long" at least 32. The code will work fine with larger data sizes, although memory may be used inefficiently in some cases. However, the JPEG compressed datastream must ultimately appear on external storage as a sequence of 8-bit bytes if it is to conform to the standard. This may pose a problem on machines where char is wider than 8 bits. The library represents compressed data as an array of values of typedef JOCTET. If no data type exactly 8 bits wide is available, custom data source and data destination modules must be written to unpack and pack the chosen JOCTET datatype into 8-bit external representation. *** System overview *** The compressor and decompressor are each divided into two main sections: the JPEG compressor or decompressor proper, and the preprocessing or postprocessing functions. The interface between these two sections is the image data that the official JPEG spec regards as its input or output: this data is in the colorspace to be used for compression, and it is downsampled to the sampling factors to be used. The preprocessing and postprocessing steps are responsible for converting a normal image representation to or from this form. (Those few applications that want to deal with YCbCr downsampled data can skip the preprocessing or postprocessing step.) Looking more closely, the compressor library contains the following main elements: Preprocessing: * Color space conversion (e.g., RGB to YCbCr). * Edge expansion and downsampling. Optionally, this step can do simple smoothing --- this is often helpful for low-quality source data. JPEG proper: * MCU assembly, DCT, quantization. * Entropy coding (sequential or progressive, Huffman or arithmetic). In addition to these modules we need overall control, marker generation, and support code (memory management & error handling). There is also a module responsible for physically writing the output data --- typically this is just an interface to fwrite(), but some applications may need to do something else with the data. The decompressor library contains the following main elements: JPEG proper: * Entropy decoding (sequential or progressive, Huffman or arithmetic). * Dequantization, inverse DCT, MCU disassembly. Postprocessing: * Upsampling. Optionally, this step may be able to do more general rescaling of the image. * Color space conversion (e.g., YCbCr to RGB). This step may also provide gamma adjustment [ currently it does not ]. * Optional color quantization (e.g., reduction to 256 colors). * Optional color precision reduction (e.g., 24-bit to 15-bit color). [This feature is not currently implemented.] We also need overall control, marker parsing, and a data source module. The support code (memory management & error handling) can be shared with the compression half of the library. There may be several implementations of each of these elements, particularly in the decompressor, where a wide range of speed/quality tradeoffs is very useful. It must be understood that some of the best speedups involve merging adjacent steps in the pipeline. For example, upsampling, color space conversion, and color quantization might all be done at once when using a low-quality ordered-dither technique. The system architecture is designed to allow such merging where appropriate. Note: it is convenient to regard edge expansion (padding to block boundaries) as a preprocessing/postprocessing function, even though the JPEG spec includes it in compression/decompression. We do this because downsampling/upsampling can be simplified a little if they work on padded data: it's not necessary to have special cases at the right and bottom edges. Therefore the interface buffer is always an integral number of blocks wide and high, and we expect compression preprocessing to pad the source data properly. Padding will occur only to the next block (block_size-sample) boundary. In an interleaved-scan situation, additional dummy blocks may be used to fill out MCUs, but the MCU assembly and disassembly logic will create or discard these blocks internally. (This is advantageous for speed reasons, since we avoid DCTing the dummy blocks. It also permits a small reduction in file size, because the compressor can choose dummy block contents so as to minimize their size in compressed form. Finally, it makes the interface buffer specification independent of whether the file is actually interleaved or not.) Applications that wish to deal directly with the downsampled data must provide similar buffering and padding for odd-sized images. *** Poor man's object-oriented programming *** It should be clear by now that we have a lot of quasi-independent processing steps, many of which have several possible behaviors. To avoid cluttering the code with lots of switch statements, we use a simple form of object-style programming to separate out the different possibilities. For example, two different color quantization algorithms could be implemented as two separate modules that present the same external interface; at runtime, the calling code will access the proper module indirectly through an "object". We can get the limited features we need while staying within portable C. The basic tool is a function pointer. An "object" is just a struct containing one or more function pointer fields, each of which corresponds to a method name in real object-oriented languages. During initialization we fill in the function pointers with references to whichever module we have determined we need to use in this run. Then invocation of the module is done by indirecting through a function pointer; on most machines this is no more expensive than a switch statement, which would be the only other way of making the required run-time choice. The really significant benefit, of course, is keeping the source code clean and well structured. We can also arrange to have private storage that varies between different implementations of the same kind of object. We do this by making all the module-specific object structs be separately allocated entities, which will be accessed via pointers in the master compression or decompression struct. The "public" fields or methods for a given kind of object are specified by a commonly known struct. But a module's initialization code can allocate a larger struct that contains the common struct as its first member, plus additional private fields. With appropriate pointer casting, the module's internal functions can access these private fields. (For a simple example, see jdatadst.c, which implements the external interface specified by struct jpeg_destination_mgr, but adds extra fields.) (Of course this would all be a lot easier if we were using C++, but we are not yet prepared to assume that everyone has a C++ compiler.) An important benefit of this scheme is that it is easy to provide multiple versions of any method, each tuned to a particular case. While a lot of precalculation might be done to select an optimal implementation of a method, the cost per invocation is constant. For example, the upsampling step might have a "generic" method, plus one or more "hardwired" methods for the most popular sampling factors; the hardwired methods would be faster because they'd use straight-line code instead of for-loops. The cost to determine which method to use is paid only once, at startup, and the selection criteria are hidden from the callers of the method. This plan differs a little bit from usual object-oriented structures, in that only one instance of each object class will exist during execution. The reason for having the class structure is that on different runs we may create different instances (choose to execute different modules). You can think of the term "method" as denoting the common interface presented by a particular set of interchangeable functions, and "object" as denoting a group of related methods, or the total shared interface behavior of a group of modules. *** Overall control structure *** We previously mentioned the need for overall control logic in the compression and decompression libraries. In IJG implementations prior to v5, overall control was mostly provided by "pipeline control" modules, which proved to be large, unwieldy, and hard to understand. To improve the situation, the control logic has been subdivided into multiple modules. The control modules consist of: 1. Master control for module selection and initialization. This has two responsibilities: 1A. Startup initialization at the beginning of image processing. The individual processing modules to be used in this run are selected and given initialization calls. 1B. Per-pass control. This determines how many passes will be performed and calls each active processing module to configure itself appropriately at the beginning of each pass. End-of-pass processing, where necessary, is also invoked from the master control module. Method selection is partially distributed, in that a particular processing module may contain several possible implementations of a particular method, which it will select among when given its initialization call. The master control code need only be concerned with decisions that affect more than one module. 2. Data buffering control. A separate control module exists for each inter-processing-step data buffer. This module is responsible for invoking the processing steps that write or read that data buffer. Each buffer controller sees the world as follows: input data => processing step A => buffer => processing step B => output data | | | ------------------ controller ------------------ The controller knows the dataflow requirements of steps A and B: how much data they want to accept in one chunk and how much they output in one chunk. Its function is to manage its buffer and call A and B at the proper times. A data buffer control module may itself be viewed as a processing step by a higher-level control module; thus the control modules form a binary tree with elementary processing steps at the leaves of the tree. The control modules are objects. A considerable amount of flexibility can be had by replacing implementations of a control module. For example: * Merging of adjacent steps in the pipeline is done by replacing a control module and its pair of processing-step modules with a single processing- step module. (Hence the possible merges are determined by the tree of control modules.) * In some processing modes, a given interstep buffer need only be a "strip" buffer large enough to accommodate the desired data chunk sizes. In other modes, a full-image buffer is needed and several passes are required. The control module determines which kind of buffer is used and manipulates virtual array buffers as needed. One or both processing steps may be unaware of the multi-pass behavior. In theory, we might be able to make all of the data buffer controllers interchangeable and provide just one set of implementations for all. In practice, each one contains considerable special-case processing for its particular job. The buffer controller concept should be regarded as an overall system structuring principle, not as a complete description of the task performed by any one controller. *** Compression object structure *** Here is a sketch of the logical structure of the JPEG compression library: |-- Colorspace conversion |-- Preprocessing controller --| | |-- Downsampling Main controller --| | |-- Forward DCT, quantize |-- Coefficient controller --| |-- Entropy encoding This sketch also describes the flow of control (subroutine calls) during typical image data processing. Each of the components shown in the diagram is an "object" which may have several different implementations available. One or more source code files contain the actual implementation(s) of each object. The objects shown above are: * Main controller: buffer controller for the subsampled-data buffer, which holds the preprocessed input data. This controller invokes preprocessing to fill the subsampled-data buffer, and JPEG compression to empty it. There is usually no need for a full-image buffer here; a strip buffer is adequate. * Preprocessing controller: buffer controller for the downsampling input data buffer, which lies between colorspace conversion and downsampling. Note that a unified conversion/downsampling module would probably replace this controller entirely. * Colorspace conversion: converts application image data into the desired JPEG color space; also changes the data from pixel-interleaved layout to separate component planes. Processes one pixel row at a time. * Downsampling: performs reduction of chroma components as required. Optionally may perform pixel-level smoothing as well. Processes a "row group" at a time, where a row group is defined as Vmax pixel rows of each component before downsampling, and Vk sample rows afterwards (remember Vk differs across components). Some downsampling or smoothing algorithms may require context rows above and below the current row group; the preprocessing controller is responsible for supplying these rows via proper buffering. The downsampler is responsible for edge expansion at the right edge (i.e., extending each sample row to a multiple of block_size samples); but the preprocessing controller is responsible for vertical edge expansion (i.e., duplicating the bottom sample row as needed to make a multiple of block_size rows). * Coefficient controller: buffer controller for the DCT-coefficient data. This controller handles MCU assembly, including insertion of dummy DCT blocks when needed at the right or bottom edge. When performing Huffman-code optimization or emitting a multiscan JPEG file, this controller is responsible for buffering the full image. The equivalent of one fully interleaved MCU row of subsampled data is processed per call, even when the JPEG file is noninterleaved. * Forward DCT and quantization: Perform DCT, quantize, and emit coefficients. Works on one or more DCT blocks at a time. (Note: the coefficients are now emitted in normal array order, which the entropy encoder is expected to convert to zigzag order as necessary. Prior versions of the IJG code did the conversion to zigzag order within the quantization step.) * Entropy encoding: Perform Huffman or arithmetic entropy coding and emit the coded data to the data destination module. Works on one MCU per call. For progressive JPEG, the same DCT blocks are fed to the entropy coder during each pass, and the coder must emit the appropriate subset of coefficients. In addition to the above objects, the compression library includes these objects: * Master control: determines the number of passes required, controls overall and per-pass initialization of the other modules. * Marker writing: generates JPEG markers (except for RSTn, which is emitted by the entropy encoder when needed). * Data destination manager: writes the output JPEG datastream to its final destination (e.g., a file). The destination manager supplied with the library knows how to write to a stdio stream or to a memory buffer; for other behaviors, the surrounding application may provide its own destination manager. * Memory manager: allocates and releases memory, controls virtual arrays (with backing store management, where required). * Error handler: performs formatting and output of error and trace messages; determines handling of nonfatal errors. The surrounding application may override some or all of this object's methods to change error handling. * Progress monitor: supports output of "percent-done" progress reports. This object represents an optional callback to the surrounding application: if wanted, it must be supplied by the application. The error handler, destination manager, and progress monitor objects are defined as separate objects in order to simplify application-specific customization of the JPEG library. A surrounding application may override individual methods or supply its own all-new implementation of one of these objects. The object interfaces for these objects are therefore treated as part of the application interface of the library, whereas the other objects are internal to the library. The error handler and memory manager are shared by JPEG compression and decompression; the progress monitor, if used, may be shared as well. *** Decompression object structure *** Here is a sketch of the logical structure of the JPEG decompression library: |-- Entropy decoding |-- Coefficient controller --| | |-- Dequantize, Inverse DCT Main controller --| | |-- Upsampling |-- Postprocessing controller --| |-- Colorspace conversion |-- Color quantization |-- Color precision reduction As before, this diagram also represents typical control flow. The objects shown are: * Main controller: buffer controller for the subsampled-data buffer, which holds the output of JPEG decompression proper. This controller's primary task is to feed the postprocessing procedure. Some upsampling algorithms may require context rows above and below the current row group; when this is true, the main controller is responsible for managing its buffer so as to make context rows available. In the current design, the main buffer is always a strip buffer; a full-image buffer is never required. * Coefficient controller: buffer controller for the DCT-coefficient data. This controller handles MCU disassembly, including deletion of any dummy DCT blocks at the right or bottom edge. When reading a multiscan JPEG file, this controller is responsible for buffering the full image. (Buffering DCT coefficients, rather than samples, is necessary to support progressive JPEG.) The equivalent of one fully interleaved MCU row of subsampled data is processed per call, even when the source JPEG file is noninterleaved. * Entropy decoding: Read coded data from the data source module and perform Huffman or arithmetic entropy decoding. Works on one MCU per call. For progressive JPEG decoding, the coefficient controller supplies the prior coefficients of each MCU (initially all zeroes), which the entropy decoder modifies in each scan. * Dequantization and inverse DCT: like it says. Note that the coefficients buffered by the coefficient controller have NOT been dequantized; we merge dequantization and inverse DCT into a single step for speed reasons. When scaled-down output is asked for, simplified DCT algorithms may be used that need fewer coefficients and emit fewer samples per DCT block, not the full 8x8. Works on one DCT block at a time. * Postprocessing controller: buffer controller for the color quantization input buffer, when quantization is in use. (Without quantization, this controller just calls the upsampler.) For two-pass quantization, this controller is responsible for buffering the full-image data. * Upsampling: restores chroma components to full size. (May support more general output rescaling, too. Note that if undersized DCT outputs have been emitted by the DCT module, this module must adjust so that properly sized outputs are created.) Works on one row group at a time. This module also calls the color conversion module, so its top level is effectively a buffer controller for the upsampling->color conversion buffer. However, in all but the highest-quality operating modes, upsampling and color conversion are likely to be merged into a single step. * Colorspace conversion: convert from JPEG color space to output color space, and change data layout from separate component planes to pixel-interleaved. Works on one pixel row at a time. * Color quantization: reduce the data to colormapped form, using either an externally specified colormap or an internally generated one. This module is not used for full-color output. Works on one pixel row at a time; may require two passes to generate a color map. Note that the output will always be a single component representing colormap indexes. In the current design, the output values are JSAMPLEs, so an 8-bit compilation cannot quantize to more than 256 colors. This is unlikely to be a problem in practice. * Color reduction: this module handles color precision reduction, e.g., generating 15-bit color (5 bits/primary) from JPEG's 24-bit output. Not quite clear yet how this should be handled... should we merge it with colorspace conversion??? Note that some high-speed operating modes might condense the entire postprocessing sequence to a single module (upsample, color convert, and quantize in one step). In addition to the above objects, the decompression library includes these objects: * Master control: determines the number of passes required, controls overall and per-pass initialization of the other modules. This is subdivided into input and output control: jdinput.c controls only input-side processing, while jdmaster.c handles overall initialization and output-side control. * Marker reading: decodes JPEG markers (except for RSTn). * Data source manager: supplies the input JPEG datastream. The source manager supplied with the library knows how to read from a stdio stream or from a memory buffer; for other behaviors, the surrounding application may provide its own source manager. * Memory manager: same as for compression library. * Error handler: same as for compression library. * Progress monitor: same as for compression library. As with compression, the data source manager, error handler, and progress monitor are candidates for replacement by a surrounding application. *** Decompression input and output separation *** To support efficient incremental display of progressive JPEG files, the decompressor is divided into two sections that can run independently: 1. Data input includes marker parsing, entropy decoding, and input into the coefficient controller's DCT coefficient buffer. Note that this processing is relatively cheap and fast. 2. Data output reads from the DCT coefficient buffer and performs the IDCT and all postprocessing steps. For a progressive JPEG file, the data input processing is allowed to get arbitrarily far ahead of the data output processing. (This occurs only if the application calls jpeg_consume_input(); otherwise input and output run in lockstep, since the input section is called only when the output section needs more data.) In this way the application can avoid making extra display passes when data is arriving faster than the display pass can run. Furthermore, it is possible to abort an output pass without losing anything, since the coefficient buffer is read-only as far as the output section is concerned. See libjpeg.txt for more detail. A full-image coefficient array is only created if the JPEG file has multiple scans (or if the application specifies buffered-image mode anyway). When reading a single-scan file, the coefficient controller normally creates only a one-MCU buffer, so input and output processing must run in lockstep in this case. jpeg_consume_input() is effectively a no-op in this situation. The main impact of dividing the decompressor in this fashion is that we must be very careful with shared variables in the cinfo data structure. Each variable that can change during the course of decompression must be classified as belonging to data input or data output, and each section must look only at its own variables. For example, the data output section may not depend on any of the variables that describe the current scan in the JPEG file, because these may change as the data input section advances into a new scan. The progress monitor is (somewhat arbitrarily) defined to treat input of the file as one pass when buffered-image mode is not used, and to ignore data input work completely when buffered-image mode is used. Note that the library has no reliable way to predict the number of passes when dealing with a progressive JPEG file, nor can it predict the number of output passes in buffered-image mode. So the work estimate is inherently bogus anyway. No comparable division is currently made in the compression library, because there isn't any real need for it. *** Data formats *** Arrays of pixel sample values use the following data structure: typedef something JSAMPLE; a pixel component value, 0..MAXJSAMPLE typedef JSAMPLE *JSAMPROW; ptr to a row of samples typedef JSAMPROW *JSAMPARRAY; ptr to a list of rows typedef JSAMPARRAY *JSAMPIMAGE; ptr to a list of color-component arrays The basic element type JSAMPLE will typically be one of unsigned char, (signed) char, or short. Short will be used if samples wider than 8 bits are to be supported (this is a compile-time option). Otherwise, unsigned char is used if possible. If the compiler only supports signed chars, then it is necessary to mask off the value when reading. Thus, all reads of JSAMPLE values must be coded as "GETJSAMPLE(value)", where the macro will be defined as "((value) & 0xFF)" on signed-char machines and "((int) (value))" elsewhere. With these conventions, JSAMPLE values can be assumed to be >= 0. This helps simplify correct rounding during downsampling, etc. The JPEG standard's specification that sample values run from -128..127 is accommodated by subtracting 128 from the sample value in the DCT step. Similarly, during decompression the output of the IDCT step will be immediately shifted back to 0..255. (NB: different values are required when 12-bit samples are in use. The code is written in terms of MAXJSAMPLE and CENTERJSAMPLE, which will be defined as 255 and 128 respectively in an 8-bit implementation, and as 4095 and 2048 in a 12-bit implementation.) We use a pointer per row, rather than a two-dimensional JSAMPLE array. This choice costs only a small amount of memory and has several benefits: * Code using the data structure doesn't need to know the allocated width of the rows. This simplifies edge expansion/compression, since we can work in an array that's wider than the logical picture width. * Indexing doesn't require multiplication; this is a performance win on many machines. * Arrays with more than 64K total elements can be supported even on machines where malloc() cannot allocate chunks larger than 64K. * The rows forming a component array may be allocated at different times without extra copying. This trick allows some speedups in smoothing steps that need access to the previous and next rows. Note that each color component is stored in a separate array; we don't use the traditional layout in which the components of a pixel are stored together. This simplifies coding of modules that work on each component independently, because they don't need to know how many components there are. Furthermore, we can read or write each component to a temporary file independently, which is helpful when dealing with noninterleaved JPEG files. In general, a specific sample value is accessed by code such as GETJSAMPLE(image[colorcomponent][row][col]) where col is measured from the image left edge, but row is measured from the first sample row currently in memory. Either of the first two indexings can be precomputed by copying the relevant pointer. Since most image-processing applications prefer to work on images in which the components of a pixel are stored together, the data passed to or from the surrounding application uses the traditional convention: a single pixel is represented by N consecutive JSAMPLE values, and an image row is an array of (# of color components)*(image width) JSAMPLEs. One or more rows of data can be represented by a pointer of type JSAMPARRAY in this scheme. This scheme is converted to component-wise storage inside the JPEG library. (Applications that want to skip JPEG preprocessing or postprocessing will have to contend with component-wise storage.) Arrays of DCT-coefficient values use the following data structure: typedef short JCOEF; a 16-bit signed integer typedef JCOEF JBLOCK[DCTSIZE2]; an 8x8 block of coefficients typedef JBLOCK *JBLOCKROW; ptr to one horizontal row of 8x8 blocks typedef JBLOCKROW *JBLOCKARRAY; ptr to a list of such rows typedef JBLOCKARRAY *JBLOCKIMAGE; ptr to a list of color component arrays The underlying type is at least a 16-bit signed integer; while "short" is big enough on all machines of interest, on some machines it is preferable to use "int" for speed reasons, despite the storage cost. Coefficients are grouped into 8x8 blocks (but we always use #defines DCTSIZE and DCTSIZE2 rather than "8" and "64"). The contents of a coefficient block may be in either "natural" or zigzagged order, and may be true values or divided by the quantization coefficients, depending on where the block is in the processing pipeline. In the current library, coefficient blocks are kept in natural order everywhere; the entropy codecs zigzag or dezigzag the data as it is written or read. The blocks contain quantized coefficients everywhere outside the DCT/IDCT subsystems. (This latter decision may need to be revisited to support variable quantization a la JPEG Part 3.) Notice that the allocation unit is now a row of 8x8 coefficient blocks, corresponding to block_size rows of samples. Otherwise the structure is much the same as for samples, and for the same reasons. On machines where malloc() can't handle a request bigger than 64Kb, this data structure limits us to rows of less than 512 JBLOCKs, or a picture width of 4000+ pixels. This seems an acceptable restriction. On 80x86 machines, the bottom-level pointer types (JSAMPROW and JBLOCKROW) must be declared as "far" pointers, but the upper levels can be "near" (implying that the pointer lists are allocated in the DS segment). We use a #define symbol FAR, which expands to the "far" keyword when compiling on 80x86 machines and to nothing elsewhere. *** Suspendable processing *** In some applications it is desirable to use the JPEG library as an incremental, memory-to-memory filter. In this situation the data source or destination may be a limited-size buffer, and we can't rely on being able to empty or refill the buffer at arbitrary times. Instead the application would like to have control return from the library at buffer overflow/underrun, and then resume compression or decompression at a later time. This scenario is supported for simple cases. (For anything more complex, we recommend that the application "bite the bullet" and develop real multitasking capability.) The libjpeg.txt file goes into more detail about the usage and limitations of this capability; here we address the implications for library structure. The essence of the problem is that the entropy codec (coder or decoder) must be prepared to stop at arbitrary times. In turn, the controllers that call the entropy codec must be able to stop before having produced or consumed all the data that they normally would handle in one call. That part is reasonably straightforward: we make the controller call interfaces include "progress counters" which indicate the number of data chunks successfully processed, and we require callers to test the counter rather than just assume all of the data was processed. Rather than trying to restart at an arbitrary point, the current Huffman codecs are designed to restart at the beginning of the current MCU after a suspension due to buffer overflow/underrun. At the start of each call, the codec's internal state is loaded from permanent storage (in the JPEG object structures) into local variables. On successful completion of the MCU, the permanent state is updated. (This copying is not very expensive, and may even lead to *improved* performance if the local variables can be registerized.) If a suspension occurs, the codec simply returns without updating the state, thus effectively reverting to the start of the MCU. Note that this implies leaving some data unprocessed in the source/destination buffer (ie, the compressed partial MCU). The data source/destination module interfaces are specified so as to make this possible. This also implies that the data buffer must be large enough to hold a worst-case compressed MCU; a couple thousand bytes should be enough. In a successive-approximation AC refinement scan, the progressive Huffman decoder has to be able to undo assignments of newly nonzero coefficients if it suspends before the MCU is complete, since decoding requires distinguishing previously-zero and previously-nonzero coefficients. This is a bit tedious but probably won't have much effect on performance. Other variants of Huffman decoding need not worry about this, since they will just store the same values again if forced to repeat the MCU. This approach would probably not work for an arithmetic codec, since its modifiable state is quite large and couldn't be copied cheaply. Instead it would have to suspend and resume exactly at the point of the buffer end. The JPEG marker reader is designed to cope with suspension at an arbitrary point. It does so by backing up to the start of the marker parameter segment, so the data buffer must be big enough to hold the largest marker of interest. Again, a couple KB should be adequate. (A special "skip" convention is used to bypass COM and APPn markers, so these can be larger than the buffer size without causing problems; otherwise a 64K buffer would be needed in the worst case.) The JPEG marker writer currently does *not* cope with suspension. We feel that this is not necessary; it is much easier simply to require the application to ensure there is enough buffer space before starting. (An empty 2K buffer is more than sufficient for the header markers; and ensuring there are a dozen or two bytes available before calling jpeg_finish_compress() will suffice for the trailer.) This would not work for writing multi-scan JPEG files, but we simply do not intend to support that capability with suspension. *** Memory manager services *** The JPEG library's memory manager controls allocation and deallocation of memory, and it manages large "virtual" data arrays on machines where the operating system does not provide virtual memory. Note that the same memory manager serves both compression and decompression operations. In all cases, allocated objects are tied to a particular compression or decompression master record, and they will be released when that master record is destroyed. The memory manager does not provide explicit deallocation of objects. Instead, objects are created in "pools" of free storage, and a whole pool can be freed at once. This approach helps prevent storage-leak bugs, and it speeds up operations whenever malloc/free are slow (as they often are). The pools can be regarded as lifetime identifiers for objects. Two pools/lifetimes are defined: * JPOOL_PERMANENT lasts until master record is destroyed * JPOOL_IMAGE lasts until done with image (JPEG datastream) Permanent lifetime is used for parameters and tables that should be carried across from one datastream to another; this includes all application-visible parameters. Image lifetime is used for everything else. (A third lifetime, JPOOL_PASS = one processing pass, was originally planned. However it was dropped as not being worthwhile. The actual usage patterns are such that the peak memory usage would be about the same anyway; and having per-pass storage substantially complicates the virtual memory allocation rules --- see below.) The memory manager deals with three kinds of object: 1. "Small" objects. Typically these require no more than 10K-20K total. 2. "Large" objects. These may require tens to hundreds of K depending on image size. Semantically they behave the same as small objects, but we distinguish them for two reasons: * On MS-DOS machines, large objects are referenced by FAR pointers, small objects by NEAR pointers. * Pool allocation heuristics may differ for large and small objects. Note that individual "large" objects cannot exceed the size allowed by type size_t, which may be 64K or less on some machines. 3. "Virtual" objects. These are large 2-D arrays of JSAMPLEs or JBLOCKs (typically large enough for the entire image being processed). The memory manager provides stripwise access to these arrays. On machines without virtual memory, the rest of the array may be swapped out to a temporary file. (Note: JSAMPARRAY and JBLOCKARRAY data structures are a combination of large objects for the data proper and small objects for the row pointers. For convenience and speed, the memory manager provides single routines to create these structures. Similarly, virtual arrays include a small control block and a JSAMPARRAY or JBLOCKARRAY working buffer, all created with one call.) In the present implementation, virtual arrays are only permitted to have image lifespan. (Permanent lifespan would not be reasonable, and pass lifespan is not very useful since a virtual array's raison d'etre is to store data for multiple passes through the image.) We also expect that only "small" objects will be given permanent lifespan, though this restriction is not required by the memory manager. In a non-virtual-memory machine, some performance benefit can be gained by making the in-memory buffers for virtual arrays be as large as possible. (For small images, the buffers might fit entirely in memory, so blind swapping would be very wasteful.) The memory manager will adjust the height of the buffers to fit within a prespecified maximum memory usage. In order to do this in a reasonably optimal fashion, the manager needs to allocate all of the virtual arrays at once. Therefore, there isn't a one-step allocation routine for virtual arrays; instead, there is a "request" routine that simply allocates the control block, and a "realize" routine (called just once) that determines space allocation and creates all of the actual buffers. The realize routine must allow for space occupied by non-virtual large objects. (We don't bother to factor in the space needed for small objects, on the grounds that it isn't worth the trouble.) To support all this, we establish the following protocol for doing business with the memory manager: 1. Modules must request virtual arrays (which may have only image lifespan) during the initial setup phase, i.e., in their jinit_xxx routines. 2. All "large" objects (including JSAMPARRAYs and JBLOCKARRAYs) must also be allocated during initial setup. 3. realize_virt_arrays will be called at the completion of initial setup. The above conventions ensure that sufficient information is available for it to choose a good size for virtual array buffers. Small objects of any lifespan may be allocated at any time. We expect that the total space used for small objects will be small enough to be negligible in the realize_virt_arrays computation. In a virtual-memory machine, we simply pretend that the available space is infinite, thus causing realize_virt_arrays to decide that it can allocate all the virtual arrays as full-size in-memory buffers. The overhead of the virtual-array access protocol is very small when no swapping occurs. A virtual array can be specified to be "pre-zeroed"; when this flag is set, never-yet-written sections of the array are set to zero before being made available to the caller. If this flag is not set, never-written sections of the array contain garbage. (This feature exists primarily because the equivalent logic would otherwise be needed in jdcoefct.c for progressive JPEG mode; we may as well make it available for possible other uses.) The first write pass on a virtual array is required to occur in top-to-bottom order; read passes, as well as any write passes after the first one, may access the array in any order. This restriction exists partly to simplify the virtual array control logic, and partly because some file systems may not support seeking beyond the current end-of-file in a temporary file. The main implication of this restriction is that rearrangement of rows (such as converting top-to-bottom data order to bottom-to-top) must be handled while reading data out of the virtual array, not while putting it in. *** Memory manager internal structure *** To isolate system dependencies as much as possible, we have broken the memory manager into two parts. There is a reasonably system-independent "front end" (jmemmgr.c) and a "back end" that contains only the code likely to change across systems. All of the memory management methods outlined above are implemented by the front end. The back end provides the following routines for use by the front end (none of these routines are known to the rest of the JPEG code): jpeg_mem_init, jpeg_mem_term system-dependent initialization/shutdown jpeg_get_small, jpeg_free_small interface to malloc and free library routines (or their equivalents) jpeg_get_large, jpeg_free_large interface to FAR malloc/free in MSDOS machines; else usually the same as jpeg_get_small/jpeg_free_small jpeg_mem_available estimate available memory jpeg_open_backing_store create a backing-store object read_backing_store, manipulate a backing-store object write_backing_store, close_backing_store On some systems there will be more than one type of backing-store object (specifically, in MS-DOS a backing store file might be an area of extended memory as well as a disk file). jpeg_open_backing_store is responsible for choosing how to implement a given object. The read/write/close routines are method pointers in the structure that describes a given object; this lets them be different for different object types. It may be necessary to ensure that backing store objects are explicitly released upon abnormal program termination. For example, MS-DOS won't free extended memory by itself. To support this, we will expect the main program or surrounding application to arrange to call self_destruct (typically via jpeg_destroy) upon abnormal termination. This may require a SIGINT signal handler or equivalent. We don't want to have the back end module install its own signal handler, because that would pre-empt the surrounding application's ability to control signal handling. The IJG distribution includes several memory manager back end implementations. Usually the same back end should be suitable for all applications on a given system, but it is possible for an application to supply its own back end at need. *** Implications of DNL marker *** Some JPEG files may use a DNL marker to postpone definition of the image height (this would be useful for a fax-like scanner's output, for instance). In these files the SOF marker claims the image height is 0, and you only find out the true image height at the end of the first scan. We could read these files as follows: 1. Upon seeing zero image height, replace it by 65535 (the maximum allowed). 2. When the DNL is found, update the image height in the global image descriptor. This implies that control modules must avoid making copies of the image height, and must re-test for termination after each MCU row. This would be easy enough to do. In cases where image-size data structures are allocated, this approach will result in very inefficient use of virtual memory or much-larger-than-necessary temporary files. This seems acceptable for something that probably won't be a mainstream usage. People might have to forgo use of memory-hogging options (such as two-pass color quantization or noninterleaved JPEG files) if they want efficient conversion of such files. (One could improve efficiency by demanding a user-supplied upper bound for the height, less than 65536; in most cases it could be much less.) The standard also permits the SOF marker to overestimate the image height, with a DNL to give the true, smaller height at the end of the first scan. This would solve the space problems if the overestimate wasn't too great. However, it implies that you don't even know whether DNL will be used. This leads to a couple of very serious objections: 1. Testing for a DNL marker must occur in the inner loop of the decompressor's Huffman decoder; this implies a speed penalty whether the feature is used or not. 2. There is no way to hide the last-minute change in image height from an application using the decoder. Thus *every* application using the IJG library would suffer a complexity penalty whether it cared about DNL or not. We currently do not support DNL because of these problems. A different approach is to insist that DNL-using files be preprocessed by a separate program that reads ahead to the DNL, then goes back and fixes the SOF marker. This is a much simpler solution and is probably far more efficient. Even if one wants piped input, buffering the first scan of the JPEG file needs a lot smaller temp file than is implied by the maximum-height method. For this approach we'd simply treat DNL as a no-op in the decompressor (at most, check that it matches the SOF image height). We will not worry about making the compressor capable of outputting DNL. Something similar to the first scheme above could be applied if anyone ever wants to make that work. ================================================ FILE: tess-two/jni/libjpeg/testimg.ppm ================================================ P6 227 149 255 0/-0/-10.21/51.51.62/72.83/83/83/:3-:3-:3-:3-:3-:2/91.91.80-80-91.91.:2/80-80-80-80-80-80-80-80-6.+6.+6.+5-*5-*4,)4,)4,)4,)4,)4,)4,)4,)4,)4,)4,).+$/,%/,%0-&1.'2/(30)30)63,63,74-85.85.96/:70:70A;/B<0D>2F@2IA4JB5KC6KD4MD5MD5MD3NB2OC3OC3PD4QE5T>1Y?2b@4nB5}E6G8G9E7F9F9E8F;F>F?G@G@CNCLCLDKDIBF>B@?@?<=;@.@.@.?-?-@-?-?-@,A.A-B,A*A)@*A*?/?/?/>,>,<+<+<+?+?+=*=*=*>+?+@,?:>7=4?1B3D3D3D4?/@2E8H;H9mB2T8*D3#:659549547326216005//50-72/72/72/61-61-50,50,50,.0-.0-.0-//-//-0/-2.-3--5,-4+,4*+4(*7(+=.1E69LUPdUPdUPd0/-0/-10.10.40-51.62/72.83/83/83/:3-:3-:3-:3-:3-91.91.80-80-80-80-91.91.80-80-80-80-80-80-80-80-6.+6.+5-*5-*5-*4,)4,)4,)5-*5-*5-*5-*5-*5-*5-*5-*/,%0-&0-&1.'2/(30)41*41*63,63,74-74-85.96/:70:70@:.A;/C=1E?3H@3IA4JB5JC3LC4LC4KB3MA1MA1NB2OC3PD4P>0U?1^A3jC4xD6D4D5B3B3@2@4B7C:EAKAICIDHDGBD@D>C;A9@9?.>.>,=+<+<+>->*>*=*=*>+?,@-@8>5>3?1A3D4D3C4A2B6E8I;G:kA3S9*D4$<66;55:4493382271161.61.72/72/72/61-61-50,50,50,.0-.0-.0-//-//-0/-2.-2.-3--5,-4*+4(*5)+<-0C47I:=h<;vDCJILJST`hk{r{|ylv[\QHsQBkOFaOFaNI_RN_[Yfnot~ojk[]\JVUCXQaXQaXQa/.,/.,0/-10.40-40-51.51.72.72.72.92,92,92,92,92,91.80-7/,7/,7/,7/,80-91.80-80-80-80-80-80-80-80-6.+5-*5-*5-*4,)4,)4,)4,)5-*5-*5-*5-*5-*5-*5-*5-*1.'1.'2/(30)30)41*41*52+63,63,63,74-85.96/96/:70?9-@:.B<0D>2G?4H@3H@3H@3I@1I@1I@1K?1K?/L@0MA1NB2MA1QA2YB2dC2qC3|C2A2@0<+:+;,>0@4C8F=G>?E@FBGCFDFCEAD?D;@:?:@=@@@A=@;>7@-@-@-?,?,?->,?,?-@-@,A+A,@*A*@)?/>.>.>.=+=+=+<+=,=,<+=)>*>*?+@,B7?5>3>2A4C5D5C4D6F9I=I=F;gA4P:,B6&=77=77<66:4493383072/72/62/62/62/52-52-41,41,41,,1-,1-.0-.0-//-//-0/-2.-5//4..5,-4*+4*+9-/>24C79_83l?:|E@IBNKZ^ftnw~zsdmUUNEtO?lMBbPEcQHcMH^NK\[[estx|xzlghXZ[KVTEZT`ZT`ZT`.-+/.,/.,0/-10.40-40-40-51.61-61-61-81+81+81+81+50-50-4/,4/,4/,4/,50-50-61.61.61.61.61.61.61.61.3.+3.+3.+2-*2-*2-*1,)1,)4/,4/,4/,4/,4/,4/,4/,4/,30+30+30+41,41,52-52-52-52-52-63.74/850850961961>8,?9-@:.B<0E=2E=2F>1F>1G=1G>/F=.I=/I=/J>0L@0L@0JD4NE4TD4^D3hE2sB1~A/>-9'9'9)<-@3E8I@CACCEDECDAC@C>A;@:?:>=@A?B=A7>5@,@,@,?->,>,?,>-?-?,@-@,@+@*@)@(>.>.>.=-=-=-<*<*=+=+<*<*=+=,>->-B6?5?2@2B4C6B5B5F:H>K@J@|F:aA4K;.?9+@86@86?75>64:5294183073062/62/62/32.32-21,21,21,-2.-2.-2./1./1.00.00.10.5106005//5,-4+,6,-:01>45W6-b<3qA7}D9H@RQ_iis|zu~my^gRQMDyM?rN@dPEgQFfLC^GBVNLZ^^fjnquzvx}vzvwzokoa`bUWYKTUG]V^]V^]V^.-+.-+.-+/.,0/-10.3/,40-3/,4/+4/+4/+4/+6/)6/)6/)4/,4/,3.+3.+3.+3.+4/,4/,50-50-50-50-50-50-50-50-3.+3.+2-*2-*2-*1,)1,)1,)4/,4/,4/,4/,4/,4/,4/,4/,41,41,41,41,41,52-52-52-52-52-63.63.74/850961961<5+=6,?8.@9/B:/C;0C;0C;.D:.D:.D:.G;-H<.I=/J>0K?1GH6KH7PG6XG5aF3jD1uB/|?,;):';(=,B2G7KDBDCDBEBC@@@>>:>:=9<;>?>B>C:A5?0@-?,?,?,>+>+>-?-?,?-?,?+?*?+?*>)?.?.>->->-=,=,=,=,=,=,=,<,=->.>.B4A4@1@3B5C7A8@7B;G?KCJ@uE;Y>3C9-78*@86@86?75>64=53:5294173062/43/43/32.23.12-12,12,,2.-2.-2.-2./1./1.00.00.3205105104..2,,4+,7./901P5*Y9,e>/n@1tB7|KGYcg~pxxs{js]eTTOGLAyPAjPAhMAeJA`GBYHEXKKWMPU^bc`fbcha`f\Z`TWZOUYKWYL`WZ`WZ`WZ,,,,,,---.-+/.,0/-10.3/,2.+2.+3.*3.*3.*3.*3.*3.*3.+3.+2-*1,)1,)2-*3.+3.+3.+3.+3.+3.+3.+3.+3.+3.+2-*2-*2-*2-*1,)1,)1,)0+(3.+3.+3.+3.+3.+3.+3.+3.+41,41,41,41,41,41,41,41,41,52-52-63.74/850850850;4*<5+=6,>7-@7.A8/A9.A9.C9/C9-C9-F:.G;/H<.J>0K?1FI8GH6MH5TG6[F3dC0lA.t?-{<*;);*=,A1F5J:M=E@FAFAE@C?@>==9<:<9;;=?=B=D8A2>,@,@,?+>->->,>,>.>-?,?,>,?+>*>)?)>->->->-=,=,=,<+=,<+<+<+<+=.>/?0C2A2@2A5B9C:@:@9@9H@NGNEoG=R@4?;039-A75A75@64>63<4194083/74/63.43.34/23.13.02-02-02--3/-3/-3/.3/.3/02/02/11/11/32032040/2.-1-,4..5//H4)M5)X8+a<,f>2nGBzYblu{|u|mubi[[SLLBQAnN?jI=cH>`HB^FCX@BO2K?3DG6EF6KE5PD4VC2^C2e@.m>,v=,|;):);*=.B2F7I:DG>F>E>C?@><>9:9:;<@.=->->,?.?-?,>,>*?*>)>->->-=,=,=,<-<-<-<-<,<,=-=0=0>1D2C1A3B6C:AkK5.>5.>5.>5,B8/B8/C9/E8/G:1I<3J=4K?3EC6FB6IC5NB4TA3\@2b>0h=-q<.w9*}8)7*:,=/B2D5E9F;GF@C?@@:9:9=;A;D:E4A-?(A-A-@.@.?.>-?->/>.@.?.?->+?*>)>+>->->-=,=.=-=-=-1?2D2C1B4B6C;C>C>D?PJ[Te\f]s_TYUJFNC>KA@70@72>71=6094.83-63,63.43.34.34.13.13..3-.3-.3--3/-3/-3/.3/.3/.3/.3/02/.0-00.22022000.0/-0/-10.8,,;,)B1*K7.S<4^IHtbnzʂyrwikXVGDI^C@[ABV>DP>EMGQSKWUQ^WU`XS_UR^TT^SV`UaZHaZHaZH,-/,-/------------.-+.-+/.,/.,1-*0,)0,)0,)/+(0+'/+*/+*/+*/+*/+*/+*/+*0,+/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*0,+0,+1-,1-,2.-1-,1-,1-,1-,1-,1-,1-,1-,0,)1-*2.+3/,3/,3/,3/,3/,3/,3/,3/,3/,40-51.62/73081+92,:3-;4.=4/>5.>5.>5.?4.?5,@6-C6.D7.F90G:1H;2F?5H@5J@6N@5R>3W<1\:0a7+k9.t8-|8+9,;/=0?1?2@3B5D8E:G=F>D?B>?=A?D?E>C8C1B.B,A.@-?,?,=-=->.?.<,=,=+>-=,=+=*>*<+<+<+<,<,<,;-;-=/F@C>DAKGXRf]qfth|rfik^S_SCSHQJBLE=D=5<8/95,74-63,33+43.34.23-13.02--2,,1+,1+-2.-2.-2.-2.-2.-2./1./1.02/02/11/11/11/11/11/11/5*2;/3A32C4/J;6]OOymyӐ݂tzjn_bYZPHmHBdA>]>>X?AVBHVLU^U`bbqnn}xv|pulyoguh_k_T`Ta[Eb\Fc]G,-/,-/,-/,-/---------.-+/.,.-+.-+0,)/+(/+(/+(/+(.*).*).*).*)/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*/+*0,+0,+0,+1-,1-,1-,1-,1-,1-,1-,1-,1-,1-,0,)0,)1-*2.+3/,3/,2.+2.+2.+2.+2.+2.+3/,40-51.62/80-91.:2/;30=4/>50>50=4-?4.?4.?4.B5-C6.E80G:2H;3H>5J=5L=6O>6Q=4V;2Z90_7/h8.p7.y6-8-9.;1<1>1@3A5B5E8E:FF8C2B/C-B0A/@.?-?->->.>.=,=.=-=,=+>-=,>,=+=+<,<,<,;-;-<-4@6A7B8H7F7G:I@HBFAJFTMdZre~op~|mlteYgZJZOPLAKI=EC7@>2=:1:7.44*11)23+23-12,/1,/1,.0+.0+.0-/1./1./1./1./1./1./1./1.02/11/11/11/11/11/11/11/5*:9-9<15?53H?:^VTxszΐׄxpykten__yXZsSUjRWjU]j\gmguvrv}vypsfteXfW_YA`ZBb\D,-/,-/,-/,-/,-/---------.-+.-+.-+-,*/+(.*'.*'.*'.*+.*+.*+.*+-)*-)*-)*-)*/+,/+,/+,/+,/+,/+,/+,/+,.*+.*+/+,/+,/+,0,-0,-0,-0,-0,-0,-1-.1-.1-.1-.1-.0,+0,+1-,2.-2.-2.-2.-1-,1-,1-,1-,1-,2.-3/.40/51080-91.:2/;30=31=31=4/=4/?40?4.?4.A4.C60D7/F91G:2H;5J;6K<7N=6P;6S:5V72[60c60k6.t5,}7/9/:0<0<1@3@4@3A3C6C8D:CG@HBH?E:C3B0B.B/A.@->->->->-?0<-=-=,=.>-=,=+=+<*<,<,;+;+<-;,;-<0<0<2>3?4A8C:D;KJDIFKGSM_Vrgqz{wrocqbVdWPQCMN@HI;DD8@@4::055+/0(01)01+/0*/0+./*./*//-//-//-//-//-//-//-//-//-//-00.00.00.00.00.00.00.00.6*>6+;8.6;63HE>_^Yyz|Î˄}{||yq~o|n}oy|{j{iXiW\V<^X>`Z@-.0-.0-.0-.0-.0-.0......---.-+-,*-,*,+).*'.*'.*',*++)*+)*+)*+)**()*()*(),*+,*+,*+,*+,*+,*+,*+,*+,*+,*+,*+,*+,*+-+,-+,-+,-+,.,-.,-.,-.,-/-./-./-./+*0,+1-,1-,1-,1-,0,+0,+0,+0,+0,+0,+1-,2.-3/.40/91/:20;31<42=31=31=31=31>3/>3/>3/@3-A4.C60D71E82G83H94I:5L:6M:6N94Q83T50^72e60o6/x8/90:/;1=1?4?4?2@1A2C5D7D:FIAH>F:C4B0B.A.A.?->,>,=.=.=.<,<.=.=-<.=-=-<,;);+;+;+;,;,;-:,;/<1<1>5@7C:EIICLGPL\Tj^oyzym{lam_UYHQUDKO@EI:@D6;=057,13(01)/0*/.).-).-).-+/.,0/-/.,/.,/.,/.,/.,/.,/.,/.,0/-0/-0/-0/-0/-0/-0/-0/-8*A6):3-1961HJ=bfX{y}~k|iUfSXT7ZV9^Z=+/2+/2-.0-.0-.0-.0-.0...------.-+-,*-,*,+),+),+),*+,*+,*++)*+)**()*()*(),*+,*+,*+,*+,*+,*+,*+,*+,*+,*+,*+,*+,*++)*+)*+)*,*+-+,-+,.,-.,-/-./-./-./+*0,+0,+0,+0,+0,+/+*.*)/+*/+*/+*/+*0,+1-,3/.40/91/:20;31<42=32=32<20<20=20=2.=2.?1.@2/A4.B5/C60D63C84D95G96G96H94K84N51V72_60h70r7/}:1<1=2>2?7?5?5?3A3C5D6E8E;F=G>F=D8B5@0@/A-A-?,>+<,<,=-=/<.<-=-<.<-<,<,<,;+:*:*:*:+:+:,:.;0<1=4?6B9D;G@HALAH?HAKGOLWQf]whw|}tqlte\eRV_LMVCEL0-?1.@2/A30A30?61@72@93A96A96B94E74G51O61W6/a6/j8/u9.0>7>5?5@4B4C4C4D4B5C8E:E;C7@4?1?2A,?-=,=,<+<+<.<.;-E5:@29<134,22*1.)/+(/*'0**3*+4+,1++1++1++1++1++1++1++0,+1-,1-,1-,1-,1-,1-,1-,/.,;(;5(23+(56$CL-\hDt`wƤШɯʰ˯ɪ{wrdx]MaHQQ5QQ5RR6,03,03,03,03./1./1./1./1/////////0/-/.,/.,.-+.-+/-..,-.,--+,,*++)*+)**()+)*+)*+)*+)*+)*+)*+)*+)*+)*+)*+)**()*()*())'()'(+)*+)*,*+-+,.,-.,-/-./-./+*/+*/+*/+*/+*.*)-)(,('0,+0,+0,+0,+1-,2.-40/40/:12;23;23<34=32<21<21;10<1/<1/<1/=/,>0->0-?1.@2/;60;62;83<94=:5=:5?82A60F5.O4-W5+b6+n8,x:-<,<.:6<5=5@4A4B3B2@0?1@4B7B9@6?5=2?2@-?->,<+;*;,;-;-;,<.;-<-;.;-;,;,9)9)9)9*9*9+~8,}9,=1=4@7B9E>HCKFMHIAGAJFSO\Xh`{ny~w{nixacr[ZhQP]IIUACL;>D60-?1.?1.96/:729839839:4:94;83>71A2+I2*S2)^4(j6)s8*|:*~;+84:5=4@3B3A1@/>-<-=0@4A7@7>4=4=3@-?,=+<*;*;,;,<-;.<.;-;,:-;-;,;,9)9)9(9*9*8*~8,}9,>2?5@7C5.>5.>5.=4-<3.<1-=2.<1-<1/;0.=/.>0/>0/?11H-&C1';5)2:++=-(=.-;.45-?-+H()R%(X((Z.+Z8.[A2\G6wC-{B.C1A3?1;0:/8+;->.B1D0D0B.?,<*6383:2<1@1B0|A/|A/C2A1>1=0;/:.9-9-v:/|@5u=0n9)s@/s@/t<+{@0{<-?4D9H?LANBQCRCHKTRd]ue{lwsz|yk{awhea]\zV[sS]mR[cLVTEPH=J;6G53B,/=&,:#+:#-9#/8".#/-#-,$-,&*+))+-(.1'/2'/4'06&14'14'13'32(32(30(3.)-0,-0,)//'=>0WZErx\gspqrrs{{z{~}|zvroi{e[jWLZIKO@CG8>B3/0*01+01+01+12,12,21,32-43.63.74/74/63.61-50,50,7/,7/,6.+6.,5-+2-*1++0,+0,-/-./-0--/-,1+*/)*.()-/(//(//(//(//)-/)-.*+.*+/+*-,*.-).-)/.*./)./)./)..0....../-./.,/.,1-*3.+3.*5.(6/)8/(90);0*<2)=3*>5,>5,>5.>5.>5.=4-<3,=2.=2.<1-;0.;0.;0.=/.>0/?10F/'D0)A3*=4+96-85.83-<1-?-+D*)K)(P*'U.)[4-_:1c?3s@+xA-A0?2?4;3:1;19.<->.A0B1B/A/@/93:3;2=1?0@0@/?/A1>0=0;/;.:-:,:,w9.x<1s9-n9)r?.s>.q9*u:,}=1@5E:H?K@MBPCQCDJQRd]vfp}w~w}oxag\`VZU}XWyXWpSPbJKVECI;@A998340-0,+/+,.)--(,*,+)+***,+),-(,/)-2(03(03(02(02(10)1/*1-*1,+3,+32-12./0,)--%9:,TWBox[iolnpppw{xwy||{xuqnh{eYjWL[HGK<@D5:>/12,12,12,12,23-23-43.43.54/74/85085085083/72.61-80-80-7/,6.,6.,3.+2,,1-,1-./-.0.1..0--/,+0+*/*).1'//(//(//)-/)-/)-.*+.*+0,+0,+/.*/.*/.*0/*/0*/0*/////////0./0/-1-,1-*2-)4/+70*90+:1*<1+=3*>4+?5,?6-?6-@7.@70?6/>5.=4->3/=2.<1-;0.;0.;0.;0.<1/=20C2*E0+H/+L,-N+/M*.J*/E+.A-,@.*@/(C/(M/'Y0*d1-j30i;+o;-w;0=4<4;594:4;2=2>2@1A2A3B5C6=2=1>1>0>/=.=.=.<.;.:-9,;,;+~=+z=*}=3z<1v:/u;-x@1x@1v<.v;-?3B6F=H?JAKANCPDDHQQc^ugnt~}{ak[eXaV`W`W]QtVMiPC[E=RA6F9/<2*5-&1+%.)$-(1&*1&*1&*1&*1&*1(-2).1+//*0-+0,+0+,0),1(-1&.1&.14.24.0.*'**"66*PUAmv[~ik~hjnn~mqx|zwvtuwyy}}ywspmh{eYkUL[HEG:=?28:-23-23-34.34.34.45/54/54/650961961:72:72:51940940:2/91.91.80-7/-4/,4/,3/.3/.3/01/01/00.1..0--/,,.2).2).2).0*.0*,0*,0*,/+*1-,1-*0/+0/+10+10+10+10+11111100010.10.2.+2.+3.*91.92,;2+<3,>4+@6-@6-A7.A8/A8/B90A8/A81@70>5.?4.=2.=2.<1-;0.;0.<1/=20=20?5,E2.O-.W(0]#/\"0W#/L'.C/.:3-55);5)E1(U.'c+*l*+e;/j;1s=3}<6;8;9;7:6>9?9B9C9B9B9A9@7B/B/@.@.>-<,:+9+8*8*9*9)<)z=(w?(t@(=3{7,x8,z3/>3/=2.=2.=20=20>31>31>7/C41O/2Y*2_%3`#2Y%1N+1B3077-39+68*?5)N1)]-)e+)c;3h<3r=7z=:<<<=;;;:;9>8A:C;CJ?K@LDOGSJycL~hSoYu]}biu|~|~|}{yn}lylwkwmtjogl~dbqZ[hTSZHIK=B@4=6,8/&5+":&(8%'6&'2&&0(&-)(++)).*'+*&,*&,*'+*'+,)*,**,**,-#$2*(50,85,BC5UZFfpWn}^tcqbtexiwkshsiwmzmxlwkvlyq{u{w|wxuzwwtqomhd{_WkPJ^CFB9>:195,560560671671782782872872983<94=:5>;6>;6?:6>95>95?74?74>63=52;62:5294194184184195484373243132021/6-.6-.6-.6-.6-.4..4/,4/,40-40-40-52-32-32-43.43.431431542540841850940:5/=60?6/@7.B8/C9/F90G:1H;2F<3F<3F<3F<3E;2C90B71A60@5/@51>50=4/=4/>42?53?53=82A64I35Q16V.6U-5R/5J22A62::08<.9;-?9)H6*P4)U3)]2+c4.k62t76}77897978}75{:6|=8{?7@9@:@;?;|E0}D0C0A/=.;-:-9,8+9+:+<+{>+x?+uA+tB+2,2,LEXQA8|90F;J>yH:zJ<{M@|NA~NBPEUJYN_uNgwRtzX{^|bis|z||x~tyqvponpp}pxmskk~bgu\_iQWZGPM0%:,+7,*5+)1,(-,'+.').((/().(+-*,,*/+*3)*6',7&,9&,2)$<3,E>4JF:QR@]bLgqVizXm]j\j]pbqeodoerhukrhqitlxrzvyvyvvtwturokjfc|^UlOJ^BHA9@91;4,671782782782893893983:94:94=:5>;6?<7?<7@;7@;7@;7B:7B:7A96@85=84=84<73<73<74<74<74;74:6395284173080.80.80.80.80.80.61.61.61-52-52-52-63.63.54/54/540540651952:72=84=82@93?80A8/C90D:0E;1H;2I=1I=1H>4H>4H>4G=4F<3D:1B8/A60B71@70@72?61?61@72@72A83=84@85B86D97E:8G96G96E:4C90B90B:/B:-D;,F:*H;*H;*].&b0)n3/x7398;;<<>;A>A<?6}=4~;3;5=8>:~C3B3A2?2=1<0;/;/;.|=.{=.|>/|>/|>/}>/}>/.*;8kf~yZTC3-<3,92*41(01).1(+1'+0)/0*2/*6,*:*+@'+D%+G$+H#+A7+LC4WP@[XE`bLgmQiwVj{Wl[gWfWj^nananbrfrkohniqnwsyvxuutssutspnlicb{[TmMH`@MD=E<5@707827828938938939:4:94:94;:5>;6?<7@=8@=8A<8A<8A<8A<8A<8A<8@;7?:6>95>95=84>95>95>95>95=84<73:51940:0.:0.:0.91.91.91.91.72.61-61-63.63.63.74/74/74/540651961;83<94?:4@;5B;3A8/B90C9/E;1H<0I=1J>2K=2K>5K>5J=4J=4F<3E;2C90B8/B92B92A81@72@72@93A:4A:4?74>95=<7>?7?@8@@6D@5J=4J70N5.Q6-Q6+O8*M:+I<)H=)l3(r6,~;3@:DAHDJGLHQJMDD;;28-7-91;4?7?7=6<5=5=4|>3y?3vA3uA3uA3y?3}=3:38373%$<;{zhcG@K@wI:mNfW@jX@r\E}aLeQj{O{{Uw\l`^_R\M[O^muxx΅~}xurruuus{sxrqlphiadtW]gLVX@LJ3GB.L40H3.D3,?2*:1(70&40'40'81):/+?-+C++H(+M%-O$-Q#-PE1[P:d^FgfJilOnuTm{Wl~VkZgVgVm]papbrdvhrlokmipmwtyxwwtustutsqokicb{[TmMGa>SJCKB;F=69:49:49:49:49:4:;5=<7=<7=<7?<7@=8@=8A>9C>:D?;D?;E@8C>8D=7B;5B;5B;5B;5B;5B;5A:4A:4A83A83A83@72@72>71>71>71<71<71;60:5/85085074/74/761961961:72<71=82A:2B;1C:1E;1F<2J>2K?3L@2N@3N@3M@7M@7L?6K>5I<3F<2E;2E;2B90A81A81?80?80?82@93@93<5/LE?IB:E<5OB:K:2J3+\>6Z5-`5.`4+^/'\0%b8,g@1gB2I;G;I?LAF>>7=6D;NDQEVHYKPB@5:0=49;9:675496@:{@8o?3oC6lB4m?2u:27435-3(1EEbaEDWUyvVOFd02b22\31L)'D'#I2,J70F5.E2,E0+H0.I-,I)*O+-V24VK/`W:f_BgdEkoLu}Xu]oWjWlXn]q`sbubudveqksmsoqosrwxzzyzxyqrmjjghdazZTnKIc@TKBSJAPG>9:49:49:49:4:;5;<6>=8?>9>=8@=8A>9A>9B?:D?;D?;D?;FA;E@:E@:E@:D?9D?9E>8E>8E>8E>6E>6D=5C<4D;4D;4C:3B92B92B92B92A81A81@91@93>71<71;60;60:5/85.74-74-96196/96/;60<8/>:1A:0C:1C;0E;1G=1J>0L@2M?2NA1NA1N@5N@5M?6J=4I<3H;2E;1E;2C:1B90A81@91@91@91?;2?;2C:3G81I0,V..j68u99{;;ECD?H@I?G>JANHPLMKE3C2B4B6>36-7+<0C5@.@.E3F6E5H9N@KRGN@F9=8:?=>?_\XQ@5UDvbJa]@Z_?ekIonOshJ{fKkP]V][SZ7SD=]P.dY9ga?ifCnrMz[zbt^r]o]o^q^ubwcwcwcrmwrzvyw~}z|qqljhc`yYTnKJdAWQEVPDUOC8938938939:4;<6<=7?>9@?:@?:B?:C@;C@;C@;D?;D?;D?;FA;FA;FA;E@:E@:G@:G@8F?7IB:HA9H?8G>5F=4E<3E<3D;2D:1D:1D:1C:1D;2D;4D;4C<4?80?80<71;60:5/:5/94.94.96/96/96/;7.<8/@9/A:0C;0E;1F<0I=/K?1M@0M@0NA1M@0N@5M?4L>3K=2I<3H;2E;1D:0C:1C:1A:0A:2?;2@<3@<3A=4SEI?MAOBRJSRNSENE2B0@0?1:-7*8+=/E4>+7$:%>+@/B2C5/89BDLKRNRLLB>}:1u;/q9,s5*2-478@?:A@;BA4G=3F<2E;1D:0D:0E;1E;1D;2E<3E<3E<3@91?80?80<71;60:5/:5/:5/96/96-;7.;7.=9.@9/C;0D<1F<0F=.J>0L?/M@0M@0O?/O?/O>4O>4N=3K=2J<1G:1G:1D:0D;2D;2B;1B;1@<3A=4A>5A>5Q9/X+&:?P`OeOfPcGO20:/?.C3F=FG>H2BH6F5B3@3?1>1B4D6G5B/<);&<(:(5&3$7<8>7>6=9@?:BA4G=1H<0G;/E;/E;/E;/E;1E;1D<1D;2D;2@9/@91@91?82<71;60;60:5/;7.;7.;7.<8-?8.A;/C;0D4N=3N=3J<1I;0G;/F90D:0D<1D;2B;1@<1A=2A>5B?6C@7_4-t42KSYiH_:Q2C#+/)9(;&=)@3A=:?0;D4B3?2>2?5C7G;J<>/?-=+:)9':*;-LDTLTNKJ>C3>.<5+7.0+9482@9[PUDxO9~dIlPbF]FeTqdsjb?eAiBkBmAm@o@o@qAqBn=hEmJpGhMiZrbsYc@D]($M-"PC2PR=CO76H.WH1eYCujT{gy~þþyvh{e\sWTmONiHTYBUZCW\E560560671782893:;5=<7>=8@?:B?:C@;DAGB>GD=GD=HC=ID>IE0I=/G>/G>/F<0F<0E;/E;1D<1C:1B90A:2@91@91?82<71;60;60;7.;7.;7,<8-?8.A;/D0K?/M@0NA0P@0O?/O@-P>2N>1M<2L;1I;0H:/F90C9/C;0B<0B;1@<1A=2A?3B@4C@7t50FEY_Ub@Q5F0;*+1%9#;!: =&=.902-:,:-9-6,91A9E;E:?2@0<,6'6)=0D9G=9*@4D=A@D<@?>C>JBRMZWPREL;G6F2D/B1G6L:T:T:T:W=\?aBeDih?jAm@n?o>m=mFn:a>dInJlMmSoXnp_jILt:6\6-O9+OD2SN:`PArdW|p̿m~k^u[VoQSlNU_DV`EWaF560560560560671893:94;:5=<7@=8A>9C@;DAHC?HC?GD=HE>ID>ID>JF=LE=MF2G=1F<0D<1D<1C:1B;1A:2@91?82?82<71<71<8/<8-<8->7-@:.B:/D2B@4@@4+)JKSV=B/6.3./0)1 9!=!== =#;#6"6-8/5.3,71@:B<@6B7A57`UqeSWCN:XGe[a_PTBIDK@D@?BHC?ID@HE>HE>ID>JE?JF=MF>MF2G=1E=2D<1C:1C:1A:2A:2@93?82<71<71<8-<8-<8-?8.@:.B:/D2??3@@467]_Z[78,,/,,#0#8$B(G*G'F$F$C!? 81;29250:6B>D=>7<3<272:<$:*.($&''%%(,)2*5*3(2'/&-%=(2>05)7/?7C9qdm]YFVEi\lfSS@H?L46,4.44BH8G2F3H5I7GY=X:W6W5Y5\6_7e;k:m;ot>vEbNkTqIf?\Rqff^wbvkys{rvfeZVTN~ĻþĪyvi|f`w[\uWbqRapQ`oP201312423653875984984983;:5<<4==5??5AA7CC9EE9EE9HH@HH>HH3B90E<5C:5@85?74@86?67>56:44F85E76B87@78>:;<:=<<>==????A@,B0D2D0B/?,>*<*=-C4F7>03&6+8,:-=/=.(9%44 9%8&6&@4QEIAMIUUVXJP9A4?9DCHCFAA?;=3=/?/@0Q@QCLCC=??@E>G8CGMENEQESAR=S>XCbGiBhHH7H?8F=6C:5C<6A:4?74?74@85>95=84;63>3/=4/>42<74=98<;9=<:>=;@?;C@9G@6J@4L@0O@-P?+P>(=B,?A,E=0H92K63J46F35A57>=;8=69?5?A4C=-J9)^B4sRCK=;-2#6&:'8$9%?(;%=(@,@-=,9*6(5(;+:*9);+?.B/B/@.?.:(<+E6H9?18+7+5+7,:.;/=/;/8/4/0----+/+4)8(;'=&:'7"8%=*;*5&;/G8;1;-<->.F5M?NEGC?@>B>F>HDJCLDPFTBS=S>XBaFhCi?i@lBpGvJzL|IxHtKpRs]z`{XwMqCkAlCjJg^ppugNIv̲Ų}/.,0/-10.21/43/540762761:94::2<<4>>4@@6BB8CC9DD8IF=IG;JH;KJ8MJ7NL7NL7OL9KI:NKBTSQ_^dihxmmlkihcYd[QZQGPJ@IH>FG>CC=A@::1>:1=90:3-94.;60=82=:3>;4?<5?<3C?4F@4I?3L@2O?0P?-Q>-P>*3@&7?'<=+A;-B8/A62>42;31=85B:7H94O2.[+)o-.:=EJ9+2$1"9'<)7$8$<&;&=)A-A/>.<-:-:.>0<.9+:+<+>->-=,?-9(>/L=H:6*2&;05*6+8,:.;/9.7/2,/-.+.+0)2'6&8$:#7$5#8'>-=.7)8.A7<5?8EAKIIJCC?A@CDCC?B;=4:.9*;*<+9)E8NEIE?@X@_DfCiDmFpIwK{L|K{CvGwJtNtZ|aUvCdHkRv=\H`z}~\F;rճξ/.,/.,0/-10,21-32.54/650872991;;3==3??5AA7BB8CC9IE<0?=1@<0?<-A;+F?/H?.K?/M@/O?/P?/Q>/P=.<@)=?*?>,?<-?;0=:3;:5:94<94D95N43[*-o&--83C7H7)7&9(?-?,9&9#;&:&<)>,@/>/<0=/=0@5=2:,8*9+:,:,:*;,;-B4E9?31'2(:13+4*7,8-8.7,3,1,0,.+.)0(1&4$6 8/04$;,4Vet͑]=2aP@wlѥº10,10,0/+0/+10,21,43.54/77/880991;;1==3??5AA7BB8KD:LF:OG:QJ:RK9SL9RM:QK=OKBVTUfdowxÎƏ{wrlid_[~UPnNJaJGXEBM?=B;7696196-86*86)581692891;;/><-?<+C<)D<'I>*J?+L?,M@/M@0M?2M?4L>3M?4K?3F<2B90=909:25<44>57<5>:1H3.\0/{48;D9E2A<+<+@.A/@-<'<'>*8%:'<+=.;/;.<0<1A6>3:/7,7,8+8+8+7+A5C88.1&3)7-6-2+3)5+6,5,4-2*/*/,.*/)0'1#4!67//2"5)9-:0?6E=F>@9<5@9KDNGF<;1=1<0C>EBJJTJYFXCYB]@_BdFjJsOxOzLyIxGwRQ}IqImStVtNiD^F]YkKFd2)jc͖ɿ˾Ⱦȿ84163.52-30+30+41,52-63,85.96/:70<90>;2@=4B?6B?6KC8ME:PF:SJ9TK:UL;SL<=;:6;8396/267465672880<:-A<)D>(G?(I?&J?)IA,JA0IA4IA6HA9G@:R9?46<*=+?-?->,>*?+@-8%9(:+:+9,9.:0;2>7;4818.8.9/8.6,7-C9?50&,#7/<44,1*1*2)3*3+2+/*.(.*-)/)2&3$5"7 75#3#2$2&5)7,;3?8YRRJHAD;F0A3A6<5<6A?EEGIJMMQAD?ECIJTN[JZF\F]A]BaEiJpNwOzMxKxR{R{OvOtVw]{SoD^UjQddt`cKLkeώ<94;8385052-41*41*52+63,74-85.96/;8/=:1?<3A>5B?6KA7MC7RF8UI9WK;WK;UL=SJASJK[Xcnlǚޞ졩홛敘ߔ֐̈zzrqfd|XWiPN\IGRFCJDBG=?K==G;:?;:8<92A;-D=*F@*F@(GA)GB.ED2CC7BC=AC@>BAG9HH,>,?+@,@-?-=*8'8)9*9,8-8.91;3;4:3818192:2706/<3>5912*3*;2<35,0(1)1*1+0+/)-(,(-).)0)2(5%6#7!8 8%8%5%4%4(6+7.7/NGXPZQRIH>E9B5?1<&<&<(;'9(;*>0@4D;?9@:FCIHHGIHJMCFADDIKSQZN]L]J`D^DaFfIlNuOxOxNyYzWvVuYx]{ZuQkI`WkUgN\^kKZSaSaQ_jfɂ~窧@=6=:3:7074-52+52+52+63,74-74-96/;8/=:1?<3@=4A>5M@7OC7RF8WJ:XK:YL-C@-CB.BC3AE7>E=UEYFL7A+A+@,A-A-A-A.A/=+7&7(8)8+8-6-7/8/;2736161729494816/A:8/3*7/=5=58/6-0'0'0(/).)-)+(+(-)/)1)4)5'8&8$8#8$9%7$6&7)8,7+4*3+NGd\`YOFB9<2:/?&>&=&;%9&9*;/>3C9A9E?KHLIGDFEJIFGCDDHMSRZR\N^OaG^GbGdIiNrRvRyRy[u\x`}_|UpMgPgYn[mbsL]SdM_RgI_E]d`tqښA>5@=4?<3=:1;8/96-74+63*52)52)63*74-:70=:3@=6B?8J@6OC7RF8VI9WJ9XK;ZL?[NHTIMXR`gd|}̗瞩꟡ܙҍurhe]ZXR~YP{YQxVOpOG_E?M?:@?;8@@6>>2@B5@F:>E=:C>9CB*?,@.@.?-=,;,6'5(6*7-7-8/91818495:685616183:3C<=670@7[Rlc]T@71'2)1*/)*&'%(&*(-)0*2)1%0#1"5$:(=&=&=)<*;,9+8,6-@871GAc^XQB<@93.<#<$<&<&:(:)<.=2>4C;PJXTOJ@;@:KEFEFEJKPTQWNVKVL\RdOfKeJfMnRsRvPt[wZuZu[w]xZsWnVictVg\mYlDXBXMeIbnhhcˎ赲C?4B>3A=2?;0=90;7.:6-95,73*73*73*83-:5/=82@;5B=7I?5LB6QE7UH8VI8YI9YK>ZMEUKLXP_ebyzɔ䚧䘘،ɀ~uqieb^cVbU]TWOtNHdFCTBAIAAA;=8@C9<7<7=9A=C=B\Q?46,+#)#,)./,-((0.4/7/6,4)2&3%5&='<'<(;(:(7)6(4(8/5-<6PJSOLHA?/,=%>&='<'9(8(9,:/>4B:OFWPQKD=B5JB7ND8RF6TG6WG7YI:YKBWKKXP[b^wsuޗ뙗Ղxtqml`i]dY^VVQyNKhEDV@@J76;?=>HBBKABN?BYFJmX_}fnt}}wpcRpE^I\EP9<3,7(;%; <*<*;);*<,<-<-<.6*8.<1>5@8>7<3:273403/93A;E?A<<5<44,4*7-2', 6*H@64--)+*+,+,*,))/+3,5.4+2(2'2':&;'<(;);*:,8+8,4+;4:5<7ONXYEE02=(<(<(:'9)8*7*7,>2A6JAUKRIH>E:H@IDHCLGSPSSPQMQNWXdZh[pZrUoQlPnRpFmOvZ}[{VqSkVk[mYhYh`m`k\fenfmT[cY}NDlfØ߹IE9HD8FB6D@4B>2@<1?;0>:/:6-95,95,94.:5/<71>93@;5E>6HA7LD7QE5RE4UF3WG7WIC_@EmDJOU]fjreklf]TyFg8U0H>PBM:<7/@.B*/?0@3@36*KBJE50FFZ\HK?B=-;+:*:*:*9,9+8,<0>2F9OBPDH3A=2=9.<8/;7.;60;60<71>93?:4B?8EA8JD8NE4PE1TE0VG4XH9ZMEVMR[Whkl~В噧铕⊌لӅ{umkdd_aX[QQsNHbUFY_CRlBLEOLVU][d]fJuNxPuLnFc?Y5J+?5EAMFK><>6H8J6B)>-=-<->/?2B4D7E:E9B7>5:26-5,3+2*1*4-6090807/6.5,/&5+6)2#1"9)>-<+=-D7KAD?56)-)-.26755301,/,/,0-/-80:1:1<0<0=0?0>17+WL`X;6;:OQEHOT=2:/8,8,:-;.;-:.:-<.B3H9I:D6@2>0E3;18/4*3*4+4,5-9/<2=4<3905-5,6-.$;.<.1".8$=);&:'9+:1=9@@;?27+1,.+,+)+(/.4488:;5564736/7-5*5(5&5'PEmcHA42CC>BUYB;=6706-9/<1=1=.9)<+@.B0B0?.=,<+C8D9H=PGSLOIOJOP_caiitm|duUjRgWoSxUtWp_poyy~msXaam`maos{숊ɂ|wjyhhpYMO:^WGqgݿSM=RL4D=5B;3A:4@93A:4A96B:7@A;CC;IE:NG7QF2RF.UF/WH5XJ=RHFXR\jh}ƒږ奦띤蛢晞⒚ۊ҅ʂ‚ymczWiP]KWGP?H9A;6<5B6H7J5G1D.@/UGG?;76488:;9866=.<.;.;,8+6*3)1&5*3*3(2)3*5,6.7/>3<2;18/7.6,4*3)3&3%4%6&=)>*9$2;(5%3'60;<=@7=27-1..--0.449:;=;>.4/3011/1*2(1%3$2#>/j_TL95@@:=RUJEB=935.8.;0<0=-<*?-@.?-;(;(<)=*>2>2D8LBPFNFMGNLbcbfhqo{hxYmUj[pXs\tbqkt퉇yy_dhrl|cskw餟z\pWFRRL4:B*D)H)N+O(L%H%D&WBF8;5>>BH>F5>08F8E7D7A3=08,3)0%0&1(2(3*5,5,4,4,C8=27-7-:/9/5+1'7*0"0!9&9%5 9#E.:&:)7+3.//055;;BIMGJDD@@>>9:28.4'/(/*.-.0+2*5)7(0!/eY]TA,A/B0=)8%9&;)>,8+8+>1GTK8>=@D@HB;D;BCG99B@D@/-HIHKAG;D8A:?<><;<9A=>9C=LCK@>27+;-9,8-7-3,0,/-1134A19)1 1"8(;*6%22454 3"3%3(3).(2+6+8*8(7&7%6'3'2,3101+2*2+4-6+1*/+,.-4.8,7(5#.3 XHZL<2OG5/IFQRLKDB<8807,9+;+;):'9%:&<)=+=+=,9.;.=1?1?1@1@2A4k_qed[mirocbjituk|ivdm_hafgjnkqk|w}Yj[wZpaz]sMIZ6LR6snX˷YPAXO@XO@VM>UL=TKD:B7?7;89:8;7F?<5<4G>LAC7;,9+7*7+7-4-2.3/5366?0<-6)4&6%6%4"4:":":#;&<*;,8,5*3.5-7-8*6&4"4!3"2$1(/+.,,-,1-3.4*,,-0.2.3*5'7'9'@,*E5?1F>WPC?BAWVRRKJC>=59.9+8(;);(:';'>+?-@/>-9.;0=0=1?0?1B3C6i\mdb[kfolbakluvpo|ir^fY^adqn|vyux~RdUrXnXn[tLN_;QZ;us\úZQBYPAYPAWN?VM>UL=TKCC>C;C7=?AA@D?=896WWBC=B:A7<586696;6HA:35+A5K>H:=/8)7)7+8,7.606387;;5)6*6*6*5(7):*?,556 7"9)8+4(0&=;>8=5*B/1 TE<0A;C?JITSVVSSOMIEC;<28+6&7&7%7$:'<*>-=,=,:.;/<.=/=.?0B4E7\Og]aYlgpoabfgkoP`^khqem`edgqqzwvsnuJ]MjUm񜡟PcVoEOd=Va?ww]\PB\PB[OAZN@YM?YM?XL>XL>UI;TH:SG9RF8RF8RF8RF8RF8JF=KG>@FCA<71>:[WAB?C=@:=8997=8A:E;9/2(/9(8)8+:,:/8083;7=:3+3,5,4-6-7.:.>/9(<)>->.=/=2>6>7?>?*<(=,^PF<3/.-?BUXvurojg^YPIA75(.8'9&8&:)=,=->,<-<.<.=/<-;->0B3E9MA`Wa[pltr`a]a^dFVYegpgodljpstxvssenCXEbRk뒘N\Ql?Ri?ZhDy|_\PB\PB[OA[OAZN@YM?YM?YM?WK=VJc7U8IAEFAIAIAFCAG;J8JDI>A@?JE?83,D@>?>=@'9&5$5'9,;0:/8-?1;-8'7&:'<)=';&>-:*>2B:.+::142673;7C>JEQISHTHUG?0>.<,<->.@.?/?.=0=.<.<.<,=.A3D6LAbZc]nlrr`c`e`gixozlt`h^fkqw{{|pq^h@W>]Oh懍XaXuE\vIgwPfŻ㾺޺޼[OA[OA[OAZN@ZN@YM?YM?YM?XL>XL>WK=VJPI?QI>SK>UL;XM9YM7YM7XM;WK=ULGYSWc_nmktt|~ȍώԏՍӐӋʂ{u|ovgpckn~eyZvMo?c2V0L6G@CGBLBMCIGCJID<45*I@LFCA>=:;;;?=E=H(9$8$8&:,?1A5B5A6I8B1<*:&<)?*<)9&;*6)0'B<1/>A.2'-3-4.71928.5*2&1#E5A2=.:+9):+:,:,/=.<+=,?/A4SGg^d_kinochjqoxp}t~mwcjdlqzw|sukpXfAY:[Kf}lojXoZx`rū٫ӦѥԩԮֱںZN>ZN>ZN>ZN>YM=YM=YM=YM=XL@E@JBKCHGBL8E;F9E68(:*:*:'8%:&:':&9&:);*9+7+5+3+4-)-)/,3.4071828587;8<9?9A9D6G6H5J)1,2024/7-9*<+=,7&9*2?4>4?6?6N0/-.38384-6.80:1;1;0:.:/L?F:?29*7)7*8*8*<->/?0=/<+<+<,>0KAc[c^kioshnrzveroyr{jslvvu}ioflRbA[6YFat{~zf{fhu˭շˮŨґēș˝ˡΧҮٻǾ[N>ZM=ZM=ZM=ZM=ZM=YLXL>YN<=A=E?GBDHAK=M:OBAGDA583.,)&.*:3C9D6@0:(<)<):';(=(;'8%6"7%8)7*5(3(3)3*03587<38,2&-'-)1,3'0%/'6+=(A:2".&0+10/1,4+5)6*6+90>5>7:4615061L?K/6(3%6)9-5*6-C<7421 89352(3)4)5)5+5*5+7+YNRFH;@4=@ABICMAN>NA<@9?6?3=/=0E8MD61;61.2.C.&/(<7E@:7/,.*41:7?3;.5)3&5*:.;08.bWZOD86,:/9-3)6,1%2&2&4'7':,<.=/:.C;\Wppsvv~yq|{xu}s{r~q}lxisbmI\=\8[:Vek}~i|d}cju|vxqwo|rtwuy§̹־ʻZM1B6?6?8A==;:<:@7=4<16;3:06-2.314364/:572DADA/+2."41?/E5G7C8?9=<9>9A:E>GAH@E@B<4908-:*9(:*?3F9665:7C=OEI<4%9&:'<)=+>,=*:)9)8'2#/#4*=3?6912+7&6&3#/"-"+%,&+(++(+'-(5%8523(5.;4?8C;D+616=8<7=4<2;/:.7*6);/@8TMgeorz~{{zxwsl}ftbn]kG^:Z9\AZ_cgk^eOhOlRtX{\}^x\qX`yO_P`UeYm`ug{jmptvyyz~ǹ˸̴[K;[K;[K;[K;[K;[K;[K;[K;ZJ:ZJ:ZJ:[K;[K;\L<\L<\L<]K=]K=]L<^M=^M;^O<^O<^O<`P@^Q@]P@\NC\NE[NF\OI]PJ`NdcSmfX{g^ohzu|{yxucOyAF@@A=F;J;J;F9B:@?;A:D7>850-&:)8)5(2'/'.',(,*+*(,)1+7';";="A8G(6/;P\`lP\^N>^N?^N?_OB`PC`OEbM\cPdcUodZlevr~wv~‰ЁwkXuFf=MDPJNJHG>GBB>C>G@HCIDDB=?9A5=/:+;*:)9*<.?6FB<;ABAA:8JBXLL>@08(3#8(<-:*7)8+0%3)8/;4:3500++'4,4-2.314345586;/4.60=1C.F*G,L1TP3D2A3>5<89733*/$2*-(61XT\ZXV@AHHB@<7706-8-9+7'3!:%9$;(=-;-6)8.>5NGEA501->9?:8171/011427392:/9.:.6*7-IB_Ynl}v}x~zxsj{dt_nUeF]6V7ZF_TRvaBJoR-H:QCTDK@AA>DAEBEFAF@EBFDEEAC:?4@3;-8(9(:)9(:-;3IE??;>682/A:ZPg[QCA34'6)9+8+6+8,0&5-;4:440/,-+-,4;3;3<2=1>0=0?0@1A2D5K5O0P-Q1X:d7BO\an`nXfQbEX8J@S:G2;/23-9-=+>(9/2(JBkcLGPM<9;9LJ@<7/7-(;%=)?-9)4':1C=HAC?722.;7:62.2-)++,.-3/61:1<1>26)4)B:XRjh|}v}y{xqh{bt^oSeI`9X9[I_QNmZ:Em8ZvCa|InSvY|]bgll{m|o}p~onllqqrronptvtwï̾ŽӫZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8[L9[L9\M:\M:\M:`J<`J<^K<_L=^M;_N<_N<^O<^O<_P;_P;aPH$H0Q;UA6>1?19+7':)=*=,>1>7=:79/3/03294NElaj[QCD>61;7UQF@918-:,9(:&;%B)<&<&=*8(3(=4MFGCEB96307341/+2-)/*/--0/4/7/;1>2:,4(;2NHb^yzz}}xn~dw^p[lN`Ha8W7YH]JGcS1Al6ZtDf~NuZcfjnsttr}p}nmlknpoolknpsrwƱοŷҤZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8ZK8[L9[L9\M:\M:\M:`J<`J<^K<_L=^M=_N<_N<^O<`Q>aR=bQ=bQ=bR;bP:aO9`N8jNMgNRbQ[cWkjfuv}}y{˃{|qsgjTXAG#M.T7W9P>NEMEH?BBDAC@AA?C?B9?4=0?19+8(=,A.B1C7D=6457,002880+5-UKzn^RD7=0<06,6+90708271401/105387=>>>==<=:@$I&N$Q%U0e=sgralXeR_Q`M]?R1B:J4?-0-(5'>&C%E"7&9(WH<0A87/3/C@XSHA916*6&5$6"9#B*<%:%<*7&3'A7SLIEGE:82.411-.)4.'-',)+*)-(1*5,9->13(7.HB\Xwu~xl|`sZlXiHZE^4S3RCXE@\L*?j4Uo?d|Lw\hlptx{xt|mzi}ghhkmmlj}ilostx«ǶȻӞ]K7]K7]K7]K7]K7]K7]K7]K7^L8^L8^L8^L8^L8^L8^L8^L8\J>]K?]M@\L=ZM=ZO=\Q?^SA_T@_R?^Q@aQAcRBdQCdNAcM@pKEjKIfOUgZknlv|}̃{~uml]fRN[DQ>LANCQ>K:G4;/8+:$C0=,6(?5D=;56183716-7)9(=';"774PLXOD98(?.C3;-4+GD.14;4?+9@Q(9&+*-*-"#$()(("+1 )&1.<$5Yn+@`j^iYcT[PTHI@;:1A2F2D.;$57#;)=+8183EC;9234544CAKFKED;:04+4*3+2*?19,.#',"7/C:G=PFE;801*/-01/3.4141201/00.1+4+8-=/2#?0>3`Wtqwe}[wXuSoJgDc7Y9]>[]kC=PI/F`;Xw^N?^N?[N>ZO=\Q?^SA_TB]QA]P@_OB`NBbPFcOFcOFkLGjMOgS\h_rnow~~̢wx|xuhjYZgN\FRHUJVER?J;E9A:>::=:?7>4+?-9(:,A6<47/<7404-4*4(7&:&;%;"52A;MDI>>/8(8);.<2JF/15<6A.68,E4H6?,1)()-':6TRHG5445<=WUGBGAB99/4+6,7/5.?5:15.3+4.83?9E=JBA86/1*0-1103.3141201/00.1+4+8->03$=.=2^Uvsue|[vWtQoIhAa8Z=_F`Q\{?7NH.Ga>Yx=eKsYxawbzf|i}j|i|i|h{e{d}c}cd{l}n}l}i}e}cccfkpu|zdoqR]_]L8]L8]L8]L8]L8]L8]L8]L8]L8]L8]L8]L8]L8]L8]L8]L8^K<_N>aP@`P@]P?[O?[O?[RC[QE[QE\OF\OG_PKcQOfTRhTUiTQiVXi]kmisvz͉ٟ֗ʪ}烅~tve`kS\GQFQHREQ@K=G6=7:99<7@7A4?0=-@-=+;*B4I?;20)926/5.7,7*7(7$:%<'3/4.A9OCH:6%3#@2>5HD134;6@4@ES3A),"&#&03--''%%12(*7:+1)13?R^=KYiafV\OTMREI:;74?96,?2C5>18-3),%' % 0*FC::,,44AB^]>:C;A9=39/=4@8@9A>=;>=A??>;9?=IDA;=45,2+2-3112/2040201/0/.0+4+8-?14%9*;0[Rzw~rcyZtTqMmFg=_:^BbQg?Fn<1OK2KcA[z?hLrZu^t_wc{gzgyfyfycxbyb{a|b}byj{j{h{e{az^|^`hnstwvypngVb`COM4@>^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^L6`N:aP<`Q>]P?ZN>YPAXPEXOH[RM_UTcWYeX_iYcl\fm]hlbclemolrtx~τߊ狇ޝ٬ɳy{߁yvnrbgU\LUFPBM>G;D5;7:97=7A6B4B1?.;,=/>0G:RGH?6.1)9181;0<0;-6%6&9'402-=4OCK=;,8*B67.>:/0164<8BNZKW>C38$&/1,,22+*0.::37-29BENYcLY?AADCF>C9=8988:58391:2A:NHVSNNAB82:5KGNLQRYZRQYX51>6C9@7?5A9CC:?58=?LJ93704+3,5.302101040201.0/.0+3+8-@26'6'9.WM}y{ocwXqNmFh?c8\=`IdYh25d<0SQ8TgG`}EjPsYt\u^wbyeyfwdvawav`x`z`{a|byhzg|fzbz_z]|]~_emrsustii_RaZDSL8G@^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;^M;_K2_M5aO9_P;\O>ZN@XPEXQKYQO^X\g`hnfsshysg{sg}tfnnzorrwv|y~׃刋쒍뛌ߞƞtkmqvj{illklfi]`QWEM;B5=596898>7A7C5C0A-8+@3;.;1RH]SNC;2907,9/>1=16*4'7(2-60=5E9F9C3A2?20&620/-1-47?OYZd[_OS.103--EE66,,-.>@2537ch=C*2-4();=AE7:378;89..43<9HESS`chndk[eB7Eb8_4\@aMcWap/+\A0XX>]lMbIlSt\u_v_xcyexbu`u`u_v_w_z`{a|byd{f|dz`y^yZ{Z}\_gmpst{nrffvi[k^RbU_N<_N<_N<_N<_N<_N<_N<_N<_N<_N<_N<_N<_N<_N<_N<_N<`L1aM2`N6^O:[N>YOE[RMZTT_Zahbprmzu{tyrzpyoovpyt}wz~Ճዋ唏㗊ҙ~yl[X>H?PIVRVURRJM=C387<9;;9=8A8C4B0@-9.A65+.$J?h\eZVI=26)4):0;05,3)6+/+61;2:/?0F7C39+1&3-31-.*.17EJS[_d\a9<9<+.JK89//55()(+YZ?B9=7: %))=>BE49,217/5(,37KNaehncl_k_m_nNIOJ]ZVTMMGH3231AcWh[fYPB?25)7,:05,2+6.0,4/7/8.>1C4?04'4*1)2/..-.1468?COTY^FKRW47FJ889;>=A6<-4)219/>)7-:9CAHAB1/4-5,5,4-3,5/50.4.2.1-0../+3+7-:.>02$7,<3tqrj}bt]pRjBb6`5a8_KfN[z;6Y?.LH/TZ@]cIbzJjTr[v^yc{dxas\pYpYqZqZt\u]y_z`x_y^z^y\xWvUwV{X~]dhlormxgrlk}ecu]_O?_O?_O?_O?_O?_O?_O?_O?^N>^N>^N>^N>^N>^N>^N>^N>eQ6cR8aP<]P@ZPG\TR_Zab^otryx~~yxwvxwt}w}Ƃƅȸп¡ϼDzkS\FG5=0H=VQVTNO?A=?<<<;=:=5;18.82<5:3>5PDYM]PgXdWM@:-8.913-2,50402-5-<3C7C4:-3%5*-&0+.,2144.,00EIY]W\puDJHN=C[aou>C~mqQT>@02<>EI9>7==F6@-8>J\hmwitdl]g^kap]nWh_YOKJG740.54/.95D?JDJA@86/5-7194$0/<1=*6/:>E>C443.5.6-5,3*3,4/5/.4.2.1-0...+2+6-9-@21$6,7/pokcx]pZnPiAd7a8d=bPiQW^2'RG3DH/PV`P@`P@_O?_O?_O?aQAbRB_O?]M=]M=aQAcSCbRB`P@eS;aP<_O?^QH[QOZSZeapsqxxz|~}xyrsnoqwv{̋ȖäŲͭЩУѠѡ̚Ɣզg_FzgteG?QMbaIL>A799;997561949550B;=5I?XKPAeVdVYKG;:/6-6/5/3//-2,70=4<08)5(8*/$/(.)0-204051408X`~~owgoipfj\_Y[^`RYCK8B7A1>+9/>=IS_`kgpepbobp`o[lTOFA853110/.2186D=B:?7<4908183845=4;3;4<5;49331/3,6-7.5+3+2,1,2./503/2.1///,3,7.@49,7+/&<5XW~he|]rRhHeAe9b5`JlRd==K. >>&?I.IO5]]EWlAcxMqZxby`t\rXqWlSmRnSoVrXt\u]u]tVtWvXwWvUvUuTtS{[{\z\uZnUc}MXrCSj>AW1?U/`P@`P@`P@_O?`P@aQAbRB`P@_O?`P@bRBcSCbRB`P@fVF_QD\OF_TRcZ_f`nmkwvwy{}}x|qtlolnoqsu|}ىԘШƹƵϩףܞߞޝܞ٠ҜʖѼ~dċw}mVJ`YqnZZJL>@<>>@:;5634=:73?86.>3L@I;^Op`aSH<5)0&5-4-/)4395<7<38.5)5(5*6.4-1+0+0,2,4.5.9;>AIMW[\d\d]e`kR]MXQ[_gjqfl[`RU07+5+5-9&5/'67DP\[dclemepdo[hP^FB<9646353202/62>9>7<2:1918295969;7:7:797957313,4,7-7.6,2+1*0,1.0503/2.1///,3,6.=2>28-2*82Z[w{a{^vWqOkFf=b:c=cLhJVw<8F5#7=#9C(DH/UP`rJnXw_v]tZpVnTkOkPlQmRoVrZs[s[tVuWuWuUtTrQqPqQnPlNhLbFXu?Nh8F]/@W+@W-@W-AX.YL<[N>^QA^QA^QA^QA_RB`SCaTD`SC_RB`SCaTDaTD`SC^QAbUM^QK[QPcYakesqmvuy{y{y~w}nseibfjnrv}zᇃᖔߩټظۤϠĘkpp`RG]Umius^_HL@D@D=@7:36>;;6A:707.?3=/G8j\j[\MB62(4+6-1*44A>GC=62)1'2'0%3*1).)/)2,7/=4A7-,43CEVX^bYaS]P[FQHSNY\fmvmtY_AG*2,41<1>*9&66EJXISOYW__fdkaiQ[BJ956375<8<9855160:3;290908183:6:8;9:999988884403+6,8-8,6,3)/)/,0.151302.1//0,3,6.9/D99/4.0,`bnu_zWsPmLlDf8_9_GfReDJi=4K@,7@%8@(ED/LE2N^9YkEg|Qr[tZqUmRkMiKhKiLkPmToUpXqZuWuWtUrTpRmMkKjLdGaE\~AUt;Li3E_/AX*>U'B\/E_2Ic6WJ:ZM=\O?^QA]P@^QA_RBaTD`SC`SC`SCaTDaTD`SC_RB]P@YNR[PVbXcjcsqmvuxzz|w|symrbi]caglrv|ȋ攑褡淴޿ܨҧßvqsecWi`rmut[[KNCG?D;?8=:8;8D?C;:0;/7)2#J;bRk]SG9.3)5+4+33ML[XKF803*4+2(-&,%,%,'0)6-<0?20(4,:6CBFHEKGPLVQ]VbXd[ggpmuY_=C.2-4-4*4%2(6@?<;857292:1908071738687<9;9:7;8:8845.4+7,8-8,7*3)/)/)/+252312/1//0,3,6.8.G<903.-*fjyjr`{TqKkFj=c3[<^PhXeDBbE7WP=DH1@D-JH3JB/IW4Sc?btLmUpXoRkNiKgIgIhKjMkPmToWpYtVsUqSnQjLgIeHdG`D]AWy=Rq8Mi6Lf6Ne7Pe:Lf6Oi9Sm=UH8WJ:[N>\O?]P@]P@_RBaTD_RB`SCaTDaTD`SC_RB_RB_RBTLY`Xgnf{tpxtxwxzy{syjq`g\b`fkqv|~Ε䞞譭齼߳سѴůy}qwkskngoi扄~sredVYLNCE>A95:7B=E?<3=3B51%1"I;YKN@=/8*6*3'34UUkh]XE>;3;2804-1,1+0)/'0$/$0#9,4'3):5CAEGBG@HDOOZVaVa^igoYaDI885526183;9CHSVa6?4;7;AFKOIM;@056195;8;9;9:77370;2;1;2:282736465<8;8;8:9;7956/4,8-9,9-7*3)0'/)0+453322010/1,3,6.7.D:7/1-21jprzhr]vPmCf_L;_ZFQP;KI4PI6MB0DR1M[8[kFf|NmSmPlMhHfGgHgIiLjOlSnVoXtVqUnPjLfIcFaF_DZ@X|?St;Pn8Pj:Tk=XmB[pEUp=Vq>Wr?RE5UH8XK;ZM=[N>\O?^QA`SC`SCaTDaTDaTD`SC`SCbUEdWG]Ulje|yu}yzywyvxswlqcj[c]ehpw}ǁІՙܡ௲廿Źxzuwvqulg~mfoib[a[smzu{|yrpccSTHHB=>:<6A;:1D:TJ>26):,=.?/A3C5?18*23LM_]XSD?;48170929292929/9.9+8))3"@2I>E>;:7;9@8AHTUaYb^g`iU[CI?:?;AAGJMRQYT]V^4:/5037:=A:?48/2619595411/20404.<4=4=3;293734333:898888987754/4+7-9,9-7*2(0&0(0*454332111/1,3,5.90<3700-AAnukucoSkIf;c1`3bRJ7QF4MB0AL.GU4Sc>`rHgMjMjKhGeFfGfHgJiNkRlUmVqSoQjNgKcH`E_F_G\E[~DWxAVr?Uo?YpB]rG_tKYtAYtAXs@NB2QE5UI9WK;XL\P@^RBaUEbVFbVFaUE_SCaUEfZJj^Nkgup|x{ywxvwptjoah^f_gempx~͉؏ܙϠ֪۴ߺ߾̼ƻŴqqstpqogevhenj`Ye_[Tg`tn{v{wwshf[ZQKGB=6C=;4G=\R;0<07+6(>.D3C2A1A08:>@DCC@=8917/7/:393:3;3>5A5E6G8.;%K8L==30+108>BJKVU`Ze]eYaLR?D4+8/<7@@DFEJBI?F5;26368<7914-2.44095640.,*/,2.2-=5=4>4<3:58565555757575656422.1*7.:-:+8*3(1&1(1*555342111/1,3,5.;24+;420UVpxcn[gKbEf7b+]1b@hKeRYd8/ZI7SN:UN;[P>VI8M@0MA1=H*CN.K[6Xj@ayGfHhIgFeDcBcEeHgLhOiRjTnPlNhLdJbH_F_H`H_H_H]~I]yH]wH`wKcxOdyP[vA[vAZu@MA1PD4SG7VJ:WK;YM=[O?]QAcWGdXHdXHbVFaUEcWGj^NpdTvqyuxvtsrrsulpbgZa^femltu}ƁЍڕ⚤ȟͦԬٰ۱ڲڵ۳ֲѮ˫Φ{|ydbgidhbY\g[[xeauXRe]OHVOaYjcvp}zwuljZUPJD>MGB9F>WO,"2'5'=0E6>-2!8%F4DF9;3262;6<7<6<6;4825.4+5+8+<.>/U;I/=';+=2;56537KRLVOYS]WaU\LSCG5)8-816455584:288<6;9=853cepy\hR_HaGh:e*]/a@hE]AFQ-!UJ8PN9OH5\O>YH8L<-NB2:D)?J*GU2Rd:]sBcEfGeDcBa@aCcFeJfMgPhRlPkOfLcIaG_H_H`I\G]H]~I`|Ka{Ld{Of{Rg|S]xC^yD_zEAC8CE:IF=OH@RGAWI@]M>`O=aQ:aS9`T>_VGaZTfaeljwrowozt~wzurohfa`^^bahgqo|xυڏ㗐흖٣ڥܦݧݦۥڦ٥֣ҢС͞ɗymrvghlc_`e[ZlYUtUPULVKRGZNZP\Smd|t~xyyyabPQEEYV611(5(7&6%8%9':+<.?18+=/?1;-5'4&:.?590907.7+7);)@+C,;3?7DC;<42*,$>5G>QHXO[RYPPGE<)<*6.648;;94:5<4;5:593736225445464717.6,6)9*:(:&9&8%8%7#7#414/4.3.4,5)6(8*:.7/96>BlyasRlGdIj5Y5];e=cPjLVT)":1 9<)EF4RL>PH;BC39E15K4FGHJ#MQ,U\:\jGcuOf}QeNcHbBa>c@eDjIlNmQjIiFgFfFfHfIcIcGdJdIc~Gc~GdFfFe~Dc|BX}8[;^>[K>^M;`O;`Q:^S?^WGa\Vhcinlyrqtnvptppmgfaa]^\\edkjtr}{φَ蘒웗Ҝӝ֞ם֝՜ҝўќ͜ʛǙēwtmtkdkf]`e[YiZSoWMzVJVIUK\RYRXRf_qjvowuufdTSYU2+/%7)7&7%8%9&:*;-=/8,9,:,:,9+9+8+8,;1908.8,8*:(;&;%4-80=5@8A9?7<4915->6H@OGQINFC;7/89"8)4,./*3(7(:+B*B)A&A$@ >=<89$;);-9297;;;94:5;6;5:593736225365464717.5,6)9*:(:&9&9%8%7#7#4-3-4,4*4*5(6)7*c@eDiHkMlPlIjGhGfFfHfIdJdHeKdIcHdHeGeGfEd}C\<_?bB69.:<1??7E@:KB=OE/>/6(/":.7-7,8,9+:)9&8#4*6,8.:0=3@6A7B8;1@6E;FG=@68.6!7&7,3/03,5*9*<'='=%=#;!:87766#8*;1<6=9;;:86:5;6;5:585736226475565616/5,5(9)9)9'8%8%7$7$7$4+4)4*5(6(7&7'8)=12+98lt]nPi=[Jl5\=e4[<`Tq?Oa#(H1+79+-8'18&:;)B=*A<(@>)@B*?GY`4s~Tfwbi~Ub|MaI`C`?a>c@hEjJkMlPnKkHhGgGgIhKfKfJeKeJcHeGfHfGeFcDbBeEhH06*58-;<4A>9G@:KB;RE.?.8(/!6)5)4(6)9+<+=*;(9/9/9/9/:0;1<2=3E;E;B8=3=3A7A7=34#6)5.31/5+6(7)<&9&;&;'<&<%<$:#:!7"7%7-95>:?9:8786:5;6;59585655427376665726/5,5(8*8(9&8&7$7$6#6#6'7(8'9(9(:(:':+;/3.IKo{VjDa=_Ci/[7`=cLlOe0=G >3--3'+8'2=,=B.B@+C;$G="MA'R_*q}Mp|mjW_{J]~E_Ca@b?fCkHlLmQmSoLlIiHhHhJiLhMiMfLdJdGeHfHhIfEeDfFiIlL-3'17-7:3<;6B=9G?UOCZUQa_dhgukklljgbaXVPPQQXY`cfjorux|Ѓֆ׉؊׌،̋ˊ͉ЉшъӉЌϋȍ}xvpScQ\qUT`^RVcOTbH_]DvUBLBRRPWPY\dejljwqvlph~v{~ka?28(;(='='=';':'8(8)8/7.8,9+;+;*:)7(9+7+8,7+7*8*<,>-=0<0<0;/:.8,7+5*@5@5=28.8.;1:06,.$0)2.23/8-9+;+>-?.?0@/@/A.?-?->)9)8*70:6=9=775386:5;6:79585655438485676746/6,5*9*9*9(9&9&8&7$7$9%:&<'=(=(=(>*=.8-;8^eaqPi;\Ai6a/].WIjYq>NX'-?+,730*1)-9-5@/:B+<<"B;VG(iV6vPlwo[aK^F`BcBeBjGoLpPoSoUoLlKiHgGiJiLiNhNfJeIdHfIgIhHgGfFgIiKlN*2%.4*470894<;7B=:HA;KD(>(=(;(;)9)8*3+6-:.:,:)9';)=,>.@2A4=17*4&8)<,:,:,;-;-;-9+6)5(6*;/>2>3?4>37,.#)%-*02290;/>/?0A0@1@2@0=/:-9,8*7/&?'A(A*@,=.71IKgrOdHf7]Am/_1^1XOjWfh39@*,?994443524925>-2<#29ECl`8}RuΗȕ}vbeQ_F`Bc@gDoJrOrRqUpVoLlKhGfFhIiLiNiOgKfJeIfIhIjJiGgEhJkMnP(0#*2'/4-350664<87@<9C>8IE3>0>0@/?.$?%A(@*>-;1:6U\_oGc>b8c6g0c4\CbMaBIL44:97<<>948>58<7379+3="8DS[,PoȈˎ̒Í}{ggQ^E^@c@iDoJsPsSqUoUnMkJgGeEgHhKiNiNfLdIdIgHiJjIiFhEiKlNoQ&.!(0%-2+130333756:97>;6GD=DD*<'8$5#B2OAN@B47)7)>/;+:*8(6'6'6(8*8+;.;/9-5*7,;1<29/7:8=:A8B4A.>,;,:/;19385857483645496;9<69453386;986979899896967465:5:7:7985827/7+8+9+:*;*:*:*:(9(: : =$?%@(@+=.81hCoJrOrRpTnToMkIgFeFfGhKiNiNfKeJdGeHgHhGhGfDjLmOpR(0!'/"(-&+-*.0/333775:94==5?@8DE?JLKQQYVWiZ\s]^|YW[Y^]eennwxڄ䊌솇䂂܀ԂӃҀāǃɄΆ҈Ջ֌ҊNJ~xwpxkeec^XpZMm[Mi\Kf^Kd_IcaHfbGl`FlR;UA^OaYYXPTQ[XbkcYRD<707/;//@/@-=*9'9)0"VJJ?.#=12<07,7->4E;AF8?3:4?2>-;,:2=7@5;687899:98665==<<:<8977767575979899::9;9<9<8<6;5:7:9::9;5907,7+9):):):):);*;)9!>%;#5:$E3@60.^eVgHc;\0X/[5cc?iDnImLlNkQjRjHfDcBcDfGhKgLdJgMhNgKfHeEfEjImJpSrUtW*0")/#).'+-(-/.222553782;<4>@5BC;HJGOPTSUaXYm[[s\Z^]dakjus}Їዋ퍌텄 ڀ~ҀσυƆȇˉ΋ьЍΎɊ{x{stknkd^e\SbaLb`Ke^Kh]Ii\Ij^Hk_Gm_EraG{]C[F[LWPQSPXS`WQKF>9505/908,8*8&8&8&8)7)5,3,2,1'4)9+=-A/@-=*9(9)<.QEH<4(:-:,5&=+=+;*;*:)8)7)6(7*8,7,3)1'1(7.=4BH7>07/:0;.;1<6?6<3632:8EBJFEA?<:9:89796858598988788999:9;9<8=7<5:596888:8:5917-8*:*:*;*;*<+<+<+9"?);$5;'>];2@>/3A05?4E=:X;?T-0X51ZI7bjEu[p||}yr`YuESq?\{B_>b>iCmFlKkMhMhQhFeDcBcDgHiLhNgMiOiMiKgGgGfGjImLnQoRrU-1"-1#,/&,.).0-11/34/45-9;0<>1@B5EH?KMLQRWUTbXWi\Yx^]fcpmzxύᐏ퐎釃~|}ȁ}DžĈƊʌˌˌnj|v{pujpod`i_Ue\MXeK]bKa_Jh[HmZIp[Hq\Go]EtcItZ?V=WDYMTSNTIU@<<984616/6.6+7(6&8&8&8'6)5,3,1,5(6(9)<+@-@-=+8(5'J=E:A57@=C7;AANKZUZURLB>62727474748596;8::7788898;9<8<7<7<38475777:7:48/7,8+:+;+<+<+<+<+<+9$@*9$7$;+2%40OTZiH`8U6V>]FfHfEat?9e?6QA2@C04?.29)>5,O61K*#W:,j\B_t{yv|m\uKHa7Nh9[xB_}?c?hBlEjGhJgLeMeCdCcBeFhIjNkOjNkOkOiMhJgHiHlIpMsVtWvY25$13&02'01+12-23.34.46+9;-;>-?B1DF9IJBNNNRQWTR]XVd\Zoda~nlzwČؑ唑쓏펋扅ڂ{}}Ë}{vzm~sfmoa`k^Vi[NgZJVdJZbJa_JjZJpYIsYJtZIs]FqY?tU9T;ZF\PRNEG:A3/4151505.4+6)8)7$8$8&9'6)5*3,2,8+7)7(:*=->/;-8+3)TK;38.A64'<->-7&8'9(:)8)7)6(3'5*3)2)4,:3>7?9>847596;5;2:397=<@UVc`njidVQA<613/71717182859697::78898;9<8<8<8<8<48686787;7<49/8.9,;,;+<+<+<+;*;*:'@,8&9';-+"54_gSdE];U1B2SE*okHfttqt}l\K_:BV1Lc7Yq?_{@d@iAkDiFgIdJbLcBcBdCgHjMkOmQnRjPjNjLiJgGiGmKqMuYvZx\78(78*66,56056156167/68+;>-=@+@C.DG4IK=NNFQPNSQTVUSYY[a_lkius}Ȍ֕㔐䐍ދӄƁ}|{~zxsznzrfjm_\j[Tk[NjZKjYI^bK_aKe^Kk[KpZLtZKw\Kz[G{WAS=U?XFSFF?76012-3/5/4.2*2'5(9(7$9$:$:'8)7*5,3,>-:)6%8';+=.;.6,80\T=54+A53$:(@-9):*:+:,;-:-8-7-3*1)1+71;7>:;77477;<7=7=69797:::=:=7;2;/9*;*<*<)=)<(<(<(:(=*9':*9-0)AAgrL^E[BYF[N^T]VWSQSU@LN9JG4JE1FD-AA'>C#@G%MU.^g,?=.==1==5=<7;<6;=2;=/?B-@D+CG,GI1KM8NOASPITQLYXDZ[M_^Zgepqo{yƏӏՍъǃ~zzw{uzw|y|~~y|tzrvkqrffm`Zl[QlZNl[KmZKmZIg^Mi]Mi]Mj]Mn]Ms^My^M[I`OWGN@I=@56.0)0*515/4/4-2)3'6&;(9$;$<$<':)9*7,5,A.;(6#5#:)=.;/6->7ZTHA90@36&4 >)7'7'7'7(7)7*7,8-<3:293<7>:=9854196<9::8:>@ORccqpheUP=82+5.;7<::9<3:2:4837365556869697;8<8>7=7=6<8:8;8:;:>:>7<2+>467>O#Jh4gTt\cdfltxpn}\Q`C=J09F,BO3O_;Xi=czDgBkDkDhFeF`G`GfCiFjKlMlOkOmQlRmQmQmPlLkJmJrOuQy]y]x\CB0DB3DB6EB9CC;CC;BB8AD3CG0EH-GJ-JM0OO7RQ?TREURI[\:\\@\]Kaa_ihvrq{z~È{ystpqmolrntqwrwrtoskxrilmb^l_Vj\OlZLn[Lo\Kq\Kq\KrZNq[Nn\Nl_Ol`PqaQy_N[K_SOEA8:25-1(1(5*706/4-3*4(5(6%9#;"<$>$>'<';*9,8,D/<(5!4!9(<.9/5-83NISMB9B5@.2?(;,9+8*6)7+9.;1;3D=A;=;;:8877939584;:JJ\[dcca=9824.81B=E@=;42;3;3928484667777696;6;8<8>7=7=6<686989;9>9>6<1<.8););(;';&;%:'9&?-7%=,:)3'QKkm\fN^I\HWJUSS]RfQjP=Sg{FhClEkDiGcFaG^GiFlImNnOlOjNkOkQpTpSpRoPoNqNvRwUz^z^y]GD3HE6HF9HE613/5/5+7*8)6/4-3,4*6*7'7%7 <">">$?'>'<*:,9,E/='33 8';.9/5./*?;YTI@D7I75D,F7D5A3?2?3B7F9;77464657799>7:473<:IHML=;(%-(5/@9C=A;=8>;?>:2:292849596999:7:6;7<8<8>7=6<7<595878:8<7<4<0:-8(:(;';&:':&:&9%?,4">,:*1&\Xy|T_TbI[DRGOSPbSlS{rSC[C?H3B7%O6"_K0prJiǀyt{qu]oHy}JXy|O\d5:D)3=$4>&WN?XO@YPAZQB\SD]TE]TEcZKbYJbXNcXRg\Zmacsfmwjs|n{~p}ss~p}wjtobli\fcb]a`[a^W_\U_[R^ZOa[ObZMe\Kg\Ji\Ii]Gk\El]Fm]Dm]D_gOkiTqZH{M@RIWLTIWHN:G2?*;(:.7223,17.7.7.8.8.7-6+6+7+7+7+7+8+8+8+8+=.=.8(2!2!;*>/:,6+6-:2B8I>G9;,1!OGIAE=E;H?G@C><:54678:9:7772:3>5KAE;=07)5&8)>.A2;/<2>5=8;97967687>7>7<8:9997:5:35.6/818497989:9:;>9;99<,<*;(:'9&8%F2>//%-(IKkolqWZOPTQVOYP[P]R^V`XMb!:O3JOf xIhrtpakN\lEWdHS\GHN@=C9;<,AB4=?2:=2,:)9,7042226-7.8.8.7-8-7,7+7+7+7+8+8+8+8+9+>/=.9(2 3 :)=.;,:-4*3+;0E:PBRCQAE@@;<6;5>7=89633696879687797=9?:C9?2:,6'5&8)=-@1A4A4@7=8976756686<6<7:89879795:392:3:3;6:8:899999;:=<=?=@;?6<2;-;+<,=+<);(:&8&7%z;)8)5*;5QPce]aMMNLSOYP\R^S^U_V^VSg*Sg(^r3zOlzn`jFau@Sf9IY5FP7?H59?358/;<,AB4=?2:=2;A5:C2@M3Rc?]uCgHqLpJmHkJkLhKmTnToSmQkLjHlHmHpJnJpLsOuTxXxXxZm\bQYH]TE]TE]TE]TE]TE]TE]TE]TE[RC\SD]TE^UF_VG`WHaXIaXIe]He]Jd[Jd[Le[Qf[Uh]Yh\\i]]j^`k_ak__i]]f[YbWU`USYVMWTKTQHRNCQMBSOCWQCXRB^WG^WEaYFc[Fg\Hi^Hk`Jk`J^cOmhUy_PXN[TVQHEE>@7>3<-9*8+9.:/;17-7-7-8.8-7,8,7+7+7+7+8+8+8+9+9+@1>.9(2 3:&=,=.?07+2(3(<0F9M?QB87432052:7>;=<;<8<5:27245697<8=8;-9+6'4%5%8(<+=.D7C6B8=7966455675:6:69797795:3:3:3;4<6<6;8:999889:;<@>A=>7:17+7(;,=+=*<(;(9&8%7$u8%y6%9,E=ROVTOOHHLHSLZO^SbUaW_V]UgxB{UnzzYYp:?R$AS)AQ-?L0:C.6<.690581:;+@A3=?29<1;A59B1@M3Qb>_wEiJsNrLoJmLmNkNpVqUoSnPlKkIlHmIpJpJpLuSxXy[uWqU_NVEOx>aXIaXIaXIaXIaXIaXIaXIaXI_VG`WH`WHaXIbYJcZKd[Ld[Le]Ff^Gf^Ig_Lg^Of\Pf\Rf\Sh]Wh]Wh^Uh^Ug]Se[QdZNdZN]YNZVKVRFRNBPL@PM>RO@UO?WQAYTA[VC^WDaZGd]Jf`JgaKadSleUt]O[Qb\YXDD9:;8:6808-8):*@.C17*7*8+8+8+8*8*8)8)8)8)8)8)9)9)9)A2>.9'4 28"=)@.>/9+6*4*7+;.02614023488;<=?;?6<38/505477764307(6'6&7&7&9':):*A3A4A7?8:78576676:6:68768694:4;492:2:4;7:8989789<:@3B%:F.=F3;A3:=2;<4<=79:*?@2<>19<1:@49B1?L2Pa=`xFjKtOsMqLoNoPmPpTqUpRoPmLlJnJoKqMrNtSyX|]w[mSdJ[LS|DNw?cZKcZKcZKcZKcZKcZKcZKcZKcZKcZKd[Ld[Le\Mf]Nf]Nf]Nf_Eg`Fh`IiaLiaNi`Oh_Ng^OjaRi`Qi`Qh_Nh`Mh`Mh`KiaLb_P^[LYVGTQBPM>NKTQ>VS@YVC\YF^[H^]I`aSf^QmWJ[Rhcb`LM@C:<7974709+>)D+H-7)7)8*9+9+9*9*8)8)8)8)9)9)9)9)9)A2>.:(7"57 >&B-<*;*:,8-8.:.<0>25<3:2736464646155:39385:8:662/,(9(:(:(:(:(:(9&7&:+<-?3?7=8:68687566666748493:3;3:2;2=5=9=:><=;==A6:;3::29:*>?1;=08;09?38A0>K1Pa=ayGkLuPtNrMqPqRoRrSrSrQpOmKmIpLrOtQvSxY{^z_qVdJY?]NVGQzBe\Me\Me\Me\Me\Me\Me\Me\Me\Mf]Nf]Nf]Ng^Og^Oh_Ph_Pg`Fh`IiaJjbMjbMjbOjbOjbOjbOiaNh`Kh`Ih`IhaGibHjcGe`Mb]J^XHXRBSM=MJ9KH7IH6KJ8LK9LM;NO=PQ?QTASVESVEYYM]WKcQEzXNhaeaUUOR=C8>6762:.@+E*I*7(7(8)9*9*9*9*8)8)9)9)9)9)9)9):)@4=/<+:$76<#B*C.@/;,7*2(4+:2@81<2<5=8>:>;>:=9<485:8<;>;<861--'<+=,>*>*=)<(:'8%6%7);.=3<5;7;8;77575758494;4;4=4>5?7A:A;A>A?????B:@8<38-5(5'8(<*;*<)<(:&9'7%6$5#y<)r3!}:*OAYLRGOEVJZN[M[M[O\Q^T`Ya[s}Xy`r|ZU`B9F,/;'0;+1;03=44;35<4:?8?B9?A6<<277+89)>?1:27@/=J0O`HO?HO?PPDVRGYOChREYMULRLXWGJ:A?CBCAC@A>?1256::<;;7734.3+>+>+>+?,>+>(<';'7$7'8+8.8.92<7?;85858494:4;4=4>4A7C9C3:/8+6(7'8):);(=)=*<):'9&7&6%~5$v4$x5%B2UEXKQCPDZLZM[N]O\Q\R\U[V\W`hCX_=JS4>G,6?*2=-4>35?74=88>:=B/;9*78(=>0:26?.=J0N_;`xFkLuPuOsNrQrSpSqMrNqMpLoKrNuRyX`~az]qUfL_G[E\HbRYISzCh_Ph_Ph_Ph_Ph_Ph_Ph_Ph_Pg^Oh_Ph_Ph_Ph_Ph_Pi`Qi`QmcWlbVjaRi`Qh_Pg^Og^Mh_NiaNiaLiaLiaJh`IhaGhaGhaGh`Kg_Je_Ib[H\WCUR?PM:ML:EF4DG6DH7BI9BI9BJ;BJ;BJ;JJ@QQERPAUNYSQOCE8:55:3>/>)<$8'8'9(;*;*;*;*;*:):):):):):):):)=2:.<,>+9#59@':$<)?0;18.7/<5A;;B>FBGCE@?;7501.0,51:5<6:29.9,9,>+>+?,@-@-A+>*=*<(:(7(5)4*80?8D>:5:5;4;4<4=4?4@5C9D:C;A9?:;685739-7*5'6':)<*:)9&=*=+=*<)~:'|7'{6&{6&y1#8*G8REPBK?SE_SXKZN\R]T\V[VYTXSV^7EM(6@8A&>G27@E>GJ?GI;BC1?>);;#78(=>09;.69.8>26?.E5>F7?G8=H8AE4HK6YS;_F0K9j]f`SSDE@@?==5=0>/3$5&6'7(7(8);,=.<-<-<-<-;,;,;,;,3,7.;-;)8"78:"B-<+7)4*6/<7C?HCBGDHCC:661808.5+:/9.8.8-9,:+<+>-=*=*>+?,@-A.B-@-<*:(7(6)6+8-;1=4:4<6?6@7A7A6@4@5G=E;A6;26.3-1,1+;-:,:+:*:);)<+=+~:'|9(|9({:({:(z9'x6&w4$z, A4NCMAL>REVHRG\R\RUMTLZUXSWR`^R[0IQ(AK&BK,>H/7@-2=-4>34;3HPEX^RW[LLO?1;=0:=29?34=,;H.Pa=bzHlMuPsMqLpOrSqTpJqKrLrNsPvU{\bfx^iO_G]G`JfOhRdU[LTyEi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qj^^j_]j_]j_[j_Yj`Wj`Vj`Vj`TjaRjaRjaRjaRjaRjaRjaRj_Kh`Kg_Jg_Jd]J^YEUR?ONE5?E7>F7>F7=E6BF8>E5=F1DN5HK0PB'yS>@=>982:+<-=.<.;-:,9+9+:,:,:,:,:,:,:,:,?9A:A7=/6#2235#7(;0A8E?IDJFJGBCEDC@;59/>1A1?.@1@0>0?/?-?.A.B.;*;*<+=,?+?+?,>+@.=-:,9*8+8-:0:190;2>5A7C7D7D9E8B6A4=1:08-5.5,5.=,=,;,;+:*;*<,=,~;*|;)y:)y:)x9(w8'u6't5&1)C9NCK?J>PDTIRGSJWQUOUR\XWTSO\XT]0Zc8_j@[eBIT66C)4@*0:-;H.Pa=c{IlMuPtNqLqPrSqTqKpLpJqMtQxW|_c{aoUcJ]FaJeNeNcLdU[LTyEi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qi`Qj^`j^`j^^j_]j_[j_Yj`Wj`Vj`Vj`Tj`Tj`Tj`Tj`Vj`Vj`VlaMk`LiaLiaNf_La\I[VCTQ@ML:HI9DG6AE6AE6?E7>D6=C5=F57@-?H3EM5AA%QA']Eu`WHbZebRSEFFHBD799+:,:,:,:,8+6)6)8+7+7+7+7+8,8,7,3/5/5-3(0"01 4$A2C7G?KFLGJFFBC?CCDA@:;1=/C1F4G3E3E2C2B0B0B/{B.xD.8*9+:);*<+<+=,<*?.=-;+9*8+9-:/;/7.90;0>3?3@4@3A4:,:,9+7+7+7,8.91=-<,<+;,:+;+<+<,};+z;*z;,w9*v8)u7(t6's5&91FMKB3;I27C-EJ3IG0K<%mN9dO`NA5SLc_^^RUJMDH>C;/9-7+7+9-:/;0;0>4>4>4>4?5?5?5?5?=B>D>F=GN@PDSJOGLGIEFCC?A=@.D2H3J6G4F3D3C1B0zA.wC.uB/8+9+9+:,:,;-;+;+:+:)8)8*9,<-=/>09/8.9/:.:.:,9+8*7)7*7(6*7+8-9/;0=.<-;,9*:+~9*}:*};-|:,z;,y;,w9,s8*q6(q7)q7)B8G=K?HB'=A&;>#78(:;-79,9<1;A57@/MKH/JH1Q?+e>-ZL`S>64+@9XUigdeRUINKQJ@F<@6>4@6D:G=G>JAJAJBJBKCJCKDKDRTSTTPSMSLSLTNUNLHHFEBB@B@B@EBEBJHD@>7>2A2C1F3I6F3D3C3@0@1}?0y@/x@19.9.:.:.;/;-;-;-9*9*9+9,:+;-<.=/;/:/9-:.9,8*8*8*8)8)8(8)9*:,:-;-;-:,9+~9*}8)}7+|8+{9+z8*y9-x:-t9+q5*o5)q7+r:-G;HJY.AR&IZ0Wi?dvLj|TXjDL\8?M,:D)C-=@-:=*89):;-68+8;0H-NC-b=-D:VPMJ++:9=;TPpnwvehY^]cVOOHG@CA=JIB@<6>3@3A2B0D3A2@2>1=1<2<1=1}=1:3;3;1;1<1<1=/=/=/.9)9*:*;+;,;+;,;+:,9+7)~6*{5){5)z6)z6+x6*x8,w9.s7,o5)o5)r:-u=0L>K>JG*SA+{E9NLEH5<19@E?@JIb`rpopbeZ^RJLDD=B;D=E>CC?C?D@EAEA?D@DDFFHIHJIIIFHACADAEACAA@>>:=8EG=<73;4@4?1>0A1=/<0;1928193:4;4:4:4<3<3<3}=3}=3|<0{=0{=0{=.{<-z;,y:+z8*z8*:0:.:-:.:.;.<.=-9):):*;*;+;,<+}<*8,8,~6*}5)|4(z4(z4*y5*u3'v6,v8-r6+n4(n5*s:/v@4PBN?N=R@VFXIUJRINIRPSO\VfZl\LML7BL3@O.KZ9WgC`rJezOdzLVl=G]/AV+7I#0A!5C*=F5QJ:MG7IC3GA13M*>G*[B.PGVV7?'3BN:C9>;:HG][gf[]ILJDF@C=C>GBGBB>=9C?B?C@DADBECECFD>C?DBEEGGGFFBC=AAD>C;A<>>>A?D@FA@C7830:4?4>1=/?2;.9.8061717384:5:3:3:3~;3|<3|<2{=2{=2u9.v;-w<.w<.x=-x=-y;,y;,{;1};/~8,7*6)5'6(5&7(8(:);)<+<,~=+{<*8,7+~6*|4(|4({2)y3)y5*t1(u5+v8-r6+n4)n5*t;0xB6TEQ@P>UBYHYISGNGSNRPPKVObUeZHFK4;K0IX;[jKgxVewQYnCSi;Me5I`28M"-B*;2@):E7;B;8<;7;<<=-<=/79,9<1=C77@/6C)DU1Rj8_{@mHpJqLrQtUrUqQtVuYsYmSdN\HZDdNaJ`HcIfJiIeDa>`PWyGPr@i`Qi`Qi`QjaRjaRkbSkbSkbSjaRjaRjaRjaRjaRjaRjaRjaRkbSkbSkbSkbSkbSkbSkbSkbSlcTlcTlcTlcTlcTlcTlcTlcTo\Nq_QtdUrdWnbTj`Th`ShbTgaSebQa^K[VBVQ;TN6NH.GA'RD)N=#cI2iVzmng[WPQBE@E@GBFDGEIGIGIBEBEBDEEDBC;D:H;F7H9H:G?EBBD?F=EBDBDBDDEDEEDEDEDDAC@B?@>?=?=?=@>E??8:280:0>4@3?2A4|@5}?4<3:3837372<-<-<-;,;-:,:,:,9-9-9-~:/~:/~:/~:/~:/~80~80}90}90}90}90|90|90|90|90z:0y9/y9/x8.w9.w9.w8/w8/v7.t8.s7-r6,q5+p6+l2'q7,m4)l3(o6+m4)q8-H=ULTLQKPJNJNLNMPLSMUK\NdOkaFTW8JX5N_;gT`zMWpFTkARg@O`0CA4B@4@<12:/2:/4:.5;-9=.A,>D*T^4E9F9G=G>GDCEAE?GCDCDCDDEDEFDFDFDEAC@B?A>A=A=@=A>FAB<=6:090;/=0=0A4|@5}?4<3:3917172<-<-;,;,;-:,:,:,9-9-9-~:/~:/~:/~:/~:/}90}90}90}90}90}90|90|90|90z:0z:0y9/y9/x:/w9.w9.w8/w8/t8.s7-r6,r6,p6+p6+k1&q7,m4)l3(o6+l3(p7,~H2><03;03;05;/6<09=/A,>D*Q[9^mDmPpRrSqRsSsRxa|exakT`I]F]F\E`IaJcLeNdMbK`I^G]MRtBIk9i`Qi`Qi`QjaRjaRkbSkbSkbSjaRjaRjaRjaRjaRjaRjaRjaRkbSkbSkbSkbSkbSkbSkbSkbSlcTlcTlcTlcTlcTlcTlcTlcTtbTo_Pm]Pm_ToeYog\keYhbVfbVpl`{xi~{jzgzuapiVf`JPVG@GCFFEFDGCDCDCDCDDEECECECDBE@D?C>C=C=B=B=F@E=C:>5:/8-9,<-A2~@3}?2=1:1918180<-;,;,;,:,:,:,:.9-9-9-~:/~:/~:/~:/~:/}90}90}90}90|90{8/{8/{8/{;1{;1z:0y;0x:/x:/x:/x:/t8.t8.s7-s7-r6,q5+o5*o5*k1&o6+m4)k2'n5*i3'm7+}G;QIPIQJQLRMRNTPUPVO[P^OtbNoiQnrWjwYfwWPf@K_:EY6BV3EV6GV7FU8ER8?I1*7;*:<.<>0<=/:;-5<45<46<26<09=/<>0=@-=C)MV7Zi@h|KlNpOqRuStSzcw`nWcL\E\E\EZC_HaJbKdMcLaJ_H]F[}KPr@Gi7i`Qi`Qi`QjaRjaRkbSkbSkbSjaRjaRjaRjaRjaRjaRjaRjaRkbSkbSkbSkbSkbSkbSkbSkbSlcTlcTlcTlcTlcTlcTlcTlcTtdWqaTm_Rk_SkaWlcZle[jf]jf]wuiy|rygZfNLV>AI2CF1ED0D?,I=-TD5M:+O8*R6*T7)X8+];/a?3eA5KASLUQNKEDABCCEF?>@=B>D@EAFDEDEDCDCDDDDDDDEDEBGCFBE?E>E>D=D=E=E=C@8;/8,9+;.@2@1~?0=/;/:/9/90;,;,;-:,:,:,9+9-9-9-~:/~:/~:/~:/~:/~:/}90|90|90{8/{8/{8/y9/x8.{;1y;0y;0y;0x:/x:/v:/v:/s7-s7-s7-r6,p6+o5*o5*n4)j1&o6+l3(h2&k5)h2&l6*|F:OGPHQIRMSNUPWPYQ]RaUy_PiZGd_IciOZgKN]@EU8AQ4=M0G2:A/7>,9=,9=.8<-7;,6=66=66;46<29<1;=/dxGjLpOsTwUwT{dr[eN\EZC\E\EZC_H`IaJbKaJ`I^G]FY{INp>Ef7i`Qi`Qi`QjaRjaRkbSkbSkbSjaRjaRjaRjaRjaRjaRjaRjaRkbSkbSkbSkbSkbSkbSkbSkbSlcTlcTlcTlcTlcTlcTlcTlcTseXugZsg[mcYjaXle]snhzwp~wv~i`hSLSADK9AJ7>G4>G4BI7GNB?@AAC@EAEAEAEADFDFDFDDEDEDEDEAFBFAF>E=F=F=F=G>@9B;D=B9>3:-;.=/?0?/~?0=/<-:-:-:.;-;-:,:,:,9+9-9-9-~:/~:/~:/~:/}:1}:1}:1|90|90|90{8/y9/x8.x8.v8-y;0y;0x:/v:/v:/u9.u9.u9.s7/r6.q6.p5-o4,n3+m4+m4+j1(o6-j4*h2(j4*g1'k5+zF;MGNHPJSLUOWPZPZQ{YMv\OkZJ]UBYXDY^HOYA>L3;G18D.5A+5A+8D.=I3AM7EN;BK8?H5.5<,4;+5;75<56;56;48;2:-;@)GP1Ra:buGiKqPuVyWxUzcnW`IZ}C[~D^G^G]F`IaJbKbKaJ`I_H^GW{KLp@Bf6haQhaQhaQibRibRjcSjcSjcSibRibRibRibRibRibRibRibRkbSkbSkbSkbSkbSkbSkbSkbSlcTlcTlcTlcTlcTlcTlcTlcTmaUndXpf\lcZkd\rmg|ľtfcTPQAEI8=F38E18G45F35F44E36D58D6;E:?G<@H=<6(L0=/=.>/?/>.=-<-;,;,;-:,:,:,:,9+9-9-~8,~:/~:/~:/~:/}:1}:1}:1}:1z:1z:1y90y90x8/v7.v7.v7.u9/u9/u9/s9.s9.s9.r8-r8-q6.q6.p5-o4,n3+m4+l3*l3*h2(l6,i3)f2'h4)e1&i5*xD9KEMFPJTLVOXNYO|\Os\Nk[L_XFUTBPS@JQ?@I64@,3<+2;*09(09(2;*5>-9B1-;@*CL/O^7_rDiMrSwXyWvUs\fOZ}CX{A\E]F]F^G`I`I`I`I`I_H^G]FVzLJn@Ae7haQhaQhaQibRibRjcSjcSjcSibRibRibRibRibRibRibRibRkbSkbSkbSkbSkbSkbSkbSkbSlcTlcTlcTlcTlcTlcTlcTlcTiaVjbWkdZmf^upjҺzym__YIKL:>F19E1>2J91`94HH\__dVZOSMOLKJJHEFBDAA?DFDFDFCECEBBCBCBDCD@E?F?F8?:B9C:C8A4<-9)>->.>-=,=,<,;,<-:,:,:,9+9-9-~8,}9.~:/~:/~:/}:1}:1}:1}:1}:1y:1y:1x90x90w8/t8.s7-s7-s9.s9.r8-r8-q8-p7,p7,p7,p5-o6-n5,n5,m4+l3*i3)i3)g1'k7,h4)e1&h4)d0%f4)uC8JELHPJTLWNYOx[Mp]Nj^N]WGPQAKN=CJ:9B12:+08)36-17-06,/5+/5)17+2:-4<-9D4;F6=H7*0640641622716929;0:<.:?)?H+KY5]pChLsTwYwWrQiT^IUx@WzB[~F[~F[~F]H_J_J_J_J^I^I]H]HUvKJk@@a6haQhaQhaQibRibRjcSjcSjcSibRibRibRibRibRibRibRibRkbSkbSkbSkbSkbSkbSkbSkbSlcTlcTlcTlcTlcTlcTlcTlcToh^ng_lh_tqjũsbaZGML7CH2AI4AH6BF7BD7C@9D<9C98C772?5;@9@93H/+c76QRgimm[\YWUSQNKKGFBB@ACGDFDFBEBEADBBBBDCCBC?C>E>E>F-=,=,<,<*=+:,:,:.9-9-~8,}9.}9.~:/~:/}:1}:1}:1}:1}:1{;2w;1w;1v:0u9/t8.s9.r8-q7,r8-q8-p7,p7,n8,m7+m7+m7+o6-o6-n5,m4+j4*j4*i3)h4)f2'k7,h4)c1&e3(b0%e3(uC8JGNIQJTMXOzZMq[Mh\LXUDHK:=D4=E69A208+/7*5=056157257247005.06,08-19,6A3:E5=J9>K9;J77F12A,0?*.42.420511605818:/:<.:?+WzB[~FY|DY|D\G_J_J^I^I^I]H]H]HSsJHh?>^5icSicSicSicSicSicSicSicSicSicSicSicSicSicSicSicSkbSkbSkbSlcTlcTmdUmdUmdUmdUmdUmdUmdUmdUmdUmdUmdUfc\gd]vsnȷɴicbFGG-EG/DF0GD3IC5H;3F42G34M797@;;@:@;8G85cGFkjŔ譩ҋtn]XSNNNIKEICGFHHKCF:>>@FIDG:;@@@@A@B>C>B.>/?.>-=,<+=*=*9-9-9-~8,~8,|8-|8-|8-}9.|90|90|90z:1z:1z:1z:1x=5w<4v;3u:2t91r7/p7.p7.o6-m7-m7-m7-m7-l8-l8-l8-i2+m6/p92o81k4-g2*g2*h3+e0(i7.d2)^,#`0&_/%b2(p@6LJOKQJQJ}YMv_QfYIRO>CF5=F58C35@02=/3;04:04:077577566446135016/05..6+.9+2=/6C29H5:I68G42D./A+,20,2.-2..3-36/780:&DR1YkChRu[w_rWjN\}HXyDTu@Tu@WxCZ{F[|GZ{F^JbNbN^J\}H_K`L^JTrNFd@:X4icSicSicSicSicSicSicSicSicSicSicSicSicSicSicSicSkbSkbSkbSlcTlcTmdUmdUmdUmdUmdUmdUmdUmdUmdUmdUmdUed_onjͱcgkJMP1II/EC,HA/J>2L93M85Q99;;9BA?MHE\RQyjg̳ǿ괪̃|c\VTPSFM=DEEEEGHIKEG<><>@C>???@@A@B>B=A/>.>-=,<+=,<,9-9-9-~8,}9.|8-|8-|8-|90|90|90z:1z:1{;2{;2{;2v=4u<3t;2s:1r90p7.m7-m7-m7-l8-l8-l8-l8-j8-j8-j8-l5.n70n91n91l7/i4,g2*e3*c1(e3*_/%^.$b2(^.$`0&n?5IEQLWRWOrVKdRDQJ:>?/:A16A14A02>02<14<15;17:388677577557446116005./7,.8-1<.4A07E49H58G44E22D.062.40.3--2,14-45-8:-9=,7?'DQ3YkEhSv`wbpYfNZzHWwETtBTtBVvDYyGYyGYyG[{I_M_M\|J[{I^~L^~L\|JTmOF_A9R4icSicSicSicSicSicSicSicSicSicSicSicSicSicSicSicSkbSkbSkbSlcTlcTmdUmdUmdUmdUmdUmdUmdUmdUneVneVneVddby{xشĝj`hCRW7DG,EC.KD4MC9N?8L=8C:;SJKi`axv画ecACBINVVRLIDABAFEEFCDBD=?>>??@?A@A=B=A/>.=-<+=,=,9-9-9-}9.}9.|8-|8-{8/}:1}:1{;2{;2{;2{;2{;2{;2t;2s:1p:0o9/n8.m7-k7,k7,l8-l8-j8-j8-j8-j8-i9-i9-n91m80m80m80m80i7.f4+c1(c3)a1']-#_0&c4*\-#_0&sD:OKUPXQqSK^J?OC7?<-37(2:+/<+0<.2=/4<15;17:37:388688668557257227016/08-.8-0;-2?.6C27E48G48G48G46=53:2/4-,1*.1(13(57*6:)6>'DQ5[lHkZyfwflX^KWwEUuCRr@Rr@TtBVvDWwEWwEXxF[{I]}K[{I[{I]}K\|JXxFPfOAW@3I2icSicSicSicSicSicSicSicSicSicSicSicSicSicSicSicSkbSkbSkbSlcTlcTmdUmdUmdUmdUmdUmdUneVneVneVneVofWgkl۲™}cdnKLS4EI0HJ5KI:GE9D@7QEEk__莎bd>CPITMOJF@FBMJJI??>>>??>@?A?B?B?C?>8?:C=E?E>B9=5;2<1=0=1=0=-~<,=-=-~:/~:/~:/}9.}9.|8-{8/{8/~;2|<3|<3{;2{;2z;4z;4z;4p:0o9/o9/m9.l8-k7,j6+h6+i7,i7,h8,h8,h8,h8,h8,h8,o:4j81h6/i70j81j81e4-a0)e4-b1*].&a2*b3+Y*"_3*zNE~]XvWRiNGWC:J<3@:.:;-8<.08)/:,1<.2=/5=25;169078079468368349338138119.19..9+/:,1<.2?.5B18E4:I6;J7;C87?428.-3)-0%/1&24'48)4<'ER8_pPrd}nwifXT}EUrBTqASp@Sp@TqAUrBVsCVsCWtD[xH]zJ\yI^{K_|L\yIVsCK\JD8f\Z|z즤ifK=QDYN[QQHD=A@?B>C?C?C?C?>9@5<4<3=2=1=0=/~<.=/Qn>Qn>Qn>Qn>Qn>Sp@Sp@WtD[xH]zJ]zJ_|L_|LZwGQn>ESF6D7(6)gdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSkbSkbSkbSlcTlcTmdUmdUmdUmdUmdUneVneVofWpgXpgXpgXinrz׹ĥregOMP;EL:EM>EODGSG~zqƽߑ}fSK:UFWKF;@8KEC>C?B?C@C>D>D>C=@6:6-85,99/8:/47,36+4:.5;/5;/69.69.68-57,46+19,19,19,19,19,19,19,19,08+.9+.9+/:*0;+3>.6A17B2gw]umvnf_RwKAh;Mj:Nk;Pm=Pm=Nk;Nk;OlVsCZwG]zJ^{K_|L_|LVsCLi9=H@/:2#.&gdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSkbSkbSkbSlcTlcTmdUmdUmdUmdUmdUneVneVofWpgXqhYqhYcjpmtzƯ}vn[ZWFOQCQWKYcZbmeq[WDSCQBMAJAG@E?E@E@E>D=Ce9Jg9Li;Nk=Nk=Li;Li;Mj
    UrDYvH[xJ]zL^{M\yKQn@Eb47@;+4/!*%gdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSgdSkbSkbSkbSlcTlcTmdUmdUmdUmdUmdUneVofWpgXpgXqhYriZhowmt|ʹƯsce]P[YM_bYovo|Ȱ}gO=Q@RDC8IAH@F@F@E=D6qB:n?7pD;g;2g;2SJaXTKpE<6=52913:27<5492/5+25,9<345-35*24)13(13(35(46)57*,7',7'-8(-8(-8(-8(-8(/7(19*08)08+/7*/7*/7*08+08+7@+9B-=D2=D2=A29;-35'/3$3:*JVBcr[f}a\wVLnICgA=c:He7Kh:Nk=Nk=Kh:Jg9Li;Nk=TqCWtFZwI[xJ]zLZwINk=A^05;9*0.!'%heVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheTheVhdYkd\kd\md]meZmfVg`MjeOnlWnl]ff^eeeqqyֵymvW\fK`lTq~lЪa\D=MEKBC:A7D:H>JAI>G>J2K4L5K4H2F2E3E5D5C6@4>3;29/7/6-~:1~:1}90|8/{7.z7.y6-x5,w7-w7-x8.x8.v8-u7,s5*q3(h91h91h91g80h70g6/g6/g6/f5.h6/i70j81i70h6/f4-g2,k1-k4/n70m80k9.j:.i>.iB1dC2gJ8aJ8raOyn\|jqOL;4:04:04:039/39/39/28.28.17-17-17-06,06,/5+/5+/5+/4./4./4./4./4./4./4./4.05//4./4..3-.3-/4./4.05/0;32=55A77C98D86B64@22?.3@.DQ=WeN\jSSaHHV=DR8FT:Ic>Ke@Ke@Ke>JeOjAUpGYtK\vO]wR]wTWpPHaC8Q3).2&+/$)-heVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheTheVhdYkd\kd\md]meZmfVjcPlgQmkVlj[gg_lll~~ЯvkrSYaI_kUto}uJ@K@JJ>D9=2?6D;H3J7M9J7G5C4D6F7C7C8A7>5<4:19181}:2}:2|91z:1y90x8/w7.v7.u6-v7.t8.t8.t8.r6,p4*o3)i81i81i81h70h70h70g6/g6/e3,e3,g5.h6/j81j81j81k92k60l71m80l:1k;/l>1j@0iD2hG6kP=gR?ufSvdsrML:4:039/39/39/28.28.28.17-17-17-17-06,06,/5+/5+/5+/4./4./4./4./4./4./4./4.05//4..3-.3-.3-.3-/4.05/-80/:21=34@66B66B66B45B16C1CPAO6BP7FT:Ic@Jd?Ke@Ke>Ic3L/).2',0$)-heVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheTheVhdYkd\kd\md]meZmfVmhTmhRmkVjk[jkcvxwۿʫyuy^kpZt{iٞL=Q@K;>1G9XMTJ?6D6H9J=I=B7?5A7E=A9A9@:>8~>5<4<4;4x<2x<2w;1w;1v:0u9/t:/t:/s9.r9.r9.r9.q8-n8,l6*k5)j81j81j81j81i70i70i70h6/g5.g5.g5.g6/h70i81k:3k:3l;4k:3i:0j;1k?2lB4iD2fE2fI7lVAjYEviVl{mEF439/28.28.28.17-17-17-06,17-17-17-06,06,/5+/5+/5+/4./4./4./4./4./4./4./4./4./4..3--2,-2,.3-/4./4.*5-+6.-9//;12>24@46B47D38E3?L:ER>CQ:;I28F->L3ES:H`>Jb@LdBKc?Ia=G`9F_8G`9RkDXpL]uS^vVZqTPgK=T8,C)).2',0%*.heVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheTheVjcYkd\kd\md]meZmfVniUljSlkVlm]pqiؼǫ}ſınQ>P=XHL?D7G<>4D;H?F>?9;6=8A>?;@<@<}@;z?9y@9x?8v?8v=4v=4v=4u<3s=3r<2r<2q;1o;0o;0o;0l:/k9.j8-j8-i7,n72n72m61l71l71k60i70i70l:3j92h70g6/f7/f7/h91h91j?6f>4e=1f>2hC3iE5gF3cG2cJ6hV@k\GskVnzor_9>*28.28.17-17-17-06,06,06,17-17-17-06,06,/5+/5+/5+.3-.3-.3-.3-.3-.3-.3-.3-.3-.3--2,-2,-2,-2,.3-.3-)4,)4,*6,+7-.:01=14@25A36C2:G5=7A;D?C?<;989:====>>@?|A=xA6s>6s>6r=5p>5p>5p>5n>4n>4m=3l<2j;1j;1i:0i:0i:0p62p62p62o51m61m61k60i70l;4k:3h91e90e90e90e:1f;2dB6cA5cC4dD5fG5eH6cH3_I2^L6eV?jbKrmWnr[`L3;&28.28.17-17-17-06,06,06,17-17-17-06,06,/5+/5+/5+.3-.3-.3-.3-.3-.3-.3-.3--2,-2,,1+,1+,1+,1+-2,-2,,6.+5-*4,*4++5,.8-0:/2=/2=-5@06A05A-1=)1=)5A+9E/=O5AS9FY=I\@J]?J]=K^>L_?TgG\oQcvZbtZYkSK]G6G4$5"&+.$),"'*heVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheTheVjcYkd\lc\md]meZlfVlgSljSlnXorasvmθͺƶø̧lXZGVCM;A8BD??>;;99:;<<>??=}@=wB7o>7n?7o@8n?7m>6i=4h<3h<3h<3i=4r73q62q62p62o51m61l71j81h70g80e90e:1d<2f>4f@5gA6]C4aG8cL:dM;cM8`K6]K3]M4]Q9`Y?miPss[mt|eFO:2>(39/28.28.28.17-17-17-06,17-17-17-06,06,/5+/5+/5+-2,-2,-2,-2,-2,-2,-2,-2,-2,,1++0*+0*+0*+0*,1+-2,,6.,6.*4,*4+*4++5*-7,.9+-8*0;+4?/5@/4?.3>-3?+4@,7F/;J3@P6DT:GWH=H>G@F@C@=:97<;=;>;A5i=4j>5j>5k?6s63r73q62p62n72l71j81i81d8/d90c;1d>3d@4cA5cA5bB5VG4^OmmSsw^zjcmU2>(5C,4:039/39/39/28.28.28.17-17-17-17-06,06,/5+/5+/5+-2,-2,-2,-2,-2,-2,-2,-2,,1+,1++0**/)*/)+0*,1+,1++5-+5-*4,*4,+5,+5,,6+-7,,7)/:,2=/6A17B27B25@/4?.2?+5B.:G3>L5AO6ES:JX?M[BTbI]kTcqZ_lXUbPERA2>0#/#(..&,,$**heVheVheVheVheVheVheVheVheVheVheVheVheVheVheVheVjdTjdVjcYkd\lc\md]lfZlfVomXmmUimVgkZembr{x׭sYSAQ?N>O?OBJ@C:<4<7>8?6@7{B7tD6qE8nG8s>:s>:s>:q>:q>:q>:q>:p?:sB=rA8l=7l=7m>8n?9r73r73q73n72m82j81i81f:1f;2d>3d@4bB5`C5]A3\@2[?1QI4[S>f^Gg_H`Y?ZS9ZS7\W:ZV;WW;knSrx^u}eUaI%37E.4:04:04:039/39/39/28.28.17-17-17-06,06,/5+/5+/5+-2,-2,-2,-2,-2,-2,-2,-2,,1++0*+0**/)*/)+0*+0*,1+)3+)3+*4,+5-+5,,6--7.-7,,6+.8-2=/6A39D69D67B46A1/<*2?-5B09F2:u@:s@9o>9o>9n72n72n93m;4l;4j;3g<3d<2c?3^>1dG9cG9T=-O8(M8'D/TR;PN7KI0MK2]Y>ieJeaDVU7XX<]`CosXzfcmT=I1,:#1?(5;15;14:04:04:039/39/39/39/39/39/28.17-17-17-06,16016005/05//4./4./4./4.,1+,1+,1+,1+,1+,1++0*+0*.5.-4--4-,3,-4--4-.5-.5-+2*-4,08-5=29A6=E:?G7B25@03>-1<+2>*9E/BN8IU?O[EVbN]hWYdTLWIF5F4D4D2}B0yB.s@-o?+v?:t=8u>9v?:t?9q<6r=7sA:q?8q?8q?8o>7o>7n=6n=6n=6l;4m<5m>6k?6j?6h@6eA5cA5dG9[A2^G7\I8N=+F7$G8%A4!IM4GK2DG,BE*MM1[[?abC`aBYY=dgJsw\sy_X`H8D,/;%6D-7=36<26<26<25;15;15;15;15;15;15;14:04:039/39/39/27127127116016016005/05/.3-.3--2,-2,,1+,1++0*+0**1**1*)0))0))0)*1*+2+,3,.5--4,.5-07/4;39@8?F>BIA:G69F56C13@.2?+5B.;I2?M6KXDR_KXeSVcRKWI8p;5q<6vA;sA:p>7r@9xG@n=6n=6n=6m>6l=5l=5l=5l=5g?5h@6gA6gC7eC7cC6`C5^D5aL;UB1ZI7`S@RG3C;&E=(GA+>G,BH.@F*<@%?B%LO2_`AijKaaEnqTvz_gmSHP84<%4=(=F18>48>48>48>47=37=37=36<28>48>47=37=37=36<26<26<25:449349349338238238227105/05//4..3--2,,1++0*+0*(/((/((/((/((/()0)*1*+2+070.5.+2++2+.5.5<5K:4-9/-3/-3/,2.gdUgdUheVheVheVheVifWifWifWifWifWifWifWifWifWifWleUldWlcZmd]md]mf^mg[khWmlWimThpXht`hthm|wڻּҽzyS3i?3i?3i?3f>2f>2f>2f>2aA4`C5`C5_C5^D5[D4ZE4VE3XI6OB/\T?oiSc^HMK4IG0LJ3;E*?H->G*48>47=37=37=39?58>48>48>48>48>48>48>47<67<67<66;56;56;55:45:438238216005//4.-2,,1+,1++0,+0,*/+*/++0,,1--2.-2.051.3/+0,+0,-2.2738=9'4.:0.5..5.-4-gdUgdUgdUheVheVifWifWifWifWifWifWifWifWifWifWifWleUldWlcZmd]md]mf^mg[khWkmWjnUiqYgs_drejytܽչѷѾӾϴu`yVBlI5mH6rM;uP>mF7iB3gB2jE5nI9oJ:pK;oK;eA1eA1cB1cB1cB1cB1cB1bC1\G6\G6\G6ZG6YH6WH5TG4RG3PH3MH2fdM~~fprZVX@IM4HL3;E*A.;>+9?59?59?58>48>47=37=37=38>48>48>48>48>48>48>48>49>89>89>88=78=78=77<67<66;55:449338227105//4./4.-2.-2.,1-+0,+0,,1--2.-2.,1-,1-,1-,1-.21043376598:H7=L9@O<@O:8F91?2,9/.5.-4-,3,fcTfcTgdUheVheVifWjgXjgXifWifWifWifWifWifWifWifWleUldWlcZmd]md]mf^mg[khWkmWioUiqYgs_bpcgxrڻѵ˴˺ӿһurd|]I}^JrVAaE0W;&Y=(Z?*X=(`E0`E0_F0_F0`G1`G1^H1^H1[L9ZM:ZM:XM9XM9UM8RL6QL6NL5QQ9ikS|glrXSY?DM2>G,:G+48>48>48>47=37=38>48>48>48>49?59?5:?9:?9:?9:?99>89>89>88=78=78=77<66;55:4493382382/40.3/-2.,1-+0,+0,+0,+0,+/.,0/-10.21/32/32/32.210A.5F3;M7>P:=O7:L47I/6H.3E-6H0:L6MJ9EB1;A7;A7;A7;A7:@6:@6:@69?58>48>48>49?59?5:@6:@6:@6;@:;@:;@::?9:?99>89>89>8:?9:?99>89>88=78=77<67<6495273162/40-2.,1-+0,+/.,0/,0/-10.21.21.23-12,01):'/@-6H2;M5=O7?I.9F*?L0=J.AN2DN3HQ4LR6IN0JM0ZY;miLhdIc]C_YA_ZD`[GZUBQN=LI8=C9=C9=C989>89>8;@:;@:;@:;@::?9:?9:?9:?99>:8=95:6384162/40.3/.21.21.21-10-12,01,01-12-12$5"*<&3E/9K3XW9UT6SR3KE/JD.FA-D?,A>/@>1??3>@5<=5;>59?59A67B48C57C57D3:B79A69A68@58@59A69A6:B7:B7:B79A6:B7;C8F;7B:7C97A66A16?.4<-39-270.5./51-7/-9+-<%.B3J7O7Z 8Y$8W+:U2:R8;P==O?>O=:L6@R8EX:EZ;DY:>U93J0(>'.5-,3++2*ZgM[hN\hP_iQakSckTglXhkXghVihVifWifWkeWmeXmeZnf[khWkhYkg[kg^jf]jf]hfZgeVgjWglVfoZerajwnz̹˾NjlRM0TM0QK+SJ+WN/UO/UN1TO1SO2QP4QP4PP6QM2PO3PN5PP6MO7KO6HM6EM5HQ6EN3BK.AH)BI(GM+JP,KQ-NR/PT1VZ9^aBaaE[[?VVVV>XV=YW>XW;XW9WV8VU7QK5OI3LG3ID1DA2B@3??3>@5<=5;>59?59A67B48C57C57D3:B79A69A68@58@59A69A6:B7:B7:B7:B7:B7;C8F;76<83=51=/3B+9M*BY-Ia1Nq7Mn9Ji=Fa>AY?:L<:K9=O9DV5:@69A67B47B47C57D3:B7:B79A69A69A69A6:B7:B7:B7:B7:B7:B7;C8F;>F;>IA>J@?I>>I9?H7>F7>D8=B;>E>;A=6@85A39H1BV3Pg;ZrB]F\}HVuIMhEBZ@9N;5G74E3XR6F;?G<>H=>I9?H7>F7>D8=B;=D=;A=6@85A39H1DX5Ri=]uEY|BXyDRqEIdA,6H2@R8L_AQfGShIMdH@W=4J329107/-4,YgMZhN\hP^jRblTemVgoZjo[lo\lm[mk\mj[nhZnhZoi]ph]liXkhYjfZie\ie\ie\ig[igXfiVchRajUerao|s{ѿɶıþ˾Ÿ̌oRL2UN2TM0WN1VM.UO/WP3VQ3UQ4QP2ON2MM1PL1NM1NL3MM3LN6LP7KP9JR:LU:IR7JS6QX9SZ9U[9]c?gmIasxpr|Z\bFLP7KM7LK6KI4NI5PK7TM:VP:WQ;VP:SN:QL9LI:IG:EE9CE:=>6F;?G<=G<=H8>G6=E6=C7=B;:A:9?;5?75A39H1BV3Ne9Wo?Sv /* to declare isdigit() */ #if TRANSFORMS_SUPPORTED /* * Lossless image transformation routines. These routines work on DCT * coefficient arrays and thus do not require any lossy decompression * or recompression of the image. * Thanks to Guido Vollbeding for the initial design and code of this feature, * and to Ben Jackson for introducing the cropping feature. * * Horizontal flipping is done in-place, using a single top-to-bottom * pass through the virtual source array. It will thus be much the * fastest option for images larger than main memory. * * The other routines require a set of destination virtual arrays, so they * need twice as much memory as jpegtran normally does. The destination * arrays are always written in normal scan order (top to bottom) because * the virtual array manager expects this. The source arrays will be scanned * in the corresponding order, which means multiple passes through the source * arrays for most of the transforms. That could result in much thrashing * if the image is larger than main memory. * * If cropping or trimming is involved, the destination arrays may be smaller * than the source arrays. Note it is not possible to do horizontal flip * in-place when a nonzero Y crop offset is specified, since we'd have to move * data from one block row to another but the virtual array manager doesn't * guarantee we can touch more than one row at a time. So in that case, * we have to use a separate destination array. * * Some notes about the operating environment of the individual transform * routines: * 1. Both the source and destination virtual arrays are allocated from the * source JPEG object, and therefore should be manipulated by calling the * source's memory manager. * 2. The destination's component count should be used. It may be smaller * than the source's when forcing to grayscale. * 3. Likewise the destination's sampling factors should be used. When * forcing to grayscale the destination's sampling factors will be all 1, * and we may as well take that as the effective iMCU size. * 4. When "trim" is in effect, the destination's dimensions will be the * trimmed values but the source's will be untrimmed. * 5. When "crop" is in effect, the destination's dimensions will be the * cropped values but the source's will be uncropped. Each transform * routine is responsible for picking up source data starting at the * correct X and Y offset for the crop region. (The X and Y offsets * passed to the transform routines are measured in iMCU blocks of the * destination.) * 6. All the routines assume that the source and destination buffers are * padded out to a full iMCU boundary. This is true, although for the * source buffer it is an undocumented property of jdcoefct.c. */ LOCAL(void) do_crop (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* Crop. This is only used when no rotate/flip is requested with the crop. */ { JDIMENSION dst_blk_y, x_crop_blocks, y_crop_blocks; int ci, offset_y; JBLOCKARRAY src_buffer, dst_buffer; jpeg_component_info *compptr; /* We simply have to copy the right amount of data (the destination's * image size) starting at the given X and Y offsets in the source. */ for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y + y_crop_blocks, (JDIMENSION) compptr->v_samp_factor, FALSE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { jcopy_block_row(src_buffer[offset_y] + x_crop_blocks, dst_buffer[offset_y], compptr->width_in_blocks); } } } } LOCAL(void) do_crop_ext (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* Crop. This is only used when no rotate/flip is requested with the crop. * Extension: If the destination size is larger than the source, we fill in * the extra area with zero (neutral gray). Note we also have to zero partial * iMCUs at the right and bottom edge of the source image area in this case. */ { JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height; JDIMENSION dst_blk_y, x_crop_blocks, y_crop_blocks; int ci, offset_y; JBLOCKARRAY src_buffer, dst_buffer; jpeg_component_info *compptr; MCU_cols = srcinfo->output_width / (dstinfo->max_h_samp_factor * dstinfo->min_DCT_h_scaled_size); MCU_rows = srcinfo->output_height / (dstinfo->max_v_samp_factor * dstinfo->min_DCT_v_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_width = MCU_cols * compptr->h_samp_factor; comp_height = MCU_rows * compptr->v_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); if (dstinfo->jpeg_height > srcinfo->output_height) { if (dst_blk_y < y_crop_blocks || dst_blk_y >= comp_height + y_crop_blocks) { for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { FMEMZERO(dst_buffer[offset_y], compptr->width_in_blocks * SIZEOF(JBLOCK)); } continue; } src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y - y_crop_blocks, (JDIMENSION) compptr->v_samp_factor, FALSE); } else { src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y + y_crop_blocks, (JDIMENSION) compptr->v_samp_factor, FALSE); } for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { if (dstinfo->jpeg_width > srcinfo->output_width) { if (x_crop_blocks > 0) { FMEMZERO(dst_buffer[offset_y], x_crop_blocks * SIZEOF(JBLOCK)); } jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y] + x_crop_blocks, comp_width); if (compptr->width_in_blocks > comp_width + x_crop_blocks) { FMEMZERO(dst_buffer[offset_y] + comp_width + x_crop_blocks, (compptr->width_in_blocks - comp_width - x_crop_blocks) * SIZEOF(JBLOCK)); } } else { jcopy_block_row(src_buffer[offset_y] + x_crop_blocks, dst_buffer[offset_y], compptr->width_in_blocks); } } } } } LOCAL(void) do_wipe (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, JDIMENSION drop_width, JDIMENSION drop_height) /* Wipe - drop content of specified area, fill with zero (neutral gray) */ { JDIMENSION comp_width, comp_height; JDIMENSION blk_y, x_wipe_blocks, y_wipe_blocks; int ci, offset_y; JBLOCKARRAY buffer; jpeg_component_info *compptr; for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_width = drop_width * compptr->h_samp_factor; comp_height = drop_height * compptr->v_samp_factor; x_wipe_blocks = x_crop_offset * compptr->h_samp_factor; y_wipe_blocks = y_crop_offset * compptr->v_samp_factor; for (blk_y = 0; blk_y < comp_height; blk_y += compptr->v_samp_factor) { buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y + y_wipe_blocks, (JDIMENSION) compptr->v_samp_factor, TRUE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { FMEMZERO(buffer[offset_y] + x_wipe_blocks, comp_width * SIZEOF(JBLOCK)); } } } } LOCAL(void) do_flip_h_no_crop (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, jvirt_barray_ptr *src_coef_arrays) /* Horizontal flip; done in-place, so no separate dest array is required. * NB: this only works when y_crop_offset is zero. */ { JDIMENSION MCU_cols, comp_width, blk_x, blk_y, x_crop_blocks; int ci, k, offset_y; JBLOCKARRAY buffer; JCOEFPTR ptr1, ptr2; JCOEF temp1, temp2; jpeg_component_info *compptr; /* Horizontal mirroring of DCT blocks is accomplished by swapping * pairs of blocks in-place. Within a DCT block, we perform horizontal * mirroring by changing the signs of odd-numbered columns. * Partial iMCUs at the right edge are left untouched. */ MCU_cols = srcinfo->output_width / (dstinfo->max_h_samp_factor * dstinfo->min_DCT_h_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_width = MCU_cols * compptr->h_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; for (blk_y = 0; blk_y < compptr->height_in_blocks; blk_y += compptr->v_samp_factor) { buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { /* Do the mirroring */ for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) { ptr1 = buffer[offset_y][blk_x]; ptr2 = buffer[offset_y][comp_width - blk_x - 1]; /* this unrolled loop doesn't need to know which row it's on... */ for (k = 0; k < DCTSIZE2; k += 2) { temp1 = *ptr1; /* swap even column */ temp2 = *ptr2; *ptr1++ = temp2; *ptr2++ = temp1; temp1 = *ptr1; /* swap odd column with sign change */ temp2 = *ptr2; *ptr1++ = -temp2; *ptr2++ = -temp1; } } if (x_crop_blocks > 0) { /* Now left-justify the portion of the data to be kept. * We can't use a single jcopy_block_row() call because that routine * depends on memcpy(), whose behavior is unspecified for overlapping * source and destination areas. Sigh. */ for (blk_x = 0; blk_x < compptr->width_in_blocks; blk_x++) { jcopy_block_row(buffer[offset_y] + blk_x + x_crop_blocks, buffer[offset_y] + blk_x, (JDIMENSION) 1); } } } } } } LOCAL(void) do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* Horizontal flip in general cropping case */ { JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y; JDIMENSION x_crop_blocks, y_crop_blocks; int ci, k, offset_y; JBLOCKARRAY src_buffer, dst_buffer; JBLOCKROW src_row_ptr, dst_row_ptr; JCOEFPTR src_ptr, dst_ptr; jpeg_component_info *compptr; /* Here we must output into a separate array because we can't touch * different rows of a single virtual array simultaneously. Otherwise, * this is essentially the same as the routine above. */ MCU_cols = srcinfo->output_width / (dstinfo->max_h_samp_factor * dstinfo->min_DCT_h_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_width = MCU_cols * compptr->h_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y + y_crop_blocks, (JDIMENSION) compptr->v_samp_factor, FALSE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { dst_row_ptr = dst_buffer[offset_y]; src_row_ptr = src_buffer[offset_y]; for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) { if (x_crop_blocks + dst_blk_x < comp_width) { /* Do the mirrorable blocks */ dst_ptr = dst_row_ptr[dst_blk_x]; src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1]; /* this unrolled loop doesn't need to know which row it's on... */ for (k = 0; k < DCTSIZE2; k += 2) { *dst_ptr++ = *src_ptr++; /* copy even column */ *dst_ptr++ = - *src_ptr++; /* copy odd column with sign change */ } } else { /* Copy last partial block(s) verbatim */ jcopy_block_row(src_row_ptr + dst_blk_x + x_crop_blocks, dst_row_ptr + dst_blk_x, (JDIMENSION) 1); } } } } } } LOCAL(void) do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* Vertical flip */ { JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y; JDIMENSION x_crop_blocks, y_crop_blocks; int ci, i, j, offset_y; JBLOCKARRAY src_buffer, dst_buffer; JBLOCKROW src_row_ptr, dst_row_ptr; JCOEFPTR src_ptr, dst_ptr; jpeg_component_info *compptr; /* We output into a separate array because we can't touch different * rows of the source virtual array simultaneously. Otherwise, this * is a pretty straightforward analog of horizontal flip. * Within a DCT block, vertical mirroring is done by changing the signs * of odd-numbered rows. * Partial iMCUs at the bottom edge are copied verbatim. */ MCU_rows = srcinfo->output_height / (dstinfo->max_v_samp_factor * dstinfo->min_DCT_v_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_height = MCU_rows * compptr->v_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); if (y_crop_blocks + dst_blk_y < comp_height) { /* Row is within the mirrorable area. */ src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], comp_height - y_crop_blocks - dst_blk_y - (JDIMENSION) compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, FALSE); } else { /* Bottom-edge blocks will be copied verbatim. */ src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y + y_crop_blocks, (JDIMENSION) compptr->v_samp_factor, FALSE); } for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { if (y_crop_blocks + dst_blk_y < comp_height) { /* Row is within the mirrorable area. */ dst_row_ptr = dst_buffer[offset_y]; src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1]; src_row_ptr += x_crop_blocks; for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) { dst_ptr = dst_row_ptr[dst_blk_x]; src_ptr = src_row_ptr[dst_blk_x]; for (i = 0; i < DCTSIZE; i += 2) { /* copy even row */ for (j = 0; j < DCTSIZE; j++) *dst_ptr++ = *src_ptr++; /* copy odd row with sign change */ for (j = 0; j < DCTSIZE; j++) *dst_ptr++ = - *src_ptr++; } } } else { /* Just copy row verbatim. */ jcopy_block_row(src_buffer[offset_y] + x_crop_blocks, dst_buffer[offset_y], compptr->width_in_blocks); } } } } } LOCAL(void) do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* Transpose source into destination */ { JDIMENSION dst_blk_x, dst_blk_y, x_crop_blocks, y_crop_blocks; int ci, i, j, offset_x, offset_y; JBLOCKARRAY src_buffer, dst_buffer; JCOEFPTR src_ptr, dst_ptr; jpeg_component_info *compptr; /* Transposing pixels within a block just requires transposing the * DCT coefficients. * Partial iMCUs at the edges require no special treatment; we simply * process all the available DCT blocks for every component. */ for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x += compptr->h_samp_factor) { src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x + x_crop_blocks, (JDIMENSION) compptr->h_samp_factor, FALSE); for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) { dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x]; src_ptr = src_buffer[offset_x][dst_blk_y + offset_y + y_crop_blocks]; for (i = 0; i < DCTSIZE; i++) for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; } } } } } } LOCAL(void) do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* 90 degree rotation is equivalent to * 1. Transposing the image; * 2. Horizontal mirroring. * These two steps are merged into a single processing routine. */ { JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y; JDIMENSION x_crop_blocks, y_crop_blocks; int ci, i, j, offset_x, offset_y; JBLOCKARRAY src_buffer, dst_buffer; JCOEFPTR src_ptr, dst_ptr; jpeg_component_info *compptr; /* Because of the horizontal mirror step, we can't process partial iMCUs * at the (output) right edge properly. They just get transposed and * not mirrored. */ MCU_cols = srcinfo->output_height / (dstinfo->max_h_samp_factor * dstinfo->min_DCT_h_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_width = MCU_cols * compptr->h_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x += compptr->h_samp_factor) { if (x_crop_blocks + dst_blk_x < comp_width) { /* Block is within the mirrorable area. */ src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], comp_width - x_crop_blocks - dst_blk_x - (JDIMENSION) compptr->h_samp_factor, (JDIMENSION) compptr->h_samp_factor, FALSE); } else { /* Edge blocks are transposed but not mirrored. */ src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x + x_crop_blocks, (JDIMENSION) compptr->h_samp_factor, FALSE); } for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) { dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x]; if (x_crop_blocks + dst_blk_x < comp_width) { /* Block is within the mirrorable area. */ src_ptr = src_buffer[compptr->h_samp_factor - offset_x - 1] [dst_blk_y + offset_y + y_crop_blocks]; for (i = 0; i < DCTSIZE; i++) { for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; i++; for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j]; } } else { /* Edge blocks are transposed but not mirrored. */ src_ptr = src_buffer[offset_x] [dst_blk_y + offset_y + y_crop_blocks]; for (i = 0; i < DCTSIZE; i++) for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; } } } } } } } LOCAL(void) do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* 270 degree rotation is equivalent to * 1. Horizontal mirroring; * 2. Transposing the image. * These two steps are merged into a single processing routine. */ { JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y; JDIMENSION x_crop_blocks, y_crop_blocks; int ci, i, j, offset_x, offset_y; JBLOCKARRAY src_buffer, dst_buffer; JCOEFPTR src_ptr, dst_ptr; jpeg_component_info *compptr; /* Because of the horizontal mirror step, we can't process partial iMCUs * at the (output) bottom edge properly. They just get transposed and * not mirrored. */ MCU_rows = srcinfo->output_width / (dstinfo->max_v_samp_factor * dstinfo->min_DCT_v_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_height = MCU_rows * compptr->v_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x += compptr->h_samp_factor) { src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x + x_crop_blocks, (JDIMENSION) compptr->h_samp_factor, FALSE); for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) { dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x]; if (y_crop_blocks + dst_blk_y < comp_height) { /* Block is within the mirrorable area. */ src_ptr = src_buffer[offset_x] [comp_height - y_crop_blocks - dst_blk_y - offset_y - 1]; for (i = 0; i < DCTSIZE; i++) { for (j = 0; j < DCTSIZE; j++) { dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; j++; dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j]; } } } else { /* Edge blocks are transposed but not mirrored. */ src_ptr = src_buffer[offset_x] [dst_blk_y + offset_y + y_crop_blocks]; for (i = 0; i < DCTSIZE; i++) for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; } } } } } } } LOCAL(void) do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* 180 degree rotation is equivalent to * 1. Vertical mirroring; * 2. Horizontal mirroring. * These two steps are merged into a single processing routine. */ { JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y; JDIMENSION x_crop_blocks, y_crop_blocks; int ci, i, j, offset_y; JBLOCKARRAY src_buffer, dst_buffer; JBLOCKROW src_row_ptr, dst_row_ptr; JCOEFPTR src_ptr, dst_ptr; jpeg_component_info *compptr; MCU_cols = srcinfo->output_width / (dstinfo->max_h_samp_factor * dstinfo->min_DCT_h_scaled_size); MCU_rows = srcinfo->output_height / (dstinfo->max_v_samp_factor * dstinfo->min_DCT_v_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_width = MCU_cols * compptr->h_samp_factor; comp_height = MCU_rows * compptr->v_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); if (y_crop_blocks + dst_blk_y < comp_height) { /* Row is within the vertically mirrorable area. */ src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], comp_height - y_crop_blocks - dst_blk_y - (JDIMENSION) compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, FALSE); } else { /* Bottom-edge rows are only mirrored horizontally. */ src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y + y_crop_blocks, (JDIMENSION) compptr->v_samp_factor, FALSE); } for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { dst_row_ptr = dst_buffer[offset_y]; if (y_crop_blocks + dst_blk_y < comp_height) { /* Row is within the mirrorable area. */ src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1]; for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) { dst_ptr = dst_row_ptr[dst_blk_x]; if (x_crop_blocks + dst_blk_x < comp_width) { /* Process the blocks that can be mirrored both ways. */ src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1]; for (i = 0; i < DCTSIZE; i += 2) { /* For even row, negate every odd column. */ for (j = 0; j < DCTSIZE; j += 2) { *dst_ptr++ = *src_ptr++; *dst_ptr++ = - *src_ptr++; } /* For odd row, negate every even column. */ for (j = 0; j < DCTSIZE; j += 2) { *dst_ptr++ = - *src_ptr++; *dst_ptr++ = *src_ptr++; } } } else { /* Any remaining right-edge blocks are only mirrored vertically. */ src_ptr = src_row_ptr[x_crop_blocks + dst_blk_x]; for (i = 0; i < DCTSIZE; i += 2) { for (j = 0; j < DCTSIZE; j++) *dst_ptr++ = *src_ptr++; for (j = 0; j < DCTSIZE; j++) *dst_ptr++ = - *src_ptr++; } } } } else { /* Remaining rows are just mirrored horizontally. */ src_row_ptr = src_buffer[offset_y]; for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) { if (x_crop_blocks + dst_blk_x < comp_width) { /* Process the blocks that can be mirrored. */ dst_ptr = dst_row_ptr[dst_blk_x]; src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1]; for (i = 0; i < DCTSIZE2; i += 2) { *dst_ptr++ = *src_ptr++; *dst_ptr++ = - *src_ptr++; } } else { /* Any remaining right-edge blocks are only copied. */ jcopy_block_row(src_row_ptr + dst_blk_x + x_crop_blocks, dst_row_ptr + dst_blk_x, (JDIMENSION) 1); } } } } } } } LOCAL(void) do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JDIMENSION x_crop_offset, JDIMENSION y_crop_offset, jvirt_barray_ptr *src_coef_arrays, jvirt_barray_ptr *dst_coef_arrays) /* Transverse transpose is equivalent to * 1. 180 degree rotation; * 2. Transposition; * or * 1. Horizontal mirroring; * 2. Transposition; * 3. Horizontal mirroring. * These steps are merged into a single processing routine. */ { JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y; JDIMENSION x_crop_blocks, y_crop_blocks; int ci, i, j, offset_x, offset_y; JBLOCKARRAY src_buffer, dst_buffer; JCOEFPTR src_ptr, dst_ptr; jpeg_component_info *compptr; MCU_cols = srcinfo->output_height / (dstinfo->max_h_samp_factor * dstinfo->min_DCT_h_scaled_size); MCU_rows = srcinfo->output_width / (dstinfo->max_v_samp_factor * dstinfo->min_DCT_v_scaled_size); for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; comp_width = MCU_cols * compptr->h_samp_factor; comp_height = MCU_rows * compptr->v_samp_factor; x_crop_blocks = x_crop_offset * compptr->h_samp_factor; y_crop_blocks = y_crop_offset * compptr->v_samp_factor; for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks; dst_blk_y += compptr->v_samp_factor) { dst_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y, (JDIMENSION) compptr->v_samp_factor, TRUE); for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) { for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x += compptr->h_samp_factor) { if (x_crop_blocks + dst_blk_x < comp_width) { /* Block is within the mirrorable area. */ src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], comp_width - x_crop_blocks - dst_blk_x - (JDIMENSION) compptr->h_samp_factor, (JDIMENSION) compptr->h_samp_factor, FALSE); } else { src_buffer = (*srcinfo->mem->access_virt_barray) ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x + x_crop_blocks, (JDIMENSION) compptr->h_samp_factor, FALSE); } for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) { dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x]; if (y_crop_blocks + dst_blk_y < comp_height) { if (x_crop_blocks + dst_blk_x < comp_width) { /* Block is within the mirrorable area. */ src_ptr = src_buffer[compptr->h_samp_factor - offset_x - 1] [comp_height - y_crop_blocks - dst_blk_y - offset_y - 1]; for (i = 0; i < DCTSIZE; i++) { for (j = 0; j < DCTSIZE; j++) { dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; j++; dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j]; } i++; for (j = 0; j < DCTSIZE; j++) { dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j]; j++; dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; } } } else { /* Right-edge blocks are mirrored in y only */ src_ptr = src_buffer[offset_x] [comp_height - y_crop_blocks - dst_blk_y - offset_y - 1]; for (i = 0; i < DCTSIZE; i++) { for (j = 0; j < DCTSIZE; j++) { dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; j++; dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j]; } } } } else { if (x_crop_blocks + dst_blk_x < comp_width) { /* Bottom-edge blocks are mirrored in x only */ src_ptr = src_buffer[compptr->h_samp_factor - offset_x - 1] [dst_blk_y + offset_y + y_crop_blocks]; for (i = 0; i < DCTSIZE; i++) { for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; i++; for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j]; } } else { /* At lower right corner, just transpose, no mirroring */ src_ptr = src_buffer[offset_x] [dst_blk_y + offset_y + y_crop_blocks]; for (i = 0; i < DCTSIZE; i++) for (j = 0; j < DCTSIZE; j++) dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j]; } } } } } } } } /* Parse an unsigned integer: subroutine for jtransform_parse_crop_spec. * Returns TRUE if valid integer found, FALSE if not. * *strptr is advanced over the digit string, and *result is set to its value. */ LOCAL(boolean) jt_read_integer (const char ** strptr, JDIMENSION * result) { const char * ptr = *strptr; JDIMENSION val = 0; for (; isdigit(*ptr); ptr++) { val = val * 10 + (JDIMENSION) (*ptr - '0'); } *result = val; if (ptr == *strptr) return FALSE; /* oops, no digits */ *strptr = ptr; return TRUE; } /* Parse a crop specification (written in X11 geometry style). * The routine returns TRUE if the spec string is valid, FALSE if not. * * The crop spec string should have the format * [f]x[f]{+-}{+-} * where width, height, xoffset, and yoffset are unsigned integers. * Each of the elements can be omitted to indicate a default value. * (A weakness of this style is that it is not possible to omit xoffset * while specifying yoffset, since they look alike.) * * This code is loosely based on XParseGeometry from the X11 distribution. */ GLOBAL(boolean) jtransform_parse_crop_spec (jpeg_transform_info *info, const char *spec) { info->crop = FALSE; info->crop_width_set = JCROP_UNSET; info->crop_height_set = JCROP_UNSET; info->crop_xoffset_set = JCROP_UNSET; info->crop_yoffset_set = JCROP_UNSET; if (isdigit(*spec)) { /* fetch width */ if (! jt_read_integer(&spec, &info->crop_width)) return FALSE; if (*spec == 'f' || *spec == 'F') { spec++; info->crop_width_set = JCROP_FORCE; } else info->crop_width_set = JCROP_POS; } if (*spec == 'x' || *spec == 'X') { /* fetch height */ spec++; if (! jt_read_integer(&spec, &info->crop_height)) return FALSE; if (*spec == 'f' || *spec == 'F') { spec++; info->crop_height_set = JCROP_FORCE; } else info->crop_height_set = JCROP_POS; } if (*spec == '+' || *spec == '-') { /* fetch xoffset */ info->crop_xoffset_set = (*spec == '-') ? JCROP_NEG : JCROP_POS; spec++; if (! jt_read_integer(&spec, &info->crop_xoffset)) return FALSE; } if (*spec == '+' || *spec == '-') { /* fetch yoffset */ info->crop_yoffset_set = (*spec == '-') ? JCROP_NEG : JCROP_POS; spec++; if (! jt_read_integer(&spec, &info->crop_yoffset)) return FALSE; } /* We had better have gotten to the end of the string. */ if (*spec != '\0') return FALSE; info->crop = TRUE; return TRUE; } /* Trim off any partial iMCUs on the indicated destination edge */ LOCAL(void) trim_right_edge (jpeg_transform_info *info, JDIMENSION full_width) { JDIMENSION MCU_cols; MCU_cols = info->output_width / info->iMCU_sample_width; if (MCU_cols > 0 && info->x_crop_offset + MCU_cols == full_width / info->iMCU_sample_width) info->output_width = MCU_cols * info->iMCU_sample_width; } LOCAL(void) trim_bottom_edge (jpeg_transform_info *info, JDIMENSION full_height) { JDIMENSION MCU_rows; MCU_rows = info->output_height / info->iMCU_sample_height; if (MCU_rows > 0 && info->y_crop_offset + MCU_rows == full_height / info->iMCU_sample_height) info->output_height = MCU_rows * info->iMCU_sample_height; } /* Request any required workspace. * * This routine figures out the size that the output image will be * (which implies that all the transform parameters must be set before * it is called). * * We allocate the workspace virtual arrays from the source decompression * object, so that all the arrays (both the original data and the workspace) * will be taken into account while making memory management decisions. * Hence, this routine must be called after jpeg_read_header (which reads * the image dimensions) and before jpeg_read_coefficients (which realizes * the source's virtual arrays). * * This function returns FALSE right away if -perfect is given * and transformation is not perfect. Otherwise returns TRUE. */ GLOBAL(boolean) jtransform_request_workspace (j_decompress_ptr srcinfo, jpeg_transform_info *info) { jvirt_barray_ptr *coef_arrays; boolean need_workspace, transpose_it; jpeg_component_info *compptr; JDIMENSION xoffset, yoffset; JDIMENSION width_in_iMCUs, height_in_iMCUs; JDIMENSION width_in_blocks, height_in_blocks; int ci, h_samp_factor, v_samp_factor; /* Determine number of components in output image */ if (info->force_grayscale && (srcinfo->jpeg_color_space == JCS_YCbCr || srcinfo->jpeg_color_space == JCS_BG_YCC) && srcinfo->num_components == 3) /* We'll only process the first component */ info->num_components = 1; else /* Process all the components */ info->num_components = srcinfo->num_components; /* Compute output image dimensions and related values. */ jpeg_core_output_dimensions(srcinfo); /* Return right away if -perfect is given and transformation is not perfect. */ if (info->perfect) { if (info->num_components == 1) { if (!jtransform_perfect_transform(srcinfo->output_width, srcinfo->output_height, srcinfo->min_DCT_h_scaled_size, srcinfo->min_DCT_v_scaled_size, info->transform)) return FALSE; } else { if (!jtransform_perfect_transform(srcinfo->output_width, srcinfo->output_height, srcinfo->max_h_samp_factor * srcinfo->min_DCT_h_scaled_size, srcinfo->max_v_samp_factor * srcinfo->min_DCT_v_scaled_size, info->transform)) return FALSE; } } /* If there is only one output component, force the iMCU size to be 1; * else use the source iMCU size. (This allows us to do the right thing * when reducing color to grayscale, and also provides a handy way of * cleaning up "funny" grayscale images whose sampling factors are not 1x1.) */ switch (info->transform) { case JXFORM_TRANSPOSE: case JXFORM_TRANSVERSE: case JXFORM_ROT_90: case JXFORM_ROT_270: info->output_width = srcinfo->output_height; info->output_height = srcinfo->output_width; if (info->num_components == 1) { info->iMCU_sample_width = srcinfo->min_DCT_v_scaled_size; info->iMCU_sample_height = srcinfo->min_DCT_h_scaled_size; } else { info->iMCU_sample_width = srcinfo->max_v_samp_factor * srcinfo->min_DCT_v_scaled_size; info->iMCU_sample_height = srcinfo->max_h_samp_factor * srcinfo->min_DCT_h_scaled_size; } break; default: info->output_width = srcinfo->output_width; info->output_height = srcinfo->output_height; if (info->num_components == 1) { info->iMCU_sample_width = srcinfo->min_DCT_h_scaled_size; info->iMCU_sample_height = srcinfo->min_DCT_v_scaled_size; } else { info->iMCU_sample_width = srcinfo->max_h_samp_factor * srcinfo->min_DCT_h_scaled_size; info->iMCU_sample_height = srcinfo->max_v_samp_factor * srcinfo->min_DCT_v_scaled_size; } break; } /* If cropping has been requested, compute the crop area's position and * dimensions, ensuring that its upper left corner falls at an iMCU boundary. */ if (info->crop) { /* Insert default values for unset crop parameters */ if (info->crop_xoffset_set == JCROP_UNSET) info->crop_xoffset = 0; /* default to +0 */ if (info->crop_yoffset_set == JCROP_UNSET) info->crop_yoffset = 0; /* default to +0 */ if (info->crop_width_set == JCROP_UNSET) { if (info->crop_xoffset >= info->output_width) ERREXIT(srcinfo, JERR_BAD_CROP_SPEC); info->crop_width = info->output_width - info->crop_xoffset; } else { /* Check for crop extension */ if (info->crop_width > info->output_width) { /* Crop extension does not work when transforming! */ if (info->transform != JXFORM_NONE || info->crop_xoffset >= info->crop_width || info->crop_xoffset > info->crop_width - info->output_width) ERREXIT(srcinfo, JERR_BAD_CROP_SPEC); } else { if (info->crop_xoffset >= info->output_width || info->crop_width <= 0 || info->crop_xoffset > info->output_width - info->crop_width) ERREXIT(srcinfo, JERR_BAD_CROP_SPEC); } } if (info->crop_height_set == JCROP_UNSET) { if (info->crop_yoffset >= info->output_height) ERREXIT(srcinfo, JERR_BAD_CROP_SPEC); info->crop_height = info->output_height - info->crop_yoffset; } else { /* Check for crop extension */ if (info->crop_height > info->output_height) { /* Crop extension does not work when transforming! */ if (info->transform != JXFORM_NONE || info->crop_yoffset >= info->crop_height || info->crop_yoffset > info->crop_height - info->output_height) ERREXIT(srcinfo, JERR_BAD_CROP_SPEC); } else { if (info->crop_yoffset >= info->output_height || info->crop_height <= 0 || info->crop_yoffset > info->output_height - info->crop_height) ERREXIT(srcinfo, JERR_BAD_CROP_SPEC); } } /* Convert negative crop offsets into regular offsets */ if (info->crop_xoffset_set != JCROP_NEG) xoffset = info->crop_xoffset; else if (info->crop_width > info->output_width) /* crop extension */ xoffset = info->crop_width - info->output_width - info->crop_xoffset; else xoffset = info->output_width - info->crop_width - info->crop_xoffset; if (info->crop_yoffset_set != JCROP_NEG) yoffset = info->crop_yoffset; else if (info->crop_height > info->output_height) /* crop extension */ yoffset = info->crop_height - info->output_height - info->crop_yoffset; else yoffset = info->output_height - info->crop_height - info->crop_yoffset; /* Now adjust so that upper left corner falls at an iMCU boundary */ if (info->transform == JXFORM_WIPE) { /* Ensure the effective wipe region will cover the requested */ info->drop_width = (JDIMENSION) jdiv_round_up ((long) (info->crop_width + (xoffset % info->iMCU_sample_width)), (long) info->iMCU_sample_width); info->drop_height = (JDIMENSION) jdiv_round_up ((long) (info->crop_height + (yoffset % info->iMCU_sample_height)), (long) info->iMCU_sample_height); } else { /* Ensure the effective crop region will cover the requested */ if (info->crop_width_set == JCROP_FORCE || info->crop_width > info->output_width) info->output_width = info->crop_width; else info->output_width = info->crop_width + (xoffset % info->iMCU_sample_width); if (info->crop_height_set == JCROP_FORCE || info->crop_height > info->output_height) info->output_height = info->crop_height; else info->output_height = info->crop_height + (yoffset % info->iMCU_sample_height); } /* Save x/y offsets measured in iMCUs */ info->x_crop_offset = xoffset / info->iMCU_sample_width; info->y_crop_offset = yoffset / info->iMCU_sample_height; } else { info->x_crop_offset = 0; info->y_crop_offset = 0; } /* Figure out whether we need workspace arrays, * and if so whether they are transposed relative to the source. */ need_workspace = FALSE; transpose_it = FALSE; switch (info->transform) { case JXFORM_NONE: if (info->x_crop_offset != 0 || info->y_crop_offset != 0 || info->output_width > srcinfo->output_width || info->output_height > srcinfo->output_height) need_workspace = TRUE; /* No workspace needed if neither cropping nor transforming */ break; case JXFORM_FLIP_H: if (info->trim) trim_right_edge(info, srcinfo->output_width); if (info->y_crop_offset != 0) need_workspace = TRUE; /* do_flip_h_no_crop doesn't need a workspace array */ break; case JXFORM_FLIP_V: if (info->trim) trim_bottom_edge(info, srcinfo->output_height); /* Need workspace arrays having same dimensions as source image. */ need_workspace = TRUE; break; case JXFORM_TRANSPOSE: /* transpose does NOT have to trim anything */ /* Need workspace arrays having transposed dimensions. */ need_workspace = TRUE; transpose_it = TRUE; break; case JXFORM_TRANSVERSE: if (info->trim) { trim_right_edge(info, srcinfo->output_height); trim_bottom_edge(info, srcinfo->output_width); } /* Need workspace arrays having transposed dimensions. */ need_workspace = TRUE; transpose_it = TRUE; break; case JXFORM_ROT_90: if (info->trim) trim_right_edge(info, srcinfo->output_height); /* Need workspace arrays having transposed dimensions. */ need_workspace = TRUE; transpose_it = TRUE; break; case JXFORM_ROT_180: if (info->trim) { trim_right_edge(info, srcinfo->output_width); trim_bottom_edge(info, srcinfo->output_height); } /* Need workspace arrays having same dimensions as source image. */ need_workspace = TRUE; break; case JXFORM_ROT_270: if (info->trim) trim_bottom_edge(info, srcinfo->output_width); /* Need workspace arrays having transposed dimensions. */ need_workspace = TRUE; transpose_it = TRUE; break; case JXFORM_WIPE: break; } /* Allocate workspace if needed. * Note that we allocate arrays padded out to the next iMCU boundary, * so that transform routines need not worry about missing edge blocks. */ if (need_workspace) { coef_arrays = (jvirt_barray_ptr *) (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE, SIZEOF(jvirt_barray_ptr) * info->num_components); width_in_iMCUs = (JDIMENSION) jdiv_round_up((long) info->output_width, (long) info->iMCU_sample_width); height_in_iMCUs = (JDIMENSION) jdiv_round_up((long) info->output_height, (long) info->iMCU_sample_height); for (ci = 0; ci < info->num_components; ci++) { compptr = srcinfo->comp_info + ci; if (info->num_components == 1) { /* we're going to force samp factors to 1x1 in this case */ h_samp_factor = v_samp_factor = 1; } else if (transpose_it) { h_samp_factor = compptr->v_samp_factor; v_samp_factor = compptr->h_samp_factor; } else { h_samp_factor = compptr->h_samp_factor; v_samp_factor = compptr->v_samp_factor; } width_in_blocks = width_in_iMCUs * h_samp_factor; height_in_blocks = height_in_iMCUs * v_samp_factor; coef_arrays[ci] = (*srcinfo->mem->request_virt_barray) ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE, width_in_blocks, height_in_blocks, (JDIMENSION) v_samp_factor); } info->workspace_coef_arrays = coef_arrays; } else info->workspace_coef_arrays = NULL; return TRUE; } /* Transpose destination image parameters */ LOCAL(void) transpose_critical_parameters (j_compress_ptr dstinfo) { int tblno, i, j, ci, itemp; jpeg_component_info *compptr; JQUANT_TBL *qtblptr; JDIMENSION jtemp; UINT16 qtemp; /* Transpose image dimensions */ jtemp = dstinfo->image_width; dstinfo->image_width = dstinfo->image_height; dstinfo->image_height = jtemp; itemp = dstinfo->min_DCT_h_scaled_size; dstinfo->min_DCT_h_scaled_size = dstinfo->min_DCT_v_scaled_size; dstinfo->min_DCT_v_scaled_size = itemp; /* Transpose sampling factors */ for (ci = 0; ci < dstinfo->num_components; ci++) { compptr = dstinfo->comp_info + ci; itemp = compptr->h_samp_factor; compptr->h_samp_factor = compptr->v_samp_factor; compptr->v_samp_factor = itemp; } /* Transpose quantization tables */ for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) { qtblptr = dstinfo->quant_tbl_ptrs[tblno]; if (qtblptr != NULL) { for (i = 0; i < DCTSIZE; i++) { for (j = 0; j < i; j++) { qtemp = qtblptr->quantval[i*DCTSIZE+j]; qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i]; qtblptr->quantval[j*DCTSIZE+i] = qtemp; } } } } } /* Adjust Exif image parameters. * * We try to adjust the Tags ExifImageWidth and ExifImageHeight if possible. */ LOCAL(void) adjust_exif_parameters (JOCTET FAR * data, unsigned int length, JDIMENSION new_width, JDIMENSION new_height) { boolean is_motorola; /* Flag for byte order */ unsigned int number_of_tags, tagnum; unsigned int firstoffset, offset; JDIMENSION new_value; if (length < 12) return; /* Length of an IFD entry */ /* Discover byte order */ if (GETJOCTET(data[0]) == 0x49 && GETJOCTET(data[1]) == 0x49) is_motorola = FALSE; else if (GETJOCTET(data[0]) == 0x4D && GETJOCTET(data[1]) == 0x4D) is_motorola = TRUE; else return; /* Check Tag Mark */ if (is_motorola) { if (GETJOCTET(data[2]) != 0) return; if (GETJOCTET(data[3]) != 0x2A) return; } else { if (GETJOCTET(data[3]) != 0) return; if (GETJOCTET(data[2]) != 0x2A) return; } /* Get first IFD offset (offset to IFD0) */ if (is_motorola) { if (GETJOCTET(data[4]) != 0) return; if (GETJOCTET(data[5]) != 0) return; firstoffset = GETJOCTET(data[6]); firstoffset <<= 8; firstoffset += GETJOCTET(data[7]); } else { if (GETJOCTET(data[7]) != 0) return; if (GETJOCTET(data[6]) != 0) return; firstoffset = GETJOCTET(data[5]); firstoffset <<= 8; firstoffset += GETJOCTET(data[4]); } if (firstoffset > length - 2) return; /* check end of data segment */ /* Get the number of directory entries contained in this IFD */ if (is_motorola) { number_of_tags = GETJOCTET(data[firstoffset]); number_of_tags <<= 8; number_of_tags += GETJOCTET(data[firstoffset+1]); } else { number_of_tags = GETJOCTET(data[firstoffset+1]); number_of_tags <<= 8; number_of_tags += GETJOCTET(data[firstoffset]); } if (number_of_tags == 0) return; firstoffset += 2; /* Search for ExifSubIFD offset Tag in IFD0 */ for (;;) { if (firstoffset > length - 12) return; /* check end of data segment */ /* Get Tag number */ if (is_motorola) { tagnum = GETJOCTET(data[firstoffset]); tagnum <<= 8; tagnum += GETJOCTET(data[firstoffset+1]); } else { tagnum = GETJOCTET(data[firstoffset+1]); tagnum <<= 8; tagnum += GETJOCTET(data[firstoffset]); } if (tagnum == 0x8769) break; /* found ExifSubIFD offset Tag */ if (--number_of_tags == 0) return; firstoffset += 12; } /* Get the ExifSubIFD offset */ if (is_motorola) { if (GETJOCTET(data[firstoffset+8]) != 0) return; if (GETJOCTET(data[firstoffset+9]) != 0) return; offset = GETJOCTET(data[firstoffset+10]); offset <<= 8; offset += GETJOCTET(data[firstoffset+11]); } else { if (GETJOCTET(data[firstoffset+11]) != 0) return; if (GETJOCTET(data[firstoffset+10]) != 0) return; offset = GETJOCTET(data[firstoffset+9]); offset <<= 8; offset += GETJOCTET(data[firstoffset+8]); } if (offset > length - 2) return; /* check end of data segment */ /* Get the number of directory entries contained in this SubIFD */ if (is_motorola) { number_of_tags = GETJOCTET(data[offset]); number_of_tags <<= 8; number_of_tags += GETJOCTET(data[offset+1]); } else { number_of_tags = GETJOCTET(data[offset+1]); number_of_tags <<= 8; number_of_tags += GETJOCTET(data[offset]); } if (number_of_tags < 2) return; offset += 2; /* Search for ExifImageWidth and ExifImageHeight Tags in this SubIFD */ do { if (offset > length - 12) return; /* check end of data segment */ /* Get Tag number */ if (is_motorola) { tagnum = GETJOCTET(data[offset]); tagnum <<= 8; tagnum += GETJOCTET(data[offset+1]); } else { tagnum = GETJOCTET(data[offset+1]); tagnum <<= 8; tagnum += GETJOCTET(data[offset]); } if (tagnum == 0xA002 || tagnum == 0xA003) { if (tagnum == 0xA002) new_value = new_width; /* ExifImageWidth Tag */ else new_value = new_height; /* ExifImageHeight Tag */ if (is_motorola) { data[offset+2] = 0; /* Format = unsigned long (4 octets) */ data[offset+3] = 4; data[offset+4] = 0; /* Number Of Components = 1 */ data[offset+5] = 0; data[offset+6] = 0; data[offset+7] = 1; data[offset+8] = 0; data[offset+9] = 0; data[offset+10] = (JOCTET)((new_value >> 8) & 0xFF); data[offset+11] = (JOCTET)(new_value & 0xFF); } else { data[offset+2] = 4; /* Format = unsigned long (4 octets) */ data[offset+3] = 0; data[offset+4] = 1; /* Number Of Components = 1 */ data[offset+5] = 0; data[offset+6] = 0; data[offset+7] = 0; data[offset+8] = (JOCTET)(new_value & 0xFF); data[offset+9] = (JOCTET)((new_value >> 8) & 0xFF); data[offset+10] = 0; data[offset+11] = 0; } } offset += 12; } while (--number_of_tags); } /* Adjust output image parameters as needed. * * This must be called after jpeg_copy_critical_parameters() * and before jpeg_write_coefficients(). * * The return value is the set of virtual coefficient arrays to be written * (either the ones allocated by jtransform_request_workspace, or the * original source data arrays). The caller will need to pass this value * to jpeg_write_coefficients(). */ GLOBAL(jvirt_barray_ptr *) jtransform_adjust_parameters (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, jvirt_barray_ptr *src_coef_arrays, jpeg_transform_info *info) { /* If force-to-grayscale is requested, adjust destination parameters */ if (info->force_grayscale) { /* First, ensure we have YCC or grayscale data, and that the source's * Y channel is full resolution. (No reasonable person would make Y * be less than full resolution, so actually coping with that case * isn't worth extra code space. But we check it to avoid crashing.) */ if ((((dstinfo->jpeg_color_space == JCS_YCbCr || dstinfo->jpeg_color_space == JCS_BG_YCC) && dstinfo->num_components == 3) || (dstinfo->jpeg_color_space == JCS_GRAYSCALE && dstinfo->num_components == 1)) && srcinfo->comp_info[0].h_samp_factor == srcinfo->max_h_samp_factor && srcinfo->comp_info[0].v_samp_factor == srcinfo->max_v_samp_factor) { /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed * properly. Among other things, it sets the target h_samp_factor & * v_samp_factor to 1, which typically won't match the source. * We have to preserve the source's quantization table number, however. */ int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no; jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE); dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no; } else { /* Sorry, can't do it */ ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL); } } else if (info->num_components == 1) { /* For a single-component source, we force the destination sampling factors * to 1x1, with or without force_grayscale. This is useful because some * decoders choke on grayscale images with other sampling factors. */ dstinfo->comp_info[0].h_samp_factor = 1; dstinfo->comp_info[0].v_samp_factor = 1; } /* Correct the destination's image dimensions as necessary * for rotate/flip, resize, and crop operations. */ dstinfo->jpeg_width = info->output_width; dstinfo->jpeg_height = info->output_height; /* Transpose destination image parameters */ switch (info->transform) { case JXFORM_TRANSPOSE: case JXFORM_TRANSVERSE: case JXFORM_ROT_90: case JXFORM_ROT_270: transpose_critical_parameters(dstinfo); break; default: break; } /* Adjust Exif properties */ if (srcinfo->marker_list != NULL && srcinfo->marker_list->marker == JPEG_APP0+1 && srcinfo->marker_list->data_length >= 6 && GETJOCTET(srcinfo->marker_list->data[0]) == 0x45 && GETJOCTET(srcinfo->marker_list->data[1]) == 0x78 && GETJOCTET(srcinfo->marker_list->data[2]) == 0x69 && GETJOCTET(srcinfo->marker_list->data[3]) == 0x66 && GETJOCTET(srcinfo->marker_list->data[4]) == 0 && GETJOCTET(srcinfo->marker_list->data[5]) == 0) { /* Suppress output of JFIF marker */ dstinfo->write_JFIF_header = FALSE; /* Adjust Exif image parameters */ if (dstinfo->jpeg_width != srcinfo->image_width || dstinfo->jpeg_height != srcinfo->image_height) /* Align data segment to start of TIFF structure for parsing */ adjust_exif_parameters(srcinfo->marker_list->data + 6, srcinfo->marker_list->data_length - 6, dstinfo->jpeg_width, dstinfo->jpeg_height); } /* Return the appropriate output data set */ if (info->workspace_coef_arrays != NULL) return info->workspace_coef_arrays; return src_coef_arrays; } /* Execute the actual transformation, if any. * * This must be called *after* jpeg_write_coefficients, because it depends * on jpeg_write_coefficients to have computed subsidiary values such as * the per-component width and height fields in the destination object. * * Note that some transformations will modify the source data arrays! */ GLOBAL(void) jtransform_execute_transform (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, jvirt_barray_ptr *src_coef_arrays, jpeg_transform_info *info) { jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays; /* Note: conditions tested here should match those in switch statement * in jtransform_request_workspace() */ switch (info->transform) { case JXFORM_NONE: if (info->output_width > srcinfo->output_width || info->output_height > srcinfo->output_height) do_crop_ext(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); else if (info->x_crop_offset != 0 || info->y_crop_offset != 0) do_crop(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); break; case JXFORM_FLIP_H: if (info->y_crop_offset != 0) do_flip_h(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); else do_flip_h_no_crop(srcinfo, dstinfo, info->x_crop_offset, src_coef_arrays); break; case JXFORM_FLIP_V: do_flip_v(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); break; case JXFORM_TRANSPOSE: do_transpose(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); break; case JXFORM_TRANSVERSE: do_transverse(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); break; case JXFORM_ROT_90: do_rot_90(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); break; case JXFORM_ROT_180: do_rot_180(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); break; case JXFORM_ROT_270: do_rot_270(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, dst_coef_arrays); break; case JXFORM_WIPE: do_wipe(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset, src_coef_arrays, info->drop_width, info->drop_height); break; } } /* jtransform_perfect_transform * * Determine whether lossless transformation is perfectly * possible for a specified image and transformation. * * Inputs: * image_width, image_height: source image dimensions. * MCU_width, MCU_height: pixel dimensions of MCU. * transform: transformation identifier. * Parameter sources from initialized jpeg_struct * (after reading source header): * image_width = cinfo.image_width * image_height = cinfo.image_height * MCU_width = cinfo.max_h_samp_factor * cinfo.block_size * MCU_height = cinfo.max_v_samp_factor * cinfo.block_size * Result: * TRUE = perfect transformation possible * FALSE = perfect transformation not possible * (may use custom action then) */ GLOBAL(boolean) jtransform_perfect_transform(JDIMENSION image_width, JDIMENSION image_height, int MCU_width, int MCU_height, JXFORM_CODE transform) { boolean result = TRUE; /* initialize TRUE */ switch (transform) { case JXFORM_FLIP_H: case JXFORM_ROT_270: if (image_width % (JDIMENSION) MCU_width) result = FALSE; break; case JXFORM_FLIP_V: case JXFORM_ROT_90: if (image_height % (JDIMENSION) MCU_height) result = FALSE; break; case JXFORM_TRANSVERSE: case JXFORM_ROT_180: if (image_width % (JDIMENSION) MCU_width) result = FALSE; if (image_height % (JDIMENSION) MCU_height) result = FALSE; break; default: break; } return result; } #endif /* TRANSFORMS_SUPPORTED */ /* Setup decompression object to save desired markers in memory. * This must be called before jpeg_read_header() to have the desired effect. */ GLOBAL(void) jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option) { #ifdef SAVE_MARKERS_SUPPORTED int m; /* Save comments except under NONE option */ if (option != JCOPYOPT_NONE) { jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF); } /* Save all types of APPn markers iff ALL option */ if (option == JCOPYOPT_ALL) { for (m = 0; m < 16; m++) jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF); } #endif /* SAVE_MARKERS_SUPPORTED */ } /* Copy markers saved in the given source object to the destination object. * This should be called just after jpeg_start_compress() or * jpeg_write_coefficients(). * Note that those routines will have written the SOI, and also the * JFIF APP0 or Adobe APP14 markers if selected. */ GLOBAL(void) jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JCOPY_OPTION option) { jpeg_saved_marker_ptr marker; /* In the current implementation, we don't actually need to examine the * option flag here; we just copy everything that got saved. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers * if the encoder library already wrote one. */ for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) { if (dstinfo->write_JFIF_header && marker->marker == JPEG_APP0 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x4A && GETJOCTET(marker->data[1]) == 0x46 && GETJOCTET(marker->data[2]) == 0x49 && GETJOCTET(marker->data[3]) == 0x46 && GETJOCTET(marker->data[4]) == 0) continue; /* reject duplicate JFIF */ if (dstinfo->write_Adobe_marker && marker->marker == JPEG_APP0+14 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x41 && GETJOCTET(marker->data[1]) == 0x64 && GETJOCTET(marker->data[2]) == 0x6F && GETJOCTET(marker->data[3]) == 0x62 && GETJOCTET(marker->data[4]) == 0x65) continue; /* reject duplicate Adobe */ #ifdef NEED_FAR_POINTERS /* We could use jpeg_write_marker if the data weren't FAR... */ { unsigned int i; jpeg_write_m_header(dstinfo, marker->marker, marker->data_length); for (i = 0; i < marker->data_length; i++) jpeg_write_m_byte(dstinfo, marker->data[i]); } #else jpeg_write_marker(dstinfo, marker->marker, marker->data, marker->data_length); #endif } } ================================================ FILE: tess-two/jni/libjpeg/transupp.h ================================================ /* * transupp.h * * Copyright (C) 1997-2013, Thomas G. Lane, Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains declarations for image transformation routines and * other utility code used by the jpegtran sample application. These are * NOT part of the core JPEG library. But we keep these routines separate * from jpegtran.c to ease the task of maintaining jpegtran-like programs * that have other user interfaces. * * NOTE: all the routines declared here have very specific requirements * about when they are to be executed during the reading and writing of the * source and destination files. See the comments in transupp.c, or see * jpegtran.c for an example of correct usage. */ /* If you happen not to want the image transform support, disable it here */ #ifndef TRANSFORMS_SUPPORTED #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */ #endif /* * Although rotating and flipping data expressed as DCT coefficients is not * hard, there is an asymmetry in the JPEG format specification for images * whose dimensions aren't multiples of the iMCU size. The right and bottom * image edges are padded out to the next iMCU boundary with junk data; but * no padding is possible at the top and left edges. If we were to flip * the whole image including the pad data, then pad garbage would become * visible at the top and/or left, and real pixels would disappear into the * pad margins --- perhaps permanently, since encoders & decoders may not * bother to preserve DCT blocks that appear to be completely outside the * nominal image area. So, we have to exclude any partial iMCUs from the * basic transformation. * * Transpose is the only transformation that can handle partial iMCUs at the * right and bottom edges completely cleanly. flip_h can flip partial iMCUs * at the bottom, but leaves any partial iMCUs at the right edge untouched. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched. * The other transforms are defined as combinations of these basic transforms * and process edge blocks in a way that preserves the equivalence. * * The "trim" option causes untransformable partial iMCUs to be dropped; * this is not strictly lossless, but it usually gives the best-looking * result for odd-size images. Note that when this option is active, * the expected mathematical equivalences between the transforms may not hold. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim * followed by -rot 180 -trim trims both edges.) * * We also offer a lossless-crop option, which discards data outside a given * image region but losslessly preserves what is inside. Like the rotate and * flip transforms, lossless crop is restricted by the current JPEG format: the * upper left corner of the selected region must fall on an iMCU boundary. If * this does not hold for the given crop parameters, we silently move the upper * left corner up and/or left to make it so, simultaneously increasing the * region dimensions to keep the lower right crop corner unchanged. (Thus, the * output image covers at least the requested region, but may cover more.) * The adjustment of the region dimensions may be optionally disabled. * * A complementary lossless-wipe option is provided to discard (gray out) data * inside a given image region while losslessly preserving what is outside. * * We also provide a lossless-resize option, which is kind of a lossless-crop * operation in the DCT coefficient block domain - it discards higher-order * coefficients and losslessly preserves lower-order coefficients of a * sub-block. * * Rotate/flip transform, resize, and crop can be requested together in a * single invocation. The crop is applied last --- that is, the crop region * is specified in terms of the destination image after transform/resize. * * We also offer a "force to grayscale" option, which simply discards the * chrominance channels of a YCbCr image. This is lossless in the sense that * the luminance channel is preserved exactly. It's not the same kind of * thing as the rotate/flip transformations, but it's convenient to handle it * as part of this package, mainly because the transformation routines have to * be aware of the option to know how many components to work on. */ /* Short forms of external names for systems with brain-damaged linkers. */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jtransform_parse_crop_spec jTrParCrop #define jtransform_request_workspace jTrRequest #define jtransform_adjust_parameters jTrAdjust #define jtransform_execute_transform jTrExec #define jtransform_perfect_transform jTrPerfect #define jcopy_markers_setup jCMrkSetup #define jcopy_markers_execute jCMrkExec #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* * Codes for supported types of image transformations. */ typedef enum { JXFORM_NONE, /* no transformation */ JXFORM_FLIP_H, /* horizontal flip */ JXFORM_FLIP_V, /* vertical flip */ JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */ JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */ JXFORM_ROT_90, /* 90-degree clockwise rotation */ JXFORM_ROT_180, /* 180-degree rotation */ JXFORM_ROT_270, /* 270-degree clockwise (or 90 ccw) */ JXFORM_WIPE /* wipe */ } JXFORM_CODE; /* * Codes for crop parameters, which can individually be unspecified, * positive or negative for xoffset or yoffset, * positive or forced for width or height. */ typedef enum { JCROP_UNSET, JCROP_POS, JCROP_NEG, JCROP_FORCE } JCROP_CODE; /* * Transform parameters struct. * NB: application must not change any elements of this struct after * calling jtransform_request_workspace. */ typedef struct { /* Options: set by caller */ JXFORM_CODE transform; /* image transform operator */ boolean perfect; /* if TRUE, fail if partial MCUs are requested */ boolean trim; /* if TRUE, trim partial MCUs as needed */ boolean force_grayscale; /* if TRUE, convert color image to grayscale */ boolean crop; /* if TRUE, crop or wipe source image */ /* Crop parameters: application need not set these unless crop is TRUE. * These can be filled in by jtransform_parse_crop_spec(). */ JDIMENSION crop_width; /* Width of selected region */ JCROP_CODE crop_width_set; /* (forced disables adjustment) */ JDIMENSION crop_height; /* Height of selected region */ JCROP_CODE crop_height_set; /* (forced disables adjustment) */ JDIMENSION crop_xoffset; /* X offset of selected region */ JCROP_CODE crop_xoffset_set; /* (negative measures from right edge) */ JDIMENSION crop_yoffset; /* Y offset of selected region */ JCROP_CODE crop_yoffset_set; /* (negative measures from bottom edge) */ /* Internal workspace: caller should not touch these */ int num_components; /* # of components in workspace */ jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */ JDIMENSION output_width; /* cropped destination dimensions */ JDIMENSION output_height; JDIMENSION x_crop_offset; /* destination crop offsets measured in iMCUs */ JDIMENSION y_crop_offset; JDIMENSION drop_width; /* drop/wipe dimensions measured in iMCUs */ JDIMENSION drop_height; int iMCU_sample_width; /* destination iMCU size */ int iMCU_sample_height; } jpeg_transform_info; #if TRANSFORMS_SUPPORTED /* Parse a crop specification (written in X11 geometry style) */ EXTERN(boolean) jtransform_parse_crop_spec JPP((jpeg_transform_info *info, const char *spec)); /* Request any required workspace */ EXTERN(boolean) jtransform_request_workspace JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info)); /* Adjust output image parameters */ EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo, jvirt_barray_ptr *src_coef_arrays, jpeg_transform_info *info)); /* Execute the actual transformation, if any */ EXTERN(void) jtransform_execute_transform JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo, jvirt_barray_ptr *src_coef_arrays, jpeg_transform_info *info)); /* Determine whether lossless transformation is perfectly * possible for a specified image and transformation. */ EXTERN(boolean) jtransform_perfect_transform JPP((JDIMENSION image_width, JDIMENSION image_height, int MCU_width, int MCU_height, JXFORM_CODE transform)); /* jtransform_execute_transform used to be called * jtransform_execute_transformation, but some compilers complain about * routine names that long. This macro is here to avoid breaking any * old source code that uses the original name... */ #define jtransform_execute_transformation jtransform_execute_transform #endif /* TRANSFORMS_SUPPORTED */ /* * Support for copying optional markers from source to destination file. */ typedef enum { JCOPYOPT_NONE, /* copy no optional markers */ JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */ JCOPYOPT_ALL /* copy all optional markers */ } JCOPY_OPTION; #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */ /* Setup decompression object to save desired markers in memory */ EXTERN(void) jcopy_markers_setup JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option)); /* Copy markers saved in the given source object to the destination object */ EXTERN(void) jcopy_markers_execute JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo, JCOPY_OPTION option)); ================================================ FILE: tess-two/jni/libjpeg/usage.txt ================================================ USAGE instructions for the Independent JPEG Group's JPEG software ================================================================= This file describes usage of the JPEG conversion programs cjpeg and djpeg, as well as the utility programs jpegtran, rdjpgcom and wrjpgcom. (See the other documentation files if you wish to use the JPEG library within your own programs.) If you are on a Unix machine you may prefer to read the Unix-style manual pages in files cjpeg.1, djpeg.1, jpegtran.1, rdjpgcom.1, wrjpgcom.1. INTRODUCTION These programs implement JPEG image encoding, decoding, and transcoding. JPEG (pronounced "jay-peg") is a standardized compression method for full-color and grayscale images. GENERAL USAGE We provide two programs, cjpeg to compress an image file into JPEG format, and djpeg to decompress a JPEG file back into a conventional image format. On Unix-like systems, you say: cjpeg [switches] [imagefile] >jpegfile or djpeg [switches] [jpegfile] >imagefile The programs read the specified input file, or standard input if none is named. They always write to standard output (with trace/error messages to standard error). These conventions are handy for piping images between programs. On most non-Unix systems, you say: cjpeg [switches] imagefile jpegfile or djpeg [switches] jpegfile imagefile i.e., both the input and output files are named on the command line. This style is a little more foolproof, and it loses no functionality if you don't have pipes. (You can get this style on Unix too, if you prefer, by defining TWO_FILE_COMMANDLINE when you compile the programs; see install.txt.) You can also say: cjpeg [switches] -outfile jpegfile imagefile or djpeg [switches] -outfile imagefile jpegfile This syntax works on all systems, so it is useful for scripts. The currently supported image file formats are: PPM (PBMPLUS color format), PGM (PBMPLUS grayscale format), BMP, Targa, and RLE (Utah Raster Toolkit format). (RLE is supported only if the URT library is available, which it isn't on most non-Unix systems.) cjpeg recognizes the input image format automatically, with the exception of some Targa-format files. You have to tell djpeg which format to generate. JPEG files are in the standard JFIF file format. There are other, less widely used JPEG-based file formats, but we don't support them. All switch names may be abbreviated; for example, -grayscale may be written -gray or -gr. Most of the "basic" switches can be abbreviated to as little as one letter. Upper and lower case are equivalent (-BMP is the same as -bmp). British spellings are also accepted (e.g., -greyscale), though for brevity these are not mentioned below. CJPEG DETAILS The basic command line switches for cjpeg are: -quality N[,...] Scale quantization tables to adjust image quality. Quality is 0 (worst) to 100 (best); default is 75. (See below for more info.) -grayscale Create monochrome JPEG file from color input. Be sure to use this switch when compressing a grayscale BMP file, because cjpeg isn't bright enough to notice whether a BMP file uses only shades of gray. By saying -grayscale, you'll get a smaller JPEG file that takes less time to process. -rgb Create RGB JPEG file. Using this switch suppresses the conversion from RGB colorspace input to the default YCbCr JPEG colorspace. You can use this switch in combination with the -block N switch (see below) for lossless JPEG coding. See also the -rgb1 switch below. -optimize Perform optimization of entropy encoding parameters. Without this, default encoding parameters are used. -optimize usually makes the JPEG file a little smaller, but cjpeg runs somewhat slower and needs much more memory. Image quality and speed of decompression are unaffected by -optimize. -progressive Create progressive JPEG file (see below). -scale M/N Scale the output image by a factor M/N. Currently supported scale factors are M/N with all N from 1 to 16, where M is the destination DCT size, which is 8 by default (see -block N switch below). -targa Input file is Targa format. Targa files that contain an "identification" field will not be automatically recognized by cjpeg; for such files you must specify -targa to make cjpeg treat the input as Targa format. For most Targa files, you won't need this switch. The -quality switch lets you trade off compressed file size against quality of the reconstructed image: the higher the quality setting, the larger the JPEG file, and the closer the output image will be to the original input. Normally you want to use the lowest quality setting (smallest file) that decompresses into something visually indistinguishable from the original image. For this purpose the quality setting should be between 50 and 95; the default of 75 is often about right. If you see defects at -quality 75, then go up 5 or 10 counts at a time until you are happy with the output image. (The optimal setting will vary from one image to another.) -quality 100 will generate a quantization table of all 1's, minimizing loss in the quantization step (but there is still information loss in subsampling, as well as roundoff error). This setting is mainly of interest for experimental purposes. Quality values above about 95 are NOT recommended for normal use; the compressed file size goes up dramatically for hardly any gain in output image quality. In the other direction, quality values below 50 will produce very small files of low image quality. Settings around 5 to 10 might be useful in preparing an index of a large image library, for example. Try -quality 2 (or so) for some amusing Cubist effects. (Note: quality values below about 25 generate 2-byte quantization tables, which are considered optional in the JPEG standard. cjpeg emits a warning message when you give such a quality value, because some other JPEG programs may be unable to decode the resulting file. Use -baseline if you need to ensure compatibility at low quality values.) The -quality option has been extended in IJG version 7 for support of separate quality settings for luminance and chrominance (or in general, for every provided quantization table slot). This feature is useful for high-quality applications which cannot accept the damage of color data by coarse subsampling settings. You can now easily reduce the color data amount more smoothly with finer control without separate subsampling. The resulting file is fully compliant with standard JPEG decoders. Note that the -quality ratings refer to the quantization table slots, and that the last value is replicated if there are more q-table slots than parameters. The default q-table slots are 0 for luminance and 1 for chrominance with default tables as given in the JPEG standard. This is compatible with the old behaviour in case that only one parameter is given, which is then used for both luminance and chrominance (slots 0 and 1). More or custom quantization tables can be set with -qtables and assigned to components with -qslots parameter (see the "wizard" switches below). CAUTION: You must explicitly add -sample 1x1 for efficient separate color quality selection, since the default value used by library is 2x2! The -progressive switch creates a "progressive JPEG" file. In this type of JPEG file, the data is stored in multiple scans of increasing quality. If the file is being transmitted over a slow communications link, the decoder can use the first scan to display a low-quality image very quickly, and can then improve the display with each subsequent scan. The final image is exactly equivalent to a standard JPEG file of the same quality setting, and the total file size is about the same --- often a little smaller. Switches for advanced users: -arithmetic Use arithmetic coding. CAUTION: arithmetic coded JPEG is not yet widely implemented, so many decoders will be unable to view an arithmetic coded JPEG file at all. -block N Set DCT block size. All N from 1 to 16 are possible. Default is 8 (baseline format). Larger values produce higher compression, smaller values produce higher quality (exact DCT stage possible with 1 or 2; with the default quality of 75 and default Luminance qtable the DCT+Quantization stage is lossless for N=1). CAUTION: An implementation of the JPEG SmartScale extension is required for this feature. SmartScale enabled JPEG is not yet widely implemented, so many decoders will be unable to view a SmartScale extended JPEG file at all. -rgb1 Create RGB JPEG file with reversible color transform. Works like the -rgb switch (see above) and inserts a simple reversible color transform into the processing which significantly improves the compression. Use this switch in combination with the -block N switch (see above) for lossless JPEG coding. CAUTION: A decoder with inverse color transform support is required for this feature. Reversible color transform support is not yet widely implemented, so many decoders will be unable to view a reversible color transformed JPEG file at all. -bgycc Create big gamut YCC JPEG file. In this type of encoding the color difference components are quantized further by a factor of 2 compared to the normal Cb/Cr values, thus creating space to allow larger color values with higher saturation than the normal gamut limits to be encoded. In order to compensate for the loss of color fidelity compared to a normal YCC encoded file, the color quantization tables can be adjusted accordingly. For example, cjpeg -bgycc -quality 80,90 will give similar results as cjpeg -quality 80. CAUTION: For correct decompression a decoder with big gamut YCC support (JFIF version 2) is required. An old decoder may or may not display a big gamut YCC encoded JPEG file, depending on JFIF version check and corresponding warning/error configuration. In case of a granted decompression the old decoder will display the image with half saturated colors. -dct int Use integer DCT method (default). -dct fast Use fast integer DCT (less accurate). -dct float Use floating-point DCT method. The float method is very slightly more accurate than the int method, but is much slower unless your machine has very fast floating-point hardware. Also note that results of the floating-point method may vary slightly across machines, while the integer methods should give the same results everywhere. The fast integer method is much less accurate than the other two. -nosmooth Don't use high-quality downsampling. -restart N Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if "B" is attached to the number. -restart 0 (the default) means no restart markers. -smooth N Smooth the input image to eliminate dithering noise. N, ranging from 1 to 100, indicates the strength of smoothing. 0 (the default) means no smoothing. -maxmemory N Set limit for amount of memory to use in processing large images. Value is in thousands of bytes, or millions of bytes if "M" is attached to the number. For example, -max 4m selects 4000000 bytes. If more space is needed, temporary files will be used. -verbose Enable debug printout. More -v's give more printout. or -debug Also, version information is printed at startup. The -restart option inserts extra markers that allow a JPEG decoder to resynchronize after a transmission error. Without restart markers, any damage to a compressed file will usually ruin the image from the point of the error to the end of the image; with restart markers, the damage is usually confined to the portion of the image up to the next restart marker. Of course, the restart markers occupy extra space. We recommend -restart 1 for images that will be transmitted across unreliable networks such as Usenet. The -smooth option filters the input to eliminate fine-scale noise. This is often useful when converting dithered images to JPEG: a moderate smoothing factor of 10 to 50 gets rid of dithering patterns in the input file, resulting in a smaller JPEG file and a better-looking image. Too large a smoothing factor will visibly blur the image, however. Switches for wizards: -baseline Force baseline-compatible quantization tables to be generated. This clamps quantization values to 8 bits even at low quality settings. (This switch is poorly named, since it does not ensure that the output is actually baseline JPEG. For example, you can use -baseline and -progressive together.) -qtables file Use the quantization tables given in the specified text file. -qslots N[,...] Select which quantization table to use for each color component. -sample HxV[,...] Set JPEG sampling factors for each color component. -scans file Use the scan script given in the specified text file. The "wizard" switches are intended for experimentation with JPEG. If you don't know what you are doing, DON'T USE THEM. These switches are documented further in the file wizard.txt. DJPEG DETAILS The basic command line switches for djpeg are: -colors N Reduce image to at most N colors. This reduces the or -quantize N number of colors used in the output image, so that it can be displayed on a colormapped display or stored in a colormapped file format. For example, if you have an 8-bit display, you'd need to reduce to 256 or fewer colors. (-colors is the recommended name, -quantize is provided only for backwards compatibility.) -fast Select recommended processing options for fast, low quality output. (The default options are chosen for highest quality output.) Currently, this is equivalent to "-dct fast -nosmooth -onepass -dither ordered". -grayscale Force grayscale output even if JPEG file is color. Useful for viewing on monochrome displays; also, djpeg runs noticeably faster in this mode. -rgb Force RGB output even if JPEG file is grayscale. This is provided to support applications that don't want to cope with grayscale as a separate case. -scale M/N Scale the output image by a factor M/N. Currently supported scale factors are M/N with all M from 1 to 16, where N is the source DCT size, which is 8 for baseline JPEG. If the /N part is omitted, then M specifies the DCT scaled size to be applied on the given input. For baseline JPEG this is equivalent to M/8 scaling, since the source DCT size for baseline JPEG is 8. Scaling is handy if the image is larger than your screen; also, djpeg runs much faster when scaling down the output. -bmp Select BMP output format (Windows flavor). 8-bit colormapped format is emitted if -colors or -grayscale is specified, or if the JPEG file is grayscale; otherwise, 24-bit full-color format is emitted. -gif Select GIF output format. Since GIF does not support more than 256 colors, -colors 256 is assumed (unless you specify a smaller number of colors). If you specify -fast, the default number of colors is 216. -os2 Select BMP output format (OS/2 1.x flavor). 8-bit colormapped format is emitted if -colors or -grayscale is specified, or if the JPEG file is grayscale; otherwise, 24-bit full-color format is emitted. -pnm Select PBMPLUS (PPM/PGM) output format (this is the default format). PGM is emitted if the JPEG file is grayscale or if -grayscale is specified; otherwise PPM is emitted. -rle Select RLE output format. (Requires URT library.) -targa Select Targa output format. Grayscale format is emitted if the JPEG file is grayscale or if -grayscale is specified; otherwise, colormapped format is emitted if -colors is specified; otherwise, 24-bit full-color format is emitted. Switches for advanced users: -dct int Use integer DCT method (default). -dct fast Use fast integer DCT (less accurate). -dct float Use floating-point DCT method. The float method is very slightly more accurate than the int method, but is much slower unless your machine has very fast floating-point hardware. Also note that results of the floating-point method may vary slightly across machines, while the integer methods should give the same results everywhere. The fast integer method is much less accurate than the other two. -dither fs Use Floyd-Steinberg dithering in color quantization. -dither ordered Use ordered dithering in color quantization. -dither none Do not use dithering in color quantization. By default, Floyd-Steinberg dithering is applied when quantizing colors; this is slow but usually produces the best results. Ordered dither is a compromise between speed and quality; no dithering is fast but usually looks awful. Note that these switches have no effect unless color quantization is being done. Ordered dither is only available in -onepass mode. -map FILE Quantize to the colors used in the specified image file. This is useful for producing multiple files with identical color maps, or for forcing a predefined set of colors to be used. The FILE must be a GIF or PPM file. This option overrides -colors and -onepass. -nosmooth Don't use high-quality upsampling. -onepass Use one-pass instead of two-pass color quantization. The one-pass method is faster and needs less memory, but it produces a lower-quality image. -onepass is ignored unless you also say -colors N. Also, the one-pass method is always used for grayscale output (the two-pass method is no improvement then). -maxmemory N Set limit for amount of memory to use in processing large images. Value is in thousands of bytes, or millions of bytes if "M" is attached to the number. For example, -max 4m selects 4000000 bytes. If more space is needed, temporary files will be used. -verbose Enable debug printout. More -v's give more printout. or -debug Also, version information is printed at startup. HINTS FOR CJPEG Color GIF files are not the ideal input for JPEG; JPEG is really intended for compressing full-color (24-bit) images. In particular, don't try to convert cartoons, line drawings, and other images that have only a few distinct colors. GIF works great on these, JPEG does not. If you want to convert a GIF to JPEG, you should experiment with cjpeg's -quality and -smooth options to get a satisfactory conversion. -smooth 10 or so is often helpful. Avoid running an image through a series of JPEG compression/decompression cycles. Image quality loss will accumulate; after ten or so cycles the image may be noticeably worse than it was after one cycle. It's best to use a lossless format while manipulating an image, then convert to JPEG format when you are ready to file the image away. The -optimize option to cjpeg is worth using when you are making a "final" version for posting or archiving. It's also a win when you are using low quality settings to make very small JPEG files; the percentage improvement is often a lot more than it is on larger files. (At present, -optimize mode is always selected when generating progressive JPEG files.) GIF input files are no longer supported, to avoid the Unisys LZW patent (now expired). (Conversion of GIF files to JPEG is usually a bad idea anyway.) HINTS FOR DJPEG To get a quick preview of an image, use the -grayscale and/or -scale switches. "-grayscale -scale 1/8" is the fastest case. Several options are available that trade off image quality to gain speed. "-fast" turns on the recommended settings. "-dct fast" and/or "-nosmooth" gain speed at a small sacrifice in quality. When producing a color-quantized image, "-onepass -dither ordered" is fast but much lower quality than the default behavior. "-dither none" may give acceptable results in two-pass mode, but is seldom tolerable in one-pass mode. If you are fortunate enough to have very fast floating point hardware, "-dct float" may be even faster than "-dct fast". But on most machines "-dct float" is slower than "-dct int"; in this case it is not worth using, because its theoretical accuracy advantage is too small to be significant in practice. Two-pass color quantization requires a good deal of memory; on MS-DOS machines it may run out of memory even with -maxmemory 0. In that case you can still decompress, with some loss of image quality, by specifying -onepass for one-pass quantization. To avoid the Unisys LZW patent (now expired), djpeg produces uncompressed GIF files. These are larger than they should be, but are readable by standard GIF decoders. HINTS FOR BOTH PROGRAMS If more space is needed than will fit in the available main memory (as determined by -maxmemory), temporary files will be used. (MS-DOS versions will try to get extended or expanded memory first.) The temporary files are often rather large: in typical cases they occupy three bytes per pixel, for example 3*800*600 = 1.44Mb for an 800x600 image. If you don't have enough free disk space, leave out -progressive and -optimize (for cjpeg) or specify -onepass (for djpeg). On MS-DOS, the temporary files are created in the directory named by the TMP or TEMP environment variable, or in the current directory if neither of those exist. Amiga implementations put the temp files in the directory named by JPEGTMP:, so be sure to assign JPEGTMP: to a disk partition with adequate free space. The default memory usage limit (-maxmemory) is set when the software is compiled. If you get an "insufficient memory" error, try specifying a smaller -maxmemory value, even -maxmemory 0 to use the absolute minimum space. You may want to recompile with a smaller default value if this happens often. On machines that have "environment" variables, you can define the environment variable JPEGMEM to set the default memory limit. The value is specified as described for the -maxmemory switch. JPEGMEM overrides the default value specified when the program was compiled, and itself is overridden by an explicit -maxmemory switch. On MS-DOS machines, -maxmemory is the amount of main (conventional) memory to use. (Extended or expanded memory is also used if available.) Most DOS-specific versions of this software do their own memory space estimation and do not need you to specify -maxmemory. JPEGTRAN jpegtran performs various useful transformations of JPEG files. It can translate the coded representation from one variant of JPEG to another, for example from baseline JPEG to progressive JPEG or vice versa. It can also perform some rearrangements of the image data, for example turning an image from landscape to portrait format by rotation. For EXIF files and JPEG files containing Exif data, you may prefer to use exiftran instead. jpegtran works by rearranging the compressed data (DCT coefficients), without ever fully decoding the image. Therefore, its transformations are lossless: there is no image degradation at all, which would not be true if you used djpeg followed by cjpeg to accomplish the same conversion. But by the same token, jpegtran cannot perform lossy operations such as changing the image quality. However, while the image data is losslessly transformed, metadata can be removed. See the -copy option for specifics. jpegtran uses a command line syntax similar to cjpeg or djpeg. On Unix-like systems, you say: jpegtran [switches] [inputfile] >outputfile On most non-Unix systems, you say: jpegtran [switches] inputfile outputfile where both the input and output files are JPEG files. To specify the coded JPEG representation used in the output file, jpegtran accepts a subset of the switches recognized by cjpeg: -optimize Perform optimization of entropy encoding parameters. -progressive Create progressive JPEG file. -arithmetic Use arithmetic coding. -restart N Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if "B" is attached to the number. -scans file Use the scan script given in the specified text file. See the previous discussion of cjpeg for more details about these switches. If you specify none of these switches, you get a plain baseline-JPEG output file. The quality setting and so forth are determined by the input file. The image can be losslessly transformed by giving one of these switches: -flip horizontal Mirror image horizontally (left-right). -flip vertical Mirror image vertically (top-bottom). -rotate 90 Rotate image 90 degrees clockwise. -rotate 180 Rotate image 180 degrees. -rotate 270 Rotate image 270 degrees clockwise (or 90 ccw). -transpose Transpose image (across UL-to-LR axis). -transverse Transverse transpose (across UR-to-LL axis). The transpose transformation has no restrictions regarding image dimensions. The other transformations operate rather oddly if the image dimensions are not a multiple of the iMCU size (usually 8 or 16 pixels), because they can only transform complete blocks of DCT coefficient data in the desired way. jpegtran's default behavior when transforming an odd-size image is designed to preserve exact reversibility and mathematical consistency of the transformation set. As stated, transpose is able to flip the entire image area. Horizontal mirroring leaves any partial iMCU column at the right edge untouched, but is able to flip all rows of the image. Similarly, vertical mirroring leaves any partial iMCU row at the bottom edge untouched, but is able to flip all columns. The other transforms can be built up as sequences of transpose and flip operations; for consistency, their actions on edge pixels are defined to be the same as the end result of the corresponding transpose-and-flip sequence. For practical use, you may prefer to discard any untransformable edge pixels rather than having a strange-looking strip along the right and/or bottom edges of a transformed image. To do this, add the -trim switch: -trim Drop non-transformable edge blocks. Obviously, a transformation with -trim is not reversible, so strictly speaking jpegtran with this switch is not lossless. Also, the expected mathematical equivalences between the transformations no longer hold. For example, "-rot 270 -trim" trims only the bottom edge, but "-rot 90 -trim" followed by "-rot 180 -trim" trims both edges. If you are only interested in perfect transformation, add the -perfect switch: -perfect Fails with an error if the transformation is not perfect. For example you may want to do jpegtran -rot 90 -perfect foo.jpg || djpeg foo.jpg | pnmflip -r90 | cjpeg to do a perfect rotation if available or an approximated one if not. We also offer a lossless-crop option, which discards data outside a given image region but losslessly preserves what is inside. Like the rotate and flip transforms, lossless crop is restricted by the current JPEG format: the upper left corner of the selected region must fall on an iMCU boundary. If this does not hold for the given crop parameters, we silently move the upper left corner up and/or left to make it so, simultaneously increasing the region dimensions to keep the lower right crop corner unchanged. (Thus, the output image covers at least the requested region, but may cover more.) The adjustment of the region dimensions may be optionally disabled by attaching an 'f' character ("force") to the width or height number. The image can be losslessly cropped by giving the switch: -crop WxH+X+Y Crop to a rectangular subarea of width W, height H starting at point X,Y. A complementary lossless-wipe option is provided to discard (gray out) data inside a given image region while losslessly preserving what is outside: -wipe WxH+X+Y Wipe (gray out) a rectangular subarea of width W, height H starting at point X,Y. Other not-strictly-lossless transformation switches are: -grayscale Force grayscale output. This option discards the chrominance channels if the input image is YCbCr (ie, a standard color JPEG), resulting in a grayscale JPEG file. The luminance channel is preserved exactly, so this is a better method of reducing to grayscale than decompression, conversion, and recompression. This switch is particularly handy for fixing a monochrome picture that was mistakenly encoded as a color JPEG. (In such a case, the space savings from getting rid of the near-empty chroma channels won't be large; but the decoding time for a grayscale JPEG is substantially less than that for a color JPEG.) -scale M/N Scale the output image by a factor M/N. Currently supported scale factors are M/N with all M from 1 to 16, where N is the source DCT size, which is 8 for baseline JPEG. If the /N part is omitted, then M specifies the DCT scaled size to be applied on the given input. For baseline JPEG this is equivalent to M/8 scaling, since the source DCT size for baseline JPEG is 8. CAUTION: An implementation of the JPEG SmartScale extension is required for this feature. SmartScale enabled JPEG is not yet widely implemented, so many decoders will be unable to view a SmartScale extended JPEG file at all. jpegtran also recognizes these switches that control what to do with "extra" markers, such as comment blocks: -copy none Copy no extra markers from source file. This setting suppresses all comments and other metadata in the source file. -copy comments Copy only comment markers. This setting copies comments from the source file, but discards any other metadata. -copy all Copy all extra markers. This setting preserves metadata found in the source file, such as JFIF thumbnails, Exif data, and Photoshop settings. In some files these extra markers can be sizable. Note that this option will copy thumbnails as-is; they will not be transformed. The default behavior is -copy comments. (Note: in IJG releases v6 and v6a, jpegtran always did the equivalent of -copy none.) Additional switches recognized by jpegtran are: -outfile filename -maxmemory N -verbose -debug These work the same as in cjpeg or djpeg. THE COMMENT UTILITIES The JPEG standard allows "comment" (COM) blocks to occur within a JPEG file. Although the standard doesn't actually define what COM blocks are for, they are widely used to hold user-supplied text strings. This lets you add annotations, titles, index terms, etc to your JPEG files, and later retrieve them as text. COM blocks do not interfere with the image stored in the JPEG file. The maximum size of a COM block is 64K, but you can have as many of them as you like in one JPEG file. We provide two utility programs to display COM block contents and add COM blocks to a JPEG file. rdjpgcom searches a JPEG file and prints the contents of any COM blocks on standard output. The command line syntax is rdjpgcom [-raw] [-verbose] [inputfilename] The switch "-raw" (or just "-r") causes rdjpgcom to also output non-printable characters in comments, which are normally escaped for security reasons. The switch "-verbose" (or just "-v") causes rdjpgcom to also display the JPEG image dimensions. If you omit the input file name from the command line, the JPEG file is read from standard input. (This may not work on some operating systems, if binary data can't be read from stdin.) wrjpgcom adds a COM block, containing text you provide, to a JPEG file. Ordinarily, the COM block is added after any existing COM blocks, but you can delete the old COM blocks if you wish. wrjpgcom produces a new JPEG file; it does not modify the input file. DO NOT try to overwrite the input file by directing wrjpgcom's output back into it; on most systems this will just destroy your file. The command line syntax for wrjpgcom is similar to cjpeg's. On Unix-like systems, it is wrjpgcom [switches] [inputfilename] The output file is written to standard output. The input file comes from the named file, or from standard input if no input file is named. On most non-Unix systems, the syntax is wrjpgcom [switches] inputfilename outputfilename where both input and output file names must be given explicitly. wrjpgcom understands three switches: -replace Delete any existing COM blocks from the file. -comment "Comment text" Supply new COM text on command line. -cfile name Read text for new COM block from named file. (Switch names can be abbreviated.) If you have only one line of comment text to add, you can provide it on the command line with -comment. The comment text must be surrounded with quotes so that it is treated as a single argument. Longer comments can be read from a text file. If you give neither -comment nor -cfile, then wrjpgcom will read the comment text from standard input. (In this case an input image file name MUST be supplied, so that the source JPEG file comes from somewhere else.) You can enter multiple lines, up to 64KB worth. Type an end-of-file indicator (usually control-D or control-Z) to terminate the comment text entry. wrjpgcom will not add a COM block if the provided comment string is empty. Therefore -replace -comment "" can be used to delete all COM blocks from a file. These utility programs do not depend on the IJG JPEG library. In particular, the source code for rdjpgcom is intended as an illustration of the minimum amount of code required to parse a JPEG file header correctly. ================================================ FILE: tess-two/jni/libjpeg/wizard.txt ================================================ Advanced usage instructions for the Independent JPEG Group's JPEG software ========================================================================== This file describes cjpeg's "switches for wizards". The "wizard" switches are intended for experimentation with JPEG by persons who are reasonably knowledgeable about the JPEG standard. If you don't know what you are doing, DON'T USE THESE SWITCHES. You'll likely produce files with worse image quality and/or poorer compression than you'd get from the default settings. Furthermore, these switches must be used with caution when making files intended for general use, because not all JPEG decoders will support unusual JPEG parameter settings. Quantization Table Adjustment ----------------------------- Ordinarily, cjpeg starts with a default set of tables (the same ones given as examples in the JPEG standard) and scales them up or down according to the -quality setting. The details of the scaling algorithm can be found in jcparam.c. At very low quality settings, some quantization table entries can get scaled up to values exceeding 255. Although 2-byte quantization values are supported by the IJG software, this feature is not in baseline JPEG and is not supported by all implementations. If you need to ensure wide compatibility of low-quality files, you can constrain the scaled quantization values to no more than 255 by giving the -baseline switch. Note that use of -baseline will result in poorer quality for the same file size, since more bits than necessary are expended on higher AC coefficients. You can substitute a different set of quantization values by using the -qtables switch: -qtables file Use the quantization tables given in the named file. The specified file should be a text file containing decimal quantization values. The file should contain one to four tables, each of 64 elements. The tables are implicitly numbered 0,1,etc. in order of appearance. Table entries appear in normal array order (NOT in the zigzag order in which they will be stored in the JPEG file). Quantization table files are free format, in that arbitrary whitespace can appear between numbers. Also, comments can be included: a comment starts with '#' and extends to the end of the line. Here is an example file that duplicates the default quantization tables: # Quantization tables given in JPEG spec, section K.1 # This is table 0 (the luminance table): 16 11 10 16 24 40 51 61 12 12 14 19 26 58 60 55 14 13 16 24 40 57 69 56 14 17 22 29 51 87 80 62 18 22 37 56 68 109 103 77 24 35 55 64 81 104 113 92 49 64 78 87 103 121 120 101 72 92 95 98 112 100 103 99 # This is table 1 (the chrominance table): 17 18 24 47 99 99 99 99 18 21 26 66 99 99 99 99 24 26 56 99 99 99 99 99 47 66 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 If the -qtables switch is used without -quality, then the specified tables are used exactly as-is. If both -qtables and -quality are used, then the tables taken from the file are scaled in the same fashion that the default tables would be scaled for that quality setting. If -baseline appears, then the quantization values are constrained to the range 1-255. By default, cjpeg will use quantization table 0 for luminance components and table 1 for chrominance components. To override this choice, use the -qslots switch: -qslots N[,...] Select which quantization table to use for each color component. The -qslots switch specifies a quantization table number for each color component, in the order in which the components appear in the JPEG SOF marker. For example, to create a separate table for each of Y,Cb,Cr, you could provide a -qtables file that defines three quantization tables and say "-qslots 0,1,2". If -qslots gives fewer table numbers than there are color components, then the last table number is repeated as necessary. Sampling Factor Adjustment -------------------------- By default, cjpeg uses 2:1 horizontal and vertical downsampling when compressing YCbCr data, and no downsampling for all other color spaces. You can override this default with the -sample switch: -sample HxV[,...] Set JPEG sampling factors for each color component. The -sample switch specifies the JPEG sampling factors for each color component, in the order in which they appear in the JPEG SOF marker. If you specify fewer HxV pairs than there are components, the remaining components are set to 1x1 sampling. For example, the default YCbCr setting is equivalent to "-sample 2x2,1x1,1x1", which can be abbreviated to "-sample 2x2". There are still some JPEG decoders in existence that support only 2x1 sampling (also called 4:2:2 sampling). Compatibility with such decoders can be achieved by specifying "-sample 2x1". This is not recommended unless really necessary, since it increases file size and encoding/decoding time with very little quality gain. Multiple Scan / Progression Control ----------------------------------- By default, cjpeg emits a single-scan sequential JPEG file. The -progressive switch generates a progressive JPEG file using a default series of progression parameters. You can create multiple-scan sequential JPEG files or progressive JPEG files with custom progression parameters by using the -scans switch: -scans file Use the scan sequence given in the named file. The specified file should be a text file containing a "scan script". The script specifies the contents and ordering of the scans to be emitted. Each entry in the script defines one scan. A scan definition specifies the components to be included in the scan, and for progressive JPEG it also specifies the progression parameters Ss,Se,Ah,Al for the scan. Scan definitions are separated by semicolons (';'). A semicolon after the last scan definition is optional. Each scan definition contains one to four component indexes, optionally followed by a colon (':') and the four progressive-JPEG parameters. The component indexes denote which color component(s) are to be transmitted in the scan. Components are numbered in the order in which they appear in the JPEG SOF marker, with the first component being numbered 0. (Note that these indexes are not the "component ID" codes assigned to the components, just positional indexes.) The progression parameters for each scan are: Ss Zigzag index of first coefficient included in scan Se Zigzag index of last coefficient included in scan Ah Zero for first scan of a coefficient, else Al of prior scan Al Successive approximation low bit position for scan If the progression parameters are omitted, the values 0,63,0,0 are used, producing a sequential JPEG file. cjpeg automatically determines whether the script represents a progressive or sequential file, by observing whether Ss and Se values other than 0 and 63 appear. (The -progressive switch is not needed to specify this; in fact, it is ignored when -scans appears.) The scan script must meet the JPEG restrictions on progression sequences. (cjpeg checks that the spec's requirements are obeyed.) Scan script files are free format, in that arbitrary whitespace can appear between numbers and around punctuation. Also, comments can be included: a comment starts with '#' and extends to the end of the line. For additional legibility, commas or dashes can be placed between values. (Actually, any single punctuation character other than ':' or ';' can be inserted.) For example, the following two scan definitions are equivalent: 0 1 2: 0 63 0 0; 0,1,2 : 0-63, 0,0 ; Here is an example of a scan script that generates a partially interleaved sequential JPEG file: 0; # Y only in first scan 1 2; # Cb and Cr in second scan Here is an example of a progressive scan script using only spectral selection (no successive approximation): # Interleaved DC scan for Y,Cb,Cr: 0,1,2: 0-0, 0, 0 ; # AC scans: 0: 1-2, 0, 0 ; # First two Y AC coefficients 0: 3-5, 0, 0 ; # Three more 1: 1-63, 0, 0 ; # All AC coefficients for Cb 2: 1-63, 0, 0 ; # All AC coefficients for Cr 0: 6-9, 0, 0 ; # More Y coefficients 0: 10-63, 0, 0 ; # Remaining Y coefficients Here is an example of a successive-approximation script. This is equivalent to the default script used by "cjpeg -progressive" for YCbCr images: # Initial DC scan for Y,Cb,Cr (lowest bit not sent) 0,1,2: 0-0, 0, 1 ; # First AC scan: send first 5 Y AC coefficients, minus 2 lowest bits: 0: 1-5, 0, 2 ; # Send all Cr,Cb AC coefficients, minus lowest bit: # (chroma data is usually too small to be worth subdividing further; # but note we send Cr first since eye is least sensitive to Cb) 2: 1-63, 0, 1 ; 1: 1-63, 0, 1 ; # Send remaining Y AC coefficients, minus 2 lowest bits: 0: 6-63, 0, 2 ; # Send next-to-lowest bit of all Y AC coefficients: 0: 1-63, 2, 1 ; # At this point we've sent all but the lowest bit of all coefficients. # Send lowest bit of DC coefficients 0,1,2: 0-0, 1, 0 ; # Send lowest bit of AC coefficients 2: 1-63, 1, 0 ; 1: 1-63, 1, 0 ; # Y AC lowest bit scan is last; it's usually the largest scan 0: 1-63, 1, 0 ; It may be worth pointing out that this script is tuned for quality settings of around 50 to 75. For lower quality settings, you'd probably want to use a script with fewer stages of successive approximation (otherwise the initial scans will be really bad). For higher quality settings, you might want to use more stages of successive approximation (so that the initial scans are not too large). ================================================ FILE: tess-two/jni/libjpeg/wrbmp.c ================================================ /* * wrbmp.c * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to write output images in Microsoft "BMP" * format (MS Windows 3.x and OS/2 1.x flavors). * Either 8-bit colormapped or 24-bit full-color format can be written. * No compression is supported. * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume output to * an ordinary stdio stream. * * This code contributed by James Arthur Boucher. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef BMP_SUPPORTED /* * To support 12-bit JPEG data, we'd have to scale output down to 8 bits. * This is not yet implemented. */ #if BITS_IN_JSAMPLE != 8 Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */ #endif /* * Since BMP stores scanlines bottom-to-top, we have to invert the image * from JPEG's top-to-bottom order. To do this, we save the outgoing data * in a virtual array during put_pixel_row calls, then actually emit the * BMP file during finish_output. The virtual array contains one JSAMPLE per * pixel if the output is grayscale or colormapped, three if it is full color. */ /* Private version of data destination object */ typedef struct { struct djpeg_dest_struct pub; /* public fields */ boolean is_os2; /* saves the OS2 format request flag */ jvirt_sarray_ptr whole_image; /* needed to reverse row order */ JDIMENSION data_width; /* JSAMPLEs per row */ JDIMENSION row_width; /* physical width of one row in the BMP file */ int pad_bytes; /* number of padding bytes needed per row */ JDIMENSION cur_output_row; /* next row# to write to virtual array */ } bmp_dest_struct; typedef bmp_dest_struct * bmp_dest_ptr; /* Forward declarations */ LOCAL(void) write_colormap JPP((j_decompress_ptr cinfo, bmp_dest_ptr dest, int map_colors, int map_entry_size)); /* * Write some pixel data. * In this module rows_supplied will always be 1. */ METHODDEF(void) put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) /* This version is for writing 24-bit pixels */ { bmp_dest_ptr dest = (bmp_dest_ptr) dinfo; JSAMPARRAY image_ptr; register JSAMPROW inptr, outptr; register JDIMENSION col; int pad; /* Access next row in virtual array */ image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, dest->whole_image, dest->cur_output_row, (JDIMENSION) 1, TRUE); dest->cur_output_row++; /* Transfer data. Note destination values must be in BGR order * (even though Microsoft's own documents say the opposite). */ inptr = dest->pub.buffer[0]; outptr = image_ptr[0]; for (col = cinfo->output_width; col > 0; col--) { outptr[2] = *inptr++; /* can omit GETJSAMPLE() safely */ outptr[1] = *inptr++; outptr[0] = *inptr++; outptr += 3; } /* Zero out the pad bytes. */ pad = dest->pad_bytes; while (--pad >= 0) *outptr++ = 0; } METHODDEF(void) put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) /* This version is for grayscale OR quantized color output */ { bmp_dest_ptr dest = (bmp_dest_ptr) dinfo; JSAMPARRAY image_ptr; register JSAMPROW inptr, outptr; register JDIMENSION col; int pad; /* Access next row in virtual array */ image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, dest->whole_image, dest->cur_output_row, (JDIMENSION) 1, TRUE); dest->cur_output_row++; /* Transfer data. */ inptr = dest->pub.buffer[0]; outptr = image_ptr[0]; for (col = cinfo->output_width; col > 0; col--) { *outptr++ = *inptr++; /* can omit GETJSAMPLE() safely */ } /* Zero out the pad bytes. */ pad = dest->pad_bytes; while (--pad >= 0) *outptr++ = 0; } /* * Startup: normally writes the file header. * In this module we may as well postpone everything until finish_output. */ METHODDEF(void) start_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { /* no work here */ } /* * Finish up at the end of the file. * * Here is where we really output the BMP file. * * First, routines to write the Windows and OS/2 variants of the file header. */ LOCAL(void) write_bmp_header (j_decompress_ptr cinfo, bmp_dest_ptr dest) /* Write a Windows-style BMP file header, including colormap if needed */ { char bmpfileheader[14]; char bmpinfoheader[40]; #define PUT_2B(array,offset,value) \ (array[offset] = (char) ((value) & 0xFF), \ array[offset+1] = (char) (((value) >> 8) & 0xFF)) #define PUT_4B(array,offset,value) \ (array[offset] = (char) ((value) & 0xFF), \ array[offset+1] = (char) (((value) >> 8) & 0xFF), \ array[offset+2] = (char) (((value) >> 16) & 0xFF), \ array[offset+3] = (char) (((value) >> 24) & 0xFF)) INT32 headersize, bfSize; int bits_per_pixel, cmap_entries; /* Compute colormap size and total file size */ if (cinfo->out_color_space == JCS_RGB) { if (cinfo->quantize_colors) { /* Colormapped RGB */ bits_per_pixel = 8; cmap_entries = 256; } else { /* Unquantized, full color RGB */ bits_per_pixel = 24; cmap_entries = 0; } } else { /* Grayscale output. We need to fake a 256-entry colormap. */ bits_per_pixel = 8; cmap_entries = 256; } /* File size */ headersize = 14 + 40 + cmap_entries * 4; /* Header and colormap */ bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height; /* Set unused fields of header to 0 */ MEMZERO(bmpfileheader, SIZEOF(bmpfileheader)); MEMZERO(bmpinfoheader, SIZEOF(bmpinfoheader)); /* Fill the file header */ bmpfileheader[0] = 0x42; /* first 2 bytes are ASCII 'B', 'M' */ bmpfileheader[1] = 0x4D; PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */ /* we leave bfReserved1 & bfReserved2 = 0 */ PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */ /* Fill the info header (Microsoft calls this a BITMAPINFOHEADER) */ PUT_2B(bmpinfoheader, 0, 40); /* biSize */ PUT_4B(bmpinfoheader, 4, cinfo->output_width); /* biWidth */ PUT_4B(bmpinfoheader, 8, cinfo->output_height); /* biHeight */ PUT_2B(bmpinfoheader, 12, 1); /* biPlanes - must be 1 */ PUT_2B(bmpinfoheader, 14, bits_per_pixel); /* biBitCount */ /* we leave biCompression = 0, for none */ /* we leave biSizeImage = 0; this is correct for uncompressed data */ if (cinfo->density_unit == 2) { /* if have density in dots/cm, then */ PUT_4B(bmpinfoheader, 24, (INT32) (cinfo->X_density*100)); /* XPels/M */ PUT_4B(bmpinfoheader, 28, (INT32) (cinfo->Y_density*100)); /* XPels/M */ } PUT_2B(bmpinfoheader, 32, cmap_entries); /* biClrUsed */ /* we leave biClrImportant = 0 */ if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14) ERREXIT(cinfo, JERR_FILE_WRITE); if (JFWRITE(dest->pub.output_file, bmpinfoheader, 40) != (size_t) 40) ERREXIT(cinfo, JERR_FILE_WRITE); if (cmap_entries > 0) write_colormap(cinfo, dest, cmap_entries, 4); } LOCAL(void) write_os2_header (j_decompress_ptr cinfo, bmp_dest_ptr dest) /* Write an OS2-style BMP file header, including colormap if needed */ { char bmpfileheader[14]; char bmpcoreheader[12]; INT32 headersize, bfSize; int bits_per_pixel, cmap_entries; /* Compute colormap size and total file size */ if (cinfo->out_color_space == JCS_RGB) { if (cinfo->quantize_colors) { /* Colormapped RGB */ bits_per_pixel = 8; cmap_entries = 256; } else { /* Unquantized, full color RGB */ bits_per_pixel = 24; cmap_entries = 0; } } else { /* Grayscale output. We need to fake a 256-entry colormap. */ bits_per_pixel = 8; cmap_entries = 256; } /* File size */ headersize = 14 + 12 + cmap_entries * 3; /* Header and colormap */ bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height; /* Set unused fields of header to 0 */ MEMZERO(bmpfileheader, SIZEOF(bmpfileheader)); MEMZERO(bmpcoreheader, SIZEOF(bmpcoreheader)); /* Fill the file header */ bmpfileheader[0] = 0x42; /* first 2 bytes are ASCII 'B', 'M' */ bmpfileheader[1] = 0x4D; PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */ /* we leave bfReserved1 & bfReserved2 = 0 */ PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */ /* Fill the info header (Microsoft calls this a BITMAPCOREHEADER) */ PUT_2B(bmpcoreheader, 0, 12); /* bcSize */ PUT_2B(bmpcoreheader, 4, cinfo->output_width); /* bcWidth */ PUT_2B(bmpcoreheader, 6, cinfo->output_height); /* bcHeight */ PUT_2B(bmpcoreheader, 8, 1); /* bcPlanes - must be 1 */ PUT_2B(bmpcoreheader, 10, bits_per_pixel); /* bcBitCount */ if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14) ERREXIT(cinfo, JERR_FILE_WRITE); if (JFWRITE(dest->pub.output_file, bmpcoreheader, 12) != (size_t) 12) ERREXIT(cinfo, JERR_FILE_WRITE); if (cmap_entries > 0) write_colormap(cinfo, dest, cmap_entries, 3); } /* * Write the colormap. * Windows uses BGR0 map entries; OS/2 uses BGR entries. */ LOCAL(void) write_colormap (j_decompress_ptr cinfo, bmp_dest_ptr dest, int map_colors, int map_entry_size) { JSAMPARRAY colormap = cinfo->colormap; int num_colors = cinfo->actual_number_of_colors; FILE * outfile = dest->pub.output_file; int i; if (colormap != NULL) { if (cinfo->out_color_components == 3) { /* Normal case with RGB colormap */ for (i = 0; i < num_colors; i++) { putc(GETJSAMPLE(colormap[2][i]), outfile); putc(GETJSAMPLE(colormap[1][i]), outfile); putc(GETJSAMPLE(colormap[0][i]), outfile); if (map_entry_size == 4) putc(0, outfile); } } else { /* Grayscale colormap (only happens with grayscale quantization) */ for (i = 0; i < num_colors; i++) { putc(GETJSAMPLE(colormap[0][i]), outfile); putc(GETJSAMPLE(colormap[0][i]), outfile); putc(GETJSAMPLE(colormap[0][i]), outfile); if (map_entry_size == 4) putc(0, outfile); } } } else { /* If no colormap, must be grayscale data. Generate a linear "map". */ for (i = 0; i < 256; i++) { putc(i, outfile); putc(i, outfile); putc(i, outfile); if (map_entry_size == 4) putc(0, outfile); } } /* Pad colormap with zeros to ensure specified number of colormap entries */ if (i > map_colors) ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, i); for (; i < map_colors; i++) { putc(0, outfile); putc(0, outfile); putc(0, outfile); if (map_entry_size == 4) putc(0, outfile); } } METHODDEF(void) finish_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { bmp_dest_ptr dest = (bmp_dest_ptr) dinfo; register FILE * outfile = dest->pub.output_file; JSAMPARRAY image_ptr; register JSAMPROW data_ptr; JDIMENSION row; register JDIMENSION col; cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; /* Write the header and colormap */ if (dest->is_os2) write_os2_header(cinfo, dest); else write_bmp_header(cinfo, dest); /* Write the file body from our virtual array */ for (row = cinfo->output_height; row > 0; row--) { if (progress != NULL) { progress->pub.pass_counter = (long) (cinfo->output_height - row); progress->pub.pass_limit = (long) cinfo->output_height; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, dest->whole_image, row-1, (JDIMENSION) 1, FALSE); data_ptr = image_ptr[0]; for (col = dest->row_width; col > 0; col--) { putc(GETJSAMPLE(*data_ptr), outfile); data_ptr++; } } if (progress != NULL) progress->completed_extra_passes++; /* Make sure we wrote the output file OK */ fflush(outfile); if (ferror(outfile)) ERREXIT(cinfo, JERR_FILE_WRITE); } /* * The module selection routine for BMP format output. */ GLOBAL(djpeg_dest_ptr) jinit_write_bmp (j_decompress_ptr cinfo, boolean is_os2) { bmp_dest_ptr dest; JDIMENSION row_width; /* Create module interface object, fill in method pointers */ dest = (bmp_dest_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(bmp_dest_struct)); dest->pub.start_output = start_output_bmp; dest->pub.finish_output = finish_output_bmp; dest->is_os2 = is_os2; if (cinfo->out_color_space == JCS_GRAYSCALE) { dest->pub.put_pixel_rows = put_gray_rows; } else if (cinfo->out_color_space == JCS_RGB) { if (cinfo->quantize_colors) dest->pub.put_pixel_rows = put_gray_rows; else dest->pub.put_pixel_rows = put_pixel_rows; } else { ERREXIT(cinfo, JERR_BMP_COLORSPACE); } /* Calculate output image dimensions so we can allocate space */ jpeg_calc_output_dimensions(cinfo); /* Determine width of rows in the BMP file (padded to 4-byte boundary). */ row_width = cinfo->output_width * cinfo->output_components; dest->data_width = row_width; while ((row_width & 3) != 0) row_width++; dest->row_width = row_width; dest->pad_bytes = (int) (row_width - dest->data_width); /* Allocate space for inversion array, prepare for write pass */ dest->whole_image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, row_width, cinfo->output_height, (JDIMENSION) 1); dest->cur_output_row = 0; if (cinfo->progress != NULL) { cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; progress->total_extra_passes++; /* count file input as separate pass */ } /* Create decompressor output buffer. */ dest->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, row_width, (JDIMENSION) 1); dest->pub.buffer_height = 1; return (djpeg_dest_ptr) dest; } #endif /* BMP_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/wrgif.c ================================================ /* * wrgif.c * * Copyright (C) 1991-1997, Thomas G. Lane. * Modified 2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to write output images in GIF format. * ************************************************************************** * NOTE: to avoid entanglements with Unisys' patent on LZW compression, * * this code has been modified to output "uncompressed GIF" files. * * There is no trace of the LZW algorithm in this file. * ************************************************************************** * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume output to * an ordinary stdio stream. */ /* * This code is loosely based on ppmtogif from the PBMPLUS distribution * of Feb. 1991. That file contains the following copyright notice: * Based on GIFENCODE by David Rowley . * Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al. * Copyright (C) 1989 by Jef Poskanzer. * 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. * * We are also required to state that * "The Graphics Interchange Format(c) is the Copyright property of * CompuServe Incorporated. GIF(sm) is a Service Mark property of * CompuServe Incorporated." */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef GIF_SUPPORTED /* Private version of data destination object */ typedef struct { struct djpeg_dest_struct pub; /* public fields */ j_decompress_ptr cinfo; /* back link saves passing separate parm */ /* State for packing variable-width codes into a bitstream */ int n_bits; /* current number of bits/code */ int maxcode; /* maximum code, given n_bits */ INT32 cur_accum; /* holds bits not yet output */ int cur_bits; /* # of bits in cur_accum */ /* State for GIF code assignment */ int ClearCode; /* clear code (doesn't change) */ int EOFCode; /* EOF code (ditto) */ int code_counter; /* counts output symbols */ /* GIF data packet construction buffer */ int bytesinpkt; /* # of bytes in current packet */ char packetbuf[256]; /* workspace for accumulating packet */ } gif_dest_struct; typedef gif_dest_struct * gif_dest_ptr; /* Largest value that will fit in N bits */ #define MAXCODE(n_bits) ((1 << (n_bits)) - 1) /* * Routines to package finished data bytes into GIF data blocks. * A data block consists of a count byte (1..255) and that many data bytes. */ LOCAL(void) flush_packet (gif_dest_ptr dinfo) /* flush any accumulated data */ { if (dinfo->bytesinpkt > 0) { /* never write zero-length packet */ dinfo->packetbuf[0] = (char) dinfo->bytesinpkt++; if (JFWRITE(dinfo->pub.output_file, dinfo->packetbuf, dinfo->bytesinpkt) != (size_t) dinfo->bytesinpkt) ERREXIT(dinfo->cinfo, JERR_FILE_WRITE); dinfo->bytesinpkt = 0; } } /* Add a character to current packet; flush to disk if necessary */ #define CHAR_OUT(dinfo,c) \ { (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c); \ if ((dinfo)->bytesinpkt >= 255) \ flush_packet(dinfo); \ } /* Routine to convert variable-width codes into a byte stream */ LOCAL(void) output (gif_dest_ptr dinfo, int code) /* Emit a code of n_bits bits */ /* Uses cur_accum and cur_bits to reblock into 8-bit bytes */ { dinfo->cur_accum |= ((INT32) code) << dinfo->cur_bits; dinfo->cur_bits += dinfo->n_bits; while (dinfo->cur_bits >= 8) { CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF); dinfo->cur_accum >>= 8; dinfo->cur_bits -= 8; } } /* The pseudo-compression algorithm. * * In this module we simply output each pixel value as a separate symbol; * thus, no compression occurs. In fact, there is expansion of one bit per * pixel, because we use a symbol width one bit wider than the pixel width. * * GIF ordinarily uses variable-width symbols, and the decoder will expect * to ratchet up the symbol width after a fixed number of symbols. * To simplify the logic and keep the expansion penalty down, we emit a * GIF Clear code to reset the decoder just before the width would ratchet up. * Thus, all the symbols in the output file will have the same bit width. * Note that emitting the Clear codes at the right times is a mere matter of * counting output symbols and is in no way dependent on the LZW patent. * * With a small basic pixel width (low color count), Clear codes will be * needed very frequently, causing the file to expand even more. So this * simplistic approach wouldn't work too well on bilevel images, for example. * But for output of JPEG conversions the pixel width will usually be 8 bits * (129 to 256 colors), so the overhead added by Clear symbols is only about * one symbol in every 256. */ LOCAL(void) compress_init (gif_dest_ptr dinfo, int i_bits) /* Initialize pseudo-compressor */ { /* init all the state variables */ dinfo->n_bits = i_bits; dinfo->maxcode = MAXCODE(dinfo->n_bits); dinfo->ClearCode = (1 << (i_bits - 1)); dinfo->EOFCode = dinfo->ClearCode + 1; dinfo->code_counter = dinfo->ClearCode + 2; /* init output buffering vars */ dinfo->bytesinpkt = 0; dinfo->cur_accum = 0; dinfo->cur_bits = 0; /* GIF specifies an initial Clear code */ output(dinfo, dinfo->ClearCode); } LOCAL(void) compress_pixel (gif_dest_ptr dinfo, int c) /* Accept and "compress" one pixel value. * The given value must be less than n_bits wide. */ { /* Output the given pixel value as a symbol. */ output(dinfo, c); /* Issue Clear codes often enough to keep the reader from ratcheting up * its symbol size. */ if (dinfo->code_counter < dinfo->maxcode) { dinfo->code_counter++; } else { output(dinfo, dinfo->ClearCode); dinfo->code_counter = dinfo->ClearCode + 2; /* reset the counter */ } } LOCAL(void) compress_term (gif_dest_ptr dinfo) /* Clean up at end */ { /* Send an EOF code */ output(dinfo, dinfo->EOFCode); /* Flush the bit-packing buffer */ if (dinfo->cur_bits > 0) { CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF); } /* Flush the packet buffer */ flush_packet(dinfo); } /* GIF header construction */ LOCAL(void) put_word (gif_dest_ptr dinfo, unsigned int w) /* Emit a 16-bit word, LSB first */ { putc(w & 0xFF, dinfo->pub.output_file); putc((w >> 8) & 0xFF, dinfo->pub.output_file); } LOCAL(void) put_3bytes (gif_dest_ptr dinfo, int val) /* Emit 3 copies of same byte value --- handy subr for colormap construction */ { putc(val, dinfo->pub.output_file); putc(val, dinfo->pub.output_file); putc(val, dinfo->pub.output_file); } LOCAL(void) emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap) /* Output the GIF file header, including color map */ /* If colormap==NULL, synthesize a grayscale colormap */ { int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte; int cshift = dinfo->cinfo->data_precision - 8; int i; if (num_colors > 256) ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors); /* Compute bits/pixel and related values */ BitsPerPixel = 1; while (num_colors > (1 << BitsPerPixel)) BitsPerPixel++; ColorMapSize = 1 << BitsPerPixel; if (BitsPerPixel <= 1) InitCodeSize = 2; else InitCodeSize = BitsPerPixel; /* * Write the GIF header. * Note that we generate a plain GIF87 header for maximum compatibility. */ putc('G', dinfo->pub.output_file); putc('I', dinfo->pub.output_file); putc('F', dinfo->pub.output_file); putc('8', dinfo->pub.output_file); putc('7', dinfo->pub.output_file); putc('a', dinfo->pub.output_file); /* Write the Logical Screen Descriptor */ put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); put_word(dinfo, (unsigned int) dinfo->cinfo->output_height); FlagByte = 0x80; /* Yes, there is a global color table */ FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */ FlagByte |= (BitsPerPixel-1); /* size of global color table */ putc(FlagByte, dinfo->pub.output_file); putc(0, dinfo->pub.output_file); /* Background color index */ putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */ /* Write the Global Color Map */ /* If the color map is more than 8 bits precision, */ /* we reduce it to 8 bits by shifting */ for (i=0; i < ColorMapSize; i++) { if (i < num_colors) { if (colormap != NULL) { if (dinfo->cinfo->out_color_space == JCS_RGB) { /* Normal case: RGB color map */ putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file); putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file); putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file); } else { /* Grayscale "color map": possible if quantizing grayscale image */ put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift); } } else { /* Create a grayscale map of num_colors values, range 0..255 */ put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1)); } } else { /* fill out the map to a power of 2 */ put_3bytes(dinfo, 0); } } /* Write image separator and Image Descriptor */ putc(',', dinfo->pub.output_file); /* separator */ put_word(dinfo, 0); /* left/top offset */ put_word(dinfo, 0); put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */ put_word(dinfo, (unsigned int) dinfo->cinfo->output_height); /* flag byte: not interlaced, no local color map */ putc(0x00, dinfo->pub.output_file); /* Write Initial Code Size byte */ putc(InitCodeSize, dinfo->pub.output_file); /* Initialize for "compression" of image data */ compress_init(dinfo, InitCodeSize+1); } /* * Startup: write the file header. */ METHODDEF(void) start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { gif_dest_ptr dest = (gif_dest_ptr) dinfo; if (cinfo->quantize_colors) emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap); else emit_header(dest, 256, (JSAMPARRAY) NULL); } /* * Write some pixel data. * In this module rows_supplied will always be 1. */ METHODDEF(void) put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) { gif_dest_ptr dest = (gif_dest_ptr) dinfo; register JSAMPROW ptr; register JDIMENSION col; ptr = dest->pub.buffer[0]; for (col = cinfo->output_width; col > 0; col--) { compress_pixel(dest, GETJSAMPLE(*ptr++)); } } /* * Finish up at the end of the file. */ METHODDEF(void) finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { gif_dest_ptr dest = (gif_dest_ptr) dinfo; /* Flush "compression" mechanism */ compress_term(dest); /* Write a zero-length data block to end the series */ putc(0, dest->pub.output_file); /* Write the GIF terminator mark */ putc(';', dest->pub.output_file); /* Make sure we wrote the output file OK */ fflush(dest->pub.output_file); if (ferror(dest->pub.output_file)) ERREXIT(cinfo, JERR_FILE_WRITE); } /* * The module selection routine for GIF format output. */ GLOBAL(djpeg_dest_ptr) jinit_write_gif (j_decompress_ptr cinfo) { gif_dest_ptr dest; /* Create module interface object, fill in method pointers */ dest = (gif_dest_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(gif_dest_struct)); dest->cinfo = cinfo; /* make back link for subroutines */ dest->pub.start_output = start_output_gif; dest->pub.put_pixel_rows = put_pixel_rows; dest->pub.finish_output = finish_output_gif; if (cinfo->out_color_space != JCS_GRAYSCALE && cinfo->out_color_space != JCS_RGB) ERREXIT(cinfo, JERR_GIF_COLORSPACE); /* Force quantization if color or if > 8 bits input */ if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) { /* Force quantization to at most 256 colors */ cinfo->quantize_colors = TRUE; if (cinfo->desired_number_of_colors > 256) cinfo->desired_number_of_colors = 256; } /* Calculate output image dimensions so we can allocate space */ jpeg_calc_output_dimensions(cinfo); if (cinfo->output_components != 1) /* safety check: just one component? */ ERREXIT(cinfo, JERR_GIF_BUG); /* Create decompressor output buffer. */ dest->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1); dest->pub.buffer_height = 1; return &dest->pub; } #endif /* GIF_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/wrjpgcom.1 ================================================ .TH WRJPGCOM 1 "15 June 1995" .SH NAME wrjpgcom \- insert text comments into a JPEG file .SH SYNOPSIS .B wrjpgcom [ .B \-replace ] [ .BI \-comment " text" ] [ .BI \-cfile " name" ] [ .I filename ] .LP .SH DESCRIPTION .LP .B wrjpgcom reads the named JPEG/JFIF file, or the standard input if no file is named, and generates a new JPEG/JFIF file on standard output. A comment block is added to the file. .PP The JPEG standard allows "comment" (COM) blocks to occur within a JPEG file. Although the standard doesn't actually define what COM blocks are for, they are widely used to hold user-supplied text strings. This lets you add annotations, titles, index terms, etc to your JPEG files, and later retrieve them as text. COM blocks do not interfere with the image stored in the JPEG file. The maximum size of a COM block is 64K, but you can have as many of them as you like in one JPEG file. .PP .B wrjpgcom adds a COM block, containing text you provide, to a JPEG file. Ordinarily, the COM block is added after any existing COM blocks; but you can delete the old COM blocks if you wish. .SH OPTIONS Switch names may be abbreviated, and are not case sensitive. .TP .B \-replace Delete any existing COM blocks from the file. .TP .BI \-comment " text" Supply text for new COM block on command line. .TP .BI \-cfile " name" Read text for new COM block from named file. .PP If you have only one line of comment text to add, you can provide it on the command line with .BR \-comment . The comment text must be surrounded with quotes so that it is treated as a single argument. Longer comments can be read from a text file. .PP If you give neither .B \-comment nor .BR \-cfile , then .B wrjpgcom will read the comment text from standard input. (In this case an input image file name MUST be supplied, so that the source JPEG file comes from somewhere else.) You can enter multiple lines, up to 64KB worth. Type an end-of-file indicator (usually control-D) to terminate the comment text entry. .PP .B wrjpgcom will not add a COM block if the provided comment string is empty. Therefore \fB\-replace \-comment ""\fR can be used to delete all COM blocks from a file. .SH EXAMPLES .LP Add a short comment to in.jpg, producing out.jpg: .IP .B wrjpgcom \-c \fI"View of my back yard" in.jpg .B > .I out.jpg .PP Attach a long comment previously stored in comment.txt: .IP .B wrjpgcom .I in.jpg .B < .I comment.txt .B > .I out.jpg .PP or equivalently .IP .B wrjpgcom .B -cfile .I comment.txt .B < .I in.jpg .B > .I out.jpg .SH SEE ALSO .BR cjpeg (1), .BR djpeg (1), .BR jpegtran (1), .BR rdjpgcom (1) .SH AUTHOR Independent JPEG Group ================================================ FILE: tess-two/jni/libjpeg/wrjpgcom.c ================================================ /* * wrjpgcom.c * * Copyright (C) 1994-1997, Thomas G. Lane. * Modified 2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a very simple stand-alone application that inserts * user-supplied text as a COM (comment) marker in a JFIF file. * This may be useful as an example of the minimum logic needed to parse * JPEG markers. */ #define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */ #include "jinclude.h" /* get auto-config symbols, */ #ifndef HAVE_STDLIB_H /* should declare malloc() */ extern void * malloc (); #endif #include /* to declare isupper(), tolower() */ #ifdef USE_SETMODE #include /* to declare setmode()'s parameter macros */ /* If you have setmode() but not , just delete this line: */ #include /* to declare setmode() */ #endif #ifdef USE_CCOMMAND /* command-line reader for Macintosh */ #ifdef __MWERKS__ #include /* Metrowerks needs this */ #include /* ... and this */ #endif #ifdef THINK_C #include /* Think declares it here */ #endif #endif #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */ #define READ_BINARY "r" #define WRITE_BINARY "w" #else #ifdef VMS /* VMS is very nonstandard */ #define READ_BINARY "rb", "ctx=stm" #define WRITE_BINARY "wb", "ctx=stm" #else /* standard ANSI-compliant case */ #define READ_BINARY "rb" #define WRITE_BINARY "wb" #endif #endif #ifndef EXIT_FAILURE /* define exit() codes if not provided */ #define EXIT_FAILURE 1 #endif #ifndef EXIT_SUCCESS #ifdef VMS #define EXIT_SUCCESS 1 /* VMS is very nonstandard */ #else #define EXIT_SUCCESS 0 #endif #endif /* Reduce this value if your malloc() can't allocate blocks up to 64K. * On DOS, compiling in large model is usually a better solution. */ #ifndef MAX_COM_LENGTH #define MAX_COM_LENGTH 65000L /* must be <= 65533 in any case */ #endif /* * These macros are used to read the input file and write the output file. * To reuse this code in another application, you might need to change these. */ static FILE * infile; /* input JPEG file */ /* Return next input byte, or EOF if no more */ #define NEXTBYTE() getc(infile) static FILE * outfile; /* output JPEG file */ /* Emit an output byte */ #define PUTBYTE(x) putc((x), outfile) /* Error exit handler */ #define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE)) /* Read one byte, testing for EOF */ static int read_1_byte (void) { int c; c = NEXTBYTE(); if (c == EOF) ERREXIT("Premature EOF in JPEG file"); return c; } /* Read 2 bytes, convert to unsigned int */ /* All 2-byte quantities in JPEG markers are MSB first */ static unsigned int read_2_bytes (void) { int c1, c2; c1 = NEXTBYTE(); if (c1 == EOF) ERREXIT("Premature EOF in JPEG file"); c2 = NEXTBYTE(); if (c2 == EOF) ERREXIT("Premature EOF in JPEG file"); return (((unsigned int) c1) << 8) + ((unsigned int) c2); } /* Routines to write data to output file */ static void write_1_byte (int c) { PUTBYTE(c); } static void write_2_bytes (unsigned int val) { PUTBYTE((val >> 8) & 0xFF); PUTBYTE(val & 0xFF); } static void write_marker (int marker) { PUTBYTE(0xFF); PUTBYTE(marker); } static void copy_rest_of_file (void) { int c; while ((c = NEXTBYTE()) != EOF) PUTBYTE(c); } /* * JPEG markers consist of one or more 0xFF bytes, followed by a marker * code byte (which is not an FF). Here are the marker codes of interest * in this program. (See jdmarker.c for a more complete list.) */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */ #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_COM 0xFE /* COMment */ /* * Find the next JPEG marker and return its marker code. * We expect at least one FF byte, possibly more if the compressor used FFs * to pad the file. (Padding FFs will NOT be replicated in the output file.) * There could also be non-FF garbage between markers. The treatment of such * garbage is unspecified; we choose to skip over it but emit a warning msg. * NB: this routine must not be used after seeing SOS marker, since it will * not deal correctly with FF/00 sequences in the compressed image data... */ static int next_marker (void) { int c; int discarded_bytes = 0; /* Find 0xFF byte; count and skip any non-FFs. */ c = read_1_byte(); while (c != 0xFF) { discarded_bytes++; c = read_1_byte(); } /* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs * are legal as pad bytes, so don't count them in discarded_bytes. */ do { c = read_1_byte(); } while (c == 0xFF); if (discarded_bytes != 0) { fprintf(stderr, "Warning: garbage data found in JPEG file\n"); } return c; } /* * Read the initial marker, which should be SOI. * For a JFIF file, the first two bytes of the file should be literally * 0xFF M_SOI. To be more general, we could use next_marker, but if the * input file weren't actually JPEG at all, next_marker might read the whole * file and then return a misleading error message... */ static int first_marker (void) { int c1, c2; c1 = NEXTBYTE(); c2 = NEXTBYTE(); if (c1 != 0xFF || c2 != M_SOI) ERREXIT("Not a JPEG file"); return c2; } /* * Most types of marker are followed by a variable-length parameter segment. * This routine skips over the parameters for any marker we don't otherwise * want to process. * Note that we MUST skip the parameter segment explicitly in order not to * be fooled by 0xFF bytes that might appear within the parameter segment; * such bytes do NOT introduce new markers. */ static void copy_variable (void) /* Copy an unknown or uninteresting variable-length marker */ { unsigned int length; /* Get the marker parameter length count */ length = read_2_bytes(); write_2_bytes(length); /* Length includes itself, so must be at least 2 */ if (length < 2) ERREXIT("Erroneous JPEG marker length"); length -= 2; /* Skip over the remaining bytes */ while (length > 0) { write_1_byte(read_1_byte()); length--; } } static void skip_variable (void) /* Skip over an unknown or uninteresting variable-length marker */ { unsigned int length; /* Get the marker parameter length count */ length = read_2_bytes(); /* Length includes itself, so must be at least 2 */ if (length < 2) ERREXIT("Erroneous JPEG marker length"); length -= 2; /* Skip over the remaining bytes */ while (length > 0) { (void) read_1_byte(); length--; } } /* * Parse the marker stream until SOFn or EOI is seen; * copy data to output, but discard COM markers unless keep_COM is true. */ static int scan_JPEG_header (int keep_COM) { int marker; /* Expect SOI at start of file */ if (first_marker() != M_SOI) ERREXIT("Expected SOI marker first"); write_marker(M_SOI); /* Scan miscellaneous markers until we reach SOFn. */ for (;;) { marker = next_marker(); switch (marker) { /* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be, * treated as SOFn. C4 in particular is actually DHT. */ case M_SOF0: /* Baseline */ case M_SOF1: /* Extended sequential, Huffman */ case M_SOF2: /* Progressive, Huffman */ case M_SOF3: /* Lossless, Huffman */ case M_SOF5: /* Differential sequential, Huffman */ case M_SOF6: /* Differential progressive, Huffman */ case M_SOF7: /* Differential lossless, Huffman */ case M_SOF9: /* Extended sequential, arithmetic */ case M_SOF10: /* Progressive, arithmetic */ case M_SOF11: /* Lossless, arithmetic */ case M_SOF13: /* Differential sequential, arithmetic */ case M_SOF14: /* Differential progressive, arithmetic */ case M_SOF15: /* Differential lossless, arithmetic */ return marker; case M_SOS: /* should not see compressed data before SOF */ ERREXIT("SOS without prior SOFn"); break; case M_EOI: /* in case it's a tables-only JPEG stream */ return marker; case M_COM: /* Existing COM: conditionally discard */ if (keep_COM) { write_marker(marker); copy_variable(); } else { skip_variable(); } break; default: /* Anything else just gets copied */ write_marker(marker); copy_variable(); /* we assume it has a parameter count... */ break; } } /* end loop */ } /* Command line parsing code */ static const char * progname; /* program name for error messages */ static void usage (void) /* complain about bad command line */ { fprintf(stderr, "wrjpgcom inserts a textual comment in a JPEG file.\n"); fprintf(stderr, "You can add to or replace any existing comment(s).\n"); fprintf(stderr, "Usage: %s [switches] ", progname); #ifdef TWO_FILE_COMMANDLINE fprintf(stderr, "inputfile outputfile\n"); #else fprintf(stderr, "[inputfile]\n"); #endif fprintf(stderr, "Switches (names may be abbreviated):\n"); fprintf(stderr, " -replace Delete any existing comments\n"); fprintf(stderr, " -comment \"text\" Insert comment with given text\n"); fprintf(stderr, " -cfile name Read comment from named file\n"); fprintf(stderr, "Notice that you must put quotes around the comment text\n"); fprintf(stderr, "when you use -comment.\n"); fprintf(stderr, "If you do not give either -comment or -cfile on the command line,\n"); fprintf(stderr, "then the comment text is read from standard input.\n"); fprintf(stderr, "It can be multiple lines, up to %u characters total.\n", (unsigned int) MAX_COM_LENGTH); #ifndef TWO_FILE_COMMANDLINE fprintf(stderr, "You must specify an input JPEG file name when supplying\n"); fprintf(stderr, "comment text from standard input.\n"); #endif exit(EXIT_FAILURE); } static int keymatch (char * arg, const char * keyword, int minchars) /* Case-insensitive matching of (possibly abbreviated) keyword switches. */ /* keyword is the constant keyword (must be lower case already), */ /* minchars is length of minimum legal abbreviation. */ { register int ca, ck; register int nmatched = 0; while ((ca = *arg++) != '\0') { if ((ck = *keyword++) == '\0') return 0; /* arg longer than keyword, no good */ if (isupper(ca)) /* force arg to lcase (assume ck is already) */ ca = tolower(ca); if (ca != ck) return 0; /* no good */ nmatched++; /* count matched characters */ } /* reached end of argument; fail if it's too short for unique abbrev */ if (nmatched < minchars) return 0; return 1; /* A-OK */ } /* * The main program. */ int main (int argc, char **argv) { int argn; char * arg; int keep_COM = 1; char * comment_arg = NULL; FILE * comment_file = NULL; unsigned int comment_length = 0; int marker; /* On Mac, fetch a command line. */ #ifdef USE_CCOMMAND argc = ccommand(&argv); #endif progname = argv[0]; if (progname == NULL || progname[0] == 0) progname = "wrjpgcom"; /* in case C library doesn't provide it */ /* Parse switches, if any */ for (argn = 1; argn < argc; argn++) { arg = argv[argn]; if (arg[0] != '-') break; /* not switch, must be file name */ arg++; /* advance over '-' */ if (keymatch(arg, "replace", 1)) { keep_COM = 0; } else if (keymatch(arg, "cfile", 2)) { if (++argn >= argc) usage(); if ((comment_file = fopen(argv[argn], "r")) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]); exit(EXIT_FAILURE); } } else if (keymatch(arg, "comment", 1)) { if (++argn >= argc) usage(); comment_arg = argv[argn]; /* If the comment text starts with '"', then we are probably running * under MS-DOG and must parse out the quoted string ourselves. Sigh. */ if (comment_arg[0] == '"') { comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH); if (comment_arg == NULL) ERREXIT("Insufficient memory"); if (strlen(argv[argn]+1) >= (size_t) MAX_COM_LENGTH) { fprintf(stderr, "Comment text may not exceed %u bytes\n", (unsigned int) MAX_COM_LENGTH); exit(EXIT_FAILURE); } strcpy(comment_arg, argv[argn]+1); for (;;) { comment_length = (unsigned int) strlen(comment_arg); if (comment_length > 0 && comment_arg[comment_length-1] == '"') { comment_arg[comment_length-1] = '\0'; /* zap terminating quote */ break; } if (++argn >= argc) ERREXIT("Missing ending quote mark"); if (strlen(comment_arg) + 1 + strlen(argv[argn]) >= (size_t) MAX_COM_LENGTH) { fprintf(stderr, "Comment text may not exceed %u bytes\n", (unsigned int) MAX_COM_LENGTH); exit(EXIT_FAILURE); } strcat(comment_arg, " "); strcat(comment_arg, argv[argn]); } } else if (strlen(comment_arg) >= (size_t) MAX_COM_LENGTH) { fprintf(stderr, "Comment text may not exceed %u bytes\n", (unsigned int) MAX_COM_LENGTH); exit(EXIT_FAILURE); } comment_length = (unsigned int) strlen(comment_arg); } else usage(); } /* Cannot use both -comment and -cfile. */ if (comment_arg != NULL && comment_file != NULL) usage(); /* If there is neither -comment nor -cfile, we will read the comment text * from stdin; in this case there MUST be an input JPEG file name. */ if (comment_arg == NULL && comment_file == NULL && argn >= argc) usage(); /* Open the input file. */ if (argn < argc) { if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]); exit(EXIT_FAILURE); } } else { /* default input file is stdin */ #ifdef USE_SETMODE /* need to hack file mode? */ setmode(fileno(stdin), O_BINARY); #endif #ifdef USE_FDOPEN /* need to re-open in binary mode? */ if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) { fprintf(stderr, "%s: can't open stdin\n", progname); exit(EXIT_FAILURE); } #else infile = stdin; #endif } /* Open the output file. */ #ifdef TWO_FILE_COMMANDLINE /* Must have explicit output file name */ if (argn != argc-2) { fprintf(stderr, "%s: must name one input and one output file\n", progname); usage(); } if ((outfile = fopen(argv[argn+1], WRITE_BINARY)) == NULL) { fprintf(stderr, "%s: can't open %s\n", progname, argv[argn+1]); exit(EXIT_FAILURE); } #else /* Unix style: expect zero or one file name */ if (argn < argc-1) { fprintf(stderr, "%s: only one input file\n", progname); usage(); } /* default output file is stdout */ #ifdef USE_SETMODE /* need to hack file mode? */ setmode(fileno(stdout), O_BINARY); #endif #ifdef USE_FDOPEN /* need to re-open in binary mode? */ if ((outfile = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) { fprintf(stderr, "%s: can't open stdout\n", progname); exit(EXIT_FAILURE); } #else outfile = stdout; #endif #endif /* TWO_FILE_COMMANDLINE */ /* Collect comment text from comment_file or stdin, if necessary */ if (comment_arg == NULL) { FILE * src_file; int c; comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH); if (comment_arg == NULL) ERREXIT("Insufficient memory"); comment_length = 0; src_file = (comment_file != NULL ? comment_file : stdin); while ((c = getc(src_file)) != EOF) { if (comment_length >= (unsigned int) MAX_COM_LENGTH) { fprintf(stderr, "Comment text may not exceed %u bytes\n", (unsigned int) MAX_COM_LENGTH); exit(EXIT_FAILURE); } comment_arg[comment_length++] = (char) c; } if (comment_file != NULL) fclose(comment_file); } /* Copy JPEG headers until SOFn marker; * we will insert the new comment marker just before SOFn. * This (a) causes the new comment to appear after, rather than before, * existing comments; and (b) ensures that comments come after any JFIF * or JFXX markers, as required by the JFIF specification. */ marker = scan_JPEG_header(keep_COM); /* Insert the new COM marker, but only if nonempty text has been supplied */ if (comment_length > 0) { write_marker(M_COM); write_2_bytes(comment_length + 2); while (comment_length > 0) { write_1_byte(*comment_arg++); comment_length--; } } /* Duplicate the remainder of the source file. * Note that any COM markers occuring after SOF will not be touched. */ write_marker(marker); copy_rest_of_file(); /* All done. */ exit(EXIT_SUCCESS); return 0; /* suppress no-return-value warnings */ } ================================================ FILE: tess-two/jni/libjpeg/wrppm.c ================================================ /* * wrppm.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2009 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to write output images in PPM/PGM format. * The extended 2-byte-per-sample raw PPM/PGM formats are supported. * The PBMPLUS library is NOT required to compile this software * (but it is highly useful as a set of PPM image manipulation programs). * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume output to * an ordinary stdio stream. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef PPM_SUPPORTED /* * For 12-bit JPEG data, we either downscale the values to 8 bits * (to write standard byte-per-sample PPM/PGM files), or output * nonstandard word-per-sample PPM/PGM files. Downscaling is done * if PPM_NORAWWORD is defined (this can be done in the Makefile * or in jconfig.h). * (When the core library supports data precision reduction, a cleaner * implementation will be to ask for that instead.) */ #if BITS_IN_JSAMPLE == 8 #define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) (v) #define BYTESPERSAMPLE 1 #define PPM_MAXVAL 255 #else #ifdef PPM_NORAWWORD #define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) ((v) >> (BITS_IN_JSAMPLE-8)) #define BYTESPERSAMPLE 1 #define PPM_MAXVAL 255 #else /* The word-per-sample format always puts the MSB first. */ #define PUTPPMSAMPLE(ptr,v) \ { register int val_ = v; \ *ptr++ = (char) ((val_ >> 8) & 0xFF); \ *ptr++ = (char) (val_ & 0xFF); \ } #define BYTESPERSAMPLE 2 #define PPM_MAXVAL ((1<pub.output_file, dest->iobuffer, dest->buffer_width); } /* * This code is used when we have to copy the data and apply a pixel * format translation. Typically this only happens in 12-bit mode. */ METHODDEF(void) copy_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) { ppm_dest_ptr dest = (ppm_dest_ptr) dinfo; register char * bufferptr; register JSAMPROW ptr; register JDIMENSION col; ptr = dest->pub.buffer[0]; bufferptr = dest->iobuffer; for (col = dest->samples_per_row; col > 0; col--) { PUTPPMSAMPLE(bufferptr, GETJSAMPLE(*ptr++)); } (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); } /* * Write some pixel data when color quantization is in effect. * We have to demap the color index values to straight data. */ METHODDEF(void) put_demapped_rgb (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) { ppm_dest_ptr dest = (ppm_dest_ptr) dinfo; register char * bufferptr; register int pixval; register JSAMPROW ptr; register JSAMPROW color_map0 = cinfo->colormap[0]; register JSAMPROW color_map1 = cinfo->colormap[1]; register JSAMPROW color_map2 = cinfo->colormap[2]; register JDIMENSION col; ptr = dest->pub.buffer[0]; bufferptr = dest->iobuffer; for (col = cinfo->output_width; col > 0; col--) { pixval = GETJSAMPLE(*ptr++); PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map0[pixval])); PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map1[pixval])); PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map2[pixval])); } (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); } METHODDEF(void) put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) { ppm_dest_ptr dest = (ppm_dest_ptr) dinfo; register char * bufferptr; register JSAMPROW ptr; register JSAMPROW color_map = cinfo->colormap[0]; register JDIMENSION col; ptr = dest->pub.buffer[0]; bufferptr = dest->iobuffer; for (col = cinfo->output_width; col > 0; col--) { PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)])); } (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); } /* * Startup: write the file header. */ METHODDEF(void) start_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { ppm_dest_ptr dest = (ppm_dest_ptr) dinfo; /* Emit file header */ switch (cinfo->out_color_space) { case JCS_GRAYSCALE: /* emit header for raw PGM format */ fprintf(dest->pub.output_file, "P5\n%ld %ld\n%d\n", (long) cinfo->output_width, (long) cinfo->output_height, PPM_MAXVAL); break; case JCS_RGB: /* emit header for raw PPM format */ fprintf(dest->pub.output_file, "P6\n%ld %ld\n%d\n", (long) cinfo->output_width, (long) cinfo->output_height, PPM_MAXVAL); break; default: ERREXIT(cinfo, JERR_PPM_COLORSPACE); } } /* * Finish up at the end of the file. */ METHODDEF(void) finish_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { /* Make sure we wrote the output file OK */ fflush(dinfo->output_file); if (ferror(dinfo->output_file)) ERREXIT(cinfo, JERR_FILE_WRITE); } /* * The module selection routine for PPM format output. */ GLOBAL(djpeg_dest_ptr) jinit_write_ppm (j_decompress_ptr cinfo) { ppm_dest_ptr dest; /* Create module interface object, fill in method pointers */ dest = (ppm_dest_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(ppm_dest_struct)); dest->pub.start_output = start_output_ppm; dest->pub.finish_output = finish_output_ppm; /* Calculate output image dimensions so we can allocate space */ jpeg_calc_output_dimensions(cinfo); /* Create physical I/O buffer. Note we make this near on a PC. */ dest->samples_per_row = cinfo->output_width * cinfo->out_color_components; dest->buffer_width = dest->samples_per_row * (BYTESPERSAMPLE * SIZEOF(char)); dest->iobuffer = (char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width); if (cinfo->quantize_colors || BITS_IN_JSAMPLE != 8 || SIZEOF(JSAMPLE) != SIZEOF(char)) { /* When quantizing, we need an output buffer for colormap indexes * that's separate from the physical I/O buffer. We also need a * separate buffer if pixel format translation must take place. */ dest->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width * cinfo->output_components, (JDIMENSION) 1); dest->pub.buffer_height = 1; if (! cinfo->quantize_colors) dest->pub.put_pixel_rows = copy_pixel_rows; else if (cinfo->out_color_space == JCS_GRAYSCALE) dest->pub.put_pixel_rows = put_demapped_gray; else dest->pub.put_pixel_rows = put_demapped_rgb; } else { /* We will fwrite() directly from decompressor output buffer. */ /* Synthesize a JSAMPARRAY pointer structure */ /* Cast here implies near->far pointer conversion on PCs */ dest->pixrow = (JSAMPROW) dest->iobuffer; dest->pub.buffer = & dest->pixrow; dest->pub.buffer_height = 1; dest->pub.put_pixel_rows = put_pixel_rows; } return (djpeg_dest_ptr) dest; } #endif /* PPM_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/wrrle.c ================================================ /* * wrrle.c * * Copyright (C) 1991-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to write output images in RLE format. * The Utah Raster Toolkit library is required (version 3.1 or later). * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume output to * an ordinary stdio stream. * * Based on code contributed by Mike Lijewski, * with updates from Robert Hutchinson. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef RLE_SUPPORTED /* rle.h is provided by the Utah Raster Toolkit. */ #include /* * We assume that JSAMPLE has the same representation as rle_pixel, * to wit, "unsigned char". Hence we can't cope with 12- or 16-bit samples. */ #if BITS_IN_JSAMPLE != 8 Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */ #endif /* * Since RLE stores scanlines bottom-to-top, we have to invert the image * from JPEG's top-to-bottom order. To do this, we save the outgoing data * in a virtual array during put_pixel_row calls, then actually emit the * RLE file during finish_output. */ /* * For now, if we emit an RLE color map then it is always 256 entries long, * though not all of the entries need be used. */ #define CMAPBITS 8 #define CMAPLENGTH (1<<(CMAPBITS)) typedef struct { struct djpeg_dest_struct pub; /* public fields */ jvirt_sarray_ptr image; /* virtual array to store the output image */ rle_map *colormap; /* RLE-style color map, or NULL if none */ rle_pixel **rle_row; /* To pass rows to rle_putrow() */ } rle_dest_struct; typedef rle_dest_struct * rle_dest_ptr; /* Forward declarations */ METHODDEF(void) rle_put_pixel_rows JPP((j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied)); /* * Write the file header. * * In this module it's easier to wait till finish_output to write anything. */ METHODDEF(void) start_output_rle (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { rle_dest_ptr dest = (rle_dest_ptr) dinfo; size_t cmapsize; int i, ci; #ifdef PROGRESS_REPORT cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; #endif /* * Make sure the image can be stored in RLE format. * * - RLE stores image dimensions as *signed* 16 bit integers. JPEG * uses unsigned, so we have to check the width. * * - Colorspace is expected to be grayscale or RGB. * * - The number of channels (components) is expected to be 1 (grayscale/ * pseudocolor) or 3 (truecolor/directcolor). * (could be 2 or 4 if using an alpha channel, but we aren't) */ if (cinfo->output_width > 32767 || cinfo->output_height > 32767) ERREXIT2(cinfo, JERR_RLE_DIMENSIONS, cinfo->output_width, cinfo->output_height); if (cinfo->out_color_space != JCS_GRAYSCALE && cinfo->out_color_space != JCS_RGB) ERREXIT(cinfo, JERR_RLE_COLORSPACE); if (cinfo->output_components != 1 && cinfo->output_components != 3) ERREXIT1(cinfo, JERR_RLE_TOOMANYCHANNELS, cinfo->num_components); /* Convert colormap, if any, to RLE format. */ dest->colormap = NULL; if (cinfo->quantize_colors) { /* Allocate storage for RLE-style cmap, zero any extra entries */ cmapsize = cinfo->out_color_components * CMAPLENGTH * SIZEOF(rle_map); dest->colormap = (rle_map *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, cmapsize); MEMZERO(dest->colormap, cmapsize); /* Save away data in RLE format --- note 8-bit left shift! */ /* Shifting would need adjustment for JSAMPLEs wider than 8 bits. */ for (ci = 0; ci < cinfo->out_color_components; ci++) { for (i = 0; i < cinfo->actual_number_of_colors; i++) { dest->colormap[ci * CMAPLENGTH + i] = GETJSAMPLE(cinfo->colormap[ci][i]) << 8; } } } /* Set the output buffer to the first row */ dest->pub.buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, dest->image, (JDIMENSION) 0, (JDIMENSION) 1, TRUE); dest->pub.buffer_height = 1; dest->pub.put_pixel_rows = rle_put_pixel_rows; #ifdef PROGRESS_REPORT if (progress != NULL) { progress->total_extra_passes++; /* count file writing as separate pass */ } #endif } /* * Write some pixel data. * * This routine just saves the data away in a virtual array. */ METHODDEF(void) rle_put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) { rle_dest_ptr dest = (rle_dest_ptr) dinfo; if (cinfo->output_scanline < cinfo->output_height) { dest->pub.buffer = (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, dest->image, cinfo->output_scanline, (JDIMENSION) 1, TRUE); } } /* * Finish up at the end of the file. * * Here is where we really output the RLE file. */ METHODDEF(void) finish_output_rle (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { rle_dest_ptr dest = (rle_dest_ptr) dinfo; rle_hdr header; /* Output file information */ rle_pixel **rle_row, *red, *green, *blue; JSAMPROW output_row; char cmapcomment[80]; int row, col; int ci; #ifdef PROGRESS_REPORT cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress; #endif /* Initialize the header info */ header = *rle_hdr_init(NULL); header.rle_file = dest->pub.output_file; header.xmin = 0; header.xmax = cinfo->output_width - 1; header.ymin = 0; header.ymax = cinfo->output_height - 1; header.alpha = 0; header.ncolors = cinfo->output_components; for (ci = 0; ci < cinfo->output_components; ci++) { RLE_SET_BIT(header, ci); } if (cinfo->quantize_colors) { header.ncmap = cinfo->out_color_components; header.cmaplen = CMAPBITS; header.cmap = dest->colormap; /* Add a comment to the output image with the true colormap length. */ sprintf(cmapcomment, "color_map_length=%d", cinfo->actual_number_of_colors); rle_putcom(cmapcomment, &header); } /* Emit the RLE header and color map (if any) */ rle_put_setup(&header); /* Now output the RLE data from our virtual array. * We assume here that (a) rle_pixel is represented the same as JSAMPLE, * and (b) we are not on a machine where FAR pointers differ from regular. */ #ifdef PROGRESS_REPORT if (progress != NULL) { progress->pub.pass_limit = cinfo->output_height; progress->pub.pass_counter = 0; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } #endif if (cinfo->output_components == 1) { for (row = cinfo->output_height-1; row >= 0; row--) { rle_row = (rle_pixel **) (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, dest->image, (JDIMENSION) row, (JDIMENSION) 1, FALSE); rle_putrow(rle_row, (int) cinfo->output_width, &header); #ifdef PROGRESS_REPORT if (progress != NULL) { progress->pub.pass_counter++; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } #endif } } else { for (row = cinfo->output_height-1; row >= 0; row--) { rle_row = (rle_pixel **) dest->rle_row; output_row = * (*cinfo->mem->access_virt_sarray) ((j_common_ptr) cinfo, dest->image, (JDIMENSION) row, (JDIMENSION) 1, FALSE); red = rle_row[0]; green = rle_row[1]; blue = rle_row[2]; for (col = cinfo->output_width; col > 0; col--) { *red++ = GETJSAMPLE(*output_row++); *green++ = GETJSAMPLE(*output_row++); *blue++ = GETJSAMPLE(*output_row++); } rle_putrow(rle_row, (int) cinfo->output_width, &header); #ifdef PROGRESS_REPORT if (progress != NULL) { progress->pub.pass_counter++; (*progress->pub.progress_monitor) ((j_common_ptr) cinfo); } #endif } } #ifdef PROGRESS_REPORT if (progress != NULL) progress->completed_extra_passes++; #endif /* Emit file trailer */ rle_puteof(&header); fflush(dest->pub.output_file); if (ferror(dest->pub.output_file)) ERREXIT(cinfo, JERR_FILE_WRITE); } /* * The module selection routine for RLE format output. */ GLOBAL(djpeg_dest_ptr) jinit_write_rle (j_decompress_ptr cinfo) { rle_dest_ptr dest; /* Create module interface object, fill in method pointers */ dest = (rle_dest_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(rle_dest_struct)); dest->pub.start_output = start_output_rle; dest->pub.finish_output = finish_output_rle; /* Calculate output image dimensions so we can allocate space */ jpeg_calc_output_dimensions(cinfo); /* Allocate a work array for output to the RLE library. */ dest->rle_row = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) cinfo->output_components); /* Allocate a virtual array to hold the image. */ dest->image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, (JDIMENSION) (cinfo->output_width * cinfo->output_components), cinfo->output_height, (JDIMENSION) 1); return (djpeg_dest_ptr) dest; } #endif /* RLE_SUPPORTED */ ================================================ FILE: tess-two/jni/libjpeg/wrtarga.c ================================================ /* * wrtarga.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modified 2015 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains routines to write output images in Targa format. * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume output to * an ordinary stdio stream. * * Based on code contributed by Lee Daniel Crocker. */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef TARGA_SUPPORTED /* * To support 12-bit JPEG data, we'd have to scale output down to 8 bits. * This is not yet implemented. */ #if BITS_IN_JSAMPLE != 8 Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */ #endif /* * The output buffer needs to be writable by fwrite(). On PCs, we must * allocate the buffer in near data space, because we are assuming small-data * memory model, wherein fwrite() can't reach far memory. If you need to * process very wide images on a PC, you might have to compile in large-memory * model, or else replace fwrite() with a putc() loop --- which will be much * slower. */ /* Private version of data destination object */ typedef struct { struct djpeg_dest_struct pub; /* public fields */ char *iobuffer; /* physical I/O buffer */ JDIMENSION buffer_width; /* width of one row */ } tga_dest_struct; typedef tga_dest_struct * tga_dest_ptr; LOCAL(void) write_header (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, int num_colors) /* Create and write a Targa header */ { char targaheader[18]; /* Set unused fields of header to 0 */ MEMZERO(targaheader, SIZEOF(targaheader)); if (num_colors > 0) { targaheader[1] = 1; /* color map type 1 */ targaheader[5] = (char) (num_colors & 0xFF); targaheader[6] = (char) (num_colors >> 8); targaheader[7] = 24; /* 24 bits per cmap entry */ } targaheader[12] = (char) (cinfo->output_width & 0xFF); targaheader[13] = (char) (cinfo->output_width >> 8); targaheader[14] = (char) (cinfo->output_height & 0xFF); targaheader[15] = (char) (cinfo->output_height >> 8); targaheader[17] = 0x20; /* Top-down, non-interlaced */ if (cinfo->out_color_space == JCS_GRAYSCALE) { targaheader[2] = 3; /* image type = uncompressed grayscale */ targaheader[16] = 8; /* bits per pixel */ } else { /* must be RGB */ if (num_colors > 0) { targaheader[2] = 1; /* image type = colormapped RGB */ targaheader[16] = 8; } else { targaheader[2] = 2; /* image type = uncompressed RGB */ targaheader[16] = 24; } } if (JFWRITE(dinfo->output_file, targaheader, 18) != (size_t) 18) ERREXIT(cinfo, JERR_FILE_WRITE); } /* * Write some pixel data. * In this module rows_supplied will always be 1. */ METHODDEF(void) put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) /* used for unquantized full-color output */ { tga_dest_ptr dest = (tga_dest_ptr) dinfo; register JSAMPROW inptr; register char * outptr; register JDIMENSION col; inptr = dest->pub.buffer[0]; outptr = dest->iobuffer; for (col = cinfo->output_width; col > 0; col--) { outptr[0] = (char) GETJSAMPLE(inptr[2]); /* RGB to BGR order */ outptr[1] = (char) GETJSAMPLE(inptr[1]); outptr[2] = (char) GETJSAMPLE(inptr[0]); inptr += 3, outptr += 3; } (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); } METHODDEF(void) put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) /* used for grayscale OR quantized color output */ { tga_dest_ptr dest = (tga_dest_ptr) dinfo; register JSAMPROW inptr; register char * outptr; register JDIMENSION col; inptr = dest->pub.buffer[0]; outptr = dest->iobuffer; for (col = cinfo->output_width; col > 0; col--) { *outptr++ = (char) GETJSAMPLE(*inptr++); } (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); } /* * Write some demapped pixel data when color quantization is in effect. * For Targa, this is only applied to grayscale data. */ METHODDEF(void) put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) { tga_dest_ptr dest = (tga_dest_ptr) dinfo; register JSAMPROW inptr; register char * outptr; register JSAMPROW color_map0 = cinfo->colormap[0]; register JDIMENSION col; inptr = dest->pub.buffer[0]; outptr = dest->iobuffer; for (col = cinfo->output_width; col > 0; col--) { *outptr++ = (char) GETJSAMPLE(color_map0[GETJSAMPLE(*inptr++)]); } (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); } /* * Startup: write the file header. */ METHODDEF(void) start_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { tga_dest_ptr dest = (tga_dest_ptr) dinfo; int num_colors, i; FILE *outfile; if (cinfo->out_color_space == JCS_GRAYSCALE) { /* Targa doesn't have a mapped grayscale format, so we will */ /* demap quantized gray output. Never emit a colormap. */ write_header(cinfo, dinfo, 0); if (cinfo->quantize_colors) dest->pub.put_pixel_rows = put_demapped_gray; else dest->pub.put_pixel_rows = put_gray_rows; } else if (cinfo->out_color_space == JCS_RGB) { if (cinfo->quantize_colors) { /* We only support 8-bit colormap indexes, so only 256 colors */ num_colors = cinfo->actual_number_of_colors; if (num_colors > 256) ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, num_colors); write_header(cinfo, dinfo, num_colors); /* Write the colormap. Note Targa uses BGR byte order */ outfile = dest->pub.output_file; for (i = 0; i < num_colors; i++) { putc(GETJSAMPLE(cinfo->colormap[2][i]), outfile); putc(GETJSAMPLE(cinfo->colormap[1][i]), outfile); putc(GETJSAMPLE(cinfo->colormap[0][i]), outfile); } dest->pub.put_pixel_rows = put_gray_rows; } else { write_header(cinfo, dinfo, 0); dest->pub.put_pixel_rows = put_pixel_rows; } } else { ERREXIT(cinfo, JERR_TGA_COLORSPACE); } } /* * Finish up at the end of the file. */ METHODDEF(void) finish_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { /* Make sure we wrote the output file OK */ fflush(dinfo->output_file); if (ferror(dinfo->output_file)) ERREXIT(cinfo, JERR_FILE_WRITE); } /* * The module selection routine for Targa format output. */ GLOBAL(djpeg_dest_ptr) jinit_write_targa (j_decompress_ptr cinfo) { tga_dest_ptr dest; /* Create module interface object, fill in method pointers */ dest = (tga_dest_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(tga_dest_struct)); dest->pub.start_output = start_output_tga; dest->pub.finish_output = finish_output_tga; /* Calculate output image dimensions so we can allocate space */ jpeg_calc_output_dimensions(cinfo); /* Create I/O buffer. Note we make this near on a PC. */ dest->buffer_width = cinfo->output_width * cinfo->output_components; dest->iobuffer = (char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (size_t) (dest->buffer_width * SIZEOF(char))); /* Create decompressor output buffer. */ dest->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width, (JDIMENSION) 1); dest->pub.buffer_height = 1; return &dest->pub; } #endif /* TARGA_SUPPORTED */ ================================================ FILE: tess-two/jni/libpng/ANNOUNCE ================================================ Libpng 1.6.25 - September 1, 2016 This is a public release of libpng, intended for use in production codes. Files available for download: Source files with LF line endings (for Unix/Linux) and with a "configure" script libpng-1.6.25.tar.xz (LZMA-compressed, recommended) libpng-1.6.25.tar.gz Source files with CRLF line endings (for Windows), without the "configure" script lpng1625.7z (LZMA-compressed, recommended) lpng1625.zip Other information: libpng-1.6.25-README.txt libpng-1.6.25-LICENSE.txt libpng-1.6.25-*.asc (armored detached GPG signatures) Changes since the last public release (1.6.24): Reject oversized iCCP profile immediately. Cleaned up PNG_DEBUG compile of pngtest.c. Conditionally compile png_inflate(). Don't install pngcp; it conflicts with pngcp in the pngtools package. Minor editing of INSTALL, (whitespace, added copyright line) Added MIPS support (Mandar Sahastrabuddhe ). Rebased contrib/intel/intel_sse.patch after the MIPS implementation. (subscription required; visit https://lists.sourceforge.net/lists/listinfo/png-mng-implement to subscribe) or to glennrp at users.sourceforge.net Glenn R-P ================================================ FILE: tess-two/jni/libpng/Android.bp ================================================ // We need to build this for both the device (as a shared library) // and the host (as a static library for tools to use). cc_defaults { name: "libpng-defaults", srcs: [ "png.c", "pngerror.c", "pngget.c", "pngmem.c", "pngpread.c", "pngread.c", "pngrio.c", "pngrtran.c", "pngrutil.c", "pngset.c", "pngtrans.c", "pngwio.c", "pngwrite.c", "pngwtran.c", "pngwutil.c", ], cflags: [ "-std=gnu89", "-Wno-unused-parameter", ], arch: { arm: { srcs: [ "arm/arm_init.c", "arm/filter_neon.S", "arm/filter_neon_intrinsics.c", ], }, arm64: { srcs: [ "arm/arm_init.c", "arm/filter_neon.S", "arm/filter_neon_intrinsics.c", ], }, x86: { srcs: [ "contrib/intel/intel_init.c", "contrib/intel/filter_sse2_intrinsics.c", ], // Disable optimizations because they crash on windows // cflags: ["-DPNG_INTEL_SSE_OPT=1"], }, x86_64: { srcs: [ "contrib/intel/intel_init.c", "contrib/intel/filter_sse2_intrinsics.c", ], // Disable optimizations because they crash on windows // cflags: ["-DPNG_INTEL_SSE_OPT=1"], }, }, target: { android: { shared_libs: ["libz"], }, android_x86: { cflags: ["-DPNG_INTEL_SSE_OPT=1"], }, android_x86_64: { cflags: ["-DPNG_INTEL_SSE_OPT=1"], }, host: { shared_libs: ["libz-host"], }, }, export_include_dirs: ["."], clang: true, } // For the host and device platform // ===================================================== cc_library { name: "libpng", host_supported: true, defaults: ["libpng-defaults"], target: { windows: { enabled: true, }, }, } // For the device (static) for NDK // ===================================================== cc_library_static { name: "libpng_ndk", defaults: ["libpng-defaults"], cflags: ["-ftrapv"], shared_libs: ["libz"], sdk_version: "14", } // For testing // ===================================================== cc_test { clang: true, host_supported: true, gtest: false, srcs: ["pngtest.c"], name: "pngtest", shared_libs: [ "libpng", ], target: { android: { shared_libs: ["libz"], }, host: { shared_libs: ["libz-host"], }, }, } ================================================ FILE: tess-two/jni/libpng/Android.mk ================================================ LOCAL_PATH:= $(call my-dir) common_SRC_FILES := \ png.c \ pngerror.c \ pngget.c \ pngmem.c \ pngpread.c \ pngread.c \ pngrio.c \ pngrtran.c \ pngrutil.c \ pngset.c \ pngtrans.c \ pngwio.c \ pngwrite.c \ pngwtran.c \ pngwutil.c \ ifeq ($(ARCH_ARM_HAVE_NEON),true) my_cflags_arm := -DPNG_ARM_NEON_OPT=2 endif my_cflags_arm64 := -DPNG_ARM_NEON_OPT=2 my_src_files_arm := \ arm/arm_init.c \ arm/filter_neon.S \ arm/filter_neon_intrinsics.c common_CFLAGS := -std=gnu89 #-fvisibility=hidden ## -fomit-frame-pointer include $(CLEAR_VARS) LOCAL_CLANG := true LOCAL_SRC_FILES := $(common_SRC_FILES) LOCAL_CFLAGS += $(common_CFLAGS) -ftrapv LOCAL_CFLAGS_arm := $(my_cflags_arm) LOCAL_ASFLAGS += $(common_ASFLAGS) LOCAL_SRC_FILES_arm := $(my_src_files_arm) LOCAL_CFLAGS_arm64 := $(my_cflags_arm64) LOCAL_SRC_FILES_arm64 := $(my_src_files_arm) LOCAL_SANITIZE := never LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH) LOCAL_EXPORT_LDLIBS := -lz LOCAL_MODULE:= libpngt_static include $(BUILD_STATIC_LIBRARY) ================================================ FILE: tess-two/jni/libpng/CHANGES ================================================ #if 0 CHANGES - changes for libpng version 0.1 [March 29, 1995] initial work-in-progress release version 0.2 [April 1, 1995] added reader into png.h fixed small problems in stub file version 0.3 [April 8, 1995] added pull reader split up pngwrite.c to several files added pnglib.txt added example.c cleaned up writer, adding a few new transformations fixed some bugs in writer interfaced with zlib 0.5 added K&R support added check for 64 KB blocks for 16 bit machines version 0.4 [April 26, 1995] cleaned up code and commented code simplified time handling into png_time created png_color_16 and png_color_8 to handle color needs cleaned up color type defines fixed various bugs made various names more consistent interfaced with zlib 0.71 cleaned up zTXt reader and writer (using zlib's Reset functions) split transformations into pngrtran.c and pngwtran.c version 0.5 [April 30, 1995] interfaced with zlib 0.8 fixed many reading and writing bugs saved using 3 spaces instead of tabs version 0.6 [May 1, 1995] first beta release added png_large_malloc() and png_large_free() added png_size_t cleaned up some compiler warnings added png_start_read_image() version 0.7 [June 24, 1995] cleaned up lots of bugs finished dithering and other stuff added test program changed name from pnglib to libpng version 0.71 [June 26, 1995] changed pngtest.png for zlib 0.93 fixed error in libpng.txt and example.c version 0.8 [August 20, 1995] cleaned up some bugs added png_set_filler() split up pngstub.c into pngmem.c, pngio.c, and pngerror.c added #define's to remove unwanted code moved png_info_init() to png.c added old_size into png_realloc() added functions to manually set filtering and compression info changed compression parameters based on image type optimized filter selection code added version info changed external functions passing floats to doubles (k&r problems?) put all the configurable stuff in pngconf.h enabled png_set_shift to work with paletted images on read added png_read_update_info() - updates info structure with transformations Version 0.81 [August, 1995] incorporated Tim Wegner's medium model code (thanks, Tim) Version 0.82 [September, 1995] [unspecified changes] Version 0.85 [December, 1995] added more medium model code (almost everything's a far) added i/o, error, and memory callback functions fixed some bugs (16-bit, 4-bit interlaced, etc.) added first run progressive reader (barely tested) Version 0.86 [January, 1996] fixed bugs improved documentation Version 0.87 [January, 1996] fixed medium model bugs fixed other bugs introduced in 0.85 and 0.86 added some minor documentation Version 0.88 [January, 1996] fixed progressive bugs replaced tabs with spaces cleaned up documentation added callbacks for read/write and warning/error functions Version 0.89 [June 5, 1996] Added new initialization API to make libpng work better with shared libs we now have png_create_read_struct(), png_create_write_struct(), png_create_info_struct(), png_destroy_read_struct(), and png_destroy_write_struct() instead of the separate calls to malloc and png_read_init(), png_info_init(), and png_write_init() Changed warning/error callback functions to fix bug - this means you should use the new initialization API if you were using the old png_set_message_fn() calls, and that the old API no longer exists so that people are aware that they need to change their code Changed filter selection API to allow selection of multiple filters since it didn't work in previous versions of libpng anyways Optimized filter selection code Fixed png_set_background() to allow using an arbitrary RGB color for paletted images Fixed gamma and background correction for paletted images, so png_correct_palette is not needed unless you are correcting an external palette (you will need to #define PNG_CORRECT_PALETTE_SUPPORTED in pngconf.h) - if nobody uses this, it may disappear in the future. Fixed bug with Borland 64K memory allocation (Alexander Lehmann) Fixed bug in interlace handling (Smarasderagd, I think) Added more error checking for writing and image to reduce invalid files Separated read and write functions so that they won't both be linked into a binary when only reading or writing functionality is used New pngtest image also has interlacing and zTXt Updated documentation to reflect new API Version 0.89c [June 17, 1996] Bug fixes. Version 0.90 [January, 1997] Made CRC errors/warnings on critical and ancillary chunks configurable libpng will use the zlib CRC routines by (compile-time) default Changed DOS small/medium model memory support - needs zlib 1.04 (Tim Wegner) Added external C++ wrapper statements to png.h (Gilles Dauphin) Allow PNG file to be read when some or all of file signature has already been read from the beginning of the stream. ****This affects the size of info_struct and invalidates all programs that use a shared libpng**** Fixed png_filler() declarations Fixed? background color conversions Fixed order of error function pointers to match documentation Current chunk name is now available in png_struct to reduce the number of nearly identical error messages (will simplify multi-lingual support when available) Try to get ready for unknown-chunk callback functions: - previously read critical chunks are flagged, so the chunk handling routines can determine if the chunk is in the right place - all chunk handling routines have the same prototypes, so we will be able to handle all chunks via a callback mechanism Try to fix Linux "setjmp" buffer size problems Removed png_large_malloc, png_large_free, and png_realloc functions. Version 0.95 [March, 1997] Fixed bug in pngwutil.c allocating "up_row" twice and "avg_row" never Fixed bug in PNG file signature compares when start != 0 Changed parameter type of png_set_filler(...filler...) from png_byte to png_uint_32 Added test for MACOS to ensure that both math.h and fp.h are not #included Added macros for libpng to be compiled as a Windows DLL (Andreas Kupries) Added "packswap" transformation, which changes the endianness of packed-pixel bytes (Kevin Bracey) Added "strip_alpha" transformation, which removes the alpha channel of input images without using it (not necessarily a good idea) Added "swap_alpha" transformation, which puts the alpha channel in front of the color bytes instead of after Removed all implicit variable tests which assume NULL == 0 (I think) Changed several variables to "png_size_t" to show 16/32-bit limitations Added new pCAL chunk read/write support Added experimental filter selection weighting (Greg Roelofs) Removed old png_set_rgbx() and png_set_xrgb() functions that have been obsolete for about 2 years now (use png_set_filler() instead) Added macros to read 16- and 32-bit ints directly from buffer, to be used only on those systems that support it (namely PowerPC and 680x0) With some testing, this may become the default for MACOS/PPC systems. Only calculate CRC on data if we are going to use it Added macros for zTXt compression type PNG_zTXt_COMPRESSION_??? Added macros for simple libpng debugging output selectable at compile time Removed PNG_READ_END_MODE in progressive reader (Smarasderagd) More description of info_struct in libpng.txt and png.h More instructions in example.c More chunk types tested in pngtest.c Renamed pngrcb.c to pngset.c, and all png_read_ functions to be png_set_. We now have corresponding png_get_ functions in pngget.c to get information in info_ptr. This isolates the application from the internal organization of png_info_struct (good for shared library implementations). Version 0.96 [May, 1997] Fixed serious bug with < 8bpp images introduced in 0.95 Fixed 256-color transparency bug (Greg Roelofs) Fixed up documentation (Greg Roelofs, Laszlo Nyul) Fixed "error" in pngconf.h for Linux setjmp() behavior Fixed DOS medium model support (Tim Wegner) Fixed png_check_keyword() for case with error in static string text Added read of CRC after IEND chunk for embedded PNGs (Laszlo Nyul) Added typecasts to quiet compiler errors Added more debugging info Version 0.97 [January, 1998] Removed PNG_USE_OWN_CRC capability Relocated png_set_crc_action from pngrutil.c to pngrtran.c Fixed typecasts of "new_key", etc. (Andreas Dilger) Added RFC 1152 [sic] date support Fixed bug in gamma handling of 4-bit grayscale Added 2-bit grayscale gamma handling (Glenn R-P) Added more typecasts. 65536L becomes (png_uint_32)65536L, etc. (Glenn R-P) Minor corrections in libpng.txt Added simple sRGB support (Glenn R-P) Easier conditional compiling, e.g., define PNG_READ/WRITE_NOT_FULLY_SUPPORTED; all configurable options can be selected from command-line instead of having to edit pngconf.h (Glenn R-P) Fixed memory leak in pngwrite.c (free info_ptr->text) (Glenn R-P) Added more conditions for png_do_background, to avoid changing black pixels to background when a background is supplied and no pixels are transparent Repaired PNG_NO_STDIO behavior Tested NODIV support and made it default behavior (Greg Roelofs) Added "-m" option and PNGTEST_DEBUG_MEMORY to pngtest (John Bowler) Regularized version numbering scheme and bumped shared-library major version number to 2 to avoid problems with libpng 0.89 apps (Greg Roelofs) Version 0.98 [January, 1998] Cleaned up some typos in libpng.txt and in code documentation Fixed memory leaks in pCAL chunk processing (Glenn R-P and John Bowler) Cosmetic change "display_gamma" to "screen_gamma" in pngrtran.c Changed recommendation about file_gamma for PC images to .51 from .45, in example.c and libpng.txt, added comments to distinguish between screen_gamma, viewing_gamma, and display_gamma. Changed all references to RFC1152 to read RFC1123 and changed the PNG_TIME_RFC1152_SUPPORTED macro to PNG_TIME_RFC1123_SUPPORTED Added png_invert_alpha capability (Glenn R-P -- suggestion by Jon Vincent) Changed srgb_intent from png_byte to int to avoid compiler bugs Version 0.99 [January 30, 1998] Free info_ptr->text instead of end_info_ptr->text in pngread.c (John Bowler) Fixed a longstanding "packswap" bug in pngtrans.c Fixed some inconsistencies in pngconf.h that prevented compiling with PNG_READ_GAMMA_SUPPORTED and PNG_READ_hIST_SUPPORTED undefined Fixed some typos and made other minor rearrangement of libpng.txt (Andreas) Changed recommendation about file_gamma for PC images to .50 from .51 in example.c and libpng.txt, and changed file_gamma for sRGB images to .45 Added a number of functions to access information from the png structure png_get_image_height(), etc. (Glenn R-P, suggestion by Brad Pettit) Added TARGET_MACOS similar to zlib-1.0.8 Define PNG_ALWAYS_EXTERN when __MWERKS__ && WIN32 are defined Added type casting to all png_malloc() function calls Version 0.99a [January 31, 1998] Added type casts and parentheses to all returns that return a value.(Tim W.) Version 0.99b [February 4, 1998] Added type cast png_uint_32 on malloc function calls where needed. Changed type of num_hist from png_uint_32 to int (same as num_palette). Added checks for rowbytes overflow, in case png_size_t is less than 32 bits. Renamed makefile.elf to makefile.lnx. Version 0.99c [February 7, 1998] More type casting. Removed erroneous overflow test in pngmem.c. Added png_buffered_memcpy() and png_buffered_memset(), apply them to rowbytes. Added UNIX manual pages libpng.3 (incorporating libpng.txt) and png.5. Version 0.99d [February 11, 1998] Renamed "far_to_near()" "png_far_to_near()" Revised libpng.3 Version 99c "buffered" operations didn't work as intended. Replaced them with png_memcpy_check() and png_memset_check(). Added many "if (png_ptr == NULL) return" to quell compiler warnings about unused png_ptr, mostly in pngget.c and pngset.c. Check for overlength tRNS chunk present when indexed-color PLTE is read. Cleaned up spelling errors in libpng.3/libpng.txt Corrected a problem with png_get_tRNS() which returned undefined trans array Version 0.99e [February 28, 1998] Corrected png_get_tRNS() again. Add parentheses for easier reading of pngget.c, fixed "||" should be "&&". Touched up example.c to make more of it compileable, although the entire file still can't be compiled (Willem van Schaik) Fixed a bug in png_do_shift() (Bryan Tsai) Added a space in png.h prototype for png_write_chunk_start() Replaced pngtest.png with one created with zlib 1.1.1 Changed pngtest to report PASS even when file size is different (Jean-loup G.) Corrected some logic errors in png_do_invert_alpha() (Chris Patterson) Version 0.99f [March 5, 1998] Corrected a bug in pngpread() introduced in version 99c (Kevin Bracey) Moved makefiles into a "scripts" directory, and added INSTALL instruction file Added makefile.os2 and pngos2.def (A. Zabolotny) and makefile.s2x (W. Sebok) Added pointers to "note on libpng versions" in makefile.lnx and README Added row callback feature when reading and writing nonprogressive rows and added a test of this feature in pngtest.c Added user transform callbacks, with test of the feature in pngtest.c Version 0.99g [March 6, 1998, morning] Minor changes to pngtest.c to suppress compiler warnings. Removed "beta" language from documentation. Version 0.99h [March 6, 1998, evening] Minor changes to previous minor changes to pngtest.c Changed PNG_READ_NOT_FULLY_SUPPORTED to PNG_READ_TRANSFORMS_NOT_SUPPORTED and added PNG_PROGRESSIVE_READ_NOT_SUPPORTED macro Added user transform capability Version 1.00 [March 7, 1998] Changed several typedefs in pngrutil.c Added makefile.wat (Pawel Mrochen), updated makefile.tc3 (Willem van Schaik) Replaced "while(1)" with "for(;;)" Added PNGARG() to prototypes in pngtest.c and removed some prototypes Updated some of the makefiles (Tom Lane) Changed some typedefs (s_start, etc.) in pngrutil.c Fixed dimensions of "short_months" array in pngwrite.c Replaced ansi2knr.c with the one from jpeg-v6 Version 1.0.0 [March 8, 1998] Changed name from 1.00 to 1.0.0 (Adam Costello) Added smakefile.ppc (with SCOPTIONS.ppc) for Amiga PPC (Andreas Kleinert) Version 1.0.0a [March 9, 1998] Fixed three bugs in pngrtran.c to make gamma+background handling consistent (Greg Roelofs) Changed format of the PNG_LIBPNG_VER integer to xyyzz instead of xyz for major, minor, and bugfix releases. This is 10001. (Adam Costello, Tom Lane) Make months range from 1-12 in png_convert_to_rfc1123 Version 1.0.0b [March 13, 1998] Quieted compiler complaints about two empty "for" loops in pngrutil.c Minor changes to makefile.s2x Removed #ifdef/#endif around a png_free() in pngread.c Version 1.0.1 [March 14, 1998] Changed makefile.s2x to reduce security risk of using a relative pathname Fixed some typos in the documentation (Greg). Fixed a problem with value of "channels" returned by png_read_update_info() Version 1.0.1a [April 21, 1998] Optimized Paeth calculations by replacing abs() function calls with intrinsics plus other loop optimizations. Improves avg decoding speed by about 20%. Commented out i386istic "align" compiler flags in makefile.lnx. Reduced the default warning level in some makefiles, to make them consistent. Removed references to IJG and JPEG in the ansi2knr.c copyright statement. Fixed a bug in png_do_strip_filler with XXRRGGBB => RRGGBB transformation. Added grayscale and 16-bit capability to png_do_read_filler(). Fixed a bug in pngset.c, introduced in version 0.99c, that sets rowbytes too large when writing an image with bit_depth < 8 (Bob Dellaca). Corrected some bugs in the experimental weighted filtering heuristics. Moved a misplaced pngrutil code block that truncates tRNS if it has more than num_palette entries -- test was done before num_palette was defined. Fixed a png_convert_to_rfc1123() bug that converts day 31 to 0 (Steve Eddins). Changed compiler flags in makefile.wat for better optimization (Pawel Mrochen). Version 1.0.1b [May 2, 1998] Relocated png_do_gray_to_rgb() within png_do_read_transformations() (Greg). Relocated the png_composite macros from pngrtran.c to png.h (Greg). Added makefile.sco (contributed by Mike Hopkirk). Fixed two bugs (missing definitions of "istop") introduced in libpng-1.0.1a. Fixed a bug in pngrtran.c that would set channels=5 under some circumstances. More work on the Paeth-filtering, achieving imperceptible speedup (A Kleinert). More work on loop optimization which may help when compiled with C++ compilers. Added warnings when people try to use transforms they've defined out. Collapsed 4 "i" and "c" loops into single "i" loops in pngrtran and pngwtran. Revised paragraph about png_set_expand() in libpng.txt and libpng.3 (Greg) Version 1.0.1c [May 11, 1998] Fixed a bug in pngrtran.c (introduced in libpng-1.0.1a) where the masks for filler bytes should have been 0xff instead of 0xf. Added max_pixel_depth=32 in pngrutil.c when using FILLER with palette images. Moved PNG_WRITE_WEIGHTED_FILTER_SUPPORTED and PNG_WRITE_FLUSH_SUPPORTED out of the PNG_WRITE_TRANSFORMS_NOT_SUPPORTED block of pngconf.h Added "PNG_NO_WRITE_TRANSFORMS" etc., as alternatives for *_NOT_SUPPORTED, for consistency, in pngconf.h Added individual "ifndef PNG_NO_[CAPABILITY]" in pngconf.h to make it easier to remove unwanted capabilities via the compile line Made some corrections to grammar (which, it's) in documentation (Greg). Corrected example.c, use of row_pointers in png_write_image(). Version 1.0.1d [May 24, 1998] Corrected several statements that used side effects illegally in pngrutil.c and pngtrans.c, that were introduced in version 1.0.1b Revised png_read_rows() to avoid repeated if-testing for NULL (A Kleinert) More corrections to example.c, use of row_pointers in png_write_image() and png_read_rows(). Added pngdll.mak and pngdef.pas to scripts directory, contributed by Bob Dellaca, to make a png32bd.dll with Borland C++ 4.5 Fixed error in example.c with png_set_text: num_text is 3, not 2 (Guido V.) Changed several loops from count-down to count-up, for consistency. Version 1.0.1e [June 6, 1998] Revised libpng.txt and libpng.3 description of png_set_read|write_fn(), and added warnings when people try to set png_read_fn and png_write_fn in the same structure. Added a test such that png_do_gamma will be done when num_trans==0 for truecolor images that have defined a background. This corrects an error that was introduced in libpng-0.90 that can cause gamma processing to be skipped. Added tests in png.h to include "trans" and "trans_values" in structures when PNG_READ_BACKGROUND_SUPPORTED or PNG_READ_EXPAND_SUPPORTED is defined. Add png_free(png_ptr->time_buffer) in png_destroy_read_struct() Moved png_convert_to_rfc_1123() from pngwrite.c to png.c Added capability for user-provided malloc_fn() and free_fn() functions, and revised pngtest.c to demonstrate their use, replacing the PNGTEST_DEBUG_MEM feature. Added makefile.w32, for Microsoft C++ 4.0 and later (Tim Wegner). Version 1.0.2 [June 14, 1998] Fixed two bugs in makefile.bor . Version 1.0.2a [December 30, 1998] Replaced and extended code that was removed from png_set_filler() in 1.0.1a. Fixed a bug in png_do_filler() that made it fail to write filler bytes in the left-most pixel of each row (Kevin Bracey). Changed "static pngcharp tIME_string" to "static char tIME_string[30]" in pngtest.c (Duncan Simpson). Fixed a bug in pngtest.c that caused pngtest to try to write a tIME chunk even when no tIME chunk was present in the source file. Fixed a problem in pngrutil.c: gray_to_rgb didn't always work with 16-bit. Fixed a problem in png_read_push_finish_row(), which would not skip some passes that it should skip, for images that are less than 3 pixels high. Interchanged the order of calls to png_do_swap() and png_do_shift() in pngwtran.c (John Cromer). Added #ifdef PNG_DEBUG/#endif surrounding use of PNG_DEBUG in png.h . Changed "bad adaptive filter type" from error to warning in pngrutil.c . Fixed a documentation error about default filtering with 8-bit indexed-color. Separated the PNG_NO_STDIO macro into PNG_NO_STDIO and PNG_NO_CONSOLE_IO (L. Peter Deutsch). Added png_set_rgb_to_gray() and png_get_rgb_to_gray_status() functions. Added png_get_copyright() and png_get_header_version() functions. Revised comments on png_set_progressive_read_fn() in libpng.txt and example.c Added information about debugging in libpng.txt and libpng.3 . Changed "ln -sf" to "ln -s -f" in makefile.s2x, makefile.lnx, and makefile.sco. Removed lines after Dynamic Dependencies" in makefile.aco . Revised makefile.dec to make a shared library (Jeremie Petit). Removed trailing blanks from all files. Version 1.0.2a [January 6, 1999] Removed misplaced #endif and #ifdef PNG_NO_EXTERN near the end of png.h Added "if" tests to silence complaints about unused png_ptr in png.h and png.c Changed "check_if_png" function in example.c to return true (nonzero) if PNG. Changed libpng.txt to demonstrate png_sig_cmp() instead of png_check_sig() which is obsolete. Version 1.0.3 [January 14, 1999] Added makefile.hux, for Hewlett Packard HPUX 10.20 and 11.00 (Jim Rice) Added a statement of Y2K compliance in png.h, libpng.3, and Y2KINFO. Version 1.0.3a [August 12, 1999] Added check for PNG_READ_INTERLACE_SUPPORTED in pngread.c; issue a warning if an attempt is made to read an interlaced image when it's not supported. Added check if png_ptr->trans is defined before freeing it in pngread.c Modified the Y2K statement to include versions back to version 0.71 Fixed a bug in the check for valid IHDR bit_depth/color_types in pngrutil.c Modified makefile.wat (added -zp8 flag, ".symbolic", changed some comments) Replaced leading blanks with tab characters in makefile.hux Changed "dworkin.wustl.edu" to "ccrc.wustl.edu" in various documents. Changed (float)red and (float)green to (double)red, (double)green in png_set_rgb_to_gray() to avoid "promotion" problems in AIX. Fixed a bug in pngconf.h that omitted when PNG_DEBUG==0 (K Bracey). Reformatted libpng.3 and libpngpf.3 with proper fonts (script by J. vanZandt). Updated documentation to refer to the PNG-1.2 specification. Removed ansi2knr.c and left pointers to the latest source for ansi2knr.c in makefile.knr, INSTALL, and README (L. Peter Deutsch) Fixed bugs in calculation of the length of rowbytes when adding alpha channels to 16-bit images, in pngrtran.c (Chris Nokleberg) Added function png_set_user_transform_info() to store user_transform_ptr, user_depth, and user_channels into the png_struct, and a function png_get_user_transform_ptr() to retrieve the pointer (Chris Nokleberg) Added function png_set_empty_plte_permitted() to make libpng useable in MNG applications. Corrected the typedef for png_free_ptr in png.h (Jesse Jones). Correct gamma with srgb is 45455 instead of 45000 in pngrutil.c, to be consistent with PNG-1.2, and allow variance of 500 before complaining. Added assembler code contributed by Intel in file pngvcrd.c and modified makefile.w32 to use it (Nirav Chhatrapati, INTEL Corporation, Gilles Vollant) Changed "ln -s -f" to "ln -f -s" in the makefiles to make Solaris happy. Added some aliases for png_set_expand() in pngrtran.c, namely png_set_expand_PLTE(), png_set_expand_depth(), and png_set_expand_tRNS() (Greg Roelofs, in "PNG: The Definitive Guide"). Added makefile.beo for BEOS on X86, contributed by Sander Stok. Version 1.0.3b [August 26, 1999] Replaced 2147483647L several places with PNG_MAX_UINT macro, defined in png.h Changed leading blanks to tabs in all makefiles. Define PNG_USE_PNGVCRD in makefile.w32, to get MMX assembler code. Made alternate versions of png_set_expand() in pngrtran.c, namely png_set_gray_1_2_4_to_8, png_set_palette_to_rgb, and png_set_tRNS_to_alpha (Greg Roelofs, in "PNG: The Definitive Guide"). Deleted the 1.0.3a aliases. Relocated start of 'extern "C"' block in png.h so it doesn't include pngconf.h Revised calculation of num_blocks in pngmem.c to avoid a potentially negative shift distance, whose results are undefined in the C language. Added a check in pngset.c to prevent writing multiple tIME chunks. Added a check in pngwrite.c to detect invalid small window_bits sizes. Version 1.0.3d [September 4, 1999] Fixed type casting of igamma in pngrutil.c Added new png_expand functions to scripts/pngdef.pas and pngos2.def Added a demo read_user_transform_fn that examines the row filters in pngtest.c Version 1.0.4 [September 24, 1999, not distributed publicly] Define PNG_ALWAYS_EXTERN in pngconf.h if __STDC__ is defined Delete #define PNG_INTERNAL and include "png.h" from pngasmrd.h Made several minor corrections to pngtest.c Renamed the makefiles with longer but more user friendly extensions. Copied the PNG copyright and license to a separate LICENSE file. Revised documentation, png.h, and example.c to remove reference to "viewing_gamma" which no longer appears in the PNG specification. Revised pngvcrd.c to use MMX code for interlacing only on the final pass. Updated pngvcrd.c to use the faster C filter algorithms from libpng-1.0.1a Split makefile.win32vc into two versions, makefile.vcawin32 (uses MMX assembler code) and makefile.vcwin32 (doesn't). Added a CPU timing report to pngtest.c (enabled by defining PNGTEST_TIMING) Added a copy of pngnow.png to the distribution. Version 1.0.4a [September 25, 1999] Increase max_pixel_depth in pngrutil.c if a user transform needs it. Changed several division operations to right-shifts in pngvcrd.c Version 1.0.4b [September 30, 1999] Added parentheses in line 3732 of pngvcrd.c Added a comment in makefile.linux warning about buggy -O3 in pgcc 2.95.1 Version 1.0.4c [October 1, 1999] Added a "png_check_version" function in png.c and pngtest.c that will generate a helpful compiler error if an old png.h is found in the search path. Changed type of png_user_transform_depth|channels from int to png_byte. Added "Libpng is OSI Certified Open Source Software" statement to png.h Version 1.0.4d [October 6, 1999] Changed 0.45 to 0.45455 in png_set_sRGB() Removed unused PLTE entries from pngnow.png Re-enabled some parts of pngvcrd.c (png_combine_row) that work properly. Version 1.0.4e [October 10, 1999] Fixed sign error in pngvcrd.c (Greg Roelofs) Replaced some instances of memcpy with simple assignments in pngvcrd (GR-P) Version 1.0.4f [October 15, 1999] Surrounded example.c code with #if 0 .. #endif to prevent people from inadvertently trying to compile it. Changed png_get_header_version() from a function to a macro in png.h Added type casting mostly in pngrtran.c and pngwtran.c Removed some pointless "ptr = NULL" in pngmem.c Added a "contrib" directory containing the source code from Greg's book. Version 1.0.5 [October 15, 1999] Minor editing of the INSTALL and README files. Version 1.0.5a [October 23, 1999] Added contrib/pngsuite and contrib/pngminus (Willem van Schaik) Fixed a typo in the png_set_sRGB() function call in example.c (Jan Nijtmans) Further optimization and bugfix of pngvcrd.c Revised pngset.c so that it does not allocate or free memory in the user's text_ptr structure. Instead, it makes its own copy. Created separate write_end_info_struct in pngtest.c for a more severe test. Added code in pngwrite.c to free info_ptr->text[i].key to stop a memory leak. Version 1.0.5b [November 23, 1999] Moved PNG_FLAG_HAVE_CHUNK_HEADER, PNG_FLAG_BACKGROUND_IS_GRAY and PNG_FLAG_WROTE_tIME from flags to mode. Added png_write_info_before_PLTE() function. Fixed some typecasting in contrib/gregbook/*.c Updated scripts/makevms.com and added makevms.com to contrib/gregbook and contrib/pngminus (Martin Zinser) Version 1.0.5c [November 26, 1999] Moved png_get_header_version from png.h to png.c, to accommodate ansi2knr. Removed all global arrays (according to PNG_NO_GLOBAL_ARRAYS macro), to accommodate making DLL's: Moved usr_png_ver from global variable to function png_get_header_ver() in png.c. Moved png_sig to png_sig_bytes in png.c and eliminated use of png_sig in pngwutil.c. Moved the various png_CHNK arrays into pngtypes.h. Eliminated use of global png_pass arrays. Declared the png_CHNK and png_pass arrays to be "const". Made the global arrays available to applications (although none are used in libpng itself) when PNG_NO_GLOBAL_ARRAYS is not defined or when PNG_GLOBAL_ARRAYS is defined. Removed some extraneous "-I" from contrib/pngminus/makefile.std Changed the PNG_sRGB_INTENT macros in png.h to be consistent with PNG-1.2. Change PNG_SRGB_INTENT to PNG_sRGB_INTENT in libpng.txt and libpng.3 Version 1.0.5d [November 29, 1999] Add type cast (png_const_charp) two places in png.c Eliminated pngtypes.h; use macros instead to declare PNG_CHNK arrays. Renamed "PNG_GLOBAL_ARRAYS" to "PNG_USE_GLOBAL_ARRAYS" and made available to applications a macro "PNG_USE_LOCAL_ARRAYS". comment out (with #ifdef) all the new declarations when PNG_USE_GLOBAL_ARRAYS is defined. Added PNG_EXPORT_VAR macro to accommodate making DLL's. Version 1.0.5e [November 30, 1999] Added iCCP, iTXt, and sPLT support; added "lang" member to the png_text structure; refactored the inflate/deflate support to make adding new chunks with trailing compressed parts easier in the future, and added new functions png_free_iCCP, png_free_pCAL, png_free_sPLT, png_free_text, png_get_iCCP, png_get_spalettes, png_set_iCCP, png_set_spalettes (Eric S. Raymond). NOTE: Applications that write text chunks MUST define png_text->lang before calling png_set_text(). It must be set to NULL if you want to write tEXt or zTXt chunks. If you want your application to be able to run with older versions of libpng, use #ifdef PNG_iTXt_SUPPORTED png_text[i].lang = NULL; #endif Changed png_get_oFFs() and png_set_oFFs() to use signed rather than unsigned offsets (Eric S. Raymond). Combined PNG_READ_cHNK_SUPPORTED and PNG_WRITE_cHNK_SUPPORTED macros into PNG_cHNK_SUPPORTED and combined the three types of PNG_text_SUPPORTED macros, leaving the separate macros also available. Removed comments on #endifs at the end of many short, non-nested #if-blocks. Version 1.0.5f [December 6, 1999] Changed makefile.solaris to issue a warning about potential problems when the ucb "ld" is in the path ahead of the ccs "ld". Removed "- [date]" from the "synopsis" line in libpng.3 and libpngpf.3. Added sCAL chunk support (Eric S. Raymond). Version 1.0.5g [December 7, 1999] Fixed "png_free_spallettes" typo in png.h Added code to handle new chunks in pngpread.c Moved PNG_CHNK string macro definitions outside of PNG_NO_EXTERN block Added "translated_key" to png_text structure and png_write_iTXt(). Added code in pngwrite.c to work around a newly discovered zlib bug. Version 1.0.5h [December 10, 1999] NOTE: regarding the note for version 1.0.5e, the following must also be included in your code: png_text[i].translated_key = NULL; Unknown chunk handling is now supported. Option to eliminate all floating point support was added. Some new fixed-point functions such as png_set_gAMA_fixed() were added. Expanded tabs and removed trailing blanks in source files. Version 1.0.5i [December 13, 1999] Added some type casts to silence compiler warnings. Renamed "png_free_spalette" to "png_free_spalettes" for consistency. Removed leading blanks from a #define in pngvcrd.c Added some parameters to the new png_set_keep_unknown_chunks() function. Added a test for up->location != 0 in the first instance of writing unknown chunks in pngwrite.c Changed "num" to "i" in png_free_spalettes() and png_free_unknowns() to prevent recursion. Added png_free_hIST() function. Various patches to fix bugs in the sCAL and integer cHRM processing, and to add some convenience macros for use with sCAL. Version 1.0.5j [December 21, 1999] Changed "unit" parameter of png_write_sCAL from png_byte to int, to work around buggy compilers. Added new type "png_fixed_point" for integers that hold float*100000 values Restored backward compatibility of tEXt/zTXt chunk processing: Restored the first four members of png_text to the same order as v.1.0.5d. Added members "lang_key" and "itxt_length" to png_text struct. Set text_length=0 when "text" contains iTXt data. Use the "compression" member to distinguish among tEXt/zTXt/iTXt types. Added PNG_ITXT_COMPRESSION_NONE (1) and PNG_ITXT_COMPRESSION_zTXt(2) macros. The "Note" above, about backward incompatibility of libpng-1.0.5e, no longer applies. Fixed png_read|write_iTXt() to read|write parameters in the right order, and to write the iTXt chunk after IDAT if it appears in the end_ptr. Added pnggccrd.c, version of pngvcrd.c Intel assembler for gcc (Greg Roelofs) Reversed the order of trying to write floating-point and fixed-point gAMA. Version 1.0.5k [December 27, 1999] Added many parentheses, e.g., "if (a && b & c)" becomes "if (a && (b & c))" Added png_handle_as_unknown() function (Glenn) Added png_free_chunk_list() function and chunk_list and num_chunk_list members of png_ptr. Eliminated erroneous warnings about multiple sPLT chunks and sPLT-after-PLTE. Fixed a libpng-1.0.5h bug in pngrutil.c that was issuing erroneous warnings about ignoring incorrect gAMA with sRGB (gAMA was in fact not ignored) Added png_free_tRNS(); png_set_tRNS() now malloc's its own trans array (ESR). Define png_get_int_32 when oFFs chunk is supported as well as when pCAL is. Changed type of proflen from png_int_32 to png_uint_32 in png_get_iCCP(). Version 1.0.5l [January 1, 2000] Added functions png_set_read_user_chunk_fn() and png_get_user_chunk_ptr() for setting a callback function to handle unknown chunks and for retrieving the associated user pointer (Glenn). Version 1.0.5m [January 7, 2000] Added high-level functions png_read_png(), png_write_png(), png_free_pixels(). Version 1.0.5n [January 9, 2000] Added png_free_PLTE() function, and modified png_set_PLTE() to malloc its own memory for info_ptr->palette. This makes it safe for the calling application to free its copy of the palette any time after it calls png_set_PLTE(). Version 1.0.5o [January 20, 2000] Cosmetic changes only (removed some trailing blanks and TABs) Version 1.0.5p [January 31, 2000] Renamed pngdll.mak to makefile.bd32 Cosmetic changes in pngtest.c Version 1.0.5q [February 5, 2000] Relocated the makefile.solaris warning about PATH problems. Fixed pngvcrd.c bug by pushing/popping registers in mmxsupport (Bruce Oberg) Revised makefile.gcmmx Added PNG_SETJMP_SUPPORTED, PNG_SETJMP_NOT_SUPPORTED, and PNG_ABORT() macros Version 1.0.5r [February 7, 2000] Removed superfluous prototype for png_get_itxt from png.h Fixed a bug in pngrtran.c that improperly expanded the background color. Return *num_text=0 from png_get_text() when appropriate, and fix documentation of png_get_text() in libpng.txt/libpng.3. Version 1.0.5s [February 18, 2000] Added "png_jmp_env()" macro to pngconf.h, to help people migrate to the new error handler that's planned for the next libpng release, and changed example.c, pngtest.c, and contrib programs to use this macro. Revised some of the DLL-export macros in pngconf.h (Greg Roelofs) Fixed a bug in png_read_png() that caused it to fail to expand some images that it should have expanded. Fixed some mistakes in the unused and undocumented INCH_CONVERSIONS functions in pngget.c Changed the allocation of palette, history, and trans arrays back to the version 1.0.5 method (linking instead of copying) which restores backward compatibility with version 1.0.5. Added some remarks about that in example.c. Added "free_me" member to info_ptr and png_ptr and added png_free_data() function. Updated makefile.linux and makefile.gccmmx to make directories conditionally. Made cosmetic changes to pngasmrd.h Added png_set_rows() and png_get_rows(), for use with png_read|write_png(). Modified png_read_png() to allocate info_ptr->row_pointers only if it hasn't already been allocated. Version 1.0.5t [March 4, 2000] Changed png_jmp_env() migration aiding macro to png_jmpbuf(). Fixed "interlace" typo (should be "interlaced") in contrib/gregbook/read2-x.c Fixed bug with use of PNG_BEFORE_IHDR bit in png_ptr->mode, introduced when PNG_FLAG_HAVE_CHUNK_HEADER was moved into png_ptr->mode in version 1.0.5b Files in contrib/gregbook were revised to use png_jmpbuf() and to select a 24-bit visual if one is available, and to allow abbreviated options. Files in contrib/pngminus were revised to use the png_jmpbuf() macro. Removed spaces in makefile.linux and makefile.gcmmx, introduced in 1.0.5s Version 1.0.5u [March 5, 2000] Simplified the code that detects old png.h in png.c and pngtest.c Renamed png_spalette (_p, _pp) to png_sPLT_t (_tp, _tpp) Increased precision of rgb_to_gray calculations from 8 to 15 bits and added png_set_rgb_to_gray_fixed() function. Added makefile.bc32 (32-bit Borland C++, C mode) Version 1.0.5v [March 11, 2000] Added some parentheses to the png_jmpbuf macro definition. Updated references to the zlib home page, which has moved to freesoftware.com. Corrected bugs in documentation regarding png_read_row() and png_write_row(). Updated documentation of png_rgb_to_gray calculations in libpng.3/libpng.txt. Renamed makefile.borland,turboc3 back to makefile.bor,tc3 as in version 1.0.3, revised borland makefiles; added makefile.ibmvac3 and makefile.gcc (Cosmin) Version 1.0.6 [March 20, 2000] Minor revisions of makefile.bor, libpng.txt, and gregbook/rpng2-win.c Added makefile.sggcc (SGI IRIX with gcc) Version 1.0.6d [April 7, 2000] Changed sprintf() to strcpy() in png_write_sCAL_s() to work without STDIO Added data_length parameter to png_decompress_chunk() function Revised documentation to remove reference to abandoned png_free_chnk functions Fixed an error in png_rgb_to_gray_fixed() Revised example.c, usage of png_destroy_write_struct(). Renamed makefile.ibmvac3 to makefile.ibmc, added libpng.icc IBM project file Added a check for info_ptr->free_me&PNG_FREE_TEXT when freeing text in png.c Simplify png_sig_bytes() function to remove use of non-ISO-C strdup(). Version 1.0.6e [April 9, 2000] Added png_data_freer() function. In the code that checks for over-length tRNS chunks, added check of info_ptr->num_trans as well as png_ptr->num_trans (Matthias Benckmann) Minor revisions of libpng.txt/libpng.3. Check for existing data and free it if the free_me flag is set, in png_set_*() and png_handle_*(). Only define PNG_WEIGHTED_FILTERS_SUPPORTED when PNG_FLOATING_POINT_SUPPORTED is defined. Changed several instances of PNG_NO_CONSOLE_ID to PNG_NO_STDIO in pngrutil.c and mentioned the purposes of the two macros in libpng.txt/libpng.3. Version 1.0.6f [April 14, 2000] Revised png_set_iCCP() and png_set_rows() to avoid prematurely freeing data. Add checks in png_set_text() for NULL members of the input text structure. Revised libpng.txt/libpng.3. Removed superfluous prototype for png_set_iTXt from png.h Removed "else" from pngread.c, after png_error(), and changed "0" to "length". Changed several png_errors about malformed ancillary chunks to png_warnings. Version 1.0.6g [April 24, 2000] Added png_pass-* arrays to pnggccrd.c when PNG_USE_LOCAL_ARRAYS is defined. Relocated paragraph about png_set_background() in libpng.3/libpng.txt and other revisions (Matthias Benckmann) Relocated info_ptr->free_me, png_ptr->free_me, and other info_ptr and png_ptr members to restore binary compatibility with libpng-1.0.5 (breaks compatibility with libpng-1.0.6). Version 1.0.6h [April 24, 2000] Changed shared library so-number pattern from 2.x.y.z to xy.z (this builds libpng.so.10 & libpng.so.10.6h instead of libpng.so.2 & libpng.so.2.1.0.6h) This is a temporary change for test purposes. Version 1.0.6i [May 2, 2000] Rearranged some members at the end of png_info and png_struct, to put unknown_chunks_num and free_me within the original size of the png_structs and free_me, png_read_user_fn, and png_free_fn within the original png_info, because some old applications allocate the structs directly instead of using png_create_*(). Added documentation of user memory functions in libpng.txt/libpng.3 Modified png_read_png so that it will use user_allocated row_pointers if present, unless free_me directs that it be freed, and added description of the use of png_set_rows() and png_get_rows() in libpng.txt/libpng.3. Added PNG_LEGACY_SUPPORTED macro, and #ifdef out all new (since version 1.00) members of png_struct and png_info, to regain binary compatibility when you define this macro. Capabilities lost in this event are user transforms (new in version 1.0.0),the user transform pointer (new in version 1.0.2), rgb_to_gray (new in 1.0.5), iCCP, sCAL, sPLT, the high-level interface, and unknown chunks support (all new in 1.0.6). This was necessary because of old applications that allocate the structs directly as authors were instructed to do in libpng-0.88 and earlier, instead of using png_create_*(). Added modes PNG_CREATED_READ_STRUCT and PNG_CREATED_WRITE_STRUCT which can be used to detect codes that directly allocate the structs, and code to check these modes in png_read_init() and png_write_init() and generate a libpng error if the modes aren't set and PNG_LEGACY_SUPPORTED was not defined. Added makefile.intel and updated makefile.watcom (Pawel Mrochen) Version 1.0.6j [May 3, 2000] Overloaded png_read_init() and png_write_init() with macros that convert calls to png_read_init_2() or png_write_init_2() that check the version and structure sizes. Version 1.0.7beta11 [May 7, 2000] Removed the new PNG_CREATED_READ_STRUCT and PNG_CREATED_WRITE_STRUCT modes which are no longer used. Eliminated the three new members of png_text when PNG_LEGACY_SUPPORTED is defined or when neither PNG_READ_iTXt_SUPPORTED nor PNG_WRITE_iTXT_SUPPORTED is defined. Made PNG_NO_READ|WRITE_iTXt the default setting, to avoid memory overrun when old applications fill the info_ptr->text structure directly. Added PNGAPI macro, and added it to the definitions of all exported functions. Relocated version macro definitions ahead of the includes of zlib.h and pngconf.h in png.h. Version 1.0.7beta12 [May 12, 2000] Revised pngset.c to avoid a problem with expanding the png_debug macro. Deleted some extraneous defines from pngconf.h Made PNG_NO_CONSOLE_IO the default condition when PNG_BUILD_DLL is defined. Use MSC _RPTn debugging instead of fprintf if _MSC_VER is defined. Added png_access_version_number() function. Check for mask&PNG_FREE_CHNK (for TEXT, SCAL, PCAL) in png_free_data(). Expanded libpng.3/libpng.txt information about png_data_freer(). Version 1.0.7beta14 [May 17, 2000] (beta13 was not published) Changed pnggccrd.c and pngvcrd.c to handle bad adaptive filter types as warnings instead of errors, as pngrutil.c does. Set the PNG_INFO_IDAT valid flag in png_set_rows() so png_write_png() will actually write IDATs. Made the default PNG_USE_LOCAL_ARRAYS depend on PNG_DLL instead of WIN32. Make png_free_data() ignore its final parameter except when freeing data that can have multiple instances (text, sPLT, unknowns). Fixed a new bug in png_set_rows(). Removed info_ptr->valid tests from png_free_data(), as in version 1.0.5. Added png_set_invalid() function. Fixed incorrect illustrations of png_destroy_write_struct() in example.c. Version 1.0.7beta15 [May 30, 2000] Revised the deliberately erroneous Linux setjmp code in pngconf.h to produce fewer error messages. Rearranged checks for Z_OK to check the most likely path first in pngpread.c and pngwutil.c. Added checks in pngtest.c for png_create_*() returning NULL, and mentioned in libpng.txt/libpng.3 the need for applications to check this. Changed names of png_default_*() functions in pngtest to pngtest_*(). Changed return type of png_get_x|y_offset_*() from png_uint_32 to png_int_32. Fixed some bugs in the unused PNG_INCH_CONVERSIONS functions in pngget.c Set each pointer to NULL after freeing it in png_free_data(). Worked around a problem in pngconf.h; AIX's strings.h defines an "index" macro that conflicts with libpng's png_color_16.index. (Dimitri Papadapoulos) Added "msvc" directory with MSVC++ project files (Simon-Pierre Cadieux). Version 1.0.7beta16 [June 4, 2000] Revised the workaround of AIX string.h "index" bug. Added a check for overlength PLTE chunk in pngrutil.c. Added PNG_NO_POINTER_INDEXING macro to use array-indexing instead of pointer indexing in pngrutil.c and pngwutil.c to accommodate a buggy compiler. Added a warning in png_decompress_chunk() when it runs out of data, e.g. when it tries to read an erroneous PhotoShop iCCP chunk. Added PNG_USE_DLL macro. Revised the copyright/disclaimer/license notice. Added contrib/msvctest directory Version 1.0.7rc1 [June 9, 2000] Corrected the definition of PNG_TRANSFORM_INVERT_ALPHA (0x0400 not 0x0200) Added contrib/visupng directory (Willem van Schaik) Version 1.0.7beta18 [June 23, 2000] Revised PNGAPI definition, and pngvcrd.c to work with __GCC__ and do not redefine PNGAPI if it is passed in via a compiler directive. Revised visupng/PngFile.c to remove returns from within the Try block. Removed leading underscores from "_PNG_H" and "_PNG_SAVE_BSD_SOURCE" macros. Updated contrib/visupng/cexcept.h to version 1.0.0. Fixed bugs in pngwrite.c and pngwutil.c that prevented writing iCCP chunks. Version 1.0.7rc2 [June 28, 2000] Updated license to include disclaimers required by UCITA. Fixed "DJBPP" typo in pnggccrd.c introduced in beta18. Version 1.0.7 [July 1, 2000] Revised the definition of "trans_values" in libpng.3/libpng.txt Version 1.0.8beta1 [July 8, 2000] Added png_free(png_ptr, key) two places in pngpread.c to stop memory leaks. Changed PNG_NO_STDIO to PNG_NO_CONSOLE_IO, several places in pngrutil.c and pngwutil.c. Changed PNG_EXPORT_VAR to use PNG_IMPEXP, in pngconf.h. Removed unused "#include " from png.c Added WindowsCE support. Revised pnggccrd.c to work with gcc-2.95.2 and in the Cygwin environment. Version 1.0.8beta2 [July 10, 2000] Added project files to the wince directory and made further revisions of pngtest.c, pngrio.c, and pngwio.c in support of WindowsCE. Version 1.0.8beta3 [July 11, 2000] Only set the PNG_FLAG_FREE_TRNS or PNG_FREE_TRNS flag in png_handle_tRNS() for indexed-color input files to avoid potential double-freeing trans array under some unusual conditions; problem was introduced in version 1.0.6f. Further revisions to pngtest.c and files in the wince subdirectory. Version 1.0.8beta4 [July 14, 2000] Added the files pngbar.png and pngbar.jpg to the distribution. Added makefile.cygwin, and cygwin support in pngconf.h Added PNG_NO_ZALLOC_ZERO macro (makes png_zalloc skip zeroing memory) Version 1.0.8rc1 [July 16, 2000] Revised png_debug() macros and statements to eliminate compiler warnings. Version 1.0.8 [July 24, 2000] Added png_flush() in pngwrite.c, after png_write_IEND(). Updated makefile.hpux to build a shared library. Version 1.0.9beta1 [November 10, 2000] Fixed typo in scripts/makefile.hpux Updated makevms.com in scripts and contrib/* and contrib/* (Martin Zinser) Fixed seqence-point bug in contrib/pngminus/png2pnm (Martin Zinser) Changed "cdrom.com" in documentation to "libpng.org" Revised pnggccrd.c to get it all working, and updated makefile.gcmmx (Greg). Changed type of "params" from voidp to png_voidp in png_read|write_png(). Make sure PNGAPI and PNG_IMPEXP are defined in pngconf.h. Revised the 3 instances of WRITEFILE in pngtest.c. Relocated "msvc" and "wince" project subdirectories into "dll" subdirectory. Updated png.rc in dll/msvc project Revised makefile.dec to define and use LIBPATH and INCPATH Increased size of global png_libpng_ver[] array from 12 to 18 chars. Made global png_libpng_ver[], png_sig[] and png_pass_*[] arrays const. Removed duplicate png_crc_finish() from png_handle_bKGD() function. Added a warning when application calls png_read_update_info() multiple times. Revised makefile.cygwin Fixed bugs in iCCP support in pngrutil.c and pngwutil.c. Replaced png_set_empty_plte_permitted() with png_permit_mng_features(). Version 1.0.9beta2 [November 19, 2000] Renamed the "dll" subdirectory "projects". Added borland project files to "projects" subdirectory. Set VS_FF_PRERELEASE and VS_FF_PATCHED flags in msvc/png.rc when appropriate. Add error message in png_set_compression_buffer_size() when malloc fails. Version 1.0.9beta3 [November 23, 2000] Revised PNG_LIBPNG_BUILD_TYPE macro in png.h, used in the msvc project. Removed the png_flush() in pngwrite.c that crashes some applications that don't set png_output_flush_fn. Added makefile.macosx and makefile.aix to scripts directory. Version 1.0.9beta4 [December 1, 2000] Change png_chunk_warning to png_warning in png_check_keyword(). Increased the first part of msg buffer from 16 to 18 in png_chunk_error(). Version 1.0.9beta5 [December 15, 2000] Added support for filter method 64 (for PNG datastreams embedded in MNG). Version 1.0.9beta6 [December 18, 2000] Revised png_set_filter() to accept filter method 64 when appropriate. Added new PNG_HAVE_PNG_SIGNATURE bit to png_ptr->mode and use it to help prevent applications from using MNG features in PNG datastreams. Added png_permit_mng_features() function. Revised libpng.3/libpng.txt. Changed "filter type" to "filter method". Version 1.0.9rc1 [December 23, 2000] Revised test for PNG_HAVE_PNG_SIGNATURE in pngrutil.c Fixed error handling of unknown compression type in png_decompress_chunk(). In pngconf.h, define __cdecl when _MSC_VER is defined. Version 1.0.9beta7 [December 28, 2000] Changed PNG_TEXT_COMPRESSION_zTXt to PNG_COMPRESSION_TYPE_BASE several places. Revised memory management in png_set_hIST and png_handle_hIST in a backward compatible manner. PLTE and tRNS were revised similarly. Revised the iCCP chunk reader to ignore trailing garbage. Version 1.0.9beta8 [January 12, 2001] Moved pngasmrd.h into pngconf.h. Improved handling of out-of-spec garbage iCCP chunks generated by PhotoShop. Version 1.0.9beta9 [January 15, 2001] Added png_set_invalid, png_permit_mng_features, and png_mmx_supported to wince and msvc project module definition files. Minor revision of makefile.cygwin. Fixed bug with progressive reading of narrow interlaced images in pngpread.c Version 1.0.9beta10 [January 16, 2001] Do not typedef png_FILE_p in pngconf.h when PNG_NO_STDIO is defined. Fixed "png_mmx_supported" typo in project definition files. Version 1.0.9beta11 [January 19, 2001] Updated makefile.sgi to make shared library. Removed png_mmx_support() function and disabled PNG_MNG_FEATURES_SUPPORTED by default, for the benefit of DLL forward compatibility. These will be re-enabled in version 1.2.0. Version 1.0.9rc2 [January 22, 2001] Revised cygwin support. Version 1.0.9 [January 31, 2001] Added check of cygwin's ALL_STATIC in pngconf.h Added "-nommx" parameter to contrib/gregbook/rpng2-win and rpng2-x demos. Version 1.0.10beta1 [March 14, 2001] Revised makefile.dec, makefile.sgi, and makefile.sggcc; added makefile.hpgcc. Reformatted libpng.3 to eliminate bad line breaks. Added checks for _mmx_supported in the read_filter_row function of pnggccrd.c Added prototype for png_mmx_support() near the top of pnggccrd.c Moved some error checking from png_handle_IHDR to png_set_IHDR. Added PNG_NO_READ_SUPPORTED and PNG_NO_WRITE_SUPPORTED macros. Revised png_mmx_support() function in pnggccrd.c Restored version 1.0.8 PNG_WRITE_EMPTY_PLTE_SUPPORTED behavior in pngwutil.c Fixed memory leak in contrib/visupng/PngFile.c Fixed bugs in png_combine_row() in pnggccrd.c and pngvcrd.c (C version) Added warnings when retrieving or setting gamma=0. Increased the first part of msg buffer from 16 to 18 in png_chunk_warning(). Version 1.0.10rc1 [March 23, 2001] Changed all instances of memcpy, strcpy, and strlen to png_memcpy, png_strcpy, and png_strlen. Revised png_mmx_supported() function in pnggccrd.c to return proper value. Fixed bug in progressive reading (pngpread.c) with small images (height < 8). Version 1.0.10 [March 30, 2001] Deleted extraneous space (introduced in 1.0.9) from line 42 of makefile.cygwin Added beos project files (Chris Herborth) Version 1.0.11beta1 [April 3, 2001] Added type casts on several png_malloc() calls (Dimitri Papadapoulos). Removed a no-longer needed AIX work-around from pngconf.h Changed several "//" single-line comments to C-style in pnggccrd.c Version 1.0.11beta2 [April 11, 2001] Removed PNGAPI from several functions whose prototypes did not have PNGAPI. Updated scripts/pngos2.def Version 1.0.11beta3 [April 14, 2001] Added checking the results of many instances of png_malloc() for NULL Version 1.0.11beta4 [April 20, 2001] Undid the changes from version 1.0.11beta3. Added a check for NULL return from user's malloc_fn(). Removed some useless type casts of the NULL pointer. Added makefile.netbsd Version 1.0.11 [April 27, 2001] Revised makefile.netbsd Version 1.0.12beta1 [May 14, 2001] Test for Windows platform in pngconf.h when including malloc.h (Emmanuel Blot) Updated makefile.cygwin and handling of Cygwin's ALL_STATIC in pngconf.h Added some never-to-be-executed code in pnggccrd.c to quiet compiler warnings. Eliminated the png_error about apps using png_read|write_init(). Instead, libpng will reallocate the png_struct and info_struct if they are too small. This retains future binary compatibility for old applications written for libpng-0.88 and earlier. Version 1.2.0beta1 [May 6, 2001] Bumped DLLNUM to 2. Re-enabled PNG_MNG_FEATURES_SUPPORTED and enabled PNG_ASSEMBLER_CODE_SUPPORTED by default. Added runtime selection of MMX features. Added png_set_strip_error_numbers function and related macros. Version 1.2.0beta2 [May 7, 2001] Finished merging 1.2.0beta1 with version 1.0.11 Added a check for attempts to read or write PLTE in grayscale PNG datastreams. Version 1.2.0beta3 [May 17, 2001] Enabled user memory function by default. Modified png_create_struct so it passes user mem_ptr to user memory allocator. Increased png_mng_features flag from png_byte to png_uint_32. Bumped shared-library (so-number) and dll-number to 3. Version 1.2.0beta4 [June 23, 2001] Check for missing profile length field in iCCP chunk and free chunk_data in case of truncated iCCP chunk. Bumped shared-library number to 3 in makefile.sgi and makefile.sggcc Bumped dll-number from 2 to 3 in makefile.cygwin Revised contrib/gregbook/rpng*-x.c to avoid a memory leak and to exit cleanly if user attempts to run it on an 8-bit display. Updated contrib/gregbook Use png_malloc instead of png_zalloc to allocate palette in pngset.c Updated makefile.ibmc Added some typecasts to eliminate gcc 3.0 warnings. Changed prototypes of png_write_oFFS width and height from png_uint_32 to png_int_32. Updated example.c Revised prototypes for png_debug_malloc and png_debug_free in pngtest.c Version 1.2.0beta5 [August 8, 2001] Revised contrib/gregbook Revised makefile.gcmmx Revised pnggccrd.c to conditionally compile some thread-unsafe code only when PNG_THREAD_UNSAFE_OK is defined. Added tests to prevent pngwutil.c from writing a bKGD or tRNS chunk with value exceeding 2^bit_depth-1 Revised makefile.sgi and makefile.sggcc Replaced calls to fprintf(stderr,...) with png_warning() in pnggccrd.c Removed restriction that do_invert_mono only operate on 1-bit opaque files Version 1.2.0 [September 1, 2001] Changed a png_warning() to png_debug() in pnggccrd.c Fixed contrib/gregbook/rpng-x.c, rpng2-x.c to avoid crash with XFreeGC(). Version 1.2.1beta1 [October 19, 2001] Revised makefile.std in contrib/pngminus Include background_1 in png_struct regardless of gamma support. Revised makefile.netbsd and makefile.macosx, added makefile.darwin. Revised example.c to provide more details about using row_callback(). Version 1.2.1beta2 [October 25, 2001] Added type cast to each NULL appearing in a function call, except for WINCE functions. Added makefile.so9. Version 1.2.1beta3 [October 27, 2001] Removed type casts from all NULLs. Simplified png_create_struct_2(). Version 1.2.1beta4 [November 7, 2001] Revised png_create_info_struct() and png_creat_struct_2(). Added error message if png_write_info() was omitted. Type cast NULLs appearing in function calls when _NO_PROTO or PNG_TYPECAST_NULL is defined. Version 1.2.1rc1 [November 24, 2001] Type cast NULLs appearing in function calls except when PNG_NO_TYPECAST_NULL is defined. Changed typecast of "size" argument to png_size_t in pngmem.c calls to the user malloc_fn, to agree with the prototype in png.h Added a pop/push operation to pnggccrd.c, to preserve Eflag (Maxim Sobolev) Updated makefile.sgi to recognize LIBPATH and INCPATH. Updated various makefiles so "make clean" does not remove previous major version of the shared library. Version 1.2.1rc2 [December 4, 2001] Always allocate 256-entry internal palette, hist, and trans arrays, to avoid out-of-bounds memory reference caused by invalid PNG datastreams. Added a check for prefix_length > data_length in iCCP chunk handler. Version 1.2.1 [December 7, 2001] None. Version 1.2.2beta1 [February 22, 2002] Fixed a bug with reading the length of iCCP profiles (Larry Reeves). Revised makefile.linux, makefile.gcmmx, and makefile.sgi to generate libpng.a, libpng12.so (not libpng.so.3), and libpng12/png.h Revised makefile.darwin to remove "-undefined suppress" option. Added checks for gamma and chromaticity values over 21474.83, which exceed the limit for PNG unsigned 32-bit integers when encoded. Revised calls to png_create_read_struct() and png_create_write_struct() for simpler debugging. Revised png_zalloc() so zlib handles errors (uses PNG_FLAG_MALLOC_NULL_MEM_OK) Version 1.2.2beta2 [February 23, 2002] Check chunk_length and idat_size for invalid (over PNG_MAX_UINT) lengths. Check for invalid image dimensions in png_get_IHDR. Added missing "fi;" in the install target of the SGI makefiles. Added install-static to all makefiles that make shared libraries. Always do gamma compensation when image is partially transparent. Version 1.2.2beta3 [March 7, 2002] Compute background.gray and background_1.gray even when color_type is RGB in case image gets reduced to gray later. Modified shared-library makefiles to install pkgconfig/libpngNN.pc. Export (with PNGAPI) png_zalloc, png_zfree, and png_handle_as_unknown Removed unused png_write_destroy_info prototype from png.h Eliminated incorrect use of width_mmx from pnggccrd.c in pixel_bytes == 8 case Added install-shared target to all makefiles that make shared libraries. Stopped a double free of palette, hist, and trans when not using free_me. Added makefile.32sunu for Sun Ultra 32 and makefile.64sunu for Sun Ultra 64. Version 1.2.2beta4 [March 8, 2002] Compute background.gray and background_1.gray even when color_type is RGB in case image gets reduced to gray later (Jason Summers). Relocated a misplaced /bin/rm in the "install-shared" makefile targets Added PNG_1_0_X macro which can be used to build a 1.0.x-compatible library. Version 1.2.2beta5 [March 26, 2002] Added missing PNGAPI to several function definitions. Check for invalid bit_depth or color_type in png_get_IHDR(), and check for missing PLTE or IHDR in png_push_read_chunk() (Matthias Clasen). Revised iTXt support to accept NULL for lang and lang_key. Compute gamma for color components of background even when color_type is gray. Changed "()" to "{}" in scripts/libpng.pc.in. Revised makefiles to put png.h and pngconf.h only in $prefix/include/libpngNN Revised makefiles to make symlink to libpng.so.NN in addition to libpngNN.so Version 1.2.2beta6 [March 31, 2002] Version 1.0.13beta1 [March 31, 2002] Prevent png_zalloc() from trying to memset memory that it failed to acquire. Add typecasts of PNG_MAX_UINT in pngset_cHRM_fixed() (Matt Holgate). Ensure that the right function (user or default) is used to free the png_struct after an error in png_create_read_struct_2(). Version 1.2.2rc1 [April 7, 2002] Version 1.0.13rc1 [April 7, 2002] Save the ebx register in pnggccrd.c (Sami Farin) Add "mem_ptr = png_ptr->mem_ptr" in png_destroy_write_struct() (Paul Gardner). Updated makefiles to put headers in include/libpng and remove old include/*.h. Version 1.2.2 [April 15, 2002] Version 1.0.13 [April 15, 2002] Revised description of png_set_filter() in libpng.3/libpng.txt. Revised makefile.netbsd and added makefile.neNNbsd and makefile.freebsd Version 1.0.13patch01 [April 17, 2002] Version 1.2.2patch01 [April 17, 2002] Changed ${PNGMAJ}.${PNGVER} bug to ${PNGVER} in makefile.sgi and makefile.sggcc Fixed VER -> PNGVER typo in makefile.macosx and added install-static to install Added install: target to makefile.32sunu and makefile.64sunu Version 1.0.13patch03 [April 18, 2002] Version 1.2.2patch03 [April 18, 2002] Revised 15 makefiles to link libpng.a to libpngNN.a and the include libpng subdirectory to libpngNN subdirectory without the full pathname. Moved generation of libpng.pc from "install" to "all" in 15 makefiles. Version 1.2.3rc1 [April 28, 2002] Added install-man target to 15 makefiles (Dimitri Papadopolous-Orfanos). Added $(DESTDIR) feature to 24 makefiles (Tim Mooney) Fixed bug with $prefix, should be $(prefix) in makefile.hpux. Updated cygwin-specific portion of pngconf.h and revised makefile.cygwin Added a link from libpngNN.pc to libpng.pc in 15 makefiles. Added links from include/libpngNN/*.h to include/*.h in 24 makefiles. Revised makefile.darwin to make relative links without full pathname. Added setjmp() at the end of png_create_*_struct_2() in case user forgets to put one in their application. Restored png_zalloc() and png_zfree() prototypes to version 1.2.1 and removed them from module definition files. Version 1.2.3rc2 [May 1, 2002] Fixed bug in reporting number of channels in pngget.c and pngset.c, that was introduced in version 1.2.2beta5. Exported png_zalloc(), png_zfree(), png_default_read(), png_default_write(), png_default_flush(), and png_push_fill_buffer() and included them in module definition files. Added "libpng.pc" dependency to the "install-shared" target in 15 makefiles. Version 1.2.3rc3 [May 1, 2002] Revised prototype for png_default_flush() Remove old libpng.pc and libpngNN.pc before installing new ones. Version 1.2.3rc4 [May 2, 2002] Typos in *.def files (png_default_read|write -> png_default_read|write_data) In makefiles, changed rm libpng.NN.pc to rm libpngNN.pc Added libpng-config and libpngNN-config and modified makefiles to install them. Changed $(MANPATH) to $(DESTDIR)$(MANPATH) in makefiles Added "Win32 DLL VB" configuration to projects/msvc/libpng.dsp Version 1.2.3rc5 [May 11, 2002] Changed "error" and "message" in prototypes to "error_message" and "warning_message" to avoid namespace conflict. Revised 15 makefiles to build libpng-config from libpng-config-*.in Once more restored png_zalloc and png_zfree to regular nonexported form. Restored png_default_read|write_data, png_default_flush, png_read_fill_buffer to nonexported form, but with PNGAPI, and removed them from module def files. Version 1.2.3rc6 [May 14, 2002] Removed "PNGAPI" from png_zalloc() and png_zfree() in png.c Changed "Gz" to "Gd" in projects/msvc/libpng.dsp and zlib.dsp. Removed leftover libpng-config "sed" script from four makefiles. Revised libpng-config creating script in 16 makefiles. Version 1.2.3 [May 22, 2002] Revised libpng-config target in makefile.cygwin. Removed description of png_set_mem_fn() from documentation. Revised makefile.freebsd. Minor cosmetic changes to 15 makefiles, e.g., $(DI) = $(DESTDIR)/$(INCDIR). Revised projects/msvc/README.txt Changed -lpng to -lpngNN in LDFLAGS in several makefiles. Version 1.2.4beta1 [May 24, 2002] Added libpng.pc and libpng-config to "all:" target in 16 makefiles. Fixed bug in 16 makefiles: $(DESTDIR)/$(LIBPATH) to $(DESTDIR)$(LIBPATH) Added missing "\" before closing double quote in makefile.gcmmx. Plugged various memory leaks; added png_malloc_warn() and png_set_text_2() functions. Version 1.2.4beta2 [June 25, 2002] Plugged memory leak of png_ptr->current_text (Matt Holgate). Check for buffer overflow before reading CRC in pngpread.c (Warwick Allison) Added -soname to the loader flags in makefile.dec, makefile.sgi, and makefile.sggcc. Added "test-installed" target to makefile.linux, makefile.gcmmx, makefile.sgi, and makefile.sggcc. Version 1.2.4beta3 [June 28, 2002] Plugged memory leak of row_buf in pngtest.c when there is a png_error(). Detect buffer overflow in pngpread.c when IDAT is corrupted with extra data. Added "test-installed" target to makefile.32sunu, makefile.64sunu, makefile.beos, makefile.darwin, makefile.dec, makefile.macosx, makefile.solaris, makefile.hpux, makefile.hpgcc, and makefile.so9. Version 1.2.4rc1 and 1.0.14rc1 [July 2, 2002] Added "test-installed" target to makefile.cygwin and makefile.sco. Revised pnggccrd.c to be able to back out version 1.0.x via PNG_1_0_X macro. Version 1.2.4 and 1.0.14 [July 8, 2002] Changed png_warning() to png_error() when width is too large to process. Version 1.2.4patch01 [July 20, 2002] Revised makefile.cygwin to use DLL number 12 instead of 13. Version 1.2.5beta1 [August 6, 2002] Added code to contrib/gregbook/readpng2.c to ignore unused chunks. Replaced toucan.png in contrib/gregbook (it has been corrupt since 1.0.11) Removed some stray *.o files from contrib/gregbook. Changed png_error() to png_warning() about "Too much data" in pngpread.c and about "Extra compressed data" in pngrutil.c. Prevent png_ptr->pass from exceeding 7 in png_push_finish_row(). Updated makefile.hpgcc Updated png.c and pnggccrd.c handling of return from png_mmx_support() Version 1.2.5beta2 [August 15, 2002] Only issue png_warning() about "Too much data" in pngpread.c when avail_in is nonzero. Updated makefiles to install a separate libpng.so.3 with its own rpath. Version 1.2.5rc1 and 1.0.15rc1 [August 24, 2002] Revised makefiles to not remove previous minor versions of shared libraries. Version 1.2.5rc2 and 1.0.15rc2 [September 16, 2002] Revised 13 makefiles to remove "-lz" and "-L$(ZLIBLIB)", etc., from shared library loader directive. Added missing "$OBJSDLL" line to makefile.gcmmx. Added missing "; fi" to makefile.32sunu. Version 1.2.5rc3 and 1.0.15rc3 [September 18, 2002] Revised libpng-config script. Version 1.2.5 and 1.0.15 [October 3, 2002] Revised makefile.macosx, makefile.darwin, makefile.hpgcc, and makefile.hpux, and makefile.aix. Relocated two misplaced PNGAPI lines in pngtest.c Version 1.2.6beta1 [October 22, 2002] Commented out warning about uninitialized mmx_support in pnggccrd.c. Changed "IBMCPP__" flag to "__IBMCPP__" in pngconf.h. Relocated two more misplaced PNGAPI lines in pngtest.c Fixed memory overrun bug in png_do_read_filler() with 16-bit datastreams, introduced in version 1.0.2. Revised makefile.macosx, makefile.dec, makefile.aix, and makefile.32sunu. Version 1.2.6beta2 [November 1, 2002] Added libpng-config "--ldopts" output. Added "AR=ar" and "ARFLAGS=rc" and changed "ar rc" to "$(AR) $(ARFLAGS)" in makefiles. Version 1.2.6beta3 [July 18, 2004] Reverted makefile changes from version 1.2.6beta2 and some of the changes from version 1.2.6beta1; these will be postponed until version 1.2.7. Version 1.2.6 is going to be a simple bugfix release. Changed the one instance of "ln -sf" to "ln -f -s" in each Sun makefile. Fixed potential overrun in pngerror.c by using strncpy instead of memcpy. Added "#!/bin/sh" at the top of configure, for recognition of the 'x' flag under Cygwin (Cosmin). Optimized vacuous tests that silence compiler warnings, in png.c (Cosmin). Added support for PNG_USER_CONFIG, in pngconf.h (Cosmin). Fixed the special memory handler for Borland C under DOS, in pngmem.c (Cosmin). Removed some spurious assignments in pngrutil.c (Cosmin). Replaced 65536 with 65536L, and 0xffff with 0xffffL, to silence warnings on 16-bit platforms (Cosmin). Enclosed shift op expressions in parentheses, to silence warnings (Cosmin). Used proper type png_fixed_point, to avoid problems on 16-bit platforms, in png_handle_sRGB() (Cosmin). Added compression_type to png_struct, and optimized the window size inside the deflate stream (Cosmin). Fixed definition of isnonalpha(), in pngerror.c and pngrutil.c (Cosmin). Fixed handling of unknown chunks that come after IDAT (Cosmin). Allowed png_error() and png_warning() to work even if png_ptr == NULL (Cosmin). Replaced row_info->rowbytes with row_bytes in png_write_find_filter() (Cosmin). Fixed definition of PNG_LIBPNG_VER_DLLNUM (Simon-Pierre). Used PNG_LIBPNG_VER and PNG_LIBPNG_VER_STRING instead of the hardcoded values in png.c (Simon-Pierre, Cosmin). Initialized png_libpng_ver[] with PNG_LIBPNG_VER_STRING (Simon-Pierre). Replaced PNG_LIBPNG_VER_MAJOR with PNG_LIBPNG_VER_DLLNUM in png.rc (Simon-Pierre). Moved the definition of PNG_HEADER_VERSION_STRING near the definitions of the other PNG_LIBPNG_VER_... symbols in png.h (Cosmin). Relocated #ifndef PNGAPI guards in pngconf.h (Simon-Pierre, Cosmin). Updated scripts/makefile.vc(a)win32 (Cosmin). Updated the MSVC project (Simon-Pierre, Cosmin). Updated the Borland C++ Builder project (Cosmin). Avoided access to asm_flags in pngvcrd.c, if PNG_1_0_X is defined (Cosmin). Commented out warning about uninitialized mmx_support in pngvcrd.c (Cosmin). Removed scripts/makefile.bd32 and scripts/pngdef.pas (Cosmin). Added extra guard around inclusion of Turbo C memory headers, in pngconf.h (Cosmin). Renamed projects/msvc/ to projects/visualc6/, and projects/borland/ to projects/cbuilder5/ (Cosmin). Moved projects/visualc6/png32ms.def to scripts/pngw32.def, and projects/visualc6/png.rc to scripts/pngw32.rc (Cosmin). Added projects/visualc6/pngtest.dsp; removed contrib/msvctest/ (Cosmin). Changed line endings to DOS style in cbuilder5 and visualc6 files, even in the tar.* distributions (Cosmin). Updated contrib/visupng/VisualPng.dsp (Cosmin). Updated contrib/visupng/cexcept.h to version 2.0.0 (Cosmin). Added a separate distribution with "configure" and supporting files (Junichi). Version 1.2.6beta4 [July 28, 2004] Added user ability to change png_size_t via a PNG_SIZE_T macro. Added png_sizeof() and png_convert_size() functions. Added PNG_SIZE_MAX (maximum value of a png_size_t variable. Added check in png_malloc_default() for (size_t)size != (png_uint_32)size which would indicate an overflow. Changed sPLT failure action from png_error to png_warning and abandon chunk. Changed sCAL and iCCP failures from png_error to png_warning and abandon. Added png_get_uint_31(png_ptr, buf) function. Added PNG_UINT_32_MAX macro. Renamed PNG_MAX_UINT to PNG_UINT_31_MAX. Made png_zalloc() issue a png_warning and return NULL on potential overflow. Turn on PNG_NO_ZALLOC_ZERO by default in version 1.2.x Revised "clobber list" in pnggccrd.c so it will compile under gcc-3.4. Revised Borland portion of png_malloc() to return NULL or issue png_error() according to setting of PNG_FLAG_MALLOC_NULL_MEM_OK. Added PNG_NO_SEQUENTIAL_READ_SUPPORTED macro to conditionally remove sequential read support. Added some "#if PNG_WRITE_SUPPORTED" blocks. Added #ifdef to remove some redundancy in png_malloc_default(). Use png_malloc instead of png_zalloc to allocate the pallete. Version 1.0.16rc1 and 1.2.6rc1 [August 4, 2004] Fixed buffer overflow vulnerability (CVE-2004-0597) in png_handle_tRNS(). Fixed NULL dereference vulnerability (CVE-2004-0598) in png_handle_iCCP(). Fixed integer overflow vulnerability (CVE-2004-0599) in png_read_png(). Fixed some harmless bugs in png_handle_sBIT, etc, that would cause duplicate chunk types to go undetected. Fixed some timestamps in the -config version Rearranged order of processing of color types in png_handle_tRNS(). Added ROWBYTES macro to calculate rowbytes without integer overflow. Updated makefile.darwin and removed makefile.macosx from scripts directory. Imposed default one million column, one-million row limits on the image dimensions, and added png_set_user_limits() function to override them. Revised use of PNG_SET_USER_LIMITS_SUPPORTED macro. Fixed wrong cast of returns from png_get_user_width|height_max(). Changed some "keep the compiler happy" from empty statements to returns, Revised libpng.txt to remove 1.2.x stuff from the 1.0.x distribution Version 1.0.16rc2 and 1.2.6rc2 [August 7, 2004] Revised makefile.darwin and makefile.solaris. Removed makefile.macosx. Revised pngtest's png_debug_malloc() to use png_malloc() instead of png_malloc_default() which is not supposed to be exported. Fixed off-by-one error in one of the conversions to PNG_ROWBYTES() in pngpread.c. Bug was introduced in 1.2.6rc1. Fixed bug in RGB to RGBX transformation introduced in 1.2.6rc1. Fixed old bug in RGB to Gray transformation. Fixed problem with 64-bit compilers by casting arguments to abs() to png_int_32. Changed "ln -sf" to "ln -f -s" in three makefiles (solaris, sco, so9). Changed "HANDLE_CHUNK_*" to "PNG_HANDLE_CHUNK_*" (Cosmin) Added "-@/bin/rm -f $(DL)/$(LIBNAME).so.$(PNGMAJ)" to 15 *NIX makefiles. Added code to update the row_info->colortype in png_do_read_filler() (MSB). Version 1.0.16rc3 and 1.2.6rc3 [August 9, 2004] Eliminated use of "abs()" in testing cHRM and gAMA values, to avoid trouble with some 64-bit compilers. Created PNG_OUT_OF_RANGE() macro. Revised documentation of png_set_keep_unknown_chunks(). Check handle_as_unknown status in pngpread.c, as in pngread.c previously. Moved "PNG_HANDLE_CHUNK_*" macros out of PNG_INTERNAL section of png.h Added "rim" definitions for CONST4 and CONST6 in pnggccrd.c Version 1.0.16rc4 and 1.2.6rc4 [August 10, 2004] Fixed mistake in pngtest.c introduced in 1.2.6rc2 (declaration of "pinfo" was out of place). Version 1.0.16rc5 and 1.2.6rc5 [August 10, 2004] Moved "PNG_HANDLE_CHUNK_*" macros out of PNG_ASSEMBLER_CODE_SUPPORTED section of png.h where they were inadvertently placed in version rc3. Version 1.2.6 and 1.0.16 [August 15, 2004] Revised pngtest so memory allocation testing is only done when PNG_DEBUG==1. Version 1.2.7beta1 [August 26, 2004] Removed unused pngasmrd.h file. Removed references to uu.net for archived files. Added references to PNG Spec (second edition) and the PNG ISO/IEC Standard. Added "test-dd" target in 15 makefiles, to run pngtest in DESTDIR. Fixed bug with "optimized window size" in the IDAT datastream, that causes libpng to write PNG files with incorrect zlib header bytes. Version 1.2.7beta2 [August 28, 2004] Fixed bug with sCAL chunk and big-endian machines (David Munro). Undid new code added in 1.2.6rc2 to update the color_type in png_set_filler(). Added png_set_add_alpha() that updates color type. Version 1.0.17rc1 and 1.2.7rc1 [September 4, 2004] Revised png_set_strip_filler() to not remove alpha if color_type has alpha. Version 1.2.7 and 1.0.17 [September 12, 2004] Added makefile.hp64 Changed projects/msvc/png32ms.def to scripts/png32ms.def in makefile.cygwin Version 1.2.8beta1 [November 1, 2004] Fixed bug in png_text_compress() that would fail to complete a large block. Fixed bug, introduced in libpng-1.2.7, that overruns a buffer during strip alpha operation in png_do_strip_filler(). Added PNG_1_2_X definition in pngconf.h Use #ifdef to comment out png_info_init in png.c and png_read_init in pngread.c (as of 1.3.0) Version 1.2.8beta2 [November 2, 2004] Reduce color_type to a nonalpha type after strip alpha operation in png_do_strip_filler(). Version 1.2.8beta3 [November 3, 2004] Revised definitions of PNG_MAX_UINT_32, PNG_MAX_SIZE, and PNG_MAXSUM Version 1.2.8beta4 [November 12, 2004] Fixed (again) definition of PNG_LIBPNG_VER_DLLNUM in png.h (Cosmin). Added PNG_LIBPNG_BUILD_PRIVATE in png.h (Cosmin). Set png_ptr->zstream.data_type to Z_BINARY, to avoid unnecessary detection of data type in deflate (Cosmin). Deprecated but continue to support SPECIALBUILD and PRIVATEBUILD in favor of PNG_LIBPNG_BUILD_SPECIAL_STRING and PNG_LIBPNG_BUILD_PRIVATE_STRING. Version 1.2.8beta5 [November 20, 2004] Use png_ptr->flags instead of png_ptr->transformations to pass PNG_STRIP_ALPHA info to png_do_strip_filler(), to preserve ABI compatibility. Revised handling of SPECIALBUILD, PRIVATEBUILD, PNG_LIBPNG_BUILD_SPECIAL_STRING and PNG_LIBPNG_BUILD_PRIVATE_STRING. Version 1.2.8rc1 [November 24, 2004] Moved handling of BUILD macros from pngconf.h to png.h Added definition of PNG_LIBPNG_BASE_TYPE in png.h, inadvertently omitted from beta5. Revised scripts/pngw32.rc Despammed mailing addresses by masking "@" with "at". Inadvertently installed a supposedly faster test version of pngrutil.c Version 1.2.8rc2 [November 26, 2004] Added two missing "\" in png.h Change tests in pngread.c and pngpread.c to if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA)) png_do_read_transformations(png_ptr); Version 1.2.8rc3 [November 28, 2004] Reverted pngrutil.c to version libpng-1.2.8beta5. Added scripts/makefile.elf with supporting code in pngconf.h for symbol versioning (John Bowler). Version 1.2.8rc4 [November 29, 2004] Added projects/visualc7 (Simon-pierre). Version 1.2.8rc5 [November 29, 2004] Fixed new typo in scripts/pngw32.rc Version 1.2.8 [December 3, 2004] Removed projects/visualc7, added projects/visualc71. Version 1.2.9beta1 [February 21, 2006] Initialized some structure members in pngwutil.c to avoid gcc-4.0.0 complaints Revised man page and libpng.txt to make it clear that one should not call png_read_end or png_write_end after png_read_png or png_write_png. Updated references to png-mng-implement mailing list. Fixed an incorrect typecast in pngrutil.c Added PNG_NO_READ_SUPPORTED conditional for making a write-only library. Added PNG_NO_WRITE_INTERLACING_SUPPORTED conditional. Optimized alpha-inversion loops in pngwtran.c Moved test for nonzero gamma outside of png_build_gamma_table() in pngrtran.c Make sure num_trans is <= 256 before copying data in png_set_tRNS(). Make sure num_palette is <= 256 before copying data in png_set_PLTE(). Interchanged order of write_swap_alpha and write_invert_alpha transforms. Added parentheses in the definition of PNG_LIBPNG_BUILD_TYPE (Cosmin). Optimized zlib window flag (CINFO) in contrib/pngsuite/*.png (Cosmin). Updated scripts/makefile.bc32 for Borland C++ 5.6 (Cosmin). Exported png_get_uint_32, png_save_uint_32, png_get_uint_16, png_save_uint_16, png_get_int_32, png_save_int_32, png_get_uint_31 (Cosmin). Added type cast (png_byte) in png_write_sCAL() (Cosmin). Fixed scripts/makefile.cygwin (Christian Biesinger, Cosmin). Default iTXt support was inadvertently enabled. Version 1.2.9beta2 [February 21, 2006] Check for png_rgb_to_gray and png_gray_to_rgb read transformations before checking for png_read_dither in pngrtran.c Revised checking of chromaticity limits to accommodate extended RGB colorspace (John Denker). Changed line endings in some of the project files to CRLF, even in the "Unix" tar distributions (Cosmin). Made png_get_int_32 and png_save_int_32 always available (Cosmin). Updated scripts/pngos2.def, scripts/pngw32.def and projects/wince/png32ce.def with the newly exported functions. Eliminated distributions without the "configure" script. Updated INSTALL instructions. Version 1.2.9beta3 [February 24, 2006] Fixed CRCRLF line endings in contrib/visupng/VisualPng.dsp Made libpng.pc respect EXEC_PREFIX (D. P. Kreil, J. Bowler) Removed reference to pngasmrd.h from Makefile.am Renamed CHANGES to ChangeLog. Renamed LICENSE to COPYING. Renamed ANNOUNCE to NEWS. Created AUTHORS file. Version 1.2.9beta4 [March 3, 2006] Changed definition of PKGCONFIG from $prefix/lib to $libdir in configure.ac Reverted to filenames LICENSE and ANNOUNCE; removed AUTHORS and COPYING. Removed newline from the end of some error and warning messages. Removed test for sqrt() from configure.ac and configure. Made swap tables in pngtrans.c PNG_CONST (Carlo Bramix). Disabled default iTXt support that was inadvertently enabled in libpng-1.2.9beta1. Added "OS2" to list of systems that don't need underscores, in pnggccrd.c Removed libpng version and date from *.c files. Version 1.2.9beta5 [March 4, 2006] Removed trailing blanks from source files. Put version and date of latest change in each source file, and changed copyright year accordingly. More cleanup of configure.ac, Makefile.am, and associated scripts. Restored scripts/makefile.elf which was inadvertently deleted. Version 1.2.9beta6 [March 6, 2006] Fixed typo (RELEASE) in configuration files. Version 1.2.9beta7 [March 7, 2006] Removed libpng.vers and libpng.sym from libpng12_la_SOURCES in Makefile.am Fixed inconsistent #ifdef's around png_sig_bytes() and png_set_sCAL_s() in png.h. Updated makefile.elf as suggested by debian. Made cosmetic changes to some makefiles, adding LN_SF and other macros. Made some makefiles accept "exec_prefix". Version 1.2.9beta8 [March 9, 2006] Fixed some "#if defined (..." which should be "#if defined(..." Bug introduced in libpng-1.2.8. Fixed inconsistency in definition of png_default_read_data() Restored blank that was lost from makefile.sggcc "clean" target in beta7. Revised calculation of "current" and "major" for irix in ltmain.sh Changed "mkdir" to "MKDIR_P" in some makefiles. Separated PNG_EXPAND and PNG_EXPAND_tRNS. Added png_set_expand_gray_1_2_4_to_8() and deprecated png_set_gray_1_2_4_to_8() which also expands tRNS to alpha. Version 1.2.9beta9 [March 10, 2006] Include "config.h" in pngconf.h when available. Added some checks for NULL png_ptr or NULL info_ptr (timeless) Version 1.2.9beta10 [March 20, 2006] Removed extra CR from contrib/visualpng/VisualPng.dsw (Cosmin) Made pnggccrd.c PIC-compliant (Christian Aichinger). Added makefile.mingw (Wolfgang Glas). Revised pngconf.h MMX checking. Version 1.2.9beta11 [March 22, 2006] Fixed out-of-order declaration in pngwrite.c that was introduced in beta9 Simplified some makefiles by using LIBSO, LIBSOMAJ, and LIBSOVER macros. Version 1.2.9rc1 [March 31, 2006] Defined PNG_USER_PRIVATEBUILD when including "pngusr.h" (Cosmin). Removed nonsensical assertion check from pngtest.c (Cosmin). Version 1.2.9 [April 14, 2006] Revised makefile.beos and added "none" selector in ltmain.sh Version 1.2.10beta1 [April 15, 2006] Renamed "config.h" to "png_conf.h" and revised Makefile.am to add -DPNG_BUILDING_LIBPNG to compile directive, and modified pngconf.h to include png_conf.h only when PNG_BUILDING_LIBPNG is defined. Version 1.2.10beta2 [April 15, 2006] Manually updated Makefile.in and configure. Changed png_conf.h.in back to config.h. Version 1.2.10beta3 [April 15, 2006] Change png_conf.h back to config.h in pngconf.h. Version 1.2.10beta4 [April 16, 2006] Change PNG_BUILDING_LIBPNG to PNG_CONFIGURE_LIBPNG in config/Makefile*. Version 1.2.10beta5 [April 16, 2006] Added a configure check for compiling assembler code in pnggccrd.c Version 1.2.10beta6 [April 17, 2006] Revised the configure check for pnggccrd.c Moved -DPNG_CONFIGURE_LIBPNG into @LIBPNG_DEFINES@ Added @LIBPNG_DEFINES@ to arguments when building libpng.sym Version 1.2.10beta7 [April 18, 2006] Change "exec_prefix=$prefix" to "exec_prefix=$(prefix)" in makefiles. Version 1.2.10rc1 [April 19, 2006] Ensure pngconf.h doesn't define both PNG_USE_PNGGCCRD and PNG_USE_PNGVCRD Fixed "LN_FS" typo in makefile.sco and makefile.solaris. Version 1.2.10rc2 [April 20, 2006] Added a backslash between -DPNG_CONFIGURE_LIBPNG and -DPNG_NO_ASSEMBLER_CODE in configure.ac and configure Made the configure warning about versioned symbols less arrogant. Version 1.2.10rc3 [April 21, 2006] Added a note in libpng.txt that png_set_sig_bytes(8) can be used when writing an embedded PNG without the 8-byte signature. Revised makefiles and configure to avoid making links to libpng.so.* Version 1.2.10 [April 23, 2006] Reverted configure to "rc2" state. Version 1.2.11beta1 [May 31, 2006] scripts/libpng.pc.in contained "configure" style version info and would not work with makefiles. The shared-library makefiles were linking to libpng.so.0 instead of libpng.so.3 compatibility as the library. Version 1.2.11beta2 [June 2, 2006] Increased sprintf buffer from 50 to 52 chars in pngrutil.c to avoid buffer overflow. Fixed bug in example.c (png_set_palette_rgb -> png_set_palette_to_rgb) Version 1.2.11beta3 [June 5, 2006] Prepended "#! /bin/sh" to ltmail.sh and contrib/pngminus/*.sh (Cosmin). Removed the accidental leftover Makefile.in~ (Cosmin). Avoided potential buffer overflow and optimized buffer in png_write_sCAL(), png_write_sCAL_s() (Cosmin). Removed the include directories and libraries from CFLAGS and LDFLAGS in scripts/makefile.gcc (Nelson A. de Oliveira, Cosmin). Version 1.2.11beta4 [June 6, 2006] Allow zero-length IDAT chunks after the entire zlib datastream, but not after another intervening chunk type. Version 1.0.19rc1, 1.2.11rc1 [June 13, 2006] Deleted extraneous square brackets from [config.h] in configure.ac Version 1.0.19rc2, 1.2.11rc2 [June 14, 2006] Added prototypes for PNG_INCH_CONVERSIONS functions to png.h Revised INSTALL and autogen.sh Fixed typo in several makefiles (-W1 should be -Wl) Added typedef for png_int_32 and png_uint_32 on 64-bit systems. Version 1.0.19rc3, 1.2.11rc3 [June 15, 2006] Removed the new typedefs for 64-bit systems (delay until version 1.4.0) Added one zero element to png_gamma_shift[] array in pngrtran.c to avoid reading out of bounds. Version 1.0.19rc4, 1.2.11rc4 [June 15, 2006] Really removed the new typedefs for 64-bit systems. Version 1.0.19rc5, 1.2.11rc5 [June 22, 2006] Removed png_sig_bytes entry from scripts/pngw32.def Version 1.0.19, 1.2.11 [June 26, 2006] None. Version 1.0.20, 1.2.12 [June 27, 2006] Really increased sprintf buffer from 50 to 52 chars in pngrutil.c to avoid buffer overflow. Version 1.2.13beta1 [October 2, 2006] Removed AC_FUNC_MALLOC from configure.ac Work around Intel-Mac compiler bug by setting PNG_NO_MMX_CODE in pngconf.h Change "logical" to "bitwise" throughout documentation. Detect and fix attempt to write wrong iCCP profile length (CVE-2006-7244) Version 1.0.21, 1.2.13 [November 14, 2006] Fix potential buffer overflow in sPLT chunk handler. Fix Makefile.am to not try to link to noexistent files. Check all exported functions for NULL png_ptr. Version 1.2.14beta1 [November 17, 2006] Relocated three misplaced tests for NULL png_ptr. Built Makefile.in with automake-1.9.6 instead of 1.9.2. Build configure with autoconf-2.60 instead of 2.59 Version 1.2.14beta2 [November 17, 2006] Added some typecasts in png_zalloc(). Version 1.2.14rc1 [November 20, 2006] Changed "strtod" to "png_strtod" in pngrutil.c Version 1.0.22, 1.2.14 [November 27, 2006] Added missing "$(srcdir)" in Makefile.am and Makefile.in Version 1.2.15beta1 [December 3, 2006] Generated configure with autoconf-2.61 instead of 2.60 Revised configure.ac to update libpng.pc and libpng-config. Version 1.2.15beta2 [December 3, 2006] Always export MMX asm functions, just stubs if not building pnggccrd.c Version 1.2.15beta3 [December 4, 2006] Add "png_bytep" typecast to profile while calculating length in pngwutil.c Version 1.2.15beta4 [December 7, 2006] Added scripts/CMakeLists.txt Changed PNG_NO_ASSEMBLER_CODE to PNG_NO_MMX_CODE in scripts, like 1.4.0beta Version 1.2.15beta5 [December 7, 2006] Changed some instances of PNG_ASSEMBLER_* to PNG_MMX_* in pnggccrd.c Revised scripts/CMakeLists.txt Version 1.2.15beta6 [December 13, 2006] Revised scripts/CMakeLists.txt and configure.ac Version 1.2.15rc1 [December 18, 2006] Revised scripts/CMakeLists.txt Version 1.2.15rc2 [December 21, 2006] Added conditional #undef jmpbuf in pngtest.c to undo #define in AIX headers. Added scripts/makefile.nommx Version 1.2.15rc3 [December 25, 2006] Fixed shared library numbering error that was introduced in 1.2.15beta6. Version 1.2.15rc4 [December 27, 2006] Fixed handling of rgb_to_gray when png_ptr->color.gray isn't set. Version 1.2.15rc5 [December 31, 2006] Revised handling of rgb_to_gray. Version 1.2.15 [January 5, 2007] Added some (unsigned long) typecasts in pngtest.c to avoid printing errors. Version 1.2.16beta1 [January 6, 2007] Fix bugs in makefile.nommx Version 1.2.16beta2 [January 16, 2007] Revised scripts/CMakeLists.txt Version 1.2.16 [January 31, 2007] No changes. Version 1.2.17beta1 [March 6, 2007] Revised scripts/CMakeLists.txt to install both shared and static libraries. Deleted a redundant line from pngset.c. Version 1.2.17beta2 [April 26, 2007] Relocated misplaced test for png_ptr == NULL in pngpread.c Change "==" to "&" for testing PNG_RGB_TO_GRAY_ERR & PNG_RGB_TO_GRAY_WARN flags. Changed remaining instances of PNG_ASSEMBLER_* to PNG_MMX_* Added pngerror() when write_IHDR fails in deflateInit2(). Added "const" to some array declarations. Mention examples of libpng usage in the libpng*.txt and libpng.3 documents. Version 1.2.17rc1 [May 4, 2007] No changes. Version 1.2.17rc2 [May 8, 2007] Moved several PNG_HAVE_* macros out of PNG_INTERNAL because applications calling set_unknown_chunk_location() need them. Changed transformation flag from PNG_EXPAND_tRNS to PNG_EXPAND in png_set_expand_gray_1_2_4_to_8(). Added png_ptr->unknown_chunk to hold working unknown chunk data, so it can be free'ed in case of error. Revised unknown chunk handling in pngrutil.c and pngpread.c to use this structure. Version 1.2.17rc3 [May 8, 2007] Revised symbol-handling in configure script. Version 1.2.17rc4 [May 10, 2007] Revised unknown chunk handling to avoid storing unknown critical chunks. Version 1.0.25 [May 15, 2007] Version 1.2.17 [May 15, 2007] Added "png_ptr->num_trans=0" before error return in png_handle_tRNS, to eliminate a vulnerability (CVE-2007-2445, CERT VU#684664) Version 1.0.26 [May 15, 2007] Version 1.2.18 [May 15, 2007] Reverted the libpng-1.2.17rc3 change to symbol-handling in configure script Version 1.2.19beta1 [May 18, 2007] Changed "const static" to "static PNG_CONST" everywhere, mostly undoing change of libpng-1.2.17beta2. Changed other "const" to "PNG_CONST" Changed some handling of unused parameters, to avoid compiler warnings. "if (unused == NULL) return;" becomes "unused = unused". Version 1.2.19beta2 [May 18, 2007] Only use the valid bits of tRNS value in png_do_expand() (Brian Cartier) Version 1.2.19beta3 [May 19, 2007] Add some "png_byte" typecasts in png_check_keyword() and write new_key instead of key in zTXt chunk (Kevin Ryde). Version 1.2.19beta4 [May 21, 2007] Add png_snprintf() function and use it in place of sprint() for improved defense against buffer overflows. Version 1.2.19beta5 [May 21, 2007] Fixed png_handle_tRNS() to only use the valid bits of tRNS value. Changed handling of more unused parameters, to avoid compiler warnings. Removed some PNG_CONST in pngwutil.c to avoid compiler warnings. Version 1.2.19beta6 [May 22, 2007] Added some #ifdef PNG_MMX_CODE_SUPPORTED where needed in pngvcrd.c Added a special "_MSC_VER" case that defines png_snprintf to _snprintf Version 1.2.19beta7 [May 22, 2007] Squelched png_squelch_warnings() in pnggccrd.c and added an #ifdef PNG_MMX_CODE_SUPPORTED block around the declarations that caused the warnings that png_squelch_warnings was squelching. Version 1.2.19beta8 [May 22, 2007] Removed __MMX__ from test in pngconf.h. Version 1.2.19beta9 [May 23, 2007] Made png_squelch_warnings() available via PNG_SQUELCH_WARNINGS macro. Revised png_squelch_warnings() so it might work. Updated makefile.sgcc and makefile.solaris; added makefile.solaris-x86. Version 1.2.19beta10 [May 24, 2007] Resquelched png_squelch_warnings(), use "__attribute__((used))" instead. Version 1.4.0beta1 [April 20, 2006] Enabled iTXt support (changes png_struct, thus requires so-number change). Cleaned up PNG_ASSEMBLER_CODE_SUPPORTED vs PNG_MMX_CODE_SUPPORTED Eliminated PNG_1_0_X and PNG_1_2_X macros. Removed deprecated functions png_read_init, png_write_init, png_info_init, png_permit_empty_plte, png_set_gray_1_2_4_to_8, png_check_sig, and removed the deprecated macro PNG_MAX_UINT. Moved "PNG_INTERNAL" parts of png.h and pngconf.h into pngintrn.h Removed many WIN32_WCE #ifdefs (Cosmin). Reduced dependency on C-runtime library when on Windows (Simon-Pierre) Replaced sprintf() with png_sprintf() (Simon-Pierre) Version 1.4.0beta2 [April 20, 2006] Revised makefiles and configure to avoid making links to libpng.so.* Moved some leftover MMX-related defines from pngconf.h to pngintrn.h Updated scripts/pngos2.def, pngw32.def, and projects/wince/png32ce.def Version 1.4.0beta3 [May 10, 2006] Updated scripts/pngw32.def to comment out MMX functions. Added PNG_NO_GET_INT_32 and PNG_NO_SAVE_INT_32 macros. Scripts/libpng.pc.in contained "configure" style version info and would not work with makefiles. Revised pngconf.h and added pngconf.h.in, so makefiles and configure can pass defines to libpng and applications. Version 1.4.0beta4 [May 11, 2006] Revised configure.ac, Makefile.am, and many of the makefiles to write their defines in pngconf.h. Version 1.4.0beta5 [May 15, 2006] Added a missing semicolon in Makefile.am and Makefile.in Deleted extraneous square brackets from configure.ac Version 1.4.0beta6 [June 2, 2006] Increased sprintf buffer from 50 to 52 chars in pngrutil.c to avoid buffer overflow. Changed sonum from 0 to 1. Removed unused prototype for png_check_sig() from png.h Version 1.4.0beta7 [June 16, 2006] Exported png_write_sig (Cosmin). Optimized buffer in png_handle_cHRM() (Cosmin). Set pHYs = 2835 x 2835 pixels per meter, and added sCAL = 0.352778e-3 x 0.352778e-3 meters, in pngtest.png (Cosmin). Added png_set_benign_errors(), png_benign_error(), png_chunk_benign_error(). Added typedef for png_int_32 and png_uint_32 on 64-bit systems. Added "(unsigned long)" typecast on png_uint_32 variables in printf lists. Version 1.4.0beta8 [June 22, 2006] Added demonstration of user chunk support in pngtest.c, to support the public sTER chunk and a private vpAg chunk. Version 1.4.0beta9 [July 3, 2006] Removed ordinals from scripts/pngw32.def and removed png_info_int and png_set_gray_1_2_4_to_8 entries. Inline call of png_get_uint_32() in png_get_uint_31(). Use png_get_uint_31() to get vpAg width and height in pngtest.c Removed WINCE and Netware projects. Removed standalone Y2KINFO file. Version 1.4.0beta10 [July 12, 2006] Eliminated automatic copy of pngconf.h to pngconf.h.in from configure and some makefiles, because it was not working reliably. Instead, distribute pngconf.h.in along with pngconf.h and cause configure and some of the makefiles to update pngconf.h from pngconf.h.in. Added pngconf.h to DEPENDENCIES in Makefile.am Version 1.4.0beta11 [August 19, 2006] Removed AC_FUNC_MALLOC from configure.ac. Added a warning when writing iCCP profile with mismatched profile length. Patched pnggccrd.c to assemble on x86_64 platforms. Moved chunk header reading into a separate function png_read_chunk_header() in pngrutil.c. The chunk header (len+sig) is now serialized in a single operation (Cosmin). Implemented support for I/O states. Added png_ptr member io_state, and functions png_get_io_chunk_name() and png_get_io_state() in pngget.c (Cosmin). Added png_get_io_chunk_name and png_get_io_state to scripts/*.def (Cosmin). Renamed scripts/pngw32.* to scripts/pngwin.* (Cosmin). Removed the include directories and libraries from CFLAGS and LDFLAGS in scripts/makefile.gcc (Cosmin). Used png_save_uint_32() to set vpAg width and height in pngtest.c (Cosmin). Cast to proper type when getting/setting vpAg units in pngtest.c (Cosmin). Added pngintrn.h to the Visual C++ projects (Cosmin). Removed scripts/list (Cosmin). Updated copyright year in scripts/pngwin.def (Cosmin). Removed PNG_TYPECAST_NULL and used standard NULL consistently (Cosmin). Disallowed the user to redefine png_size_t, and enforced a consistent use of png_size_t across libpng (Cosmin). Changed the type of png_ptr->rowbytes, PNG_ROWBYTES() and friends to png_size_t (Cosmin). Removed png_convert_size() and replaced png_sizeof with sizeof (Cosmin). Removed some unnecessary type casts (Cosmin). Changed prototype of png_get_compression_buffer_size() and png_set_compression_buffer_size() to work with png_size_t instead of png_uint_32 (Cosmin). Removed png_memcpy_check() and png_memset_check() (Cosmin). Fixed a typo (png_byte --> png_bytep) in libpng.3 and libpng.txt (Cosmin). Clarified that png_zalloc() does not clear the allocated memory, and png_zalloc() and png_zfree() cannot be PNGAPI (Cosmin). Renamed png_mem_size_t to png_alloc_size_t, fixed its definition in pngconf.h, and used it in all memory allocation functions (Cosmin). Renamed pngintrn.h to pngpriv.h, added a comment at the top of the file mentioning that the symbols declared in that file are private, and updated the scripts and the Visual C++ projects accordingly (Cosmin). Removed circular references between pngconf.h and pngconf.h.in in scripts/makefile.vc*win32 (Cosmin). Removing trailing '.' from the warning and error messages (Cosmin). Added pngdefs.h that is built by makefile or configure, instead of pngconf.h.in (Glenn). Detect and fix attempt to write wrong iCCP profile length. Version 1.4.0beta12 [October 19, 2006] Changed "logical" to "bitwise" in the documentation. Work around Intel-Mac compiler bug by setting PNG_NO_MMX_CODE in pngconf.h Add a typecast to stifle compiler warning in pngrutil.c Version 1.4.0beta13 [November 10, 2006] Fix potential buffer overflow in sPLT chunk handler. Fix Makefile.am to not try to link to noexistent files. Version 1.4.0beta14 [November 15, 2006] Check all exported functions for NULL png_ptr. Version 1.4.0beta15 [November 17, 2006] Relocated two misplaced tests for NULL png_ptr. Built Makefile.in with automake-1.9.6 instead of 1.9.2. Build configure with autoconf-2.60 instead of 2.59 Add "install: all" in Makefile.am so "configure; make install" will work. Version 1.4.0beta16 [November 17, 2006] Added a typecast in png_zalloc(). Version 1.4.0beta17 [December 4, 2006] Changed "new_key[79] = '\0';" to "(*new_key)[79] = '\0';" in pngwutil.c Add "png_bytep" typecast to profile while calculating length in pngwutil.c Version 1.4.0beta18 [December 7, 2006] Added scripts/CMakeLists.txt Version 1.4.0beta19 [May 16, 2007] Revised scripts/CMakeLists.txt Rebuilt configure and Makefile.in with newer tools. Added conditional #undef jmpbuf in pngtest.c to undo #define in AIX headers. Added scripts/makefile.nommx Version 1.4.0beta20 [July 9, 2008] Moved several PNG_HAVE_* macros from pngpriv.h to png.h because applications calling set_unknown_chunk_location() need them. Moved several macro definitions from pngpriv.h to pngconf.h Merge with changes to the 1.2.X branch, as of 1.2.30beta04. Deleted all use of the MMX assembler code and Intel-licensed optimizations. Revised makefile.mingw Version 1.4.0beta21 [July 21, 2008] Moved local array "chunkdata" from pngrutil.c to the png_struct, so it will be freed by png_read_destroy() in case of a read error (Kurt Christensen). Version 1.4.0beta22 [July 21, 2008] Change "purpose" and "buffer" to png_ptr->chunkdata to avoid memory leaking. Version 1.4.0beta23 [July 22, 2008] Change "chunkdata = NULL" to "png_ptr->chunkdata = NULL" several places in png_decompress_chunk(). Version 1.4.0beta24 [July 25, 2008] Change all remaining "chunkdata" to "png_ptr->chunkdata" in png_decompress_chunk(), and remove "chunkdata" from parameter list. Put a call to png_check_chunk_name() in png_read_chunk_header(). Revised png_check_chunk_name() to reject a name with a lowercase 3rd byte. Removed two calls to png_check_chunk_name() occurring later in the process. Define PNG_NO_ERROR_NUMBERS by default in pngconf.h Version 1.4.0beta25 [July 30, 2008] Added a call to png_check_chunk_name() in pngpread.c Reverted png_check_chunk_name() to accept a name with a lowercase 3rd byte. Added png_push_have_buffer() function to pngpread.c Eliminated PNG_BIG_ENDIAN_SUPPORTED and associated png_get_* macros. Made inline expansion of png_get_*() optional with PNG_USE_READ_MACROS. Eliminated all PNG_USELESS_TESTS and PNG_CORRECT_PALETTE_SUPPORTED code. Synced contrib directory and configure files with libpng-1.2.30beta06. Eliminated no-longer-used pngdefs.h (but it's still built in the makefiles) Relocated a misplaced "#endif /* PNG_NO_WRITE_FILTER */" in pngwutil.c Version 1.4.0beta26 [August 4, 2008] Removed png_push_have_buffer() function in pngpread.c. It increased the compiled library size slightly. Changed "-Wall" to "-W -Wall" in the CFLAGS in all makefiles (Cosmin Truta) Declared png_ptr "volatile" in pngread.c and pngwrite.c to avoid warnings. Updated contrib/visupng/cexcept.h to version 2.0.1 Added PNG_LITERAL_CHARACTER macros for #, [, and ]. Version 1.4.0beta27 [August 5, 2008] Revised usage of PNG_LITERAL_SHARP in pngerror.c. Moved newline character from individual png_debug messages into the png_debug macros. Allow user to #define their own png_debug, png_debug1, and png_debug2. Version 1.4.0beta28 [August 5, 2008] Revised usage of PNG_LITERAL_SHARP in pngerror.c. Added PNG_STRING_NEWLINE macro Version 1.4.0beta29 [August 9, 2008] Revised usage of PNG_STRING_NEWLINE to work on non-ISO compilers. Added PNG_STRING_COPYRIGHT macro. Added non-ISO versions of png_debug macros. Version 1.4.0beta30 [August 14, 2008] Added premultiplied alpha feature (Volker Wiendl). Version 1.4.0beta31 [August 18, 2008] Moved png_set_premultiply_alpha from pngtrans.c to pngrtran.c Removed extra crc check at the end of png_handle_cHRM(). Bug introduced in libpng-1.4.0beta20. Version 1.4.0beta32 [August 19, 2008] Added PNG_WRITE_FLUSH_SUPPORTED block around new png_flush() call. Revised PNG_NO_STDIO version of png_write_flush() Version 1.4.0beta33 [August 20, 2008] Added png_get|set_chunk_cache_max() to limit the total number of sPLT, text, and unknown chunks that can be stored. Version 1.4.0beta34 [September 6, 2008] Shortened tIME_string to 29 bytes in pngtest.c Fixed off-by-one error introduced in png_push_read_zTXt() function in libpng-1.2.30beta04/pngpread.c (Harald van Dijk) Version 1.4.0beta35 [October 6, 2008] Changed "trans_values" to "trans_color". Changed so-number from 0 to 14. Some OS do not like 0. Revised makefile.darwin to fix shared library numbering. Change png_set_gray_1_2_4_to_8() to png_set_expand_gray_1_2_4_to_8() in example.c (debian bug report) Version 1.4.0beta36 [October 25, 2008] Sync with tEXt vulnerability fix in libpng-1.2.33rc02. Version 1.4.0beta37 [November 13, 2008] Added png_check_cHRM in png.c and moved checking from pngget.c, pngrutil.c, and pngwrite.c Version 1.4.0beta38 [November 22, 2008] Added check for zero-area RGB cHRM triangle in png_check_cHRM() and png_check_cHRM_fixed(). Version 1.4.0beta39 [November 23, 2008] Revised png_warning() to write its message on standard output by default when warning_fn is NULL. Version 1.4.0beta40 [November 24, 2008] Eliminated png_check_cHRM(). Instead, always use png_check_cHRM_fixed(). In png_check_cHRM_fixed(), ensure white_y is > 0, and removed redundant check for all-zero coordinates that is detected by the triangle check. Version 1.4.0beta41 [November 26, 2008] Fixed string vs pointer-to-string error in png_check_keyword(). Rearranged test expressions in png_check_cHRM_fixed() to avoid internal overflows. Added PNG_NO_CHECK_cHRM conditional. Version 1.4.0beta42, 43 [December 1, 2008] Merge png_debug with version 1.2.34beta04. Version 1.4.0beta44 [December 6, 2008] Removed redundant check for key==NULL before calling png_check_keyword() to ensure that new_key gets initialized and removed extra warning (Merge with version 1.2.34beta05 -- Arvan Pritchard). Version 1.4.0beta45 [December 9, 2008] In png_write_png(), respect the placement of the filler bytes in an earlier call to png_set_filler() (Jim Barry). Version 1.4.0beta46 [December 10, 2008] Undid previous change and added PNG_TRANSFORM_STRIP_FILLER_BEFORE and PNG_TRANSFORM_STRIP_FILLER_AFTER conditionals and deprecated PNG_TRANSFORM_STRIP_FILLER (Jim Barry). Version 1.4.0beta47 [December 15, 2008] Support for dithering was disabled by default, because it has never been well tested and doesn't work very well. The code has not been removed, however, and can be enabled by building libpng with PNG_READ_DITHER_SUPPORTED defined. Version 1.4.0beta48 [February 14, 2009] Added new exported function png_calloc(). Combined several instances of png_malloc(); png_memset() into png_calloc(). Removed prototype for png_freeptr() that was added in libpng-1.4.0beta24 but was never defined. Version 1.4.0beta49 [February 28, 2009] Added png_fileno() macro to pngconf.h, used in pngwio.c Corrected order of #ifdef's in png_debug definition in png.h Fixed bug introduced in libpng-1.4.0beta48 with the memset arguments for pcal_params. Fixed order of #ifdef directives in the png_debug defines in png.h (bug introduced in libpng-1.2.34/1.4.0beta29). Revised comments in png_set_read_fn() and png_set_write_fn(). Version 1.4.0beta50 [March 18, 2009] Use png_calloc() instead of png_malloc() to allocate big_row_buf when reading an interlaced file, to avoid a possible UMR. Undid revision of PNG_NO_STDIO version of png_write_flush(). Users having trouble with fflush() can build with PNG_NO_WRITE_FLUSH defined or supply their own flush_fn() replacement. Revised libpng*.txt and png.h documentation about use of png_write_flush() and png_set_write_fn(). Removed fflush() from pngtest.c. Added "#define PNG_NO_WRITE_FLUSH" to contrib/pngminim/encoder/pngusr.h Version 1.4.0beta51 [March 21, 2009] Removed new png_fileno() macro from pngconf.h . Version 1.4.0beta52 [March 27, 2009] Relocated png_do_chop() ahead of building gamma tables in pngrtran.c This avoids building 16-bit gamma tables unnecessarily. Removed fflush() from pngtest.c. Added "#define PNG_NO_WRITE_FLUSH" to contrib/pngminim/encoder/pngusr.h Added a section on differences between 1.0.x and 1.2.x to libpng.3/libpng.txt Version 1.4.0beta53 [April 1, 2009] Removed some remaining MMX macros from pngpriv.h Fixed potential memory leak of "new_name" in png_write_iCCP() (Ralph Giles) Version 1.4.0beta54 [April 13, 2009] Added "ifndef PNG_SKIP_SETJMP_CHECK" block in pngconf.h to allow application code writers to bypass the check for multiple inclusion of setjmp.h when they know that it is safe to ignore the situation. Eliminated internal use of setjmp() in pngread.c and pngwrite.c Reordered ancillary chunks in pngtest.png to be the same as what pngtest now produces, and made some cosmetic changes to pngtest output. Eliminated deprecated png_read_init_3() and png_write_init_3() functions. Version 1.4.0beta55 [April 15, 2009] Simplified error handling in pngread.c and pngwrite.c by putting the new png_read_cleanup() and png_write_cleanup() functions inline. Version 1.4.0beta56 [April 25, 2009] Renamed "user_chunk_data" to "my_user_chunk_data" in pngtest.c to suppress "shadowed declaration" warning from gcc-4.3.3. Renamed "gamma" to "png_gamma" in pngset.c to avoid "shadowed declaration" warning about a global "gamma" variable in math.h on some platforms. Version 1.4.0beta57 [May 2, 2009] Removed prototype for png_freeptr() that was added in libpng-1.4.0beta24 but was never defined (again). Rebuilt configure scripts with autoconf-2.63 instead of 2.62 Removed pngprefs.h and MMX from makefiles Version 1.4.0beta58 [May 14, 2009] Changed pngw32.def to pngwin.def in makefile.mingw (typo was introduced in beta57). Clarified usage of sig_bit versus sig_bit_p in example.c (Vincent Torri) Version 1.4.0beta59 [May 15, 2009] Reformated sources in libpng style (3-space intentation, comment format) Fixed typo in libpng docs (PNG_FILTER_AVE should be PNG_FILTER_AVG) Added sections about the git repository and our coding style to the documentation Relocated misplaced #endif in pngwrite.c, sCAL chunk handler. Version 1.4.0beta60 [May 19, 2009] Conditionally compile png_read_finish_row() which is not used by progressive readers. Added contrib/pngminim/preader to demonstrate building minimal progressive decoder, based on contrib/gregbook with embedded libpng and zlib. Version 1.4.0beta61 [May 20, 2009] In contrib/pngminim/*, renamed "makefile.std" to "makefile", since there is only one makefile in those directories, and revised the README files accordingly. More reformatting of comments, mostly to capitalize sentences. Version 1.4.0beta62 [June 2, 2009] Added "#define PNG_NO_WRITE_SWAP" to contrib/pngminim/encoder/pngusr.h and "define PNG_NO_READ_SWAP" to decoder/pngusr.h and preader/pngusr.h Reformatted several remaining "else statement" into two lines. Added a section to the libpng documentation about using png_get_io_ptr() in configure scripts to detect the presence of libpng. Version 1.4.0beta63 [June 15, 2009] Revised libpng*.txt and libpng.3 to mention calling png_set_IHDR() multiple times and to specify the sample order in the tRNS chunk, because the ISO PNG specification has a typo in the tRNS table. Changed several PNG_UNKNOWN_CHUNK_SUPPORTED to PNG_HANDLE_AS_UNKNOWN_SUPPORTED, to make the png_set_keep mechanism available for ignoring known chunks even when not saving unknown chunks. Adopted preference for consistent use of "#ifdef" and "#ifndef" versus "#if defined()" and "if !defined()" where possible. Version 1.4.0beta64 [June 24, 2009] Eliminated PNG_LEGACY_SUPPORTED code. Moved the various unknown chunk macro definitions outside of the PNG_READ|WRITE_ANCILLARY_CHUNK_SUPPORTED blocks. Version 1.4.0beta65 [June 26, 2009] Added a reference to the libpng license in each file. Version 1.4.0beta66 [June 27, 2009] Refer to the libpng license instead of the libpng license in each file. Version 1.4.0beta67 [July 6, 2009] Relocated INVERT_ALPHA within png_read_png() and png_write_png(). Added high-level API transform PNG_TRANSFORM_GRAY_TO_RGB. Added an "xcode" project to the projects directory (Alam Arias). Version 1.4.0beta68 [July 19, 2009] Avoid some tests in filter selection in pngwutil.c Version 1.4.0beta69 [July 25, 2009] Simplified the new filter-selection test. This runs faster in the common "PNG_ALL_FILTERS" and PNG_FILTER_NONE cases. Removed extraneous declaration from the new call to png_read_gray_to_rgb() (bug introduced in libpng-1.4.0beta67). Fixed up xcode project (Alam Arias) Added a prototype for png_64bit_product() in png.c Version 1.4.0beta70 [July 27, 2009] Avoid a possible NULL dereference in debug build, in png_set_text_2(). (bug introduced in libpng-0.95, discovered by Evan Rouault) Version 1.4.0beta71 [July 29, 2009] Rebuilt configure scripts with autoconf-2.64. Version 1.4.0beta72 [August 1, 2009] Replaced *.tar.lzma with *.tar.xz in distribution. Get the xz codec from . Version 1.4.0beta73 [August 1, 2009] Reject attempt to write iCCP chunk with negative embedded profile length (JD Chen) (CVE-2009-5063). Version 1.4.0beta74 [August 8, 2009] Changed png_ptr and info_ptr member "trans" to "trans_alpha". Version 1.4.0beta75 [August 21, 2009] Removed an extra png_debug() recently added to png_write_find_filter(). Fixed incorrect #ifdef in pngset.c regarding unknown chunk support. Version 1.4.0beta76 [August 22, 2009] Moved an incorrectly located test in png_read_row() in pngread.c Version 1.4.0beta77 [August 27, 2009] Removed lpXYZ.tar.bz2 (with CRLF), KNOWNBUG, libpng-x.y.z-KNOWNBUG.txt, and the "noconfig" files from the distribution. Moved CMakeLists.txt from scripts into the main libpng directory. Various bugfixes and improvements to CMakeLists.txt (Philip Lowman) Version 1.4.0beta78 [August 31, 2009] Converted all PNG_NO_* tests to PNG_*_SUPPORTED everywhere except pngconf.h Eliminated PNG_NO_FREE_ME and PNG_FREE_ME_SUPPORTED macros. Use png_malloc plus a loop instead of png_calloc() to initialize row_pointers in png_read_png(). Version 1.4.0beta79 [September 1, 2009] Eliminated PNG_GLOBAL_ARRAYS and PNG_LOCAL_ARRAYS; always use local arrays. Eliminated PNG_CALLOC_SUPPORTED macro and always provide png_calloc(). Version 1.4.0beta80 [September 17, 2009] Removed scripts/libpng.icc Changed typecast of filler from png_byte to png_uint_16 in png_set_filler(). (Dennis Gustafsson) Fixed typo introduced in beta78 in pngtest.c ("#if def " should be "#ifdef ") Version 1.4.0beta81 [September 23, 2009] Eliminated unused PNG_FLAG_FREE_* defines from pngpriv.h Expanded TAB characters in pngrtran.c Removed PNG_CONST from all "PNG_CONST PNG_CHNK" declarations to avoid compiler complaints about doubly declaring things "const". Changed all "#if [!]defined(X)" to "if[n]def X" where possible. Eliminated unused png_ptr->row_buf_size Version 1.4.0beta82 [September 25, 2009] Moved redundant IHDR checking into new png_check_IHDR() in png.c and report all errors found in the IHDR data. Eliminated useless call to png_check_cHRM() from pngset.c Version 1.4.0beta83 [September 25, 2009] Revised png_check_IHDR() to eliminate bogus complaint about filter_type. Version 1.4.0beta84 [September 30, 2009] Fixed some inconsistent indentation in pngconf.h Revised png_check_IHDR() to add a test for width variable less than 32-bit. Version 1.4.0beta85 [October 1, 2009] Revised png_check_IHDR() again, to check info_ptr members instead of the contents of the returned parameters. Version 1.4.0beta86 [October 9, 2009] Updated the "xcode" project (Alam Arias). Eliminated a shadowed declaration of "pp" in png_handle_sPLT(). Version 1.4.0rc01 [October 19, 2009] Trivial cosmetic changes. Version 1.4.0beta87 [October 30, 2009] Moved version 1.4.0 back into beta. Version 1.4.0beta88 [October 30, 2009] Revised libpng*.txt section about differences between 1.2.x and 1.4.0 because most of the new features have now been ported back to 1.2.41 Version 1.4.0beta89 [November 1, 2009] More bugfixes and improvements to CMakeLists.txt (Philip Lowman) Removed a harmless extra png_set_invert_alpha() from pngwrite.c Apply png_user_chunk_cache_max within png_decompress_chunk(). Merged libpng-1.2.41.txt with libpng-1.4.0.txt where appropriate. Version 1.4.0beta90 [November 2, 2009] Removed all remaining WIN32_WCE #ifdefs except those involving the time.h "tm" structure Version 1.4.0beta91 [November 3, 2009] Updated scripts/pngw32.def and projects/wince/png32ce.def Copied projects/wince/png32ce.def to the scripts directory. Added scripts/makefile.wce Patched ltmain.sh for wince support. Added PNG_CONVERT_tIME_SUPPORTED macro. Version 1.4.0beta92 [November 4, 2009] Make inclusion of time.h in pngconf.h depend on PNG_CONVERT_tIME_SUPPORTED Make #define PNG_CONVERT_tIME_SUPPORTED depend on PNG_WRITE_tIME_SUPPORTED Revised libpng*.txt to describe differences from 1.2.40 to 1.4.0 (instead of differences from 1.2.41 to 1.4.0) Version 1.4.0beta93 [November 7, 2009] Added PNG_DEPSTRUCT, PNG_DEPRECATED, PNG_USE_RESULT, PNG_NORETURN, and PNG_ALLOCATED macros to detect deprecated direct access to the png_struct or info_struct members and other deprecated usage in applications (John Bowler). Updated scripts/makefile* to add "-DPNG_CONFIGURE_LIBPNG" to CFLAGS, to prevent warnings about direct access to png structs by libpng functions while building libpng. They need to be tested, especially those using compilers other than gcc. Updated projects/visualc6 and visualc71 with "/d PNG_CONFIGURE_LIBPNG". They should work but still need to be updated to remove references to pnggccrd.c or pngvcrd.c and ASM building. Added README.txt to the beos, cbuilder5, netware, and xcode projects warning that they need to be updated, to remove references to pnggccrd.c and pngvcrd.c and to depend on pngpriv.h Removed three direct references to read_info_ptr members in pngtest.c that were detected by the new PNG_DEPSTRUCT macro. Moved the png_debug macro definitions and the png_read_destroy(), png_write_destroy() and png_far_to_near() prototypes from png.h to pngpriv.h (John Bowler) Moved the synopsis lines for png_read_destroy(), png_write_destroy() png_debug(), png_debug1(), and png_debug2() from libpng.3 to libpngpf.3. Version 1.4.0beta94 [November 9, 2009] Removed the obsolete, unused pnggccrd.c and pngvcrd.c files. Updated CMakeLists.txt to add "-DPNG_CONFIGURE_LIBPNG" to the definitions. Removed dependency of pngtest.o on pngpriv.h in the makefiles. Only #define PNG_DEPSTRUCT, etc. in pngconf.h if not already defined. Version 1.4.0beta95 [November 10, 2009] Changed png_check_sig() to !png_sig_cmp() in contrib programs. Added -DPNG_CONFIGURE_LIBPNG to contrib/pngminm/*/makefile Changed png_check_sig() to !png_sig_cmp() in contrib programs. Corrected the png_get_IHDR() call in contrib/gregbook/readpng2.c Changed pngminim/*/gather.sh to stop trying to remove pnggccrd.c and pngvcrd.c Added dependency on pngpriv.h in contrib/pngminim/*/makefile Version 1.4.0beta96 [November 12, 2009] Renamed scripts/makefile.wce to scripts/makefile.cegcc Revised Makefile.am to use libpng.sys while building libpng.so so that only PNG_EXPORT functions are exported. Removed the deprecated png_check_sig() function/macro. Removed recently removed function names from scripts/*.def Revised pngtest.png to put chunks in the same order written by pngtest (evidently the same change made in libpng-1.0beta54 was lost). Added PNG_PRIVATE macro definition in pngconf.h for possible future use. Version 1.4.0beta97 [November 13, 2009] Restored pngtest.png to the libpng-1.4.0beta7 version. Removed projects/beos and netware.txt; no one seems to be supporting them. Revised Makefile.in Version 1.4.0beta98 [November 13, 2009] Added the "xcode" project to zip distributions, Fixed a typo in scripts/pngwin.def introduced in beta97. Version 1.4.0beta99 [November 14, 2009] Moved libpng-config.in and libpng.pc-configure.in out of the scripts directory, to libpng-config.in and libpng-pc.in, respectively, and modified Makefile.am and configure.ac accordingly. Now "configure" needs nothing from the "scripts" directory. Avoid redefining PNG_CONST in pngconf.h Version 1.4.0beta100 [November 14, 2009] Removed ASM builds from projects/visualc6 and projects/visualc71 Removed scripts/makefile.nommx and makefile.vcawin32 Revised CMakeLists.txt to account for new location of libpng-config.in and libpng-pc.in Updated INSTALL to reflect removal and relocation of files. Version 1.4.0beta101 [November 14, 2009] Restored the binary files (*.jpg, *.png, some project files) that were accidentally deleted from the zip and 7z distributions when the xcode project was added. Version 1.4.0beta102 [November 18, 2009] Added libpng-config.in and libpng-pc.in to the zip and 7z distributions. Fixed a typo in projects/visualc6/pngtest.dsp, introduced in beta100. Moved descriptions of makefiles and other scripts out of INSTALL into scripts/README.txt Updated the copyright year in scripts/pngwin.rc from 2006 to 2009. Version 1.4.0beta103 [November 21, 2009] Removed obsolete comments about ASM from projects/visualc71/README_zlib.txt Align row_buf on 16-byte boundary in memory. Restored the PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED guard around the call to png_flush() after png_write_IEND(). See 1.4.0beta32, 1.4.0beta50 changes above and 1.2.30, 1.2.30rc01 and rc03 in 1.2.41 CHANGES. Someone needs this feature. Make the 'png_jmpbuf' macro expand to a call that records the correct longjmp function as well as returning a pointer to the setjmp jmp_buf buffer, and marked direct access to jmpbuf 'deprecated'. (John Bowler) Version 1.4.0beta104 [November 22, 2009] Removed png_longjmp_ptr from scripts/*.def and libpng.3 Rebuilt configure scripts with autoconf-2.65 Version 1.4.0beta105 [November 25, 2009] Use fast integer PNG_DIVIDE_BY_255() or PNG_DIVIDE_BY_65535() to accomplish alpha premultiplication when PNG_READ_COMPOSITE_NODIV_SUPPORTED is defined. Changed "/255" to "/255.0" in background calculations to make it clear that the 255 is used as a double. Version 1.4.0beta106 [November 27, 2009] Removed premultiplied alpha feature. Version 1.4.0beta107 [December 4, 2009] Updated README Added "#define PNG_NO_PEDANTIC_WARNINGS" in the libpng source files. Removed "-DPNG_CONFIGURE_LIBPNG" from the makefiles and projects. Revised scripts/makefile.netbsd, makefile.openbsd, and makefile.sco to put png.h and pngconf.h in $prefix/include, like the other scripts, instead of in $prefix/include/libpng. Also revised makefile.sco to put them in $prefix/include/libpng15 instead of in $prefix/include/libpng/libpng15. Version 1.4.0beta108 [December 11, 2009] Removed leftover "-DPNG_CONFIGURE_LIBPNG" from contrib/pngminim/*/makefile Relocated png_do_chop() to its original position in pngrtran.c; the change in version 1.2.41beta08 caused transparency to be handled wrong in some 16-bit datastreams (Yusaku Sugai). Version 1.4.0beta109 [December 13, 2009] Added "bit_depth" parameter to the private png_build_gamma_table() function. Pass bit_depth=8 to png_build_gamma_table() when bit_depth is 16 but the PNG_16_TO_8 transform has been set, to avoid unnecessary build of 16-bit tables. Version 1.4.0rc02 [December 20, 2009] Declared png_cleanup_needed "volatile" in pngread.c and pngwrite.c Version 1.4.0rc03 [December 22, 2009] Renamed libpng-pc.in back to libpng.pc.in and revised CMakeLists.txt (revising the change in 1.4.0beta99) Version 1.4.0rc04 [December 25, 2009] Swapped PNG_UNKNOWN_CHUNKS_SUPPORTED and PNG_HANDLE_AS_UNKNOWN_SUPPORTED in pngset.c to be consistent with other changes in version 1.2.38. Version 1.4.0rc05 [December 25, 2009] Changed "libpng-pc.in" to "libpng.pc.in" in configure.ac, configure, and Makefile.in to be consistent with changes in libpng-1.4.0rc03 Version 1.4.0rc06 [December 29, 2009] Reverted the gamma_table changes from libpng-1.4.0beta109. Fixed some indentation errors. Version 1.4.0rc07 [January 1, 2010] Revised libpng*.txt and libpng.3 about 1.2.x->1.4.x differences. Use png_calloc() instead of png_malloc(); png_memset() in pngrutil.c Update copyright year to 2010. Version 1.4.0rc08 [January 2, 2010] Avoid deprecated references to png_ptr-io_ptr and png_ptr->error_ptr in pngtest.c Version 1.4.0 [January 3, 2010] No changes. Version 1.4.1beta01 [January 8, 2010] Updated CMakeLists.txt for consistent indentation and to avoid an unclosed if-statement warning (Philip Lowman). Revised Makefile.am and Makefile.in to remove references to Y2KINFO, KNOWNBUG, and libpng.la (Robert Schwebel). Revised the makefiles to install the same files and symbolic links as configure, except for libpng.la and libpng14.la. Make png_set|get_compression_buffer_size() available even when PNG_WRITE_SUPPORTED is not enabled. Revised Makefile.am and Makefile.in to simplify their maintenance. Revised scripts/makefile.linux to install a link to libpng14.so.14.1 Version 1.4.1beta02 [January 9, 2010] Revised the rest of the makefiles to install a link to libpng14.so.14.1 Version 1.4.1beta03 [January 10, 2010] Removed png_set_premultiply_alpha() from scripts/*.def Version 1.4.1rc01 [January 16, 2010] No changes. Version 1.4.1beta04 [January 23, 2010] Revised png_decompress_chunk() to improve speed and memory usage when decoding large chunks. Added png_set|get_chunk_malloc_max() functions. Version 1.4.1beta05 [January 26, 2010] Relocated "int k" declaration in pngtest.c to minimize its scope. Version 1.4.1beta06 [January 28, 2010] Revised png_decompress_chunk() to use a two-pass method suggested by John Bowler. Version 1.4.1beta07 [February 6, 2010] Folded some long lines in the source files. Added defineable PNG_USER_CHUNK_CACHE_MAX, PNG_USER_CHUNK_MALLOC_MAX, and a PNG_USER_LIMITS_SUPPORTED flag. Eliminated use of png_ptr->irowbytes and reused the slot in png_ptr as png_ptr->png_user_chunk_malloc_max. Revised png_push_save_buffer() to do fewer but larger png_malloc() calls. Version 1.4.1beta08 [February 6, 2010] Minor cleanup and updating of dates and copyright year. Version 1.5.0beta01 [February 7, 2010] Moved declaration of png_struct into private pngstruct.h and png_info into pnginfo.h Version 1.4.1beta09 and 1.5.0beta02 [February 7, 2010] Reverted to original png_push_save_buffer() code. Version 1.4.1beta10 and 1.5.0beta03 [February 8, 2010] Return allocated "old_buffer" in png_push_save_buffer() before calling png_error(), to avoid a potential memory leak. Updated configure script to use SO number 15. Version 1.5.0beta04 [February 9, 2010] Removed malformed "incomplete struct declaration" of png_info from png.h Version 1.5.0beta05 [February 12, 2010] Removed PNG_DEPSTRUCT markup in pngstruct.h and pnginfo.h, and undid the linewrapping that it entailed. Revised comments in pngstruct.h and pnginfo.h and added pointers to the libpng license. Changed PNG_INTERNAL to PNG_EXPOSE_INTERNAL_STRUCTURES Removed the cbuilder5 project, which has not been updated to 1.4.0. Version 1.4.1beta12 and 1.5.0beta06 [February 14, 2010] Fixed type declaration of png_get_chunk_malloc_max() in pngget.c (Daisuke Nishikawa) Version 1.5.0beta07 [omitted] Version 1.5.0beta08 [February 19, 2010] Changed #ifdef PNG_NO_STDIO_SUPPORTED to #ifdef PNG_NO_CONSOLE_IO_SUPPORTED wherever png_snprintf() is used to construct error and warning messages. Noted in scripts/makefile.mingw that it expects to be run under MSYS. Removed obsolete unused MMX-querying support from contrib/gregbook Added exported png_longjmp() function. Removed the AIX redefinition of jmpbuf in png.h Added -D_ALLSOURCE in configure.ac, makefile.aix, and CMakeLists.txt when building on AIX. Version 1.5.0beta09 [February 19, 2010] Removed -D_ALLSOURCE from configure.ac, makefile.aix, and CMakeLists.txt. Changed the name of png_ptr->jmpbuf to png_ptr->png_jmpbuf in pngstruct.h Version 1.5.0beta10 [February 25, 2010] Removed unused gzio.c from contrib/pngminim gather and makefile scripts Removed replacement error handlers from contrib/gregbook. Because of the new png_longjmp() function they are no longer needed. Version 1.5.0beta11 [March 6, 2010] Removed checking for already-included setjmp.h from pngconf.h Fixed inconsistent indentations and made numerous cosmetic changes. Revised the "SEE ALSO" style of libpng.3, libpngpf.3, and png.5 Version 1.5.0beta12 [March 9, 2010] Moved "#include png.h" inside pngpriv.h and removed "#include png.h" from the source files, along with "#define PNG_EXPOSE_INTERNAL_STRUCTURES" and "#define PNG_NO_PEDANTIC_WARNINGS" (John Bowler). Created new pngdebug.h and moved debug definitions there. Version 1.5.0beta13 [March 10, 2010] Protect pngstruct.h, pnginfo.h, and pngdebug.h from being included twice. Revise the "#ifdef" blocks in png_inflate() so it will compile when neither PNG_USER_CHUNK_MALLOC_MAX nor PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED is defined. Removed unused png_measure_compressed_chunk() from pngpriv.h and libpngpf.3 Moved the 'config.h' support from pngconf.h to pngpriv.h Removed PNGAPI from the png_longjmp_ptr typedef. Eliminated dependence of pngtest.c on the private pngdebug.h file. Make all png_debug macros into *unterminated* statements or expressions (i.e. a trailing ';' must always be added) and correct the format statements in various png_debug messages. Version 1.5.0beta14 [March 14, 2010] Removed direct access to png_ptr->io_ptr from the Windows code in pngtest.c Revised Makefile.am to account for recent additions and replacements. Corrected CE and OS/2 DEF files (scripts/png*def) for symbols removed and added ordinal numbers to the Windows DEF file and corrected the duplicated ordinal numbers on CE symbols that are commented out. Added back in export symbols that can be present in the Windows build but are disabled by default. PNG_EXPORT changed to include an 'ordinal' field for DEF file generation. PNG_CALLBACK added to make callback definitions uniform. PNGAPI split into PNGCAPI (base C form), PNGAPI (exports) and PNGCBAPI (callbacks), and appropriate changes made to all files. Cygwin builds re-hinged to allow procedure call standard changes and to remove the need for the DEF file (fixes build on Cygwin). Enabled 'attribute' warnings that are relevant to library APIs and callbacks. Changed rules for generation of the various symbol files and added a new rule for a DEF file (which is also added to the distribution). Updated the symbol file generation to stop it adding spurious spaces to EOL (coming from preprocessor macro expansion). Added a facility to join tokens in the output and rewrite *.dfn to use this. Eliminated scripts/*.def in favor of libpng.def; updated projects/visualc71 and removed scripts/makefile.cygwin. Made PNG_BUILD_DLL safe: it can be set whenever a DLL is being built. Removed the include of sys/types.h - apparently unnecessary now on the platforms on which it happened (all but Mac OS and RISC OS). Moved the Mac OS test into pngpriv.h (the only place it is used.) Version 1.5.0beta15 [March 17, 2010] Added symbols.chk target to Makefile.am to validate the symbols in png.h against the new DEF file scripts/symbols.def. Changed the default DEF file back to pngwin.def. Removed makefile.mingw. Eliminated PNG_NO_EXTERN and PNG_ALL_EXTERN Version 1.5.0beta16 [April 1, 2010] Make png_text_struct independent of PNG_iTXt_SUPPORTED, so that fields are initialized in all configurations. The READ/WRITE macros (PNG_(READ|WRITE)_iTXt_SUPPORTED) still function as before to disable code to actually read or write iTXt chunks and iTXt_SUPPORTED can be used to detect presence of either read or write support (but it is probably better to check for the one actually required - read or write.) Combined multiple png_warning() calls for a single error. Restored the macro definition of png_check_sig(). Version 1.5.0beta17 [April 17, 2010] Added some "(long)" typecasts to printf calls in png_handle_cHRM(). Documented the fact that png_set_dither() was disabled since libpng-1.4.0. Reenabled png_set_dither() but renamed it to png_set_quantize() to reflect more accurately what it actually does. At the same time, renamed the PNG_DITHER_[RED,GREEN_BLUE]_BITS macros to PNG_QUANTIZE_[RED,GREEN,BLUE]_BITS. Added some "(long)" typecasts to printf calls in png_handle_cHRM(). Freeze build-time only configuration in the build. In all prior versions of libpng most configuration options controlled by compiler #defines had to be repeated by the application code that used libpng. This patch changes this so that compilation options that can only be changed at build time are frozen in the build. Options that are compiler dependent (and those that are system dependent) are evaluated each time - pngconf.h holds these. Options that can be changed per-file in the application are in png.h. Frozen options are in the new installed header file pnglibconf.h (John Bowler) Removed the xcode project because it has not been updated to work with libpng-1.5.0. Removed the ability to include optional pngusr.h Version 1.5.0beta18 [April 17, 2010] Restored the ability to include optional pngusr.h Moved replacements for png_error() and png_warning() from the contrib/pngminim project to pngerror.c, for use when warnings or errors are disabled via PNG_NO_WARN or PNG_NO_ERROR_TEXT, to avoid storing unneeded error/warning text. Updated contrib/pngminim project to work with the new pnglibconf.h Added some PNG_NO_* defines to contrib/pngminim/*/pngusr.h to save space. Version 1.5.0beta19 [April 24, 2010] Added PNG_{READ,WRITE}_INT_FUNCTIONS_SUPPORTED. This allows the functions to read and write ints to be disabled independently of PNG_USE_READ_MACROS, which allows libpng to be built with the functions even though the default is to use the macros - this allows applications to choose at app build time whether or not to use macros (previously impossible because the functions weren't in the default build.) Changed Windows calling convention back to __cdecl for API functions. For Windows/x86 platforms only: __stdcall is no longer needed for Visual Basic, so libpng-1.5.0 uses __cdecl throughout (both API functions and callbacks) on Windows/x86 platforms. Replaced visualc6 and visualc71 projects with new vstudio project Relaxed the overly-restrictive permissions of some files. Version 1.5.0beta20 [April 24, 2010] Relaxed more overly-restrictive permissions of some files. Version 1.5.0beta21 [April 27, 2010] Removed some unwanted binary bytes and changed CRLF to NEWLINE in the new vstudio project files, and some trivial editing of some files in the scripts directory. Set PNG_NO_READ_BGR, PNG_NO_IO_STATE, and PNG_NO_TIME_RFC1123 in contrib/pngminim/decoder/pngusr.h to make a smaller decoder application. Version 1.5.0beta22 [April 28, 2010] Fixed dependencies of GET_INT_32 - it does not require READ_INT_FUNCTIONS because it has a macro equivalent. Improved the options.awk script; added an "everything off" option. Revised contrib/pngminim to use the "everything off" option in pngusr.dfa. Version 1.5.0beta23 [April 29, 2010] Corrected PNG_REMOVED macro to take five arguments. The macro was documented with two arguments (name,ordinal), however the symbol checking .dfn files assumed five arguments. The five argument form seems more useful so it is changed to that. Corrected PNG_UNKNOWN_CHUNKS_SUPPORTED to PNG_HANDLE_AS_UNKNOWN_SUPPORTED in gregbook/readpng2.c Corrected protection of png_get_user_transform_ptr. The API declaration in png.h is removed if both READ and WRITE USER_TRANSFORM are turned off but was left defined in pngtrans.c Added logunsupported=1 to cause pnglibconf.h to document disabled options. This makes the installed pnglibconf.h more readable but causes no other change. The intention is that users of libpng will find it easier to understand if an API they need is missing. Include png_reset_zstream() in png.c only when PNG_READ_SUPPORTED is defined. Removed dummy_inflate.c from contrib/pngminim/encoder Removed contrib/pngminim/*/gather.sh; gathering is now done in the makefile. Version 1.5.0beta24 [May 7, 2010] Use bitwise "&" instead of arithmetic mod in pngrutil.c calculation of the offset of the png_ptr->rowbuf pointer into png_ptr->big_row_buf. Added more blank lines for readability. Version 1.5.0beta25 [June 18, 2010] In pngpread.c: png_push_have_row() add check for new_row > height Removed the now-redundant check for out-of-bounds new_row from example.c Version 1.5.0beta26 [June 18, 2010] In pngpread.c: png_push_process_row() add check for too many rows. Version 1.5.0beta27 [June 18, 2010] Removed the check added in beta25 as it is now redundant. Version 1.5.0beta28 [June 20, 2010] Rewrote png_process_IDAT_data to consistently treat extra data as warnings and handle end conditions more cleanly. Removed the new (beta26) check in png_push_process_row(). Version 1.5.0beta29 [June 21, 2010] Revised scripts/options.awk to work on Sunos (but still doesn't work) Added comment to options.awk and contrib/pngminim/*/makefile to try nawk. Version 1.5.0beta30 [June 22, 2010] Stop memory leak when reading a malformed sCAL chunk. Version 1.5.0beta31 [June 26, 2010] Revised pngpread.c patch of beta28 to avoid an endless loop. Removed some trailing blanks. Version 1.5.0beta32 [June 26, 2010] Removed leftover scripts/options.patch and scripts/options.rej Version 1.5.0beta33 [July 6, 3010] Made FIXED and FLOATING options consistent in the APIs they enable and disable. Corrected scripts/options.awk to handle both command line options and options specified in the .dfa files. Changed char *msg to PNG_CONST char *msg in pngrutil.c Make png_set_sRGB_gAMA_and_cHRM set values using either the fixed or floating point APIs, but not both. Reversed patch to remove error handler when the jmp_buf is stored in the main program structure, not the png_struct. The error handler is needed because the default handler in libpng will always use the jmp_buf in the library control structure; this is never set. The gregbook code is a useful example because, even though it uses setjmp/longjmp, it shows how error handling can be implemented using control mechanisms not directly supported by libpng. The technique will work correctly with mechanisms such as Microsoft Structure Exceptions or C++ exceptions (compiler willing - note that gcc does not by default support interworking of C and C++ error handling.) Reverted changes to call png_longjmp in contrib/gregbook where it is not appropriate. If mainprog->jmpbuf is used by setjmp, then png_longjmp cannot be used. Changed "extern PNG_EXPORT" to "PNG_EXPORT" in png.h (Jan Nijtmans) Changed "extern" to "PNG_EXTERN" in pngpriv.h (except for the 'extern "C" {') Version 1.5.0beta34 [July 12, 2010] Put #ifndef PNG_EXTERN, #endif around the define PNG_EXTERN in pngpriv.h Version 1.5.0beta35 [July 24, 2010] Removed some newly-added TAB characters. Added -DNO_PNG_SNPRINTF to CFLAGS in scripts/makefile.dj2 Moved the definition of png_snprintf() outside of the enclosing #ifdef blocks in pngconf.h Version 1.5.0beta36 [July 29, 2010] Patches by John Bowler: Fixed point APIs are now supported throughout (no missing APIs). Internal fixed point arithmetic support exists for all internal floating point operations. sCAL validates the floating point strings it is passed. Safe, albeit rudimentary, Watcom support is provided by PNG_API_RULE==2 Two new APIs exist to get the number of passes without turning on the PNG_INTERLACE transform and to get the number of rows in the current pass. A new test program, pngvalid.c, validates the gamma code. Errors in the 16-bit gamma correction (overflows) have been corrected. cHRM chunk testing is done consistently (previously the floating point API bypassed it, because the test really didn't work on FP, now the test is performed on the actual values to be stored in the PNG file so it works in the FP case too.) Most floating point APIs now simply call the fixed point APIs after converting the values to the fixed point form used in the PNG file. The standard headers no longer include zlib.h, which is currently only required for pngstruct.h and can therefore be internal. Revised png_get_int_32 to undo the PNG two's complement representation of negative numbers. Version 1.5.0beta37 [July 30, 2010] Added a typecast in png_get_int_32() in png.h and pngrutil.h to avoid a compiler warning. Replaced oFFs 0,0 with oFFs -10,20 in pngtest.png Version 1.5.0beta38 [July 31, 2010] Implemented remaining "_fixed" functions. Corrected a number of recently introduced warnings mostly resulting from safe but uncast assignments to shorter integers. Also added a zlib VStudio release library project because the latest zlib Official Windows build does not include such a thing. Revised png_get_int_16() to be similar to png_get_int_32(). Restored projects/visualc71. Version 1.5.0beta39 [August 2, 2010] VisualC/GCC warning fixes, VisualC build fixes The changes include support for function attributes in VC in addition to those already present in GCC - necessary because without these some warnings are unavoidable. Fixes include signed/unsigned fixes in pngvalid and checks with gcc -Wall -Wextra -Wunused. VC requires function attributes on function definitions as well as declarations, PNG_FUNCTION has been added to enable this and the relevant function definitions changed. Version 1.5.0beta40 [August 6, 2010] Correct use of _WINDOWS_ in pngconf.h Removed png_mem_ #defines; they are no longer used. Added the sRGB chunk to pngtest.png Version 1.5.0beta41 [August 11, 2010] Added the cHRM chunk to pngtest.png Don't try to use version-script with cygwin/mingw. Revised contrib/gregbook to work under cygwin/mingw. Version 1.5.0beta42 [August 18, 2010] Add .dll.a to the list of extensions to be symlinked by Makefile.am (Yaakov) Made all API functions that have const arguments and constant string literal pointers declare them (John Bowler). Version 1.5.0beta43 [August 20, 2010] Removed spurious tabs, shorten long lines (no source change) Also added scripts/chkfmt to validate the format of all the files that can reasonably be validated (it is suggested to run "make distclean" before checking, because some machine generated files have long lines.) Reformatted the CHANGES file to be more consistent throughout. Made changes to address various issues identified by GCC, mostly signed/unsigned and shortening problems on assignment but also a few difficult to optimize (for GCC) loops. Fixed non-GCC fixed point builds. In png.c a declaration was misplaced in an earlier update. Fixed to declare the auto variables at the head. Use cexcept.h in pngvalid.c. Version 1.5.0beta44 [August 24, 2010] Updated CMakeLists.txt to use CMAKE_INSTALL_LIBDIR variable; useful for installing libpng in /usr/lib64 (Funda Wang). Revised CMakeLists.txt to put the man pages in share/man/man* not man/man* Revised CMakeLists.txt to make symlinks instead of copies when installing. Changed PNG_LIB_NAME from pngNN to libpngNN in CMakeLists.txt (Philip Lowman) Implemented memory checks within pngvalid Reformatted/rearranged pngvalid.c to assist use of progressive reader. Check interlaced images in pngvalid Clarified pngusr.h comments in pnglibconf.dfa Simplified the pngvalid error-handling code now that cexcept.h is in place. Implemented progressive reader in pngvalid.c for standard tests Implemented progressive read in pngvalid.c gamma tests Turn on progressive reader in pngvalid.c by default and tidy code. Version 1.5.0beta45 [August 26, 2010] Added an explicit make step to projects/vstudio for pnglibconf.h Also corrected zlib.vcxproj into which Visual Studio had introduced what it calls an "authoring error". The change to make pnglibconf.h simply copies the file; in the future it may actually generate the file from scripts/pnglibconf.dfa as the other build systems do. Changed pngvalid to work when floating point APIs are disabled Renamed the prebuilt scripts/pnglibconf.h to scripts/pnglibconf.h.prebuilt Supply default values for PNG_USER_PRIVATEBUILD and PNG_USER_DLLFNAME_POSTFIX in pngpriv.h in case the user neglected to define them in their pngusr.h Version 1.5.0beta46 [August 28, 2010] Added new private header files to libpng_sources in CMakeLists.txt Added PNG_READ_16BIT, PNG_WRITE_16BIT, and PNG_16BIT options. Added reference to scripts/pnglibconf.h.prebuilt in the visualc71 project. Version 1.5.0beta47 [September 11, 2010] Fixed a number of problems with 64-bit compilation reported by Visual Studio 2010 (John Bowler). Version 1.5.0beta48 [October 4, 2010] Updated CMakeLists.txt (Philip Lowman). Revised autogen.sh to recognize and use $AUTOCONF, $AUTOMAKE, $AUTOHEADER, $AUTOPOINT, $ACLOCAL and $LIBTOOLIZE Fixed problem with symbols creation in Makefile.am which was assuming that all versions of ccp write to standard output by default (Martin Banky). The bug was introduced in libpng-1.2.9beta5. Removed unused mkinstalldirs. Version 1.5.0beta49 [October 8, 2010] Undid Makefile.am revision of 1.5.0beta48. Version 1.5.0beta50 [October 14, 2010] Revised Makefile.in to account for mkinstalldirs being removed. Added some "(unsigned long)" typecasts in printf statements in pngvalid.c. Suppressed a compiler warning in png_handle_sPLT(). Check for out-of-range text compression mode in png_set_text(). Version 1.5.0beta51 [October 15, 2010] Changed embedded dates to "(PENDING RELEASE) in beta releases (and future rc releases) to minimize the difference between releases. Version 1.5.0beta52 [October 16, 2010] Restored some of the embedded dates (in png.h, png.c, documentation, etc.) Version 1.5.0beta53 [October 18, 2010] Updated INSTALL to mention using "make maintainer-clean" and to remove obsolete statement about a custom ltmain.sh Disabled "color-tests" by default in Makefile.am so it will work with automake versions earlier than 1.11.1 Use document name "libpng-manual.txt" instead of "libpng-.txt" to simplify version differences. Removed obsolete remarks about setjmp handling from INSTALL. Revised and renamed the typedef in png.h and png.c that was designed to catch library and header mismatch. Version 1.5.0beta54 [November 10, 2010] Require 48 bytes, not 64 bytes, for big_row_buf in overflow checks. Used a consistent structure for the pngget.c functions. Version 1.5.0beta55 [November 21, 2010] Revised png_get_uint_32, png_get_int_32, png_get_uint_16 (Cosmin) Moved reading of file signature into png_read_sig (Cosmin) Fixed atomicity of chunk header serialization (Cosmin) Added test for io_state in pngtest.c (Cosmin) Added "#!/bin/sh" at the top of contrib/pngminim/*/gather.sh scripts. Changes to remove gcc warnings (John Bowler) Certain optional gcc warning flags resulted in warnings in libpng code. With these changes only -Wconversion and -Wcast-qual cannot be turned on. Changes are trivial rearrangements of code. -Wconversion is not possible for pngrutil.c (because of the widespread use of += et al on variables smaller than (int) or (unsigned int)) and -Wcast-qual is not possible with pngwio.c and pngwutil.c because the 'write' callback and zlib compression both fail to declare their input buffers with 'const'. Version 1.5.0beta56 [December 7, 2010] Added the private PNG_UNUSED() macro definition in pngpriv.h. Added some commentary about PNG_EXPORT in png.h and pngconf.h Revised PNG_EXPORT() macro and added PNG_EXPORTA() macro, with the objective of simplifying and improving the cosmetic appearance of png.h. Fixed some incorrect "=" macro names in pnglibconf.dfa Included documentation of changes in 1.5.0 from 1.4.x in libpng-manual.txt Version 1.5.0beta57 [December 9, 2010] Documented the pngvalid gamma error summary with additional comments and print statements. Improved missing symbol handling in checksym.awk; symbols missing in both the old and new files can now be optionally ignored, treated as errors or warnings. Removed references to pngvcrd.c and pnggccrd.c from the vstudio project. Updated "libpng14" to "libpng15" in the visualc71 project. Enabled the strip16 tests in pngvalid.` Don't display test results (except PASS/FAIL) when running "make test". Instead put them in pngtest-log.txt Added "--with-zprefix=" to configure.ac Updated the prebuilt configuration files to autoconf version 2.68 Version 1.5.0beta58 [December 19, 2010] Fixed interlace image handling and add test cases (John Bowler) Fixed the clean rule in Makefile.am to remove pngtest-log.txt Made minor changes to work around warnings in gcc 3.4 Version 1.5.0rc01 [December 27, 2010] No changes. Version 1.5.0rc02 [December 27, 2010] Eliminated references to the scripts/*.def files in project/visualc71. Version 1.5.0rc03 [December 28, 2010] Eliminated scripts/*.def and revised Makefile.am accordingly Version 1.5.0rc04 [December 29, 2010] Fixed bug in background transformation handling in pngrtran.c (it was looking for the flag in png_ptr->transformations instead of in png_ptr->flags) (David Raymond). Version 1.5.0rc05 [December 31, 2010] Fixed typo in a comment in CMakeLists.txt (libpng14 => libpng15) (Cosmin) Version 1.5.0rc06 [January 4, 2011] Changed the new configure option "zprefix=string" to "zlib-prefix=string" Version 1.5.0rc07 [January 4, 2011] Updated copyright year. Version 1.5.0 [January 6, 2011] No changes. version 1.5.1beta01 [January 8, 2011] Added description of png_set_crc_action() to the manual. Added a note in the manual that the type of the iCCP profile was changed from png_charpp to png_bytepp in png_get_iCCP(). This change happened in version 1.5.0beta36 but is not noted in the CHANGES. Similarly, it was changed from png_charpp to png_const_bytepp in png_set_iCCP(). Ensure that png_rgb_to_gray ignores palette mapped images, if libpng internally happens to call it with one, and fixed a failure to handle palette mapped images correctly. This fixes CVE-2690. Version 1.5.1beta02 [January 14, 2011] Fixed a bug in handling of interlaced images (bero at arklinux.org). Updated CMakeLists.txt (Clifford Yapp) Version 1.5.1beta03 [January 14, 2011] Fixed typecasting of some png_debug() statements (Cosmin) Version 1.5.1beta04 [January 16, 2011] Updated documentation of png_set|get_tRNS() (Thomas Klausner). Mentioned in the documentation that applications must #include "zlib.h" if they need access to anything in zlib.h, and that a number of macros such as png_memset() are no longer accessible by applications. Corrected pngvalid gamma test "sample" function to access all of the color samples of each pixel, instead of sampling the red channel three times. Prefixed variable names index, div, exp, gamma with "png_" to avoid "shadow" warnings, and (mistakenly) changed png_exp() to exp(). Version 1.5.1beta05 [January 16, 2011] Changed variable names png_index, png_div, png_exp, and png_gamma to char_index, divisor, exp_b10, and gamma_val, respectively, and changed exp() back to png_exp(). Version 1.5.1beta06 [January 20, 2011] Prevent png_push_crc_skip() from hanging while reading an unknown chunk or an over-large compressed zTXt chunk with the progressive reader. Eliminated more GCC "shadow" warnings. Revised png_fixed() in png.c to avoid compiler warning about reaching the end without returning anything. Version 1.5.1beta07 [January 22, 2011] In the manual, describe the png_get_IHDR() arguments in the correct order. Added const_png_structp and const_png_infop types, and used them in prototypes for most png_get_*() functions. Version 1.5.1beta08 [January 23, 2011] Added png_get_io_chunk_type() and deprecated png_get_io_chunk_name() Added synopses for the IO_STATE functions and other missing synopses to the manual. Removed the synopses from libpngpf.3 because they were out of date and no longer useful. Better information can be obtained by reading the prototypes and comments in pngpriv.h Attempted to fix cpp on Solaris with S. Studio 12 cc, fix build Added a make macro DFNCPP that is a CPP that will accept the tokens in a .dfn file and adds configure stuff to test for such a CPP. ./configure should fail if one is not available. Corrected const_png_ in png.h to png_const_ to avoid polluting the namespace. Added png_get_current_row_number and png_get_current_pass_number for the benefit of the user transform callback. Added png_process_data_pause and png_process_data_skip for the benefit of progressive readers that need to stop data processing or want to optimize skipping of unread data (e.g., if the reader marks a chunk to be skipped.) Version 1.5.1beta09 [January 24, 2011] Enhanced pngvalid, corrected an error in gray_to_rgb, corrected doc error. pngvalid contains tests of transforms, which tests are currently disabled because they are incompletely tested. gray_to_rgb was failing to expand the bit depth for smaller bit depth images; this seems to be a long standing error and resulted, apparently, in invalid output (CVE-2011-0408, CERT VU#643140). The documentation did not accurately describe what libpng really does when converting RGB to gray. Version 1.5.1beta10 [January 27, 2010] Fixed incorrect examples of callback prototypes in the manual, that were introduced in libpng-1.0.0. In addition the order of the png_get_uint macros with respect to the relevant function definitions has been reversed. This helps the preprocessing of the symbol files be more robust. Furthermore, the symbol file preprocessing now uses -DPNG_NO_USE_READ_MACROS even when the library may actually be built with PNG_USE_READ_MACROS; this stops the read macros interfering with the symbol file format. Made the manual, synopses, and function prototypes use the function argument names file_gamma, int_file_gamma, and srgb_intent consistently. Version 1.5.1beta11 [January 28, 2011] Changed PNG_UNUSED from "param=param;" to "{if(param){}}". Corrected local variable type in new API png_process_data_skip() The type was self-evidently incorrect but only causes problems on 64-bit architectures. Added transform tests to pngvalid and simplified the arguments. Version 1.5.1rc01 [January 29, 2011] No changes. Version 1.5.1rc02 [January 31, 2011] Added a request in the manual that applications do not use "png_" or "PNG_" to begin any of their own symbols. Changed PNG_UNUSED to "(void)param;" and updated the commentary in pngpriv.h Version 1.5.1 [February 3, 2011] No changes. Version 1.5.2beta01 [February 13, 2011] More -Wshadow fixes for older gcc compilers. Older gcc versions apparently check formal parameters names in function declarations (as well as definitions) to see if they match a name in the global namespace. Revised PNG_EXPORTA macro to not use an empty parameter, to accommodate the old VisualC++ preprocessor. Turned on interlace handling in png_read_png(). Fixed gcc pendantic warnings. Handle longjmp in Cygwin. Fixed png_get_current_row_number() in the interlaced case. Cleaned up ALPHA flags and transformations. Implemented expansion to 16 bits. Version 1.5.2beta02 [February 19, 2011] Fixed mistake in the descriptions of user read_transform and write_transform function prototypes in the manual. The row_info struct is png_row_infop. Reverted png_get_current_row_number() to previous (1.5.2beta01) behavior. Corrected png_get_current_row_number documentation Fixed the read/write row callback documentation. This documents the current behavior, where the callback is called after every row with information pertaining to the next row. Version 1.5.2beta03 [March 3, 2011] Fixed scripts/makefile.vcwin32 Updated contrib/pngsuite/README to add the word "modify". Define PNG_ALLOCATED to blank when _MSC_VER<1300. Version 1.5.2rc01 [March 19, 2011] Define remaining attributes to blank when MSC_VER<1300. ifdef out mask arrays in pngread.c when interlacing is not supported. Version 1.5.2rc02 [March 22, 2011] Added a hint to try CPP=/bin/cpp if "cpp -E" fails in scripts/pnglibconf.mak and in contrib/pngminim/*/makefile, eg., on SunOS 5.10, and removed "strip" from the makefiles. Fixed a bug (present since libpng-1.0.7) that makes png_handle_sPLT() fail to compile when PNG_NO_POINTER_INDEXING is defined (Chubanov Kirill) Version 1.5.2rc03 [March 24, 2011] Don't include standard header files in png.h while building the symbol table, to avoid cpp failure on SunOS (introduced PNG_BUILDING_SYMBOL_TABLE macro). Version 1.5.2 [March 31, 2011] No changes. Version 1.5.3beta01 [April 1, 2011] Re-initialize the zlib compressor before compressing non-IDAT chunks. Added API functions (png_set_text_compression_level() and four others) to set parameters for zlib compression of non-IDAT chunks. Version 1.5.3beta02 [April 3, 2011] Updated scripts/symbols.def with new API functions. Only compile the new zlib re-initializing code when text or iCCP is supported, using PNG_WRITE_COMPRESSED_TEXT_SUPPORTED macro. Improved the optimization of the zlib CMF byte (see libpng-1.2.6beta03). Optimize the zlib CMF byte in non-IDAT compressed chunks Version 1.5.3beta03 [April 16, 2011] Fixed gcc -ansi -pedantic compile. A strict ANSI system does not have snprintf, and the "__STRICT_ANSI__" detects that condition more reliably than __STDC__ (John Bowler). Removed the PNG_PTR_NORETURN attribute because it too dangerous. It tells the compiler that a user supplied callback (the error handler) does not return, yet there is no guarantee in practice that the application code will correctly implement the error handler because the compiler only issues a warning if there is a mistake (John Bowler). Removed the no-longer-used PNG_DEPSTRUCT macro. Updated the zlib version to 1.2.5 in the VStudio project. Fixed 64-bit builds where png_uint_32 is smaller than png_size_t in pngwutil.c (John Bowler). Fixed bug with stripping the filler or alpha channel when writing, that was introduced in libpng-1.5.2beta01 (bug report by Andrew Church). Version 1.5.3beta04 [April 27, 2011] Updated pngtest.png with the new zlib CMF optimization. Cleaned up conditional compilation code and of background/gamma handling Internal changes only except a new option to avoid compiling the png_build_grayscale_palette API (which is not used at all internally.) The main change is to move the transform tests (READ_TRANSFORMS, WRITE_TRANSFORMS) up one level to the caller of the APIs. This avoids calls to spurious functions if all transforms are disabled and slightly simplifies those functions. Pngvalid modified to handle this. A minor change is to stop the strip_16 and expand_16 interfaces from disabling each other; this allows the future alpha premultiplication code to use 16-bit intermediate values while still producing 8-bit output. png_do_background and png_do_gamma have been simplified to take a single pointer to the png_struct rather than pointers to every item required from the png_struct. This makes no practical difference to the internal code. A serious bug in the pngvalid internal routine 'standard_display_init' has been fixed - this failed to initialize the red channel and accidentally initialized the alpha channel twice. Changed png_struct jmp_buf member name from png_jmpbuf to tmp_jmpbuf to avoid a possible clash with the png_jmpbuf macro on some platforms. Version 1.5.3beta05 [May 6, 2011] Added the "_POSIX_SOURCE" feature test macro to ensure libpng sees the correct API. _POSIX_SOURCE is defined in pngpriv.h, pngtest.c and pngvalid.c to ensure that POSIX conformant systems disable non-POSIX APIs. Removed png_snprintf and added formatted warning messages. This change adds internal APIs to allow png_warning messages to have parameters without requiring the host OS to implement snprintf. As a side effect the dependency of the tIME-supporting RFC1132 code on stdio is removed and PNG_NO_WARNINGS does actually work now. Pass "" instead of '\0' to png_default_error() in png_err(). This mistake was introduced in libpng-1.2.20beta01. This fixes CVE-2011-2691. Added PNG_WRITE_OPTIMIZE_CMF_SUPPORTED macro to make the zlib "CMF" byte optimization configureable. IDAT compression failed if preceded by a compressed text chunk (bug introduced in libpng-1.5.3beta01-02). This was because the attempt to reset the zlib stream in png_write_IDAT happened after the first IDAT chunk had been deflated - much too late. In this change internal functions were added to claim/release the z_stream and, hopefully, make the code more robust. Also deflateEnd checking is added - previously libpng would ignore an error at the end of the stream. Version 1.5.3beta06 [May 8, 2011] Removed the -D_ALL_SOURCE from definitions for AIX in CMakeLists.txt Implemented premultiplied alpha support: png_set_alpha_mode API Version 1.5.3beta07 [May 11, 2011] Added expand_16 support to the high level interface. Added named value and 'flag' gamma support to png_set_gamma. Made a minor change from the previous (unreleased) ABI/API to hide the exact value used for Macs - it's not a good idea to embed this in the ABI! Moved macro definitions for PNG_HAVE_IHDR, PNG_HAVE_PLTE, and PNG_AFTER_IDAT from pngpriv.h to png.h because they must be visible to applications that call png_set_unknown_chunks(). Check for up->location !PNG_AFTER_IDAT when writing unknown chunks before IDAT. Version 1.5.3beta08 [May 16, 2011] Improved "pngvalid --speed" to exclude more of pngvalid from the time. Documented png_set_alpha_mode(), other changes in libpng.3/libpng-manual.txt The cHRM chunk now sets the defaults for png_set_rgb_to_gray() (when negative parameters are supplied by the caller), while in the absence of cHRM sRGB/Rec 709 values are still used. This introduced a divide-by-zero bug in png_handle_cHRM(). The bKGD chunk no longer overwrites the background value set by png_set_background(), allowing the latter to be used before the file header is read. It never performed any useful function to override the default anyway. Added memory overwrite and palette image checks to pngvalid.c Previously palette image code was poorly checked. Since the transformation code has a special palette path in most cases this was a severe weakness. Minor cleanup and some extra checking in pngrutil.c and pngrtran.c. When expanding an indexed image, always expand to RGBA if transparency is present. Version 1.5.3beta09 [May 17, 2011] Reversed earlier 1.5.3 change of transformation order; move png_expand_16 back where it was. The change doesn't work because it requires 16-bit gamma tables when the code only generates 8-bit ones. This fails silently; the libpng code just doesn't do any gamma correction. Moving the tests back leaves the old, inaccurate, 8-bit gamma calculations, but these are clearly better than none! Version 1.5.3beta10 [May 20, 2011] png_set_background() and png_expand_16() did not work together correctly. This problem is present in 1.5.2; if png_set_background is called with need_expand false and the matching 16 bit color libpng erroneously just treats it as an 8-bit color because of where png_do_expand_16 is in the transform list. This simple fix reduces the supplied colour to 8-bits, so it gets smashed, but this is better than the current behavior. Added tests for expand16, more fixes for palette image tests to pngvalid. Corrects the code for palette image tests and disables attempts to validate palette colors. Version 1.5.3rc01 [June 3, 2011] No changes. Version 1.5.3rc02 [June 8, 2011] Fixed uninitialized memory read in png_format_buffer() (Bug report by Frank Busse, CVE-2011-2501, related to CVE-2004-0421). Version 1.5.3beta11 [June 11, 2011] Fixed png_handle_sCAL which is broken in 1.5. This fixes CVE 2011-2692. Added sCAL to pngtest.png Revised documentation about png_set_user_limits() to say that it also affects png writing. Revised handling of png_set_user_limits() so that it can increase the limit beyond the PNG_USER_WIDTH|HEIGHT_MAX; previously it could only reduce it. Make the 16-to-8 scaling accurate. Dividing by 256 with no rounding is wrong (high by one) 25% of the time. Dividing by 257 with rounding is wrong in 128 out of 65536 cases. Getting the right answer all the time without division is easy. Added "_SUPPORTED" to the PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION macro. Added projects/owatcom, an IDE project for OpenWatcom to replace scripts/makefile.watcom. This project works with OpenWatcom 1.9. The IDE autogenerates appropriate makefiles (libpng.mk) for batch processing. The project is configurable, unlike the Visual Studio project, so long as the developer has an awk. Changed png_set_gAMA to limit the gamma value range so that the inverse of the stored value cannot overflow the fixed point representation, and changed other things OpenWatcom warns about. Revised pngvalid.c to test PNG_ALPHA_MODE_SUPPORTED correctly. This allows pngvalid to build when ALPHA_MODE is not supported, which is required if it is to build on libpng 1.4. Removed string/memory macros that are no longer used and are not necessarily fully supportable, particularly png_strncpy and png_snprintf. Added log option to pngvalid.c and attempted to improve gamma messages. Version 1.5.3 [omitted] People found the presence of a beta release following an rc release to be confusing; therefore we bump the version to libpng-1.5.4beta01 and there will be no libpng-1.5.3 release. Version 1.5.4beta01 [June 14, 2011] Made it possible to undefine PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED to get the same (inaccurate) output as libpng-1.5.2 and earlier. Moved definitions of PNG_HAVE_IHDR, PNG_AFTER_IDAT, and PNG_HAVE_PLTE outside of an unknown-chunk block in png.h because they are also needed for other uses. Version 1.5.4beta02 [June 14, 2011] Fixed and clarified LEGACY 16-to-8 scaling code. Added png_set_chop_16() API, to match inaccurate results from previous libpng versions. Removed the ACCURATE and LEGACY options (they are no longer useable) Use the old scaling method for background if png_set_chop_16() was called. Made png_set_chop_16() API removeable by disabling PNG_CHOP_16_TO_8_SUPPORTED Version 1.5.4beta03 [June 15, 2011] Fixed a problem in png_do_expand_palette() exposed by optimization in 1.5.3beta06 Also removed a spurious and confusing "trans" member ("trans") from png_info. The palette expand optimization prevented expansion to an intermediate RGBA form if tRNS was present but alpha was marked to be stripped; this exposed a check for tRNS in png_do_expand_palette() which is inconsistent with the code elsewhere in libpng. Correction to the expand_16 code; removed extra instance of png_set_scale_16_to_8 from pngpriv.h Version 1.5.4beta04 [June 16, 2011] Added a missing "#ifdef PNG_READ_BACKGROUND_SUPPORTED/#endif" in pngrtran.c Added PNG_TRANSFORM_CHOP_16 to the high-level read transforms. Made PNG_READ_16_TO_8_ACCURATE_SCALE configurable again. If this is not enabled, png_set_strip_16() and png_do_scale_16_to_8() aren't built. Revised contrib/visupng, gregbook, and pngminim to demonstrate chop_16_to_8 Version 1.5.4beta05 [June 16, 2011] Renamed png_set_strip_16() to png_set_scale_16() and renamed png_set_chop_16() to png_set_strip(16) in an attempt to minimize the behavior changes between libpng14 and libpng15. Version 1.5.4beta06 [June 18, 2011] Fixed new bug that was causing both strip_16 and scale_16 to be applied. Version 1.5.4beta07 [June 19, 2011] Fixed pngvalid, simplified macros, added checking for 0 in sCAL. The ACCURATE scale macro is no longer defined in 1.5 - call the png_scale_16_to_8 API. Made sure that PNG_READ_16_TO_8 is still defined if the png_strip_16_to_8 API is present. png_check_fp_number now maintains some state so that positive, negative and zero values are identified. sCAL uses these to be strictly spec conformant. Version 1.5.4beta08 [June 23, 2011] Fixed pngvalid if ACCURATE_SCALE is defined. Updated scripts/pnglibconf.h.prebuilt. Version 1.5.4rc01 [June 30, 2011] Define PNG_ALLOCATED to "restrict" only if MSC_VER >= 1400. Version 1.5.4 [July 7, 2011] No changes. Version 1.5.5beta01 [July 13, 2011] Fixed some typos and made other minor changes in the manual. Updated contrib/pngminus/makefile.std (Samuli Souminen) Version 1.5.5beta02 [July 14, 2011] Revised Makefile.am and Makefile.in to look in the right directory for pnglibconf.h.prebuilt Version 1.5.5beta03 [July 27, 2011] Enabled compilation with g++ compiler. This compiler does not recognize the file extension, so it always compiles with C++ rules. Made minor changes to pngrutil.c to cast results where C++ expects it but C does not. Minor editing of libpng.3 and libpng-manual.txt. Version 1.5.5beta04 [July 29, 2011] Revised CMakeLists.txt (Clifford Yapp) Updated commentary about the png_rgb_to_gray() default coefficients in the manual and in pngrtran.c Version 1.5.5beta05 [August 17, 2011] Prevent unexpected API exports from non-libpng DLLs on Windows. The "_DLL" is removed from the test of whether a DLL is being built (this erroneously caused the libpng APIs to be marked as DLL exports in static builds under Microsoft Visual Studio). Almost all of the libpng building configuration is moved from pngconf.h to pngpriv.h, but PNG_DLL_EXPORT remains in pngconf.h, though, so that it is colocated with the import definition (it is no longer used anywhere in the installed headers). The VStudio project definitions have been cleaned up: "_USRDLL" has been removed from the static library builds (this was incorrect), and PNG_USE_DLL has been added to pngvalid to test the functionality (pngtest does not supply it, deliberately). The spurious "_EXPORTS" has been removed from the libpng build (all these errors were a result of copy/paste between project configurations.) Added new types and internal functions for CIE RGB end point handling to pngpriv.h (functions yet to be implemented). Version 1.5.5beta06 [August 26, 2011] Ensure the CMAKE_LIBRARY_OUTPUT_DIRECTORY is set in CMakeLists.txt (Clifford Yap) Fixes to rgb_to_gray and cHRM XYZ APIs (John Bowler): The rgb_to_gray code had errors when combined with gamma correction. Some pixels were treated as true grey when they weren't and such pixels and true grey ones were not gamma corrected (the original value of the red component was used instead). APIs to get and set cHRM using color space end points have been added and the rgb_to_gray code that defaults based on cHRM, and the divide-by-zero bug in png_handle_cHRM (CERT VU#477046, CVE-2011-3328, introduced in 1.5.4) have been corrected. A considerable number of tests has been added to pngvalid for the rgb_to_gray transform. Arithmetic errors in rgb_to_gray whereby the calculated gray value was truncated to the bit depth rather than rounded have been fixed except in the 8-bit non-gamma-corrected case (where consistency seems more important than correctness.) The code still has considerable inaccuracies in the 8-bit case because 8-bit linear arithmetic is used. Version 1.5.5beta07 [September 7, 2011] Added "$(ARCH)" option to makefile.darwin Added SunOS support to configure.ac and Makefile.am Changed png_chunk_benign_error() to png_warning() in png.c, in png_XYZ_from_xy_checked(). Version 1.5.5beta08 [September 10, 2011] Fixed 64-bit compilation errors (gcc). The errors fixed relate to conditions where types that are 32 bits in the GCC 32-bit world (uLong and png_size_t) become 64 bits in the 64-bit world. This produces potential truncation errors which the compiler correctly flags. Relocated new HAVE_SOLARIS_LD definition in configure.ac Constant changes for 64-bit compatibility (removal of L suffixes). The 16-bit cases still use "L" as we don't have a 16-bit test system. Version 1.5.5rc01 [September 15, 2011] Removed "L" suffixes in pngpriv.h Version 1.5.5 [September 22, 2011] No changes. Version 1.5.6beta01 [September 22, 2011] Fixed some 64-bit type conversion warnings in pngrtran.c Moved row_info from png_struct to a local variable. The various interlace mask arrays have been made into arrays of bytes and made PNG_CONST and static (previously some arrays were marked PNG_CONST and some weren't). Additional checks have been added to the transform code to validate the pixel depths after the transforms on both read and write. Removed some redundant code from pngwrite.c, in png_destroy_write_struct(). Changed chunk reading/writing code to use png_uint_32 instead of png_byte[4]. This removes the need to allocate temporary strings for chunk names on the stack in the read/write code. Unknown chunk handling still uses the string form because this is exposed in the API. Version 1.5.6beta02 [September 26, 2011] Added a note in the manual the png_read_update_info() must be called only once with a particular info_ptr. Fixed a typo in the definition of the new PNG_STRING_FROM_CHUNK(s,c) macro. Version 1.5.6beta03 [September 28, 2011] Revised test-pngtest.sh to report FAIL when pngtest fails. Added "--strict" option to pngtest, to report FAIL when the failure is only because the resulting valid files are different. Revised CMakeLists.txt to work with mingw and removed some material from CMakeLists.txt that is no longer useful in libpng-1.5. Version 1.5.6beta04 [October 5, 2011] Fixed typo in Makefile.in and Makefile.am ("-M Wl" should be "-M -Wl")." Version 1.5.6beta05 [October 12, 2011] Speed up png_combine_row() for interlaced images. This reduces the generality of the code, allowing it to be optimized for Adam7 interlace. The masks passed to png_combine_row() are now generated internally, avoiding some code duplication and localizing the interlace handling somewhat. Align png_struct::row_buf - previously it was always unaligned, caused by a bug in the code that attempted to align it; the code needs to subtract one from the pointer to take account of the filter byte prepended to each row. Optimized png_combine_row() when rows are aligned. This gains a small percentage for 16-bit and 32-bit pixels in the typical case where the output row buffers are appropriately aligned. The optimization was not previously possible because the png_struct buffer was always misaligned. Fixed bug in png_write_chunk_header() debug print, introduced in 1.5.6beta01. Version 1.5.6beta06 [October 17, 2011] Removed two redundant tests for unitialized row. Fixed a relatively harmless memory overwrite in compressed text writing with a 1 byte zlib buffer. Add ability to call png_read_update_info multiple times to pngvalid.c. Fixes for multiple calls to png_read_update_info. These fixes attend to most of the errors revealed in pngvalid, however doing the gamma work twice results in inaccuracies that can't be easily fixed. There is now a warning in the code if this is going to happen. Turned on multiple png_read_update_info in pngvalid transform tests. Prevent libpng from overwriting unused bits at the end of the image when it is not byte aligned, while reading. Prior to libpng-1.5.6 libpng would overwrite the partial byte at the end of each row if the row width was not an exact multiple of 8 bits and the image is not interlaced. Version 1.5.6beta07 [October 21, 2011] Made png_ptr->prev_row an aligned pointer into png_ptr->big_prev_row (Mans Rullgard). Version 1.5.6rc01 [October 26, 2011] Changed misleading "Missing PLTE before cHRM" warning to "Out of place cHRM" Version 1.5.6rc02 [October 27, 2011] Added LSR() macro to defend against buggy compilers that evaluate non-taken code branches and complain about out-of-range shifts. Version 1.5.6rc03 [October 28, 2011] Renamed the LSR() macro to PNG_LSR() and added PNG_LSL() macro. Fixed compiler warnings with Intel and MSYS compilers. The logical shift fix for Microsoft Visual C is required by other compilers, so this enables that fix for all compilers when using compile-time constants. Under MSYS 'byte' is a name declared in a system header file, so we changed the name of a local variable to avoid the warnings that result. Added #define PNG_ALIGN_TYPE PNG_ALIGN_NONE to contrib/pngminim/*/pngusr.h Version 1.5.6 [November 3, 2011] No changes. Version 1.5.7beta01 [November 4, 2011] Added support for ARM processor, when decoding all PNG up-filtered rows and any other-filtered rows with 3 or 4 bytes per pixel (Mans Rullgard). Fixed bug in pngvalid on early allocation failure; fixed type cast in pngmem.c; pngvalid would attempt to call png_error() if the allocation of a png_struct or png_info failed. This would probably have led to a crash. The pngmem.c implementation of png_malloc() included a cast to png_size_t which would fail on large allocations on 16-bit systems. Fix for the preprocessor of the Intel C compiler. The preprocessor splits adjacent @ signs with a space; this changes the concatentation token from @-@-@ to PNG_JOIN; that should work with all compiler preprocessors. Paeth filter speed improvements from work by Siarhei Siamashka. This changes the 'Paeth' reconstruction function to improve the GCC code generation on x86. The changes are only part of the suggested ones; just the changes that definitely improve speed and remain simple. The changes also slightly increase the clarity of the code. Version 1.5.7beta02 [November 11, 2011] Check compression_type parameter in png_get_iCCP and remove spurious casts. The compression_type parameter is always assigned to, so must be non-NULL. The cast of the profile length potentially truncated the value unnecessarily on a 16-bit int system, so the cast of the (byte) compression type to (int) is specified by ANSI-C anyway. Fixed FP division by zero in pngvalid.c; the 'test_pixel' code left the sBIT fields in the test pixel as 0, which resulted in a floating point division by zero which was irrelevant but causes systems where FP exceptions cause a crash. Added code to pngvalid to turn on FP exceptions if the appropriate glibc support is there to ensure this is tested in the future. Updated scripts/pnglibconf.mak and scripts/makefile.std to handle the new PNG_JOIN macro. Added versioning to pnglibconf.h comments. Simplified read/write API initial version; basic read/write tested on a variety of images, limited documentation (in the header file.) Installed more accurate linear to sRGB conversion tables. The slightly modified tables reduce the number of 16-bit values that convert to an off-by-one 8-bit value. The "makesRGB.c" code that was used to generate the tables is now in a contrib/sRGBtables sub-directory. Version 1.5.7beta03 [November 17, 2011] Removed PNG_CONST from the sRGB table declarations in pngpriv.h and png.c Added run-time detection of NEON support. Added contrib/libtests; includes simplified API test and timing test and a color conversion utility for rapid checking of failed 'pngstest' results. Multiple transform bug fixes plus a work-round for double gamma correction. libpng does not support more than one transform that requires linear data at once - if this is tried typically the results is double gamma correction. Since the simplified APIs can need rgb to gray combined with a compose operation it is necessary to do one of these outside the main libpng transform code. This check-in also contains fixes to various bugs in the simplified APIs themselves and to some bugs in compose and rgb to gray (on palette) itself. Fixes for C++ compilation using g++ When libpng source is compiled using g++. The compiler imposes C++ rules on the C source; thus it is desireable to make the source work with either C or C++ rules without throwing away useful error information. This change adds png_voidcast to allow C semantic (void*) cases or the corresponding C++ static_cast operation, as appropriate. Added --noexecstack to assembler file compilation. GCC does not set this on assembler compilation, even though it does on C compilation. This creates security issues if assembler code is enabled; the work-around is to set it by default in the flags for $(CCAS) Work around compilers that don't support declaration of const data. Some compilers fault 'extern const' data declarations (because the data is not initialized); this turns on const-ness only for compilers where this is known to work. Version 1.5.7beta04 [November 17, 2011] Since the gcc driver does not recognize the --noexecstack flag, we must use the -Wa prefix to have it passed through to the assembler. Also removed a duplicate setting of this flag. Added files that were omitted from the libpng-1.5.7beta03 zip distribution. Version 1.5.7beta05 [November 25, 2011] Removed "zTXt" from warning in generic chunk decompression function. Validate time settings passed to png_set_tIME() and png_convert_to_rfc1123() (Frank Busse). Note: This prevented CVE-2015-7981 from affecting libpng-1.5.7 and later. Added MINGW support to CMakeLists.txt Reject invalid compression flag or method when reading the iTXt chunk. Backed out 'simplified' API changes. The API seems too complex and there is a lack of consensus or enthusiasm for the proposals. The API also reveals significant bugs inside libpng (double gamma correction and the known bug of being unable to retrieve a corrected palette). It seems better to wait until the bugs, at least, are corrected. Moved pngvalid.c into contrib/libtests Rebuilt Makefile.in, configure, etc., with autoconf-2.68 Version 1.5.7rc01 [December 1, 2011] Replaced an "#if" with "#ifdef" in pngrtran.c Revised #if PNG_DO_BC block in png.c (use #ifdef and add #else) Version 1.5.7rc02 [December 5, 2011] Revised project files and contrib/pngvalid/pngvalid.c to account for the relocation of pngvalid into contrib/libtests. Revised pngconf.h to use " __declspec(restrict)" only when MSC_VER >= 1400, as in libpng-1.5.4. Put CRLF line endings in the owatcom project files. Version 1.5.7rc03 [December 7, 2011] Updated CMakeLists.txt to account for the relocation of pngvalid.c Version 1.5.7 [December 15, 2011] Minor fixes to pngvalid.c for gcc 4.6.2 compatibility to remove warnings reported by earlier versions. Fixed minor memset/sizeof errors in pngvalid.c. Version 1.6.0beta01 [December 15, 2011] Removed machine-generated configure files from the GIT repository (they will continue to appear in the tarball distributions and in the libpng15 and earlier GIT branches). Restored the new 'simplified' API, which was started in libpng-1.5.7beta02 but later deleted from libpng-1.5.7beta05. Added example programs for the new 'simplified' API. Added ANSI-C (C90) headers and require them, and take advantage of the change. Also fixed some of the projects/* and contrib/* files that needed updates for libpng16 and the move of pngvalid.c. With this change the required ANSI-C header files are assumed to exist: the implementation must provide float.h, limits.h, stdarg.h and stddef.h and libpng relies on limits.h and stddef.h existing and behaving as defined (the other two required headers aren't used). Non-ANSI systems that don't have stddef.h or limits.h will have to provide an appropriate fake containing the relevant types and #defines. Dropped support for 16-bit platforms. The use of FAR/far has been eliminated and the definition of png_alloc_size_t is now controlled by a flag so that 'small size_t' systems can select it if necessary. Libpng 1.6 may not currently work on such systems -- it seems likely that it will ask 'malloc' for more than 65535 bytes with any image that has a sufficiently large row size (rather than simply failing to read such images). New tools directory containing tools used to generate libpng code. Fixed race conditions in parallel make builds. With higher degrees of parallelism during 'make' the use of the same temporary file names such as 'dfn*' can result in a race where a temporary file from one arm of the build is deleted or overwritten in another arm. This changes the temporary files for suffix rules to always use $* and ensures that the non-suffix rules use unique file names. Version 1.6.0beta02 [December 21, 2011] Correct configure builds where build and source directories are separate. The include path of 'config.h' was erroneously made relative in pngvalid.c in libpng 1.5.7. Version 1.6.0beta03 [December 22, 2011] Start-up code size improvements, error handler flexibility. These changes alter how the tricky allocation of the initial png_struct and png_info structures are handled. png_info is now handled in pretty much the same way as everything else, except that the allocations handle NULL return silently. png_struct is changed in a similar way on allocation and on deallocation a 'safety' error handler is put in place (which should never be required). The error handler itself is changed to permit mismatches in the application and libpng error buffer size; however, this means a silent change to the API to return the jmp_buf if the size doesn't match the size from the libpng compilation; libpng now allocates the memory and this may fail. Overall these changes result in slight code size reductions; however, this is a reduction in code that is always executed so is particularly valuable. Overall on a 64-bit system the libpng DLL decreases in code size by 1733 bytes. pngerror.o increases in size by about 465 bytes because of the new functionality. Added png_convert_to_rfc1123_buffer() and deprecated png_convert_to_rfc1123() to avoid including a spurious buffer in the png_struct. Version 1.6.0beta04 [December 30, 2011] Regenerated configure scripts with automake-1.11.2 Eliminated png_info_destroy(). It is now used only in png.c and only calls one other internal function and memset(). Enabled png_get_sCAL_fixed() if floating point APIs are enabled. Previously it was disabled whenever internal fixed point arithmetic was selected, which meant it didn't exist even on systems where FP was available but not preferred. Added pngvalid.c compile time checks for const APIs. Implemented 'restrict' for png_info and png_struct. Because of the way libpng works both png_info and png_struct are always accessed via a single pointer. This means adding C99 'restrict' to the pointer gives the compiler some opportunity to optimize the code. This change allows that. Moved AC_MSG_CHECKING([if libraries can be versioned]) later to the proper location in configure.ac (Gilles Espinasse). Changed png_memcpy to C assignment where appropriate. Changed all those uses of png_memcpy that were doing a simple assignment to assignments (all those cases where the thing being copied is a non-array C L-value). Added some error checking to png_set_*() routines. Removed the reference to the non-exported function png_memcpy() from example.c. Fixed the Visual C 64-bit build - it requires jmp_buf to be aligned, but it had become misaligned. Revised contrib/pngminus/pnm2png.c to avoid warnings when png_uint_32 and unsigned long are of different sizes. Version 1.6.0beta05 [January 15, 2012] Updated manual with description of the simplified API (copied from png.h) Fix bug in pngerror.c: some long warnings were being improperly truncated (CVE-2011-3464, bug introduced in libpng-1.5.3beta05). Version 1.6.0beta06 [January 24, 2012] Added palette support to the simplified APIs. This commit changes some of the macro definitions in png.h, app code may need corresponding changes. Increased the formatted warning buffer to 192 bytes. Added color-map support to simplified API. This is an initial version for review; the documentation has not yet been updated. Fixed Min/GW uninstall to remove libpng.dll.a Version 1.6.0beta07 [January 28, 2012] Eliminated Intel icc/icl compiler warnings. The Intel (GCC derived) compiler issues slightly different warnings from those issued by the current vesions of GCC. This eliminates those warnings by adding/removing casts and small code rewrites. Updated configure.ac from autoupdate: added --enable-werror option. Also some layout regularization and removal of introduced tab characters (replaced with 3-character indentation). Obsolete macros identified by autoupdate have been removed; the replacements are all in 2.59 so the pre-req hasn't been changed. --enable-werror checks for support for -Werror (or the given argument) in the compiler. This mimics the gcc configure option by allowing -Werror to be turned on safely; without the option the tests written in configure itself fail compilation because they cause compiler warnings. Rewrote autogen.sh to run autoreconf instead of running tools one-by-one. Conditionalize the install rules for MINGW and CYGWIN in CMakeLists.txt and set CMAKE_LIBRARY_OUTPUT_DIRECTORY to "lib" on all platforms (C. Yapp). Freeze libtool files in the 'scripts' directory. This version of autogen.sh attempts to dissuade people from running it when it is not, or should not, be necessary. In fact, autogen.sh does not work when run in a libpng directory extracted from a tar distribution anymore. You must run it in a GIT clone instead. Added two images to contrib/pngsuite (1-bit and 2-bit transparent grayscale), and renamed three whose names were inconsistent with those in pngsuite/README.txt. Version 1.6.0beta08 [February 1, 2012] Fixed Image::colormap misalignment in pngstest.c Check libtool/libtoolize version number (2.4.2) in configure.ac Divide test-pngstest.sh into separate pngstest runs for basic and transparent images. Moved automake options to AM_INIT_AUTOMAKE in configure.ac Added color-tests, silent-rules (Not yet implemented in Makefile.am) and version checking to configure.ac Improved pngstest speed by not doing redundant tests and add const to the background parameter of png_image_finish_read. The --background option is now done automagically only when required, so that commandline option no longer exists. Cleaned up pngpriv.h to consistently declare all functions and data. Also eliminated PNG_CONST_DATA, which is apparently not needed but we can't be sure until it is gone. Added symbol prefixing that allows all the libpng external symbols to be prefixed (suggested by Reuben Hawkins). Updated "ftbb*.png" list in the owatcom and vstudio projects. Fixed 'prefix' builds on clean systems. The generation of pngprefix.h should not require itself. Updated INSTALL to explain that autogen.sh must be run in a GIT clone, not in a libpng directory extracted from a tar distribution. Version 1.6.0beta09 [February 1, 2012] Reverted the prebuilt configure files to libpng-1.6.0beta05 condition. Version 1.6.0beta10 [February 3, 2012] Added Z_SOLO for zlib-1.2.6+ and correct pngstest tests Updated list of test images in CMakeLists.txt Updated the prebuilt configure files to current condition. Revised INSTALL information about autogen.sh; it works in tar distributions. Version 1.6.0beta11 [February 16, 2012] Fix character count in pngstest command in projects/owatcom/pngstest.tgt Revised test-pngstest.sh to report PASS/FAIL for each image. Updated documentation about the simplified API. Corrected estimate of error in libpng png_set_rgb_to_gray API. The API is extremely inaccurate for sRGB conversions because it uses an 8-bit intermediate linear value and it does not use the sRGB transform, so it suffers from the known instability in gamma transforms for values close to 0 (see Poynton). The net result is that the calculation has a maximum error of 14.99/255; 0.5/255^(1/2.2). pngstest now uses 15 for the permitted 8-bit error. This may still not be enough because of arithmetic error. Removed some unused arrays (with #ifdef) from png_read_push_finish_row(). Fixed a memory overwrite bug in simplified read of RGB PNG with non-linear gamma Also bugs in the error checking in pngread.c and changed quite a lot of the checks in pngstest.c to be correct; either correctly written or not over-optimistic. The pngstest changes are insufficient to allow all possible RGB transforms to be passed; pngstest cmppixel needs to be rewritten to make it clearer which errors it allows and then changed to permit known inaccuracies. Removed tests for no-longer-used *_EMPTY_PLTE_SUPPORTED from pngstruct.h Fixed fixed/float API export conditionals. 1) If FIXED_POINT or FLOATING_POINT options were switched off, png.h ended up with lone ';' characters. This is not valid ANSI-C outside a function. The ';' characters have been moved inside the definition of PNG_FP_EXPORT and PNG_FIXED_EXPORT. 2) If either option was switched off, the declaration of the corresponding functions were completely omitted, even though some of them are still used internally. The result is still valid, but produces warnings from gcc with some warning options (including -Wall). The fix is to cause png.h to declare the functions with PNG_INTERNAL_FUNCTION when png.h is included from pngpriv.h. Check for invalid palette index while reading paletted PNG. When one is found, issue a warning and increase png_ptr->num_palette accordingly. Apps are responsible for checking to see if that happened. Version 1.6.0beta12 [February 18, 2012] Do not increase num_palette on invalid_index. Relocated check for invalid palette index to pngrtran.c, after unpacking the sub-8-bit pixels. Fixed CVE-2011-3026 buffer overrun bug. This bug was introduced when iCCP chunk support was added at libpng-1.0.6. Deal more correctly with the test on iCCP chunk length. Also removed spurious casts that may hide problems on 16-bit systems. Version 1.6.0beta13 [February 24, 2012] Eliminated redundant png_push_read_tEXt|zTXt|iTXt|unknown code from pngpread.c and use the sequential png_handle_tEXt, etc., in pngrutil.c; now that png_ptr->buffer is inaccessible to applications, the special handling is no longer useful. Added PNG_SAFE_LIMITS feature to pnglibconf.dfa, pngpriv.h, and new pngusr.dfa to reset the user limits to safe ones if PNG_SAFE_LIMITS is defined. To enable, use "CPPFLAGS=-DPNG_SAFE_LIMITS_SUPPORTED=1" on the configure command or put #define PNG_SAFE_LIMITS_SUPPORTED in pnglibconf.h.prebuilt and pnglibconf.h. Version 1.6.0beta14 [February 27, 2012] Added information about the new limits in the manual. Updated Makefile.in Version 1.6.0beta15 [March 2, 2012] Removed unused "current_text" members of png_struct and the png_free() of png_ptr->current_text from pngread.c Rewrote pngstest.c for substantial speed improvement. Fixed transparent pixel and 16-bit rgb tests in pngstest and removed a spurious check in pngwrite.c Added PNG_IMAGE_FLAG_FAST for the benefit of applications that store intermediate files, or intermediate in-memory data, while processing image data with the simplified API. The option makes the files larger but faster to write and read. pngstest now uses this by default; this can be disabled with the --slow option. Improved pngstest fine tuning of error numbers, new test file generator. The generator generates images that test the full range of sample values, allow the error numbers in pngstest to be tuned and checked. makepng also allows generation of images with extra chunks, although this is still work-in-progress. Added check for invalid palette index while reading. Fixed some bugs in ICC profile writing. The code should now accept all potentially valid ICC profiles and reject obviously invalid ones. It now uses png_error() to do so rather than casually writing a PNG without the necessary color data. Removed whitespace from the end of lines in all source files and scripts. Version 1.6.0beta16 [March 6, 2012] Relocated palette-index checking function from pngrutil.c to pngtrans.c Added palette-index checking while writing. Changed png_inflate() and calling routines to avoid overflow problems. This is an intermediate check-in that solves the immediate problems and introduces one performance improvement (avoiding a copy via png_ptr->zbuf.) Further changes will be made to make ICC profile handling more secure. Fixed build warnings (MSVC, GCC, GCC v3). Cygwin GCC with default options declares 'index' as a global, causing a warning if it is used as a local variable. GCC 64-bit warns about assigning a (size_t) (unsigned 64-bit) to an (int) (signed 32-bit). MSVC, however, warns about using the unary '-' operator on an unsigned value (even though it is well defined by ANSI-C to be ~x+1). The padding calculation was changed to use a different method. Removed the tests on png_ptr->pass. Added contrib/libtests/tarith.c to test internal arithmetic functions from png.c. This is a libpng maintainer program used to validate changes to the internal arithmetic functions. Made read 'inflate' handling like write 'deflate' handling. The read code now claims and releases png_ptr->zstream, like the write code. The bug whereby the progressive reader failed to release the zstream is now fixed, all initialization is delayed, and the code checks for changed parameters on deflate rather than always calling deflatedEnd/deflateInit. Validate the zTXt strings in pngvalid. Added code to validate the windowBits value passed to deflateInit2(). If the call to deflateInit2() is wrong a png_warning will be issued (in fact this is harmless, but the PNG data produced may be sub-optimal). Version 1.6.0beta17 [March 10, 2012] Fixed PNG_LIBPNG_BUILD_BASE_TYPE definition. Reject all iCCP chunks after the first, even if the first one is invalid. Deflate/inflate was reworked to move common zlib calls into single functions [rw]util.c. A new shared keyword check routine was also added and the 'zbuf' is no longer allocated on progressive read. It is now possible to call png_inflate() incrementally. A warning is no longer issued if the language tag or translated keyword in the iTXt chunk has zero length. If benign errors are disabled use maximum window on ancilliary inflate. This works round a bug introduced in 1.5.4 where compressed ancillary chunks could end up with a too-small windowBits value in the deflate header. Version 1.6.0beta18 [March 16, 2012] Issue a png_benign_error() instead of png_warning() about bad palette index. In pngtest, treat benign errors as errors if "-strict" is present. Fixed an off-by-one error in the palette index checking function. Fixed a compiler warning under Cygwin (Windows-7, 32-bit system) Revised example.c to put text strings in a temporary character array instead of directly assigning string constants to png_textp members. This avoids compiler warnings when -Wwrite-strings is enabled. Added output flushing to aid debugging under Visual Studio. Unfortunately this is necessary because the VS2010 output window otherwise simply loses the error messages on error (they weren't flushed to the window before the process exited, apparently!) Added configuration support for benign errors and changed the read default. Also changed some warnings in the iCCP and sRGB handling from to benign errors. Configuration now makes read benign errors warnings and write benign errors to errors by default (thus changing the behavior on read). The simplified API always forces read benign errors to warnings (regardless of the system default, unless this is disabled in which case the simplified API can't be built.) Version 1.6.0beta19 [March 18, 2012] Work around for duplicate row start calls; added warning messages. This turns on PNG_FLAG_DETECT_UNINITIALIZED to detect app code that fails to call one of the 'start' routines (not enabled in libpng-1.5 because it is technically an API change, since it did normally work before.) It also makes duplicate calls to png_read_start_row (an internal function called at the start of the image read) benign, as they were before changes to use png_inflate_claim. Somehow webkit is causing this to happen; this is probably a mis-feature in the zlib changes so this commit is only a work-round. Removed erroneous setting of DETECT_UNINITIALIZED and added more checks. The code now does a png_error if an attempt is made to do the row initialization twice; this is an application error and it has serious consequences because the transform data in png_struct is changed by each call. Added application error reporting and added chunk names to read benign errors; also added --strict to pngstest - not enabled yet because a warning is produced. Avoid the double gamma correction warning in the simplified API. This allows the --strict option to pass in the pngstest checks Version 1.6.0beta20 [March 29, 2012] Changed chunk handler warnings into benign errors, incrementally load iCCP Added checksum-icc.c to contrib/tools Prevent PNG_EXPAND+PNG_SHIFT doing the shift twice. Recognize known sRGB ICC profiles while reading; prefer writing the iCCP profile over writing the sRGB chunk, controlled by the PNG_sRGB_PROFILE_CHECKS option. Revised png_set_text_2() to avoid potential memory corruption (fixes CVE-2011-3048, also known as CVE-2012-3425). Version 1.6.0beta21 [April 27, 2012] Revised scripts/makefile.darwin: use system zlib; remove quotes around architecture list; add missing ppc architecture; add architecture options to shared library link; don't try to create a shared lib based on missing RELEASE variable. Enable png_set_check_for_invalid_index() for both read and write. Removed #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED in pngpriv.h around declaration of png_handle_unknown(). Added -lssp_nonshared in a comment in scripts/makefile.freebsd and changed deprecated NOOBJ and NOPROFILE to NO_OBJ and NO_PROFILE. Version 1.6.0beta22 [May 23, 2012] Removed need for -Wno-cast-align with clang. clang correctly warns on alignment increasing pointer casts when -Wcast-align is passed. This fixes the cases that clang warns about either by eliminating the casts from png_bytep to png_uint_16p (pngread.c), or, for pngrutil.c where the cast is previously verified or pngstest.c where it is OK, by introducing new png_aligncast macros to do the cast in a way that clang accepts. Version 1.6.0beta23 [June 6, 2012] Revised CMakeLists.txt to not attempt to make a symlink under mingw. Made fixes for new optimization warnings from gcc 4.7.0. The compiler performs an optimization which is safe; however it then warns about it. Changing the type of 'palette_number' in pngvalid.c removes the warning. Do not depend upon a GCC feature macro being available for use in generating the linker mapfile symbol prefix. Improved performance of new do_check_palette_indexes() function (only update the value when it actually increases, move test for whether the check is wanted out of the function. Version 1.6.0beta24 [June 7, 2012] Don't check palette indexes if num_palette is 0 (as it can be in MNG files). Version 1.6.0beta25 [June 16, 2012] Revised png_set_keep_unknown_chunks() so num_chunks < 0 means ignore all unknown chunks and all known chunks except for IHDR, PLTE, tRNS, IDAT, and IEND. Previously it only meant ignore all unknown chunks, the same as num_chunks == 0. Revised png_image_skip_unused_chunks() to provide a list of chunks to be processed instead of a list of chunks to ignore. Revised contrib/gregbook/readpng2.c accordingly. Version 1.6.0beta26 [July 10, 2012] Removed scripts/makefile.cegcc from the *.zip and *.7z distributions; it depends on configure, which is not included in those archives. Moved scripts/chkfmt to contrib/tools. Changed "a+w" to "u+w" in Makefile.in to fix CVE-2012-3386. Version 1.6.0beta27 [August 11, 2012] Do not compile PNG_DEPRECATED, PNG_ALLOC and PNG_PRIVATE when __GNUC__ < 3. Do not use __restrict when GNUC is <= 3.1 Removed references to png_zalloc() and png_zfree() from the manual. Fixed configurations where floating point is completely disabled. Because of the changes to support symbol prefixing PNG_INTERNAL_FUNCTION declares floating point APIs during libpng builds even if they are completely disabled. This requires the png floating point types (png_double*) to be declared even though the functions are never actually defined. This change provides a dummy definition so that the declarations work, yet any implementation will fail to compile because of an incomplete type. Re-eliminated the use of strcpy() in pngtest.c. An unncessary use of strcpy() was accidentally re-introduced in libpng16; this change replaces it with strncpy(). Eliminated use of png_sizeof(); use sizeof() instead. Use a consistent style for (sizeof type) and (sizeof (array)) Cleanup of png_set_filler(). This function does very different things on read and write. In libpng 1.6 the two cases can be distinguished and considerable code cleanup, and extra error checking, is possible. This makes calls on the write side that have no effect be ignored with a png_app_error(), which can be disabled in the app using png_set_benign_errors(), and removes the spurious use of usr_channels on the read side. Insist on autotools 1.12.1 for git builds because there are security issues with 1.12 and insisting on anything less would allow 1.12 to be used. Removed info_ptr->signature[8] from WRITE-only builds. Add some conditions for compiling png_fixed(). This is a small function but it requires "-lm" on some platforms. Cause pngtest --strict to fail on any warning from libpng (not just errors) and cause it not to fail at the comparison step if libpng lacks support for writing chunks that it reads from the input (currently only implemented for compressed text chunks). Make all three "make check" test programs work without READ or WRITE support. Now "make check" will succeed even if libpng is compiled with -DPNG_NO_READ or -DPNG_NO_WRITE. The tests performed are reduced, but the basic reading and writing of a PNG file is always tested by one or more of the tests. Consistently use strlen(), memset(), memcpy(), and memcmp() instead of the png_strlen(), png_memset(), png_memcpy(), and png_memcmp() macros. Removed the png_sizeof(), png_strlen(), png_memset(), png_memcpy(), and png_memcmp() macros. Work around gcc 3.x and Microsoft Visual Studio 2010 complaints. Both object to the split initialization of num_chunks. Version 1.6.0beta28 [August 29, 2012] Unknown handling fixes and clean up. This adds more correct option control of the unknown handling, corrects the pre-existing bug where the per-chunk 'keep' setting is ignored and makes it possible to skip IDAT chunks in the sequential reader (broken in earlier 1.6 versions). There is a new test program, test-unknown.c, which is a work in progress (not currently part of the test suite). Comments in the header files now explain how the unknown handling works. Allow fine grain control of unknown chunk APIs. This change allows png_set_keep_unknown_chunks() to be turned off if not required and causes both read and write to behave appropriately (on read this is only possible if the user callback is used to handle unknown chunks). The change also removes the support for storing unknown chunks in the info_struct if the only unknown handling enabled is via the callback, allowing libpng to be configured with callback reading and none of the unnecessary code. Corrected fix for unknown handling in pngtest. This reinstates the libpng handling of unknown chunks other than vpAg and sTER (including unsafe-to-copy chunks which were dropped before) and eliminates the repositioning of vpAg and sTER in pngtest.png by changing pngtest.png (so the chunks are where libpng would put them). Added "tunknown" test and corrected a logic error in png_handle_unknown() when SAVE support is absent. Moved the shell test scripts for contrib/libtests from the libpng top directory to contrib/libtests. png_handle_unknown() must always read or skip the chunk, if SAVE_UNKNOWN_CHUNKS is turned off *and* the application does not set a user callback an unknown chunk will not be read, leading to a read error, which was revealed by the "tunknown" test. Cleaned up and corrected ICC profile handling. contrib/libtests/makepng: corrected 'rgb' and 'gray' cases. profile_error messages could be truncated; made a correct buffer size calculation and adjusted pngerror.c appropriately. png_icc_check_* checking improved; changed the functions to receive the correct color type of the PNG on read or write and check that it matches the color space of the profile (despite what the comments said before, there is danger in assuming the app will cope correctly with an RGB profile on a grayscale image and, since it violates the PNG spec, allowing it is certain to produce inconsistent app behavior and might even cause app crashes.) Check that profiles contain the tags needed to process the PNG (tags all required by the ICC spec). Removed unused PNG_STATIC from pngpriv.h. Version 1.6.0beta29 [September 4, 2012] Fixed the simplified API example programs to add the *colormap parameter to several of he API and improved the error message if the version field is not set. Added contrib/examples/* to the *.zip and *.7z distributions. Updated simplified API synopses and description of the png_image structure in the manual. Made makepng and pngtest produce identical PNGs, add "--relaxed" option to pngtest. The "--relaxed" option turns off the benign errors that are enabled by default in pre-RC builds. makepng can now write ICC profiles where the length has not been extended to a multiple of 4, and pngtest now intercepts all libpng errors, allowing the previously-introduced "--strict test" on no warnings to actually work. Improved ICC profile handling including cHRM chunk generation and fixed Cygwin+MSVC build errors. The ICC profile handling now includes more checking. Several errors that caused rejection of the profile are now handled with a warning in such a way that the invalid profiles will be read by default in release (but not pre-RC) builds but will not be written by default. The easy part of handling the cHRM chunk is written, where the ICC profile contains the required data. The more difficult part plus guessing a gAMA value requires code to pass selected RGB values through the profile. Version 1.6.0beta30 [October 24, 2012] Changed ICC profile matrix/vector types to not depend on array type rules. By the ANSI-C standard the new types should be identical to the previous versions, and all known versions of gcc tested with the previous versions except for GCC-4.2.1 work with this version. The change makes the ANSI-C rule that const applied to an array of elements applies instead to the elements in the array moot by explicitly applying const to the base elements of the png_icc_matrix and png_icc_vector types. The accidental (harmless) 'const' previously applied to the parameters of two of the functions have also been removed. Added a work around for GCC 4.2 optimization bug. Marked the broken (bad white point) original HP sRGB profiles correctly and correct comments. Added -DZ_SOLO to contrib/pngminim/*/makefile to work with zlib-1.2.7 Use /MDd for vstudio debug builds. Also added pngunkown to the vstudio builds, fixed build errors and corrected a minor exit code error in pngvalid if the 'touch' file name is invalid. Add updated WARNING file to projects/vstudio from libpng 1.5/vstudio Fixed build when using #define PNG_NO_READ_GAMMA in png_do_compose() in pngrtran.c (Domani Hannes). Version 1.6.0beta31 [November 1, 2012] Undid the erroneous change to vstudio/pngvalid build in libpng-1.6.0beta30. Made pngvalid so that it will build outside the libpng source tree. Made builds -DPNG_NO_READ_GAMMA compile (the unit tests still fail). Made PNG_NO_READ_GAMMA switch off interfaces that depend on READ_GAMMA. Prior to 1.6.0 switching off READ_GAMMA did unpredictable things to the interfaces that use it (specifically, png_do_background in 1.4 would simply display composite for grayscale images but do composition with the incorrect arithmetic for color ones). In 1.6 the semantic of -DPNG_NO_READ_GAMMA is changed to simply disable any interface that depends on it; this obliges people who set it to consider whether they really want it off if they happen to use any of the interfaces in question (typically most users who disable it won't). Fixed GUIDs in projects/vstudio. Some were duplicated or missing, resulting in VS2010 having to update the files. Removed non-working ICC profile support code that was mostly added to libpng-1.6.0beta29 and beta30. There was too much code for too little gain; implementing full ICC color correction may be desireable but is left up to applications. Version 1.6.0beta32 [November 25, 2012] Fixed an intermittent SEGV in pngstest due to an uninitialized array element. Added the ability for contrib/libtests/makepng.c to make a PNG with just one color. This is useful for debugging pngstest color inaccuracy reports. Fixed error checking in the simplified write API (Olaf van der Spek) Made png_user_version_check() ok to use with libpng version 1.10.x and later. Version 1.6.0beta33 [December 15, 2012] Fixed typo in png.c (PNG_SET_CHUNK_MALLOC_MAX should be PNG_CHUNK_MALLOC_MAX) that causes the MALLOC_MAX limit not to work (John Bowler) Change png_warning() to png_app_error() in pngwrite.c and comment the fall-through condition. Change png_warning() to png_app_warning() in png_write_tRNS(). Rearranged the ARM-NEON optimizations: Isolated the machine specific code to the hardware subdirectory and added comments to pngrutil.c so that implementors of other optimizations know what to do. Fixed cases of unquoted DESTDIR in Makefile.am Rebuilt Makefile.in, etc., with autoconf-2.69 and automake-1.12.5. Version 1.6.0beta34 [December 19, 2012] Cleaned up whitespace in the synopsis portion of the manpage "libpng.3" Disassembled the version number in scripts/options.awk (necessary for building on SunOs). Version 1.6.0beta35 [December 23, 2012] Made default Zlib compression settings be configurable. This adds #defines to pnglibconf.h to control the defaults. Fixed Windows build issues, enabled ARM compilation. Various warnings issued by earlier versions of GCC fixed for Cygwin and Min/GW (which both use old GCCs.) ARM support is enabled by default in zlib.props (unsupported by Microsoft) and ARM compilation is made possible by deleting the check for x86. The test programs cannot be run because they are not signed. Version 1.6.0beta36 [January 2, 2013] Discontinued distributing libpng-1.x.x.tar.bz2. Discontinued distributing libpng-1.7.0-1.6.0-diff.txt and similar. Rebuilt configure with autoconf-2.69 (inadvertently not done in beta33) Fixed 'make distcheck' on SUN OS - libpng.so was not being removed Version 1.6.0beta37 [January 10, 2013] Fixed conceivable but difficult to repro overflow. Also added two test programs to generate and test a PNG which should have the problem. Version 1.6.0beta39 [January 19, 2013] Again corrected attempt at overflow detection in png_set_unknown_chunks() (CVE-2013-7353). Added overflow detection in png_set_sPLT() and png_set_text_2() (CVE-2013-7354). Version 1.6.0beta40 [January 20, 2013] Use consistent handling of overflows in text, sPLT and unknown png_set_* APIs Version 1.6.0rc01 [January 26, 2013] No changes. Version 1.6.0rc02 [February 4, 2013] Added png_get_palette_max() function. Version 1.6.0rc03 [February 5, 2013] Fixed the png_get_palette_max API. Version 1.6.0rc04 [February 7, 2013] Turn serial tests back on (recently turned off by autotools upgrade). Version 1.6.0rc05 [February 8, 2013] Update manual about png_get_palette_max(). Version 1.6.0rc06 [February 9, 2013] Fixed missing dependency in --prefix builds The intermediate internal 'prefix.h' file can only be generated correctly after pnglibconf.h, however the dependency was not in Makefile.am. The symptoms are unpredictable depending on the order make chooses to build pngprefix.h and pnglibconf.h, often the error goes unnoticed because there is a system pnglibconf.h to use instead. Version 1.6.0rc07 [February 10, 2013] Enclosed the new png_get_palette_max in #ifdef PNG_GET_PALETTE_MAX_SUPPORTED block, and revised pnglibconf.h and pnglibconf.h.prebuilt accordingly. Version 1.6.0rc08 [February 10, 2013] Fix typo in png.h #ifdef Version 1.6.0 [February 14, 2013] No changes. Version 1.6.1beta01 [February 16, 2013] Made symbol prefixing work with the ARM neon optimizations. Also allow pngpriv.h to be included for preprocessor definitions only, so it can be used in non-C/C++ files. Back ported from libpng 1.7. Made sRGB check numbers consistent. Ported libpng 1.5 options.awk/dfn file handling to 1.6, fixed one bug. Removed cc -E workround, corrected png_get_palette_max API Tested on SUN OS cc 5.9, which demonstrates the tokenization problem previously avoided by using /lib/cpp. Since all .dfn output is now protected in double quotes unless it is to be macro substituted the fix should work everywhere. Enabled parallel tests - back ported from libpng-1.7. scripts/pnglibconf.dfa formatting improvements back ported from libpng17. Fixed a race condition in the creation of the build 'scripts' directory while building with a parallel make. Use approved/supported Android method to check for NEON, use Linux/POSIX 1003.1 API to check /proc/self/auxv avoiding buffer allocation and other library calls (ported from libpng15). Version 1.6.1beta02 [February 19, 2013] Use parentheses more consistently in "#if defined(MACRO)" tests. Folded long lines. Reenabled code to allow zero length PLTE chunks for MNG. Version 1.6.1beta03 [February 22, 2013] Fixed ALIGNED_MEMORY support. Added a new configure option: --enable-arm-neon=always will stop the run-time checks. New checks within arm/arm_init.c will cause the code not to be compiled unless __ARM_NEON__ is set. This should make it fail safe (if someone asks for it on then the build will fail if it can't be done.) Updated the INSTALL document. Version 1.6.1beta04 [February 27, 2013] Revised INSTALL to recommend using CPPFLAGS instead of INCLUDES. Revised scripts/makefile.freebsd to respect ZLIBLIB and ZLIBINC. Revised scripts/dfn.awk to work with the buggy MSYS awk that has trouble with CRLF line endings. Version 1.6.1beta05 [March 1, 2013] Avoid a possible memory leak in contrib/gregbook/readpng.c Version 1.6.1beta06 [March 4, 2013] Better documentation of unknown handling API interactions. Corrected Android builds and corrected libpng.vers with symbol prefixing. It also makes those tests compile and link on Android. Added an API png_set_option() to set optimization options externally, providing an alternative and general solution for the non-portable run-time tests used by the ARM Neon code, using the PNG_ARM_NEON option. The order of settings vs options in pnglibconf.h is reversed to allow settings to depend on options and options can now set (or override) the defaults for settings. Version 1.6.1beta07 [March 7, 2013] Corrected simplified API default gamma for color-mapped output, added a flag to change default. In 1.6.0 when the simplified API was used to produce color-mapped output from an input image with no gamma information the gamma assumed for the input could be different from that assumed for non-color-mapped output. In particular 16-bit depth input files were assumed to be sRGB encoded, whereas in the 'direct' case they were assumed to have linear data. This was an error. The fix makes the simplified API treat all input files the same way and adds a new flag to the png_image::flags member to allow the application/user to specify that 16-bit files contain sRGB data rather than the default linear. Fixed bugs in the pngpixel and makepng test programs. Version 1.6.1beta08 [March 7, 2013] Fixed CMakelists.txt to allow building a single variant of the library (Claudio Bley): Introduced a PNG_LIB_TARGETS variable that lists all activated library targets. It is an error if this variable ends up empty, ie. you have to build at least one library variant. Made the *_COPY targets only depend on library targets actually being build. Use PNG_LIB_TARGETS to unify a code path. Changed the CREATE_SYMLINK macro to expect the full path to a file as the first argument. When symlinking the filename component of that path is determined and used as the link target. Use copy_if_different in the CREATE_SYMLINK macro. Version 1.6.1beta09 [March 13, 2013] Eliminated two warnings from the Intel C compiler. The warnings are technically valid, although a reasonable treatment of division would show it to be incorrect. Version 1.6.1rc01 [March 21, 2013] No changes. Version 1.6.1 [March 28, 2013] No changes. Version 1.6.2beta01 [April 14, 2013] Updated documentation of 1.5.x to 1.6.x changes in iCCP chunk handling. Fixed incorrect warning of excess deflate data. End condition - the warning would be produced if the end of the deflate stream wasn't read in the last row. The warning is harmless. Corrected the test on user transform changes on read. It was in the png_set of the transform function, but that doesn't matter unless the transform function changes the rowbuf size, and that is only valid if transform_info is called. Corrected a misplaced closing bracket in contrib/libtests/pngvalid.c (Flavio Medeiros). Corrected length written to uncompressed iTXt chunks (Samuli Suominen). Bug was introduced in libpng-1.6.0. Version 1.6.2rc01 [April 18, 2013] Added contrib/tools/fixitxt.c, to repair the erroneous iTXt chunk length written by libpng-1.6.0 and 1.6.1. Disallow storing sRGB information when the sRGB is not supported. Version 1.6.2rc02 [April 18, 2013] Merge pngtest.c with libpng-1.7.0 Version 1.6.2rc03 [April 22, 2013] Trivial spelling cleanup. Version 1.6.2rc04 and 1.6.2rc05 [omitted] Version 1.6.2rc06 [April 24, 2013] Reverted to version 1.6.2rc03. Recent changes to arm/neon support have been ported to libpng-1.7.0beta09 and will reappear in version 1.6.3beta01. Version 1.6.2 [April 25, 2013] No changes. Version 1.6.3beta01 [April 25, 2013] Revised stack marking in arm/filter_neon.S and configure.ac. Ensure that NEON filter stuff is completely disabled when switched 'off'. Previously the ARM NEON specific files were still built if the option was switched 'off' as opposed to being explicitly disabled. Version 1.6.3beta02 [April 26, 2013] Test for 'arm*' not just 'arm' in the host_cpu configure variable. Rebuilt the configure scripts. Version 1.6.3beta03 [April 30, 2013] Expanded manual paragraph about writing private chunks, particularly the need to call png_set_keep_unknown_chunks() when writing them. Avoid dereferencing NULL pointer possibly returned from png_create_write_struct() (Andrew Church). Version 1.6.3beta05 [May 9, 2013] Calculate our own zlib windowBits when decoding rather than trusting the CMF bytes in the PNG datastream. Added an option to force maximum window size for inflating, which was the behavior of libpng15 and earlier, via a new PNG_MAXIMUM_INFLATE_WINDOW option for png_set_options(). Added png-fix-itxt and png-fix-too-far-back to the built programs and removed warnings from the source code and timepng that are revealed as a result. Detect wrong libpng versions linked to png-fix-too-far-back, which currently only works with libpng versions that can be made to reliably fail when the deflate data contains an out-of-window reference. This means only 1.6 and later. Fixed gnu issues: g++ needs a static_cast, gcc 4.4.7 has a broken warning message which it is easier to work round than ignore. Updated contrib/pngminus/pnm2png.c (Paul Stewart): Check for EOF Ignore "#" delimited comments in input file to pnm2png.c. Fixed whitespace handling Added a call to png_set_packing() Initialize dimension values so if sscanf fails at least we have known invalid values. Attempt to detect configuration issues with png-fix-too-far-back, which requires both the correct libpng and the correct zlib to function correctly. Check ZLIB_VERNUM for mismatches, enclose #error in quotes Added information in the documentation about problems with and fixes for the bad CRC and bad iTXt chunk situations. Version 1.6.3beta06 [May 12, 2013] Allow contrib/pngminus/pnm2png.c to compile without WRITE_INVERT and WRITE_PACK supported (writes error message that it can't read P1 or P4 PBM files). Improved png-fix-too-far-back usage message, added --suffix option. Revised contrib/pngminim/*/makefile to generate pnglibconf.h with the right zlib header files. Separated CPPFLAGS and CFLAGS in contrib/pngminim/*/makefile Version 1.6.3beta07 [June 8, 2013] Removed a redundant test in png_set_IHDR(). Added set(CMAKE_CONFIGURATION_TYPES ...) to CMakeLists.txt (Andrew Hundt) Deleted set(CMAKE_BUILD_TYPE) block from CMakeLists.txt Enclose the prototypes for the simplified write API in #ifdef PNG_STDIO_SUPPORTED/#endif Make ARM NEON support work at compile time (not just configure time). This moves the test on __ARM_NEON__ into pngconf.h to avoid issues when using a compiler that compiles for multiple architectures at one time. Removed PNG_FILTER_OPTIMIZATIONS and PNG_ARM_NEON_SUPPORTED from pnglibconf.h, allowing more of the decisions to be made internally (pngpriv.h) during the compile. Without this, symbol prefixing is broken under certain circumstances on ARM platforms. Now only the API parts of the optimizations ('check' vs 'api') are exposed in the public header files except that the new setting PNG_ARM_NEON_OPT documents how libpng makes the decision about whether or not to use the optimizations. Protect symbol prefixing against CC/CPPFLAGS/CFLAGS useage. Previous iOS/Xcode fixes for the ARM NEON optimizations moved the test on __ARM_NEON__ from configure time to compile time. This breaks symbol prefixing because the definition of the special png_init_filter_functions call was hidden at configure time if the relevant compiler arguments are passed in CFLAGS as opposed to CC. This change attempts to avoid all the confusion that would result by declaring the init function even when it is not used, so that it will always get prefixed. Version 1.6.3beta08 [June 18, 2013] Revised libpng.3 so that "doclifter" can process it. Version 1.6.3beta09 [June 27, 2013] Revised example.c to illustrate use of PNG_DEFAULT_sRGB and PNG_GAMMA_MAC_18 as parameters for png_set_gamma(). These have been available since libpng-1.5.4. Renamed contrib/tools/png-fix-too-far-back.c to pngfix.c and revised it to check all compressed chunks known to libpng. Version 1.6.3beta10 [July 5, 2013] Updated documentation to show default behavior of benign errors correctly. Only compile ARM code when PNG_READ_SUPPORTED is defined. Fixed undefined behavior in contrib/tools/pngfix.c and added new strip option. pngfix relied on undefined behavior and even a simple change from gcc to g++ caused it to fail. The new strip option 'unsafe' has been implemented and is the default if --max is given. Option names have been clarified, with --strip=transform now stripping the bKGD chunk, which was stripped previously with --strip=unused. Added all documented chunk types to pngpriv.h Unified pngfix.c source with libpng17. Version 1.6.3rc01 [July 11, 2013] No changes. Version 1.6.3 [July 18, 2013] Revised manual about changes in iTXt chunk handling made in libpng-1.6.0. Added "/* SAFE */" comments in pngrutil.c and pngrtran.c where warnings may be erroneously issued by code-checking applications. Version 1.6.4beta01 [August 21, 2013] Added information about png_set_options() to the manual. Delay calling png_init_filter_functions() until a row with nonzero filter is found. Version 1.6.4beta02 [August 30, 2013] Fixed inconsistent conditional compilation of png_chunk_unknown_handling() prototype, definition, and usage. Made it depend on PNG_HANDLE_AS_UNKNOWN_SUPPORTED everywhere. Version 1.6.4rc01 [September 5, 2013] No changes. Version 1.6.4 [September 12, 2013] No changes. Version 1.6.5 [September 14, 2013] Removed two stray lines of code from arm/arm_init.c. Version 1.6.6 [September 16, 2013] Removed two stray lines of code from arm/arm_init.c, again. Version 1.6.7beta01 [September 30, 2013] Revised unknown chunk code to correct several bugs in the NO_SAVE_/NO_WRITE combination Allow HANDLE_AS_UNKNOWN to work when other options are configured off. Also fixed the pngminim makefiles to work when $(MAKEFLAGS) contains stuff which terminates the make options (as by default in recent versions of Gentoo). Avoid up-cast warnings in pngvalid.c. On ARM the alignment requirements of png_modifier are greater than that of png_store and as a consequence compilation of pngvalid.c results in a warning about increased alignment requirements because of the bare cast to (png_modifier*). The code is safe, because the pointer is known to point to a stack allocated png_modifier, but this change avoids the warning. Fixed default behavior of ARM_NEON_API. If the ARM NEON API option was compiled without the CHECK option it defaulted to on, not off. Check user callback behavior in pngunknown.c. Previous versions compiled if SAVE_UNKNOWN was not available but did nothing since the callback was never implemented. Merged pngunknown.c with 1.7 version and back ported 1.7 improvements/fixes Version 1.6.7beta02 [October 12, 2013] Made changes for compatibility with automake 1.14: 1) Added the 'compile' program to the list of programs that must be cleaned in autogen.sh 2) Added 'subdir-objects' which causes .c files in sub-directories to be compiled such that the corresponding .o files are also in the sub-directory. This is because automake 1.14 warns that the current behavior of compiling to the top level directory may be removed in the future. 3) Updated dependencies on pnglibconf.h to match the new .o locations and added all the files in contrib/libtests and contrib/tools that depend on pnglibconf.h 4) Added 'BUILD_SOURCES = pnglibconf.h'; this is the automake recommended way of handling the dependencies of sources that are machine generated; unfortunately it only works if the user does 'make all' or 'make check', so the dependencies (3) are still required. Cleaned up (char*) casts of zlib messages. The latest version of the Intel C compiler complains about casting a string literal as (char*), so copied the treatment of z_const from the library code into pngfix.c Simplified error message code in pngunknown. The simplification has the useful side effect of avoiding a bogus warning generated by the latest version of the Intel C compiler (it objects to condition ? string-literal : string-literal). Make autogen.sh work with automake 1.13 as well as 1.14. Do this by always removing the 1.14 'compile' script but never checking for it. Version 1.6.7beta03 [October 19, 2013] Added ARMv8 support (James Yu ). Added file arm/filter_neon_intrinsics.c; enable with -mfpu=neon. Revised pngvalid to generate size images with as many filters as it can manage, limited by the number of rows. Cleaned up ARM NEON compilation handling. The tests are now in pngpriv.h and detect the broken GCC compilers. Version 1.6.7beta04 [October 26, 2013] Allow clang derived from older GCC versions to use ARM intrinsics. This causes all clang builds that use -mfpu=neon to use the intrinsics code, not the assembler code. This has only been tested on iOS 7. It may be necessary to exclude some earlier clang versions but this seems unlikely. Changed NEON implementation selection mechanism. This allows assembler or intrinsics to be turned on at compile time during the build by defining PNG_ARM_NEON_IMPLEMENTATION to the correct value (2 or 1). This macro is undefined by default and the build type is selected in pngpriv.h. Version 1.6.7rc01 [November 2, 2013] No changes. Version 1.6.7rc02 [November 7, 2013] Fixed #include in filter_neon_intrinsics.c and ctype macros. The ctype char checking macros take an unsigned char argument, not a signed char. Version 1.6.7 [November 14, 2013] No changes. Version 1.6.8beta01 [November 24, 2013] Moved prototype for png_handle_unknown() in pngpriv.h outside of the #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED/#endif block. Added "-Wall" to CFLAGS in contrib/pngminim/*/makefile Conditionally compile some unused functions reported by -Wall in pngminim. Fixed 'minimal' builds. Various obviously useful minimal configurations don't build because of missing contrib/libtests test programs and overly complex dependencies in scripts/pnglibconf.dfa. This change adds contrib/conftest/*.dfa files that can be used in automatic build scripts to ensure that these configurations continue to build. Enabled WRITE_INVERT and WRITE_PACK in contrib/pngminim/encoder. Fixed pngvalid 'fail' function declaration on the Intel C Compiler. This reverts to the previous 'static' implementation and works round the 'unused static function' warning by using PNG_UNUSED(). Version 1.6.8beta02 [November 30, 2013] Removed or marked PNG_UNUSED some harmless "dead assignments" reported by clang scan-build. Changed tabs to 3 spaces in png_debug macros and changed '"%s"m' to '"%s" m' to improve portability among compilers. Changed png_free_default() to free() in pngtest.c Version 1.6.8rc01 [December 12, 2013] Tidied up pngfix inits and fixed pngtest no-write builds. Version 1.6.8rc02 [December 14, 2013] Handle zero-length PLTE chunk or NULL palette with png_error() instead of png_chunk_report(), which by default issues a warning rather than an error, leading to later reading from a NULL pointer (png_ptr->palette) in png_do_expand_palette(). This is CVE-2013-6954 and VU#650142. Libpng-1.6.1 through 1.6.7 are vulnerable. Libpng-1.6.0 and earlier do not have this bug. Version 1.6.8 [December 19, 2013] No changes. Version 1.6.9beta01 [December 26, 2013] Bookkeeping: Moved functions around (no changes). Moved transform function definitions before the place where they are called so that they can be made static. Move the intrapixel functions and the grayscale palette builder out of the png?tran.c files. The latter isn't a transform function and is no longer used internally, and the former MNG specific functions are better placed in pngread/pngwrite.c Made transform implementation functions static. This makes the internal functions called by png_do_{read|write}_transformations static. On an x86-64 DLL build (Gentoo Linux) this reduces the size of the text segment of the DLL by 1208 bytes, about 0.6%. It also simplifies maintenance by removing the declarations from pngpriv.h and allowing easier changes to the internal interfaces. Rebuilt configure scripts with automake-1.14.1 and autoconf-2.69 in the tar distributions. Version 1.6.9beta02 [January 1, 2014] Added checks for libpng 1.5 to pngvalid.c. This supports the use of this version of pngvalid in libpng 1.5 Merged with pngvalid.c from libpng-1.7 changes to create a single pngvalid.c Removed #error macro from contrib/tools/pngfix.c (Thomas Klausner). Merged pngrio.c, pngtrans.c, pngwio.c, and pngerror.c with libpng-1.7.0 Merged libpng-1.7.0 changes to make no-interlace configurations work with test programs. Revised pngvalid.c to support libpng 1.5, which does not support the PNG_MAXIMUM_INFLATE_WINDOW option, so #define it out when appropriate in pngvalid.c Allow unversioned links created on install to be disabled in configure. In configure builds 'make install' changes/adds links like png.h and libpng.a to point to the newly installed, versioned, files (e.g. libpng17/png.h and libpng17.a). Three new configure options and some rearrangement of Makefile.am allow creation of these links to be disabled. Version 1.6.9beta03 [January 10, 2014] Removed potentially misleading warning from png_check_IHDR(). Version 1.6.9beta04 [January 20, 2014] Updated scripts/makefile.* to use CPPFLAGS (Cosmin). Added clang attribute support (Cosmin). Version 1.6.9rc01 [January 28, 2014] No changes. Version 1.6.9rc02 [January 30, 2014] Quiet an uninitialized memory warning from VC2013 in png_get_png(). Version 1.6.9 [February 6, 2014] Version 1.6.10beta01 [February 9, 2014] Backported changes from libpng-1.7.0beta30 and beta31: Fixed a large number of instances where PNGCBAPI was omitted from function definitions. Added pngimage test program for png_read_png() and png_write_png() with two new test scripts. Removed dependence on !PNG_READ_EXPAND_SUPPORTED for calling png_set_packing() in png_read_png(). Fixed combination of ~alpha with shift. On read invert alpha, processing occurred after shift processing, which causes the final values to be outside the range that should be produced by the shift. Reversing the order on read makes the two transforms work together correctly and mirrors the order used on write. Do not read invalid sBIT chunks. Previously libpng only checked sBIT values on write, so a malicious PNG writer could therefore cause the read code to return an invalid sBIT chunk, which might lead to application errors or crashes. Such chunks are now skipped (with chunk_benign_error). Make png_read_png() and png_write_png() prototypes in png.h depend upon PNG_READ_SUPPORTED and PNG_WRITE_SUPPORTED. Support builds with unsupported PNG_TRANSFORM_* values. All of the PNG_TRANSFORM_* values are always defined in png.h and, because they are used for both read and write in some cases, it is not reliable to #if out ones that are totally unsupported. This change adds error detection in png_read_image() and png_write_image() to do a png_app_error() if the app requests something that cannot be done and it adds corresponding code to pngimage.c to handle such options by not attempting to test them. Version 1.6.10beta02 [February 23, 2014] Moved redefines of png_error(), png_warning(), png_chunk_error(), and png_chunk_warning() from pngpriv.h to png.h to make them visible to libpng-calling applications. Moved OS dependent code from arm/arm_init.c, to allow the included implementation of the ARM NEON discovery function to be set at build-time and provide sample implementations from the current code in the contrib/arm-neon subdirectory. The __linux__ code has also been changed to compile and link on Android by using /proc/cpuinfo, and the old linux code is in contrib/arm-neon/linux-auxv.c. The new code avoids POSIX and Linux dependencies apart from opening /proc/cpuinfo and is C90 compliant. Check for info_ptr == NULL early in png_read_end() so we don't need to run all the png_handle_*() and depend on them to return if info_ptr == NULL. This improves the performance of png_read_end(png_ptr, NULL) and makes it more robust against future programming errors. Check for __has_extension before using it in pngconf.h, to support older Clang versions (Jeremy Sequoia). Treat CRC error handling with png_set_crc_action(), instead of with png_set_benign_errors(), which has been the case since libpng-1.6.0beta18. Use a user warning handler in contrib/gregbook/readpng2.c instead of default, so warnings will be put on stderr even if libpng has CONSOLE_IO disabled. Added png_ptr->process_mode = PNG_READ_IDAT_MODE in png_push_read_chunk after recognizing the IDAT chunk, which avoids an infinite loop while reading a datastream whose first IDAT chunk is of zero-length. This fixes CERT VU#684412 and CVE-2014-0333. Don't recognize known sRGB profiles as sRGB if they have been hacked, but don't reject them and don't issue a copyright violation warning. Version 1.6.10beta03 [February 25, 2014] Moved some documentation from png.h to libpng.3 and libpng-manual.txt Minor editing of contrib/arm-neon/README and contrib/examples/*.c Version 1.6.10rc01 [February 27, 2014] Fixed typos in the manual and in scripts/pnglibconf.dfa (CFLAGS -> CPPFLAGS and PNG_USR_CONFIG -> PNG_USER_CONFIG). Version 1.6.10rc02 [February 28, 2014] Removed unreachable return statement after png_chunk_error() in pngrutil.c Version 1.6.10rc03 [March 4, 2014] Un-deprecated png_data_freer(). Version 1.6.10 [March 6, 2014] No changes. Version 1.6.11beta01 [March 17, 2014] Use "if (value != 0)" instead of "if (value)" consistently. Changed ZlibSrcDir from 1.2.5 to 1.2.8 in projects/vstudio. Moved configuration information from the manual to the INSTALL file. Version 1.6.11beta02 [April 6, 2014] Removed #if/#else/#endif from inside two pow() calls in pngvalid.c because they were handled improperly by Portland Group's PGI-14.1 - PGI-14.3 when using its "__builtin_pow()" function. Silence 'unused parameter' build warnings (Cosmin Truta). $(CP) is now used alongside $(RM_F). Also, use 'copy' instead of 'cp' where applicable, and applied other minor makefile changes (Cosmin). Don't warn about invalid dimensions exceeding user limits (Cosmin). Allow an easy replacement of the default pre-built configuration header with a custom header, via the make PNGLIBCONF_H_PREBUILT macro (Cosmin). Version 1.6.11beta03 [April 6, 2014] Fixed a typo in pngrutil.c, introduced in libpng-1.5.6, that interferes with "blocky" expansion of sub-8-bit interlaced PNG files (Eric Huss). Optionally use __builtin_bswap16() in png_do_swap(). Version 1.6.11beta04 [April 19, 2014] Made progressive reading of interlaced images consistent with the behavior of the sequential reader and consistent with the manual, by moving some code out of the PNG_READ_INTERLACING_SUPPORTED blocks. The row_callback now receives the proper pass number and unexpanded rows, when png_combine_row() isn't built or used, and png_set_interlace_handling() is not called. Allow PNG_sRGB_PROFILE_CHECKING = (-1) to mean no sRGB profile checking. Version 1.6.11beta05 [April 26, 2014] Do not reject ICC V2 profiles that lack padding (Kai-Uwe Behrmann). Relocated closing bracket of the sRGB profile test loop to avoid getting "Not recognizing known sRGB profile that has been edited" warning for ICC V2 profiles that lack the MD5 signature in the profile header. Version 1.6.11beta06 [May 19, 2014] Added PNG_SKIP_sRGB_CHECK_PROFILE choice for png_set_option(). Version 1.6.11rc01 [May 27, 2014] No changes. Version 1.6.11rc02 [June 3, 2014] Test ZLIB_VERNUM instead of PNG_ZLIB_VERNUM in contrib/tools/pngfix.c Version 1.6.11 [June 5, 2014] No changes. Version 1.6.12rc01 [June 6, 2014] Relocated new code from 1.6.11beta06 in png.c to a point after the declarations (Max Stepin). Version 1.6.12rc02 [June 7, 2014] Changed file permissions of contrib/tools/intgamma.sh, test-driver, and compile from 0644 to 0755 (Cosmin). Version 1.6.12rc03 [June 8, 2014] Ensure "__has_attribute()" macro exists before trying to use it with old clang compilers (MacPorts Ticket #43939). Version 1.6.12 [June 12, 2014] No changes. Version 1.6.13beta01 [July 4, 2014] Quieted -Wsign-compare and -Wclobber compiler warnings in contrib/pngminus/*.c Added "(void) png_ptr;" where needed in contrib/gregbook to quiet compiler complaints about unused pointers. Split a long output string in contrib/gregbook/rpng2-x.c. Added "PNG_SET_OPTION" requirement for sRGB chunk support to pnglibconf.dfa, Needed for write-only support (John Bowler). Changed "if defined(__ARM_NEON__)" to "if (defined(__ARM_NEON__) || defined(__ARM_NEON))" (James Wu). Fixed clang no-warning builds: png_digit was defined but never used. Version 1.6.13beta02 [July 21, 2014] Fixed an incorrect separator ("/" should be "\") in scripts/makefile.vcwin32 (bug report from Wolfgang S. Kechel). Bug was introduced in libpng-1.6.11. Also fixed makefile.bc32, makefile.bor, makefile.msc, makefile.intel, and makefile.tc3 similarly. Version 1.6.13beta03 [August 3, 2014] Removed scripts/makefile.elf. It has not worked since libpng-1.5.0beta14 due to elimination of the PNG_FUNCTION_EXPORT and PNG_DATA_EXPORT definitions from pngconf.h. Ensure that CMakeLists.txt makes the target "lib" directory before making symbolic link into it (SourceForge bug report #226 by Rolf Timmermans). Version 1.6.13beta04 [August 8, 2014] Added opinion that the ECCN (Export Control Classification Number) for libpng is EAR99 to the README file. Eliminated use of "$<" in makefile explicit rules, when copying $PNGLIBCONF_H_PREBUILT. This does not work on some versions of make; bug introduced in libpng version 1.6.11. Version 1.6.13rc01 [August 14, 2014] Made "ccopts" agree with "CFLAGS" in scripts/makefile.hp* and makefile.*sunu Version 1.6.13 [August 21, 2014] No changes. Version 1.6.14beta01 [September 14, 2014] Guard usage of png_ptr->options with #ifdef PNG_SET_OPTION_SUPPORTED. Do not build contrib/tools/pngfix.c when PNG_SETJMP_NOT_SUPPORTED, to allow "make" to complete without setjmp support (bug report by Claudio Fontana) Add "#include " to contrib/tools/pngfix.c (John Bowler) Version 1.6.14beta02 [September 18, 2014] Use nanosleep() instead of usleep() in contrib/gregbook/rpng2-x.c because usleep() is deprecated. Define usleep() in contrib/gregbook/rpng2-x.c if not already defined in unistd.h and nanosleep() is not available; fixes error introduced in libpng-1.6.13. Disable floating point exception handling in pngvalid.c when PNG_FLOATING_ARITHMETIC is not supported (bug report by "zootus at users.sourceforge.net"). Version 1.6.14beta03 [September 19, 2014] Define FE_DIVBYZERO, FE_INVALID, and FE_OVERFLOW in pngvalid.c if not already defined. Revert floating point exception handling in pngvalid.c to version 1.6.14beta01 behavior. Version 1.6.14beta04 [September 27, 2014] Fixed incorrect handling of the iTXt compression flag in pngrutil.c (bug report by Shunsaku Hirata). Bug was introduced in libpng-1.6.0. Version 1.6.14beta05 [October 1, 2014] Added "option READ_iCCP enables READ_COMPRESSED_TEXT" to pnglibconf.dfa Version 1.6.14beta06 [October 5, 2014] Removed unused "text_len" parameter from private function png_write_zTXt(). Conditionally compile some code in png_deflate_claim(), when PNG_WARNINGS_SUPPORTED and PNG_ERROR_TEXT_SUPPORTED are disabled. Replaced repeated code in pngpread.c with PNG_PUSH_SAVE_BUFFER_IF_FULL. Added "chunk iTXt enables TEXT" and "chunk zTXt enables TEXT" to pnglibconf.dfa. Removed "option READ_COMPRESSED_TEXT enables READ_TEXT" from pnglibconf.dfa, to make it possible to configure a libpng that supports iCCP but not TEXT. Version 1.6.14beta07 [October 7, 2014] Removed "option WRITE_COMPRESSED_TEXT enables WRITE_TEXT" from pnglibconf.dfa Only mark text chunks as written after successfully writing them. Version 1.6.14rc01 [October 15, 2014] Fixed some typos in comments. Version 1.6.14rc02 [October 17, 2014] Changed png_convert_to_rfc_1123() to png_convert_to_rfc_1123_buffer() in the manual, to reflect the change made in libpng-1.6.0. Updated README file to explain that direct access to the png_struct and info_struct members has not been permitted since libpng-1.5.0. Version 1.6.14 [October 23, 2014] No changes. Version 1.6.15beta01 [October 29, 2014] Changed "if (!x)" to "if (x == 0)" and "if (x)" to "if (x != 0)" Simplified png_free_data(). Added missing "ptr = NULL" after some instances of png_free(). Version 1.6.15beta02 [November 1, 2014] Changed remaining "if (!x)" to "if (x == 0)" and "if (x)" to "if (x != 0)" Version 1.6.15beta03 [November 3, 2014] Added PNG_USE_ARM_NEON configuration flag (Marcin Juszkiewicz). Version 1.6.15beta04 [November 4, 2014] Removed new PNG_USE_ARM_NEON configuration flag and made a one-line revision to configure.ac to support ARM on aarch64 instead (John Bowler). Version 1.6.15beta05 [November 5, 2014] Use png_get_libpng_ver(NULL) instead of PNG_LIBPNG_VER_STRING in example.c, pngtest.c, and applications in the contrib directory. Fixed an out-of-range read in png_user_version_check() (Bug report from Qixue Xiao, CVE-2015-8540). Simplified and future-proofed png_user_version_check(). Fixed GCC unsigned int->float warnings. Various versions of GCC seem to generate warnings when an unsigned value is implicitly converted to double. This is probably a GCC bug but this change avoids the issue by explicitly converting to (int) where safe. Free all allocated memory in pngimage. The file buffer cache was left allocated at the end of the program, harmless but it causes memory leak reports from clang. Fixed array size calculations to avoid warnings. At various points in the code the number of elements in an array is calculated using sizeof. This generates a compile time constant of type (size_t) which is then typically assigned to an (unsigned int) or (int). Some versions of GCC on 64-bit systems warn about the apparent narrowing, even though the same compiler does apparently generate the correct, in-range, numeric constant. This adds appropriate, safe, casts to make the warnings go away. Version 1.6.15beta06 [November 6, 2014] Reverted use png_get_libpng_ver(NULL) instead of PNG_LIBPNG_VER_STRING in the manual, example.c, pngtest.c, and applications in the contrib directory. It was incorrect advice. Version 1.6.15beta07 [November 7, 2014] Removed #ifdef PNG_16BIT_SUPPORTED/#endif around png_product2(); it is needed by png_reciprocal2(). Added #ifdef PNG_16BIT_SUPPORTED/#endif around png_log16bit() and png_do_swap(). Changed all "#endif /* PNG_FEATURE_SUPPORTED */" to "#endif /* FEATURE */" Version 1.6.15beta08 [November 8, 2014] More housecleaning in *.h Version 1.6.15rc01 [November 13, 2014] Version 1.6.15rc02 [November 14, 2014] The macros passed in the command line to Borland make were ignored if similarly-named macros were already defined in makefiles. This behavior is different from POSIX make and other make programs. Surround the macro definitions with ifndef guards (Cosmin). Version 1.6.15rc03 [November 16, 2014] Added "-D_CRT_SECURE_NO_WARNINGS" to CFLAGS in scripts/makefile.vcwin32. Removed the obsolete $ARCH variable from scripts/makefile.darwin. Version 1.6.15 [November 20, 2014] No changes. Version 1.6.16beta01 [December 14, 2014] Added ".align 2" to arm/filter_neon.S to support old GAS assemblers that don't do alignment correctly. Revised Makefile.am and scripts/symbols.dfn to work with MinGW/MSYS (Bob Friesenhahn). Version 1.6.16beta02 [December 15, 2014] Revised Makefile.am and scripts/*.dfn again to work with MinGW/MSYS; renamed scripts/*.dfn to scripts/*.c (John Bowler). Version 1.6.16beta03 [December 21, 2014] Quiet a "comparison always true" warning in pngstest.c (John Bowler). Version 1.6.16rc01 [December 21, 2014] Restored a test on width that was removed from png.c at libpng-1.6.9 (Bug report by Alex Eubanks, CVE-2015-0973). Version 1.6.16rc02 [December 21, 2014] Undid the update to pngrutil.c in 1.6.16rc01. Version 1.6.16rc03 [December 21, 2014] Fixed an overflow in png_combine_row() with very wide interlaced images (Bug report and fix by John Bowler, CVE-2014-9495). Version 1.6.16 [December 22, 2014] No changes. Version 1.6.17beta01 [January 29, 2015] Removed duplicate PNG_SAFE_LIMITS_SUPPORTED handling from pngconf.h Corrected the width limit calculation in png_check_IHDR(). Removed user limits from pngfix. Also pass NULL pointers to png_read_row to skip the unnecessary row de-interlace stuff. Added testing of png_set_packing() to pngvalid.c Regenerated configure scripts in the *.tar distributions with libtool-2.4.4 Implement previously untested cases of libpng transforms in pngvalid.c Fixed byte order in png_do_read_filler() with 16-bit input. Previously the high and low bytes of the filler, from png_set_filler() or from png_set_add_alpha(), were read in the wrong order. Made the check for out-of-range values in png_set_tRNS() detect values that are exactly 2^bit_depth, and work on 16-bit platforms. Merged some parts of libpng-1.6.17beta01 and libpng-1.7.0beta47. Added #ifndef __COVERITY__ where needed in png.c, pngrutil.c and pngset.c to avoid warnings about dead code. Added "& 0xff" to many instances of expressions that are typecast to (png_byte), to avoid Coverity warnings. Version 1.6.17beta02 [February 7, 2015] Work around one more Coverity-scan dead-code warning. Do not build png_product2() when it is unused. Version 1.6.17beta03 [February 17, 2015] Display user limits in the output from pngtest. Eliminated the PNG_SAFE_LIMITS macro and restored the 1-million-column and 1-million-row default limits in pnglibconf.dfa, that can be reset by the user at build time or run time. This provides a more robust defense against DOS and as-yet undiscovered overflows. Version 1.6.17beta04 [February 21, 2015] Added PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED macro, on by default. Allow user to call png_get_IHDR() with NULL arguments (Reuben Hawkins). Rebuilt configure scripts with automake-1.15 and libtool-2.4.6 Version 1.6.17beta05 [February 25, 2015] Restored compiling of png_reciprocal2 with PNG_NO_16BIT. Version 1.6.17beta06 [February 27, 2015] Moved png_set_filter() prototype into a PNG_WRITE_SUPPORTED block of png.h. Avoid runtime checks when converting integer to png_byte with Visual Studio (Sergey Kosarevsky) Version 1.6.17rc01 [March 4, 2015] No changes. Version 1.6.17rc02 [March 9, 2015] Removed some comments that the configure script did not handle properly from scripts/pnglibconf.dfa and pnglibconf.h.prebuilt. Free the unknown_chunks structure even when it contains no data. Version 1.6.17rc03 [March 12, 2015] Updated CMakeLists.txt to add OSX framework, change YES/NO to ON/OFF for consistency, and remove some useless tests (Alexey Petruchik). Version 1.6.17rc04 [March 16, 2015] Remove pnglibconf.h, pnglibconf.c, and pnglibconf.out instead of pnglibconf.* in "make clean" (Cosmin). Fix bug in calculation of maxbits, in png_write_sBIT, introduced in libpng-1.6.17beta01 (John Bowler). Version 1.6.17rc05 [March 21, 2015] Define PNG_FILTER_* and PNG_FILTER_VALUE_* in png.h even when WRITE is not supported (John Bowler). This fixes an error introduced in libpng-1.6.17beta06. Reverted "& 0xff" additions of version 1.6.17beta01. Libpng passes the Coverity scan without them. Version 1.6.17rc06 [March 23, 2015] Remove pnglibconf.dfn and pnglibconf.pre with "make clean". Reformatted some "&0xff" instances to "& 0xff". Fixed simplified 8-bit-linear to sRGB alpha. The calculated alpha value was wrong. It's not clear if this affected the final stored value; in the obvious code path the upper and lower 8-bits of the alpha value were identical and the alpha was truncated to 8-bits rather than dividing by 257 (John Bowler). Version 1.6.17 [March 26, 2015] No changes. Version 1.6.18beta01 [April 1, 2015] Removed PNG_SET_CHUNK_[CACHE|MALLOC]_LIMIT_SUPPORTED macros. They have been combined with PNG_SET_USER_LIMITS_SUPPORTED (resolves bug report by Andrew Church). Fixed rgb_to_gray checks and added tRNS checks to pngvalid.c. This fixes some arithmetic errors that caused some tests to fail on some 32-bit platforms (Bug reports by Peter Breitenlohner [i686] and Petr Gajdos [i586]). Version 1.6.18beta02 [April 26, 2015] Suppressed some warnings from the Borland C++ 5.5.1/5.82 compiler (Bug report by Viktor Szakats). Version 1.6.18beta03 [May 6, 2015] Replaced "unexpected" with an integer (0xabadca11) in pngset.c where a long was expected, to avoid a compiler warning when PNG_DEBUG > 1. Added contrib/examples/simpleover.c, to demonstrate how to handle alpha compositing of multiple images, using the "simplified API" and an example PNG generation tool, contrib/examples/genpng.c (John Bowler). Version 1.6.18beta04 [May 20, 2015] PNG_RELEASE_BUILD replaces tests where the code depended on the build base type and can be defined on the command line, allowing testing in beta builds (John Bowler). Avoid Coverity issue 80858 (REVERSE NULL) in pngtest.c PNG_DEBUG builds. Avoid a harmless potential integer overflow in png_XYZ_from_xy() (Bug report from Christopher Ferris). Version 1.6.18beta05 [May 31, 2015] Backport filter selection code from libpng-1.7.0beta51, to combine sub_row, up_row, avg_row, and paeth_row into try_row and tst_row. Changed png_voidcast(), etc., to voidcast(), etc., in contrib/tools/pngfix.c to avoid confusion with the libpng private macros. Fixed old cut&paste bug in the weighted filter selection code in pngwutil.c, introduced in libpng-0.95, March 1997. Version 1.6.18beta06 [June 1, 2015] Removed WRITE_WEIGHTED_FILTERED code, to save a few kbytes of the compiled library size. It never worked properly and as far as we can tell, no one uses it. The png_set_filter_heuristics() and png_set_filter_heuristics_fixed() APIs are retained but deprecated and do nothing. Version 1.6.18beta07 [June 6, 2015] Removed non-working progressive reader 'skip' function. This function has apparently never been used. It was implemented to support back-door modification of png_struct in libpng-1.4.x but (because it does nothing and cannot do anything) was apparently never tested (John Bowler). Fixed cexcept.h in which GCC 5 now reports that one of the auto variables in the Try macro needs to be volatile to prevent value being lost over the setjmp (John Bowler). Fixed NO_WRITE_FILTER and -Wconversion build breaks (John Bowler). Fix g++ build breaks (John Bowler). Quieted some Coverity issues in pngfix.c, png-fix-itxt.c, pngvalid.c, pngstest.c, and pngimage.c. Most seem harmless, but png-fix-itxt would only work with iTXt chunks with length 255 or less. Added #ifdef's to contrib/examples programs so people don't try to compile them without the minimum required support enabled (suggested by Flavio Medeiros). Version 1.6.18beta08 [June 30, 2015] Eliminated the final two Coverity defects (insecure temporary file handling in contrib/libtests/pngstest.c; possible overflow of unsigned char in contrib/tools/png-fix-itxt.c). To use the "secure" file handling, define PNG_USE_MKSTEMP, otherwise "tmpfile()" will be used. Removed some unused WEIGHTED_FILTER macros from png.h and pngstruct.h Version 1.6.18beta09 [July 5, 2015] Removed some useless typecasts from contrib/tools/png-fix-itxt.c Fixed a new signed-unsigned comparison in pngrtran.c (Max Stepin). Replaced arbitrary use of 'extern' with #define PNG_LINKAGE_*. To preserve API compatibility, the new defines all default to "extern" (requested by Jan Nijtmans). Version 1.6.18rc01 [July 9, 2015] Belatedly added Mans Rullgard and James Yu to the list of Contributing Authors. Version 1.6.18rc02 [July 12, 2015] Restored unused FILTER_HEURISTIC macros removed at libpng-1.6.18beta08 to png.h to avoid compatibility warnings. Version 1.6.18rc03 [July 15, 2015] Minor changes to the man page Version 1.6.18 [July 23, 2015] No changes. Version 1.6.19beta01 [July 30, 2015] Updated obsolete information about the simplified API macros in the manual pages (Bug report by Arc Riley). Avoid potentially dereferencing NULL info_ptr in png_info_init_3(). Rearranged png.h to put the major sections in the same order as in libpng17. Eliminated unused PNG_COST_SHIFT, PNG_WEIGHT_SHIFT, PNG_COST_FACTOR, and PNG_WEIGHT_FACTOR macros. Suppressed some warnings from the Borland C++ 5.5.1/5.82 compiler (Bug report by Viktor Szakats). Several warnings remain and are unavoidable, where we test for overflow. Fixed potential leak of png_pixels in contrib/pngminus/pnm2png.c Fixed uninitialized variable in contrib/gregbook/rpng2-x.c Version 1.6.19beta02 [August 19, 2015] Moved config.h.in~ from the "libpng_autotools_files" list to the "libpng_autotools_extra" list in autogen.sh because it was causing a false positive for missing files (bug report by Robert C. Seacord). Removed unreachable "break" statements in png.c, pngread.c, and pngrtran.c to suppress clang warnings (Bug report by Viktor Szakats). Fixed some bad links in the man page. Changed "n bit" to "n-bit" in comments. Added signed/unsigned 16-bit safety net. This removes the dubious 0x8000 flag definitions on 16-bit systems. They aren't supported yet the defs *probably* work, however it seems much safer to do this and be advised if anyone, contrary to advice, is building libpng 1.6 on a 16-bit system. It also adds back various switch default clauses for GCC; GCC errors out if they are not present (with an appropriately high level of warnings). Safely convert num_bytes to a png_byte in png_set_sig_bytes() (Robert Seacord). Fixed the recently reported 1's complement security issue by replacing the value that is illegal in the PNG spec, in both signed and unsigned values, with 0. Illegal unsigned values (anything greater than or equal to 0x80000000) can still pass through, but since these are not illegal in ANSI-C (unlike 0x80000000 in the signed case) the checking that occurs later can catch them (John Bowler). Version 1.6.19beta03 [September 26, 2015] Fixed png_save_int_32 when int is not 2's complement (John Bowler). Updated libpng16 with all the recent test changes from libpng17, including changes to pngvalid.c to ensure that the original, distributed, version of contrib/visupng/cexcept.h can be used (John Bowler). pngvalid contains the correction to the use of SAVE/STORE_ UNKNOWN_CHUNKS; a bug revealed by changes in libpng 1.7. More tests contain the --strict option to detect warnings and the pngvalid-standard test has been corrected so that it does not turn on progressive-read. There is a separate test which does that. (John Bowler) Also made some signed/unsigned fixes. Make pngstest error limits version specific. Splitting the machine generated error structs out to a file allows the values to be updated without changing pngstest.c itself. Since libpng 1.6 and 1.7 have slightly different error limits this simplifies maintenance. The makepngs.sh script has also been updated to more accurately reflect current problems in libpng 1.7 (John Bowler). Incorporated new test PNG files into make check. tests/pngstest-* are changed so that the new test files are divided into 8 groups by gamma and alpha channel. These tests have considerably better code and pixel-value coverage than contrib/pngsuite; however,coverage is still incomplete (John Bowler). Removed the '--strict' in 1.6 because of the double-gamma-correction warning, updated pngstest-errors.h for the errors detected with the new contrib/testspngs PNG test files (John Bowler). Version 1.6.19beta04 [October 15, 2015] Worked around rgb-to-gray issues in libpng 1.6. The previous attempts to ignore the errors in the code aren't quite enough to deal with the 'channel selection' encoding added to libpng 1.7; abort. pngvalid.c is changed to drop this encoding in prior versions. Fixed 'pow' macros in pngvalid.c. It is legal for 'pow' to be a macro, therefore the argument list cannot contain preprocessing directives. Make sure pow is a function where this happens. This is a minimal safe fix, the issue only arises in non-performance-critical code (bug report by Curtis Leach, fix by John Bowler). Added sPLT support to pngtest.c Version 1.6.19rc01 [October 23, 2015] No changes. Version 1.6.19rc02 [October 31, 2015] Prevent setting or writing over-length PLTE chunk (Cosmin Truta). Silently truncate over-length PLTE chunk while reading. Libpng incorrectly calculated the output rowbytes when the application decreased either the number of channels or the bit depth (or both) in a user transform. This was safe; libpng overallocated buffer space (potentially by quite a lot; up to 4 times the amount required) but, from 1.5.4 on, resulted in a png_error (John Bowler). Version 1.6.19rc03 [November 3, 2015] Fixed some inconsequential cut-and-paste typos in png_set_cHRM_XYZ_fixed(). Clarified COPYRIGHT information to state explicitly that versions are derived from previous versions. Removed much of the long list of previous versions from png.h and libpng.3. Version 1.6.19rc04 [November 5, 2015] Fixed new bug with CRC error after reading an over-length palette (bug report by Cosmin Truta) (CVE-2015-8126). Version 1.6.19 [November 12, 2015] Cleaned up coding style in png_handle_PLTE(). Version 1.6.20beta01 [November 20, 2015] Avoid potential pointer overflow/underflow in png_handle_sPLT() and png_handle_pCAL() (Bug report by John Regehr). Version 1.6.20beta02 [November 23, 2015] Fixed incorrect implementation of png_set_PLTE() that uses png_ptr not info_ptr, that left png_set_PLTE() open to the CVE-2015-8126 vulnerability. Fixes CVE-2015-8472. Version 1.6.20beta03 [November 24, 2015] Backported tests from libpng-1.7.0beta69. Version 1.6.20rc01 [November 26, 2015] Fixed an error in handling of bad zlib CMINFO field in pngfix, found by American Fuzzy Lop, reported by Brian Carpenter. inflate() doesn't immediately fault a bad CMINFO field; instead a 'too far back' error happens later (at least some times). pngfix failed to limit CMINFO to the allowed values but then assumed that window_bits was in range, triggering an assert. The bug is mostly harmless; the PNG file cannot be fixed. Version 1.6.20rc02 [November 29, 2015] In libpng 1.6 zlib initialization was changed to use the window size in the zlib stream, not a fixed value. This causes some invalid images, where CINFO is too large, to display 'correctly' if the rest of the data is valid. This provides a workaround for zlib versions where the error arises (ones that support the API change to use the window size in the stream). Version 1.6.20 [December 3, 2015] No changes. Version 1.6.21beta01 [December 11, 2015] Fixed syntax "$(command)" in tests/pngstest that some shells other than bash could not parse (Bug report by Nelson Beebe). Use `command` instead. Version 1.6.21beta02 [December 14, 2015] Moved png_check_keyword() from pngwutil.c to pngset.c Removed LE/BE dependencies in pngvalid, to 'fix' the current problem in the BigEndian tests by not testing it, making the BE code the same as the LE version. Fixes to pngvalid for various reduced build configurations (eliminate unused statics) and a fix for the case in rgb_to_gray when the digitize option reduces graylo to 0, producing a large error. Version 1.6.21beta03 [December 18, 2015] Widened the 'limit' check on the internally calculated error limits in the 'DIGITIZE' case (the code used prior to 1.7 for rgb_to_gray error checks) and changed the check to only operate in non-release builds (base build type not RC or RELEASE.) Fixed undefined behavior in pngvalid.c, undefined because (png_byte) << shift is undefined if it changes the signed bit (because png_byte is promoted to int). The libpng exported functions png_get_uint_32 and png_get_uint_16 handle this. (Bug reported by David Drysdale as a result of reports from UBSAN in clang 3.8). This changes pngvalid to use BE random numbers; this used to produce errors but these should not be fixed as a result of the previous changes. Version 1.6.21rc01 [January 4, 2016] In projects/vstudio, combined readme.txt and WARNING into README.txt Version 1.6.21rc02 [January 7, 2016] Relocated assert() in contrib/tools/pngfix.c, bug found by American Fuzzy Lop, reported by Brian Carpenter. Marked 'limit' UNUSED in transform_range_check(). This only affects release builds. Version 1.6.21 [January 15, 2016] Worked around a false-positive Coverity issue in pngvalid.c. Version 1.6.22beta01 [January 23, 2016] Changed PNG_USE_MKSTEMP to __COVERITY__ to select alternate "tmpfile()" implementation in contrib/libtests/pngstest.c Fixed NO_STDIO build of pngunknown.c to skip calling png_init_io() if there is no stdio.h support. Added a png_image_write_to_memory() API and a number of assist macros to allow an application that uses the simplified API write to bypass stdio and write directly to memory. Added some warnings (png.h) and some check code to detect *possible* overflow in the ROW_STRIDE and simplified image SIZE macros. This disallows image width/height/format that *might* overflow. This is a quiet API change that limits in-memory image size (uncompressed) to less than 4GByte and image row size (stride) to less than 2GByte. Revised workaround for false-positive Coverity issue in pngvalid.c. Version 1.6.22beta02 [February 8, 2016] Only use exit(77) in configure builds. Corrected error in PNG_IMAGE_PNG_SIZE_MAX. This new macro underreported the palette size because it failed to take into account that the memory palette has to be expanded to full RGB when it is written to PNG. Updated CMakeLists.txt, added supporting scripts/gen*.cmake.in and test.cmake.in (Roger Leigh). Relaxed limit checks on gamma values in pngrtran.c. As suggested in the comments gamma values outside the range currently permitted by png_set_alpha_mode are useful for HDR data encoding. These values are already permitted by png_set_gamma so it is reasonable caution to extend the png_set_alpha_mode range as HDR imaging systems are starting to emerge. Version 1.6.22beta03 [March 9, 2016] Added a common-law trademark notice and export control information to the LICENSE file, png.h, and the man page. Restored "& 0xff" in png_save_uint_16() and png_save_uint_32() that were accidentally removed from libpng-1.6.17. Changed PNG_INFO_cHNK and PNG_FREE_cHNK from 0xnnnn to 0xnnnnU in png.h (Robert C. Seacord). Removed dubious "#if INT_MAX" test from png.h that was added to libpng-1.6.19beta02 (John Bowler). Add ${INCLUDES} in scripts/genout.cmake.in (Bug report by Nixon Kwok). Updated LICENSE to say files in the contrib directory are not necessarily under the libpng license, and that some makefiles have other copyright owners. Added INTEL-SSE2 support (Mike Klein and Matt Sarett, Google, Inc.). Made contrib/libtests/timepng more robust. The code no longer gives up/fails on invalid PNG data, it just skips it (with error messages). The code no longer fails on PNG files with data beyond IEND. Options exist to use png_read_png (reading the whole image, not by row) and, in that case, to apply any of the supported transforms. This makes for more realistic testing; the decoded data actually gets used in a meaningful fashion (John Bowler). Fixed some misleading indentation (Krishnaraj Bhat). Version 1.6.22beta04 [April 5, 2016] Force GCC compilation to C89 if needed (Dagobert Michelsen). SSE filter speed improvements for bpp=3: memcpy-free implementations of load3() / store3(). call load3() only when needed at the end of a scanline. Version 1.6.22beta05 [April 27, 2016] Added PNG_FAST_FILTERS macro (defined as PNG_FILTER_NONE|PNG_FILTER_SUB|PNG_FILTER_UP). Various fixes for contrib/libtests/timepng.c Moved INTEL-SSE code from pngpriv.h into contrib/intel/intel_sse.patch. Fixed typo (missing underscore) in #define PNG_READ_16_TO_8_SUPPORTED (Bug report by Y.Ohashik). Version 1.6.22beta06 [May 5, 2016] Rebased contrib/intel_sse.patch. Quieted two Coverity issues in contrib/libtests/timepng.c. Fixed issues with scripts/genout.cmake.in (David Capello, Nixon Kwok): Added support to use multiple directories in ZLIBINCDIR variable, Fixed CMAKE_C_FLAGS with multiple values when genout is compiled on MSVC, Fixed pnglibconf.c compilation on OS X including the sysroot path. Version 1.6.22rc01 [May 14, 2016] No changes. Version 1.6.22rc02 [May 16, 2016] Removed contrib/timepng from default build; it does not build on platforms that don't supply clock_gettime(). Version 1.6.22rc03 [May 17, 2016] Restored contrib/timepng to default build but check for the presence of clock_gettime() in configure.ac and Makefile.am. Version 1.6.22 [May 26, 2016] No changes. Version 1.6.23beta01 [May 29, 2016] Stop a potential memory leak in png_set_tRNS() (Bug report by Ted Ying). Fixed the progressive reader to handle empty first IDAT chunk properly (patch by Timothy Nikkel). This bug was introduced in libpng-1.6.0 and only affected the libpng16 branch. Added tests in pngvalid.c to check zero-length IDAT chunks in various positions. Fixed the sequential reader to handle these more robustly (John Bowler). Version 1.6.23rc01 [June 2, 2016] Corrected progressive read input buffer in pngvalid.c. The previous version the code invariably passed just one byte at a time to libpng. The intent was to pass a random number of bytes in the range 0..511. Moved sse2 prototype from pngpriv.h to contrib/intel/intel_sse.patch. Added missing ")" in pngerror.c (Matt Sarrett). Version 1.6.23rc02 [June 4, 2016] Fixed undefined behavior in png_push_save_buffer(). Do not call memcpy() with a null source, even if count is zero (Leon Scroggins III). Version 1.6.23 [June 9, 2016] Fixed bad link to RFC2083 in png.5 (Nikola Forro). Version 1.6.24beta01 [June 11, 2016] Avoid potential overflow of the PNG_IMAGE_SIZE macro. This macro is not used within libpng, but is used in some of the examples. Version 1.6.24beta02 [June 23, 2016] Correct filter heuristic overflow handling. This was broken when the write filter code was moved out-of-line; if there is a single filter and the heuristic sum overflows the calculation of the filtered line is not completed. In versions prior to 1.6 the code was duplicated in-line and the check not performed, so the filter operation completed; however, in the multi-filter case where the sum is performed the 'none' filter would be selected if all the sums overflowed, even if it wasn't in the filter list. The fix to the first problem is simply to provide PNG_SIZE_MAX as the current lmins sum value; this means the sum can never exceed it and overflows silently. A reasonable compiler that does choose to inline the code will simply eliminate the sum check. The fix to the second problem is to use high precision arithmetic (this is implemented in 1.7), however a simple safe fix here is to chose the lowest numbered filter in the list from png_set_filter (this only works if the first problem is also fixed) (John Bowler). Use a more efficient absolute value calculation on SSE2 (Matthieu Darbois). Fixed the case where PNG_IMAGE_BUFFER_SIZE can overflow in the application as a result of the application using an increased 'row_stride'; previously png_image_finish_read only checked for overflow on the base calculation of components. (I.e. it checked for overflow of a 32-bit number on the total number of pixel components in the output format, not the possibly padded row length and not the number of bytes, which for linear formats is twice the number of components.) MSVC does not like '-(unsigned)', so replaced it with 0U-(unsigned) MSVC does not like (uInt) = -(unsigned) (i.e. as an initializer), unless the conversion is explicitly invoked by a cast. Put the SKIP definition in the correct place. It needs to come after the png.h include (see all the other .c files in contrib/libtests) because it depends on PNG_LIBPNG_VER. Removed the three compile warning options from the individual project files into the zlib.props globals. It increases the warning level from 4 to All and adds a list of the warnings that need to be turned off. This is semi-documentary; the intent is to tell libpng users which warnings have been examined and judged non-fixable at present. The warning about structure padding is fixable, but it would be a signficant change (moving structure members around). Version 1.6.24beta03 [July 4, 2016] Optimized absolute value calculation in filter selection, similar to code in the PAETH decoder in pngrutil.c. Build with PNG_USE_ABS to use this. Added pngcp to the build together with a pngcp.dfa configuration test. Added high resolution timing to pngcp. Added "Common linking failures" section to INSTALL. Relocated misplaced #endif in png.c sRGB profile checking. Fixed two Coverity issues in pngcp.c. Version 1.6.24beta04 [July 8, 2016] Avoid filter-selection heuristic sum calculations in cases where only one filter is a candidate for selection. This trades off code size (added private png_setup_*_row_only() functions) for speed. Version 1.6.24beta05 [July 13, 2016] Fixed some indentation to comply with our coding style. Added contrib/tools/reindent. Version 1.6.24beta06 [July 18, 2016] Fixed more indentation to comply with our coding style. Eliminated unnecessary tests of boolean png_isaligned() vs 0. Version 1.6.24rc01 [July 25, 2016] No changes. Version 1.6.24rc02 [August 1, 2016] Conditionally compile SSE2 headers in contrib/intel/intel_sse.patch Conditionally compile png_decompress_chunk(). Version 1.6.24rc03 [August 2, 2016] Conditionally compile ARM_NEON headers in pngpriv.h Updated contrib/intel/intel_sse.patch Version 1.6.24[August 4, 2016] No changes. Version 1.6.25beta01 [August 12, 2016] Reject oversized iCCP profile immediately. Cleaned up PNG_DEBUG compile of pngtest.c. Conditionally compile png_inflate(). Version 1.6.25beta02 [August 18, 2016] Don't install pngcp; it conflicts with pngcp in the pngtools package. Minor editing of INSTALL, (whitespace, added copyright line) Version 1.6.25rc01 [August 24, 2016] No changes. Version 1.6.25rc02 [August 29, 2016] Added MIPS support (Mandar Sahastrabuddhe ). Only the UP filter is currently implemented. Version 1.6.25rc03 [August 29, 2016] Rebased contrib/intel/intel_sse.patch after the MIPS implementation. Version 1.6.25rc04 [August 30, 2016] Added MIPS support for SUB, AVG, and PAETH filters (Mandar Sahastrabuddhe). Version 1.6.25rc05 [August 30, 2016] Rebased contrib/intel/intel_sse.patch after the MIPS implementation update.. Version 1.6.25 [September 1, 2016] No changes. Send comments/corrections/commendations to png-mng-implement at lists.sf.net (subscription required; visit https://lists.sourceforge.net/lists/listinfo/png-mng-implement to subscribe) or to glennrp at users.sourceforge.net Glenn R-P #endif ================================================ FILE: tess-two/jni/libpng/CMakeLists.txt ================================================ # CMakeLists.txt # Copyright (C) 2007,2009-2016 Glenn Randers-Pehrson # Written by Christian Ehrlicher, 2007 # Revised by Roger Lowman, 2009-2010 # Revised by Clifford Yapp, 2011-2012 # Revised by Roger Leigh, 2016 # This code is released under the libpng license. # For conditions of distribution and use, see the disclaimer # and license in png.h cmake_minimum_required(VERSION 2.8.3) cmake_policy(VERSION 2.8.3) # Set MacOSX @rpath usage globally. if (POLICY CMP0020) cmake_policy(SET CMP0020 NEW) endif(POLICY CMP0020) if (POLICY CMP0042) cmake_policy(SET CMP0042 NEW) endif(POLICY CMP0042) # Use new variable expansion policy. if (POLICY CMP0053) cmake_policy(SET CMP0053 NEW) endif(POLICY CMP0053) if (POLICY CMP0054) cmake_policy(SET CMP0054 NEW) endif(POLICY CMP0054) set(CMAKE_CONFIGURATION_TYPES "Release;Debug;MinSizeRel;RelWithDebInfo") project(libpng C) enable_testing() set(PNGLIB_MAJOR 1) set(PNGLIB_MINOR 6) set(PNGLIB_RELEASE 25) set(PNGLIB_NAME libpng${PNGLIB_MAJOR}${PNGLIB_MINOR}) set(PNGLIB_VERSION ${PNGLIB_MAJOR}.${PNGLIB_MINOR}.${PNGLIB_RELEASE}) # needed packages find_package(ZLIB REQUIRED) include_directories(${ZLIB_INCLUDE_DIR}) if(NOT WIN32) find_library(M_LIBRARY NAMES m PATHS /usr/lib /usr/local/lib ) if(NOT M_LIBRARY) message(STATUS "math lib 'libm' not found; floating point support disabled") endif() else() # not needed on windows set(M_LIBRARY "") endif() # COMMAND LINE OPTIONS option(PNG_SHARED "Build shared lib" ON) option(PNG_STATIC "Build static lib" ON) option(PNG_TESTS "Build libpng tests" ON) # Many more configuration options could be added here option(PNG_FRAMEWORK "Build OS X framework" OFF) option(PNG_DEBUG "Build with debug output" OFF) option(PNGARG "Disable ANSI-C prototypes" OFF) set(PNG_PREFIX "" CACHE STRING "Prefix to add to the API function names") set(DFA_XTRA "" CACHE FILEPATH "File containing extra configuration settings") # SET LIBNAME set(PNG_LIB_NAME png${PNGLIB_MAJOR}${PNGLIB_MINOR}) # to distinguish between debug and release lib set(CMAKE_DEBUG_POSTFIX "d") include(CheckCSourceCompiles) option(ld-version-script "Enable linker version script" ON) if(ld-version-script AND NOT APPLE) # Check if LD supports linker scripts. file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/conftest.map" "VERS_1 { global: sym; local: *; }; VERS_2 { global: sym2; main; } VERS_1; ") set(CMAKE_REQUIRED_FLAGS_SAVE ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} "-Wl,--version-script='${CMAKE_CURRENT_BINARY_DIR}/conftest.map'") check_c_source_compiles("void sym(void) {} void sym2(void) {} int main(void) {return 0;} " HAVE_LD_VERSION_SCRIPT) if(NOT HAVE_LD_VERSION_SCRIPT) set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS_SAVE} "-Wl,-M -Wl,${CMAKE_CURRENT_BINARY_DIR}/conftest.map") check_c_source_compiles("void sym(void) {} void sym2(void) {} int main(void) {return 0;} " HAVE_SOLARIS_LD_VERSION_SCRIPT) endif() set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS_SAVE}) file(REMOVE "${CMAKE_CURRENT_BINARY_DIR}/conftest.map") endif() # Find symbol prefix. Likely obsolete and unnecessary with recent # toolchains (it's not done in many other projects). function(symbol_prefix) set(SYMBOL_PREFIX) execute_process(COMMAND "${CMAKE_C_COMPILER}" "-E" "-" INPUT_FILE /dev/null OUTPUT_VARIABLE OUT RESULT_VARIABLE STATUS) if(CPP_FAIL) message(WARNING "Failed to run the C preprocessor") endif() string(REPLACE "\n" ";" OUT "${OUT}") foreach(line ${OUT}) string(REGEX MATCH "^PREFIX=" found_match "${line}") if(found_match) STRING(REGEX REPLACE "^PREFIX=(.*\)" "\\1" prefix "${line}") string(REGEX MATCH "__USER_LABEL_PREFIX__" found_match "${prefix}") if(found_match) STRING(REGEX REPLACE "(.*)__USER_LABEL_PREFIX__(.*)" "\\1\\2" prefix "${prefix}") endif() set(SYMBOL_PREFIX "${prefix}") endif() endforeach() message(STATUS "Symbol prefix: ${SYMBOL_PREFIX}") set(SYMBOL_PREFIX "${SYMBOL_PREFIX}" PARENT_SCOPE) endfunction() if(UNIX) symbol_prefix() endif() find_program(AWK NAMES gawk awk) include_directories(${CMAKE_CURRENT_BINARY_DIR}) if(NOT AWK) # No awk available to generate sources; use pre-built pnglibconf.h configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/pnglibconf.h.prebuilt ${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.h) add_custom_target(genfiles) # Dummy else() include(CMakeParseArguments) # Generate .chk from .out with awk # generate_chk(INPUT inputfile OUTPUT outputfile [DEPENDS dep1 [dep2...]]) function(generate_chk) set(options) set(oneValueArgs INPUT OUTPUT) set(multiValueArgs DEPENDS) cmake_parse_arguments(_GC "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if (NOT _GC_INPUT) message(FATAL_ERROR "Invalid arguments. generate_out requires input.") endif() if (NOT _GC_OUTPUT) message(FATAL_ERROR "Invalid arguments. generate_out requires output.") endif() add_custom_command(OUTPUT "${_GC_OUTPUT}" COMMAND "${CMAKE_COMMAND}" "-DINPUT=${_GC_INPUT}" "-DOUTPUT=${_GC_OUTPUT}" -P "${CMAKE_CURRENT_BINARY_DIR}/scripts/genchk.cmake" DEPENDS "${_GC_INPUT}" ${_GC_DEPENDS} WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") endfunction() # Generate .out from .c with awk # generate_out(INPUT inputfile OUTPUT outputfile [DEPENDS dep1 [dep2...]]) function(generate_out) set(options) set(oneValueArgs INPUT OUTPUT) set(multiValueArgs DEPENDS) cmake_parse_arguments(_GO "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if (NOT _GO_INPUT) message(FATAL_ERROR "Invalid arguments. generate_out requires input.") endif() if (NOT _GO_OUTPUT) message(FATAL_ERROR "Invalid arguments. generate_out requires output.") endif() add_custom_command(OUTPUT "${_GO_OUTPUT}" COMMAND "${CMAKE_COMMAND}" "-DINPUT=${_GO_INPUT}" "-DOUTPUT=${_GO_OUTPUT}" -P "${CMAKE_CURRENT_BINARY_DIR}/scripts/genout.cmake" DEPENDS "${_GO_INPUT}" ${_GO_DEPENDS} WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") endfunction() # Generate specific source file with awk # generate_source(OUTPUT outputfile [DEPENDS dep1 [dep2...]]) function(generate_source) set(options) set(oneValueArgs OUTPUT) set(multiValueArgs DEPENDS) cmake_parse_arguments(_GSO "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if (NOT _GSO_OUTPUT) message(FATAL_ERROR "Invalid arguments. generate_source requires output.") endif() add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${_GSO_OUTPUT}" COMMAND "${CMAKE_COMMAND}" "-DOUTPUT=${_GSO_OUTPUT}" -P "${CMAKE_CURRENT_BINARY_DIR}/scripts/gensrc.cmake" DEPENDS ${_GSO_DEPENDS} WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") endfunction() # Copy file function(generate_copy source destination) add_custom_command(OUTPUT "${destination}" COMMAND "${CMAKE_COMMAND}" -E remove "${destination}" COMMAND "${CMAKE_COMMAND}" -E copy "${source}" "${destination}" DEPENDS "${source}") endfunction() # Generate scripts/pnglibconf.h generate_source(OUTPUT "scripts/pnglibconf.c" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/scripts/pnglibconf.dfa" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/options.awk" "${CMAKE_CURRENT_SOURCE_DIR}/pngconf.h") # Generate pnglibconf.c generate_source(OUTPUT "pnglibconf.c" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/scripts/pnglibconf.dfa" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/options.awk" "${CMAKE_CURRENT_SOURCE_DIR}/pngconf.h") if(PNG_PREFIX) set(PNGLIBCONF_H_EXTRA_DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/scripts/prefix.out" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/macro.lst") set(PNGPREFIX_H_EXTRA_DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/scripts/intprefix.out") endif() generate_out(INPUT "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.c" OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.out") # Generate pnglibconf.h generate_source(OUTPUT "pnglibconf.h" DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.out" ${PNGLIBCONF_H_EXTRA_DEPENDS}) generate_out(INPUT "${CMAKE_CURRENT_SOURCE_DIR}/scripts/intprefix.c" OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/scripts/intprefix.out" DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.h") generate_out(INPUT "${CMAKE_CURRENT_SOURCE_DIR}/scripts/prefix.c" OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/scripts/prefix.out" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/png.h" "${CMAKE_CURRENT_SOURCE_DIR}/pngconf.h" "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.out") # Generate pngprefix.h generate_source(OUTPUT "pngprefix.h" DEPENDS ${PNGPREFIX_H_EXTRA_DEPENDS}) generate_out(INPUT "${CMAKE_CURRENT_SOURCE_DIR}/scripts/sym.c" OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/scripts/sym.out" DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.h") generate_out(INPUT "${CMAKE_CURRENT_SOURCE_DIR}/scripts/symbols.c" OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/scripts/symbols.out" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/png.h" "${CMAKE_CURRENT_SOURCE_DIR}/pngconf.h" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/pnglibconf.h.prebuilt") generate_out(INPUT "${CMAKE_CURRENT_SOURCE_DIR}/scripts/vers.c" OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/scripts/vers.out" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/png.h" "${CMAKE_CURRENT_SOURCE_DIR}/pngconf.h" "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.h") generate_chk(INPUT "${CMAKE_CURRENT_BINARY_DIR}/scripts/symbols.out" OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/scripts/symbols.chk" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/scripts/checksym.awk" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/symbols.def") add_custom_target(symbol-check DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/scripts/symbols.chk") generate_copy("${CMAKE_CURRENT_BINARY_DIR}/scripts/sym.out" "${CMAKE_CURRENT_BINARY_DIR}/libpng.sym") generate_copy("${CMAKE_CURRENT_BINARY_DIR}/scripts/vers.out" "${CMAKE_CURRENT_BINARY_DIR}/libpng.vers") add_custom_target(genvers DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/libpng.vers") add_custom_target(gensym DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/libpng.sym") add_custom_target("genprebuilt" COMMAND "${CMAKE_COMMAND}" "-DOUTPUT=scripts/pnglibconf.h.prebuilt" -P "${CMAKE_CURRENT_BINARY_DIR}/scripts/gensrc.cmake" WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") # A single target handles generation of all generated files. If # they are dependend upon separately by multiple targets, this # confuses parallel make (it would require a separate top-level # target for each file to track the dependencies properly). add_custom_target(genfiles DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/libpng.sym" "${CMAKE_CURRENT_BINARY_DIR}/libpng.vers" "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.c" "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.h" "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.out" "${CMAKE_CURRENT_BINARY_DIR}/pngprefix.h" "${CMAKE_CURRENT_BINARY_DIR}/scripts/intprefix.out" "${CMAKE_CURRENT_BINARY_DIR}/scripts/pnglibconf.c" "${CMAKE_CURRENT_BINARY_DIR}/scripts/prefix.out" "${CMAKE_CURRENT_BINARY_DIR}/scripts/sym.out" "${CMAKE_CURRENT_BINARY_DIR}/scripts/symbols.chk" "${CMAKE_CURRENT_BINARY_DIR}/scripts/symbols.out" "${CMAKE_CURRENT_BINARY_DIR}/scripts/vers.out") endif(NOT AWK) # OUR SOURCES set(libpng_public_hdrs png.h pngconf.h "${CMAKE_CURRENT_BINARY_DIR}/pnglibconf.h" ) set(libpng_private_hdrs pngpriv.h pngdebug.h pnginfo.h pngstruct.h ) if(AWK) list(APPEND libpng_private_hdrs "${CMAKE_CURRENT_BINARY_DIR}/pngprefix.h") endif() set(libpng_sources ${libpng_public_hdrs} ${libpng_private_hdrs} png.c pngerror.c pngget.c pngmem.c pngpread.c pngread.c pngrio.c pngrtran.c pngrutil.c pngset.c pngtrans.c pngwio.c pngwrite.c pngwtran.c pngwutil.c ) set(pngtest_sources pngtest.c ) set(pngvalid_sources contrib/libtests/pngvalid.c ) set(pngstest_sources contrib/libtests/pngstest.c ) set(pngunknown_sources contrib/libtests/pngunknown.c ) set(pngimage_sources contrib/libtests/pngimage.c ) set(pngfix_sources contrib/tools/pngfix.c ) set(png_fix_itxt_sources contrib/tools/png-fix-itxt.c ) if(MSVC) add_definitions(-D_CRT_SECURE_NO_DEPRECATE) endif(MSVC) if(PNG_DEBUG) add_definitions(-DPNG_DEBUG) endif() # NOW BUILD OUR TARGET include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${ZLIB_INCLUDE_DIR}) unset(PNG_LIB_TARGETS) if(PNG_SHARED) add_library(png SHARED ${libpng_sources}) set(PNG_LIB_TARGETS png) set_target_properties(png PROPERTIES OUTPUT_NAME ${PNG_LIB_NAME}) add_dependencies(png genfiles) if(MSVC) # msvc does not append 'lib' - do it here to have consistent name set_target_properties(png PROPERTIES PREFIX "lib") set_target_properties(png PROPERTIES IMPORT_PREFIX "lib") endif() target_link_libraries(png ${ZLIB_LIBRARY} ${M_LIBRARY}) if(UNIX AND AWK) if(HAVE_LD_VERSION_SCRIPT) set_target_properties(png PROPERTIES LINK_FLAGS "-Wl,--version-script='${CMAKE_CURRENT_BINARY_DIR}/libpng.vers'") elseif(HAVE_SOLARIS_LD_VERSION_SCRIPT) set_target_properties(png PROPERTIES LINK_FLAGS "-Wl,-M -Wl,'${CMAKE_CURRENT_BINARY_DIR}/libpng.vers'") endif() endif() endif() if(PNG_STATIC) # does not work without changing name set(PNG_LIB_NAME_STATIC png_static) add_library(png_static STATIC ${libpng_sources}) add_dependencies(png_static genfiles) # MSVC doesn't use a different file extension for shared vs. static # libs. We are able to change OUTPUT_NAME to remove the _static # for all other platforms. if(NOT MSVC) set_target_properties(png_static PROPERTIES OUTPUT_NAME "${PNG_LIB_NAME}" CLEAN_DIRECT_OUTPUT 1) else() set_target_properties(png_static PROPERTIES OUTPUT_NAME "${PNG_LIB_NAME}_static" CLEAN_DIRECT_OUTPUT 1) endif() list(APPEND PNG_LIB_TARGETS png_static) if(MSVC) # msvc does not append 'lib' - do it here to have consistent name set_target_properties(png_static PROPERTIES PREFIX "lib") endif() target_link_libraries(png_static ${ZLIB_LIBRARY} ${M_LIBRARY}) endif() if(PNG_FRAMEWORK) set(PNG_LIB_NAME_FRAMEWORK png_framework) add_library(png_framework SHARED ${libpng_sources}) add_dependencies(png_framework genfiles) list(APPEND PNG_LIB_TARGETS png_framework) set_target_properties(png_framework PROPERTIES FRAMEWORK TRUE FRAMEWORK_VERSION ${PNGLIB_VERSION} MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${PNGLIB_MAJOR}.${PNGLIB_MINOR} MACOSX_FRAMEWORK_BUNDLE_VERSION ${PNGLIB_VERSION} MACOSX_FRAMEWORK_IDENTIFIER org.libpng.libpng XCODE_ATTRIBUTE_INSTALL_PATH "@rpath" PUBLIC_HEADER "${libpng_public_hdrs}" OUTPUT_NAME png) target_link_libraries(png_framework ${ZLIB_LIBRARY} ${M_LIBRARY}) endif() if(NOT PNG_LIB_TARGETS) message(SEND_ERROR "No library variant selected to build. " "Please enable at least one of the following options: " " PNG_STATIC, PNG_SHARED, PNG_FRAMEWORK") endif() if(PNG_SHARED AND WIN32) set_target_properties(png PROPERTIES DEFINE_SYMBOL PNG_BUILD_DLL) endif() function(png_add_test) set(options) set(oneValueArgs NAME COMMAND) set(multiValueArgs OPTIONS FILES) cmake_parse_arguments(_PAT "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if (NOT _PAT_NAME) message(FATAL_ERROR "Invalid arguments. png_add_test requires name.") endif() if (NOT _PAT_COMMAND) message(FATAL_ERROR "Invalid arguments. png_add_test requires command.") endif() set(TEST_OPTIONS "${_PAT_OPTIONS}") set(TEST_FILES "${_PAT_FILES}") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/scripts/test.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/tests/${_PAT_NAME}.cmake" @ONLY) if(CMAKE_MAJOR_VERSION GREATER 2) # have generator expressions add_test(NAME "${_PAT_NAME}" COMMAND "${CMAKE_COMMAND}" "-DLIBPNG=$" "-DTEST_COMMAND=$" -P "${CMAKE_CURRENT_BINARY_DIR}/tests/${_PAT_NAME}.cmake") else() # old 2.x add_test; limited and won't work well on Windows # Note LIBPNG is a dummy value as there are no generator expressions add_test("${_PAT_NAME}" "${CMAKE_COMMAND}" "-DLIBPNG=${CMAKE_CURRENT_BINARY_DIR}/libpng.so" "-DTEST_COMMAND=./${_PAT_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/tests/${_PAT_NAME}.cmake") endif() endfunction() if(PNG_TESTS AND PNG_SHARED) # Find test PNG files by globbing, but sort lists to ensure # consistency between different filesystems. file(GLOB PNGSUITE_PNGS "${CMAKE_CURRENT_SOURCE_DIR}/contrib/pngsuite/*.png") list(SORT PNGSUITE_PNGS) file(GLOB TEST_PNGS "${CMAKE_CURRENT_SOURCE_DIR}/contrib/testpngs/*.png") list(SORT TEST_PNGS) set(PNGTEST_PNG "${CMAKE_CURRENT_SOURCE_DIR}/pngtest.png") add_executable(pngtest ${pngtest_sources}) target_link_libraries(pngtest png) png_add_test(NAME pngtest COMMAND pngtest FILES "${PNGTEST_PNG}") add_executable(pngvalid ${pngvalid_sources}) target_link_libraries(pngvalid png) png_add_test(NAME pngvalid-gamma-16-to-8 COMMAND pngvalid OPTIONS --gamma-16-to-8) png_add_test(NAME pngvalid-gamma-alpha-mode COMMAND pngvalid OPTIONS --gamma-alpha-mode) png_add_test(NAME pngvalid-gamma-background COMMAND pngvalid OPTIONS --gamma-background) png_add_test(NAME pngvalid-gamma-expand16-alpha-mode COMMAND pngvalid OPTIONS --gamma-alpha-mode --expand16) png_add_test(NAME pngvalid-gamma-expand16-background COMMAND pngvalid OPTIONS --gamma-background --expand16) png_add_test(NAME pngvalid-gamma-expand16-transform COMMAND pngvalid OPTIONS --gamma-transform --expand16) png_add_test(NAME pngvalid-gamma-sbit COMMAND pngvalid OPTIONS --gamma-sbit) png_add_test(NAME pngvalid-gamma-threshold COMMAND pngvalid OPTIONS --gamma-threshold) png_add_test(NAME pngvalid-gamma-transform COMMAND pngvalid OPTIONS --gamma-transform) png_add_test(NAME pngvalid-progressive-interlace-standard COMMAND pngvalid OPTIONS --standard --progressive-read --interlace) png_add_test(NAME pngvalid-progressive-size COMMAND pngvalid OPTIONS --size --progressive-read) png_add_test(NAME pngvalid-progressive-standard COMMAND pngvalid OPTIONS --standard --progressive-read) png_add_test(NAME pngvalid-standard COMMAND pngvalid OPTIONS --standard) png_add_test(NAME pngvalid-transform COMMAND pngvalid OPTIONS --transform) add_executable(pngstest ${pngstest_sources}) target_link_libraries(pngstest png) foreach(gamma_type 1.8 linear none sRGB) foreach(alpha_type none alpha) set(PNGSTEST_FILES) foreach(test_png ${TEST_PNGS}) string(REGEX MATCH ".*-linear[-.].*" TEST_PNG_LINEAR "${test_png}") string(REGEX MATCH ".*-sRGB[-.].*" TEST_PNG_SRGB "${test_png}") string(REGEX MATCH ".*-1.8[-.].*" TEST_PNG_G18 "${test_png}") string(REGEX MATCH ".*-alpha-.*" TEST_PNG_ALPHA "${test_png}") set(TEST_PNG_VALID TRUE) if(TEST_PNG_ALPHA) if (NOT "${alpha_type}" STREQUAL "alpha") set(TEST_PNG_VALID FALSE) endif() else() if ("${alpha_type}" STREQUAL "alpha") set(TEST_PNG_VALID FALSE) endif() endif() if(TEST_PNG_LINEAR) if(NOT "${gamma_type}" STREQUAL "linear") set(TEST_PNG_VALID FALSE) endif() elseif(TEST_PNG_SRGB) if(NOT "${gamma_type}" STREQUAL "sRGB") set(TEST_PNG_VALID FALSE) endif() elseif(TEST_PNG_G18) if(NOT "${gamma_type}" STREQUAL "1.8") set(TEST_PNG_VALID FALSE) endif() else() if(NOT "${gamma_type}" STREQUAL "none") set(TEST_PNG_VALID FALSE) endif() endif() if(TEST_PNG_VALID) list(APPEND PNGSTEST_FILES "${test_png}") endif() endforeach() # Should already be sorted, but sort anyway to be certain. list(SORT PNGSTEST_FILES) png_add_test(NAME pngstest-${gamma_type}-${alpha_type} COMMAND pngstest OPTIONS --tmpfile "${gamma_type}-${alpha_type}-" --log FILES ${PNGSTEST_FILES}) endforeach() endforeach() add_executable(pngunknown ${pngunknown_sources}) target_link_libraries(pngunknown png) png_add_test(NAME pngunknown-discard COMMAND pngunknown OPTIONS --strict default=discard FILES "${PNGTEST_PNG}") png_add_test(NAME pngunknown-IDAT COMMAND pngunknown OPTIONS --strict default=discard IDAT=save FILES "${PNGTEST_PNG}") png_add_test(NAME pngunknown-if-safe COMMAND pngunknown OPTIONS --strict default=if-safe FILES "${PNGTEST_PNG}") png_add_test(NAME pngunknown-sAPI COMMAND pngunknown OPTIONS --strict bKGD=save cHRM=save gAMA=save all=discard iCCP=save sBIT=save sRGB=save FILES "${PNGTEST_PNG}") png_add_test(NAME pngunknown-save COMMAND pngunknown OPTIONS --strict default=save FILES "${PNGTEST_PNG}") png_add_test(NAME pngunknown-sTER COMMAND pngunknown OPTIONS --strict sTER=if-safe FILES "${PNGTEST_PNG}") png_add_test(NAME pngunknown-vpAg COMMAND pngunknown OPTIONS --strict vpAg=if-safe FILES "${PNGTEST_PNG}") add_executable(pngimage ${pngimage_sources}) target_link_libraries(pngimage png) png_add_test(NAME pngimage-quick COMMAND pngimage OPTIONS --list-combos --log FILES ${PNGSUITE_PNGS}) png_add_test(NAME pngimage-full COMMAND pngimage OPTIONS --exhaustive --list-combos --log FILES ${PNGSUITE_PNGS}) endif() if(PNG_SHARED) add_executable(pngfix ${pngfix_sources}) target_link_libraries(pngfix png) set(PNG_BIN_TARGETS pngfix) add_executable(png-fix-itxt ${png_fix_itxt_sources}) target_link_libraries(png-fix-itxt ${ZLIB_LIBRARY} ${M_LIBRARY}) list(APPEND PNG_BIN_TARGETS png-fix-itxt) endif() # Ensure the CMAKE_LIBRARY_OUTPUT_DIRECTORY is set IF(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY "lib") ENDIF(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) # Set a variable with CMake code which: # Creates a symlink from src to dest (if possible) or alternatively # copies if different. macro(CREATE_SYMLINK SRC_FILE DEST_FILE) FILE(REMOVE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${DEST_FILE}) if(WIN32 AND NOT CYGWIN AND NOT MSYS) ADD_CUSTOM_COMMAND( OUTPUT ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${DEST_FILE} ${CMAKE_CURRENT_BINARY_DIR}/${DEST_FILE} COMMAND ${CMAKE_COMMAND} -E copy_if_different "${SRC_FILE}" ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${DEST_FILE} COMMAND ${CMAKE_COMMAND} -E copy_if_different "${SRC_FILE}" ${CMAKE_CURRENT_BINARY_DIR}/${DEST_FILE} DEPENDS ${PNG_LIB_TARGETS} ) ADD_CUSTOM_TARGET(${DEST_FILE}_COPY ALL DEPENDS ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${DEST_FILE}) else(WIN32 AND NOT CYGWIN AND NOT MSYS) get_filename_component(LINK_TARGET "${SRC_FILE}" NAME) execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink "${LINK_TARGET}" ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${DEST_FILE} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink "${LINK_TARGET}" ${DEST_FILE} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) endif(WIN32 AND NOT CYGWIN AND NOT MSYS) endmacro() # Create source generation scripts. configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/genchk.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/scripts/genchk.cmake @ONLY) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/genout.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/scripts/genout.cmake @ONLY) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/gensrc.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/scripts/gensrc.cmake @ONLY) # libpng is a library so default to 'lib' if(NOT DEFINED CMAKE_INSTALL_LIBDIR) set(CMAKE_INSTALL_LIBDIR lib) endif(NOT DEFINED CMAKE_INSTALL_LIBDIR) # CREATE PKGCONFIG FILES # we use the same files like ./configure, so we have to set its vars # Only do this on Windows for Cygwin - the files don't make much sense outside # a UNIX look alike if(NOT WIN32 OR CYGWIN OR MINGW) set(prefix ${CMAKE_INSTALL_PREFIX}) set(exec_prefix ${CMAKE_INSTALL_PREFIX}) set(libdir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}) set(includedir ${CMAKE_INSTALL_PREFIX}/include) set(LIBS "-lz -lm") configure_file(${CMAKE_CURRENT_SOURCE_DIR}/libpng.pc.in ${CMAKE_CURRENT_BINARY_DIR}/${PNGLIB_NAME}.pc @ONLY) CREATE_SYMLINK(${PNGLIB_NAME}.pc libpng.pc) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/libpng-config.in ${CMAKE_CURRENT_BINARY_DIR}/${PNGLIB_NAME}-config @ONLY) CREATE_SYMLINK(${PNGLIB_NAME}-config libpng-config) endif(NOT WIN32 OR CYGWIN OR MINGW) # SET UP LINKS if(PNG_SHARED) set_target_properties(png PROPERTIES # VERSION 16.${PNGLIB_RELEASE}.1.6.25 VERSION 16.${PNGLIB_RELEASE}.0 SOVERSION 16 CLEAN_DIRECT_OUTPUT 1) endif() # If CMake > 2.4.x, we set a variable used below to export # targets to an export file. # TODO: Use VERSION_GREATER after our cmake_minimum_required >= 2.6.2 if(CMAKE_MAJOR_VERSION GREATER 1 AND CMAKE_MINOR_VERSION GREATER 4) set(PNG_EXPORT_RULE EXPORT libpng) elseif(CMAKE_MAJOR_VERSION GREATER 2) # future proof set(PNG_EXPORT_RULE EXPORT libpng) endif() # INSTALL if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL ) install(TARGETS ${PNG_LIB_TARGETS} ${PNG_EXPORT_RULE} RUNTIME DESTINATION bin LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} FRAMEWORK DESTINATION ${CMAKE_INSTALL_LIBDIR}) if(PNG_SHARED) # Create a symlink for libpng.dll.a => libpng16.dll.a on Cygwin if(CYGWIN OR MINGW) get_target_property(BUILD_TARGET_LOCATION png LOCATION_${CMAKE_BUILD_TYPE}) CREATE_SYMLINK(${BUILD_TARGET_LOCATION} libpng${CMAKE_IMPORT_LIBRARY_SUFFIX}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libpng${CMAKE_IMPORT_LIBRARY_SUFFIX} DESTINATION ${CMAKE_INSTALL_LIBDIR}) endif(CYGWIN OR MINGW) if(NOT WIN32) get_target_property(BUILD_TARGET_LOCATION png LOCATION_${CMAKE_BUILD_TYPE}) CREATE_SYMLINK(${BUILD_TARGET_LOCATION} libpng${CMAKE_SHARED_LIBRARY_SUFFIX}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libpng${CMAKE_SHARED_LIBRARY_SUFFIX} DESTINATION ${CMAKE_INSTALL_LIBDIR}) endif(NOT WIN32) endif(PNG_SHARED) if(PNG_STATIC) if(NOT WIN32 OR CYGWIN OR MINGW) get_target_property(BUILD_TARGET_LOCATION png_static LOCATION_${CMAKE_BUILD_TYPE}) CREATE_SYMLINK(${BUILD_TARGET_LOCATION} libpng${CMAKE_STATIC_LIBRARY_SUFFIX}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libpng${CMAKE_STATIC_LIBRARY_SUFFIX} DESTINATION ${CMAKE_INSTALL_LIBDIR}) endif(NOT WIN32 OR CYGWIN OR MINGW) endif() endif() if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL ) install(FILES ${libpng_public_hdrs} DESTINATION include) install(FILES ${libpng_public_hdrs} DESTINATION include/${PNGLIB_NAME}) endif() if(NOT SKIP_INSTALL_EXECUTABLES AND NOT SKIP_INSTALL_ALL ) if(NOT WIN32 OR CYGWIN OR MINGW) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/libpng-config DESTINATION bin) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${PNGLIB_NAME}-config DESTINATION bin) endif(NOT WIN32 OR CYGWIN OR MINGW) endif() if(NOT SKIP_INSTALL_PROGRAMS AND NOT SKIP_INSTALL_ALL ) install(TARGETS ${PNG_BIN_TARGETS} RUNTIME DESTINATION bin) endif() if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) # Install man pages if(NOT PNG_MAN_DIR) set(PNG_MAN_DIR "share/man") endif() install(FILES libpng.3 libpngpf.3 DESTINATION ${PNG_MAN_DIR}/man3) install(FILES png.5 DESTINATION ${PNG_MAN_DIR}/man5) # Install pkg-config files if(NOT WIN32 OR CYGWIN OR MINGW) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libpng.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/libpng-config DESTINATION bin) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PNGLIB_NAME}.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${PNGLIB_NAME}-config DESTINATION bin) endif(NOT WIN32 OR CYGWIN OR MINGW) endif() # On versions of CMake that support it, create an export file CMake # users can include() to import our targets if(PNG_EXPORT_RULE AND NOT SKIP_INSTALL_EXPORT AND NOT SKIP_INSTALL_ALL ) install(EXPORT libpng DESTINATION lib/libpng FILE lib${PNG_LIB_NAME}.cmake) endif() # what's with libpng-manual.txt and all the extra files? # UNINSTALL # do we need this? # DIST # do we need this? # to create msvc import lib for mingw compiled shared lib # pexports libpng.dll > libpng.def # lib /def:libpng.def /machine:x86 ================================================ FILE: tess-two/jni/libpng/CleanSpec.mk ================================================ # Copyright (C) 2007 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # If you don't need to do a full clean build but would like to touch # a file or delete some intermediate files, add a clean step to the end # of the list. These steps will only be run once, if they haven't been # run before. # # E.g.: # $(call add-clean-step, touch -c external/sqlite/sqlite3.h) # $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates) # # Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with # files that are missing or have been moved. # # Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory. # Use $(OUT_DIR) to refer to the "out" directory. # # If you need to re-do something that's already mentioned, just copy # the command and add it to the bottom of the list. E.g., if a change # that you made last week required touching a file and a change you # made today requires touching the same file, just copy the old # touch step and add it to the end of the list. # # ************************************************ # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST # ************************************************ # For example: #$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates) #$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates) #$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f) #$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*) # ************************************************ # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST # ************************************************ ================================================ FILE: tess-two/jni/libpng/INSTALL ================================================ Installing libpng Contents I. Simple installation II. Rebuilding the configure scripts III. Using scripts/makefile* IV. Using cmake V. Directory structure VI. Building with project files VII. Building with makefiles VIII. Configuring libpng for 16-bit platforms IX. Configuring for DOS X. Configuring for Medium Model XI. Prepending a prefix to exported symbols XII. Configuring for compiler xxx: XIII. Removing unwanted object code XIV. Changes to the build and configuration of libpng in libpng-1.5.x XV. Setjmp/longjmp issues XVI. Common linking failures XVII. Other sources of information about libpng I. Simple installation On Unix/Linux and similar systems, you can simply type ./configure [--prefix=/path] make check make install and ignore the rest of this document. "/path" is the path to the directory where you want to install the libpng "lib", "include", and "bin" subdirectories. If you downloaded a GIT clone, you will need to run ./autogen.sh before running ./configure, to create "configure" and "Makefile.in" which are not included in the GIT repository. Note that "configure" is only included in the "*.tar" distributions and not in the "*.zip" or "*.7z" distributions. If you downloaded one of those distributions, see "Building with project files" or "Building with makefiles", below. II. Rebuilding the configure scripts If configure does not work on your system, or if you have a need to change configure.ac or Makefile.am, and you have a reasonably up-to-date set of tools, running ./autogen.sh in a git clone before running ./configure may fix the problem. To be really sure that you aren't using any of the included pre-built scripts, especially if you are building from a tar distribution instead of a git distribution, do this: ./configure --enable-maintainer-mode make maintainer-clean ./autogen.sh --maintainer --clean ./autogen.sh --maintainer ./configure [--prefix=/path] [other options] make make install make check III. Using scripts/makefile* Instead, you can use one of the custom-built makefiles in the "scripts" directory cp scripts/pnglibconf.h.prebuilt pnglibconf.h cp scripts/makefile.system makefile make test make install The files that are presently available in the scripts directory are listed and described in scripts/README.txt. Or you can use one of the "projects" in the "projects" directory. Before installing libpng, you must first install zlib, if it is not already on your system. zlib can usually be found wherever you got libpng; otherwise go to http://zlib.net. You can place zlib in the same directory as libpng or in another directory. If your system already has a preinstalled zlib you will still need to have access to the zlib.h and zconf.h include files that correspond to the version of zlib that's installed. If you wish to test with a particular zlib that is not first in the standard library search path, put ZLIBLIB, ZLIBINC, CPPFLAGS, LDFLAGS, and LD_LIBRARY_PATH in your environment before running "make test" or "make distcheck": ZLIBLIB=/path/to/lib export ZLIBLIB ZLIBINC=/path/to/include export ZLIBINC CPPFLAGS="-I$ZLIBINC" export CPPFLAGS LDFLAGS="-L$ZLIBLIB" export LDFLAGS LD_LIBRARY_PATH="$ZLIBLIB:$LD_LIBRARY_PATH" export LD_LIBRARY_PATH If you are using one of the makefile scripts, put ZLIBLIB and ZLIBINC in your environment and type make ZLIBLIB=$ZLIBLIB ZLIBINC=$ZLIBINC test IV. Using cmake If you want to use "cmake" (see www.cmake.org), type cmake . -DCMAKE_INSTALL_PREFIX=/path make make install As when using the simple configure method described above, "/path" points to the installation directory where you want to put the libpng "lib", "include", and "bin" subdirectories. V. Directory structure You can rename the directories that you downloaded (they might be called "libpng-x.y.z" or "libpngNN" and "zlib-1.2.8" or "zlib128") so that you have directories called "zlib" and "libpng". Your directory structure should look like this: .. (the parent directory) libpng (this directory) INSTALL (this file) README *.h, *.c => libpng source files CMakeLists.txt => "cmake" script configuration files: configure.ac, configure, Makefile.am, Makefile.in, autogen.sh, config.guess, ltmain.sh, missing, libpng.pc.in, libpng-config.in, aclocal.m4, config.h.in, config.sub, depcomp, install-sh, mkinstalldirs, test-pngtest.sh contrib arm-neon, conftest, examples, gregbook, libtests, pngminim, pngminus, pngsuite, tools, visupng projects cbuilder5, owatcom, visualc71, vstudio, xcode scripts makefile.* *.def (module definition files) etc. pngtest.png etc. zlib README, *.h, *.c contrib, etc. If the line endings in the files look funny, you may wish to get the other distribution of libpng. It is available in both tar.gz (UNIX style line endings) and zip (DOS style line endings) formats. VI. Building with project files If you are building libpng with MSVC, you can enter the libpng projects\visualc71 or vstudio directory and follow the instructions in README.txt. Otherwise enter the zlib directory and follow the instructions in zlib/README, then come back here and run "configure" or choose the appropriate makefile.sys in the scripts directory. VII. Building with makefiles Copy the file (or files) that you need from the scripts directory into this directory, for example MSDOS example: copy scripts\makefile.msc makefile copy scripts\pnglibconf.h.prebuilt pnglibconf.h UNIX example: cp scripts/makefile.std makefile cp scripts/pnglibconf.h.prebuilt pnglibconf.h Read the makefile to see if you need to change any source or target directories to match your preferences. Then read pnglibconf.dfa to see if you want to make any configuration changes. Then just run "make" which will create the libpng library in this directory and "make test" which will run a quick test that reads the "pngtest.png" file and writes a "pngout.png" file that should be identical to it. Look for "9782 zero samples" in the output of the test. For more confidence, you can run another test by typing "pngtest pngnow.png" and looking for "289 zero samples" in the output. Also, you can run "pngtest -m contrib/pngsuite/*.png" and compare your output with the result shown in contrib/pngsuite/README. Most of the makefiles will allow you to run "make install" to put the library in its final resting place (if you want to do that, run "make install" in the zlib directory first if necessary). Some also allow you to run "make test-installed" after you have run "make install". VIII. Configuring libpng for 16-bit platforms You will want to look into zconf.h to tell zlib (and thus libpng) that it cannot allocate more than 64K at a time. Even if you can, the memory won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K. IX. Configuring for DOS For DOS users who only have access to the lower 640K, you will have to limit zlib's memory usage via a png_set_compression_mem_level() call. See zlib.h or zconf.h in the zlib library for more information. X. Configuring for Medium Model Libpng's support for medium model has been tested on most of the popular compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets defined, and FAR gets defined to far in pngconf.h, and you should be all set. Everything in the library (except for zlib's structure) is expecting far data. You must use the typedefs with the p or pp on the end for pointers (or at least look at them and be careful). Make note that the rows of data are defined as png_bytepp, which is an "unsigned char far * far *". XI. Prepending a prefix to exported symbols Starting with libpng-1.6.0, you can configure libpng (when using the "configure" script) to prefix all exported symbols by means of the configuration option "--with-libpng-prefix=FOO_", where FOO_ can be any string beginning with a letter and containing only uppercase and lowercase letters, digits, and the underscore (i.e., a C language identifier). This creates a set of macros in pnglibconf.h, so this is transparent to applications; their function calls get transformed by the macros to use the modified names. XII. Configuring for compiler xxx: All includes for libpng are in pngconf.h. If you need to add, change or delete an include, this is the place to do it. The includes that are not needed outside libpng are placed in pngpriv.h, which is only used by the routines inside libpng itself. The files in libpng proper only include pngpriv.h and png.h, which in turn includes pngconf.h and, as of libpng-1.5.0, pnglibconf.h. As of libpng-1.5.0, pngpriv.h also includes three other private header files, pngstruct.h, pnginfo.h, and pngdebug.h, which contain material that previously appeared in the public headers. XIII. Removing unwanted object code There are a bunch of #define's in pngconf.h that control what parts of libpng are compiled. All the defines end in _SUPPORTED. If you are never going to use a capability, you can change the #define to #undef before recompiling libpng and save yourself code and data space, or you can turn off individual capabilities with defines that begin with "PNG_NO_". In libpng-1.5.0 and later, the #define's are in pnglibconf.h instead. You can also turn all of the transforms and ancillary chunk capabilities off en masse with compiler directives that define PNG_NO_READ[or WRITE]_TRANSFORMS, or PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS, or all four, along with directives to turn on any of the capabilities that you do want. The PNG_NO_READ[or WRITE]_TRANSFORMS directives disable the extra transformations but still leave the library fully capable of reading and writing PNG files with all known public chunks. Use of the PNG_NO_READ[or WRITE]_ANCILLARY_CHUNKS directive produces a library that is incapable of reading or writing ancillary chunks. If you are not using the progressive reading capability, you can turn that off with PNG_NO_PROGRESSIVE_READ (don't confuse this with the INTERLACING capability, which you'll still have). All the reading and writing specific code are in separate files, so the linker should only grab the files it needs. However, if you want to make sure, or if you are building a stand alone library, all the reading files start with "pngr" and all the writing files start with "pngw". The files that don't match either (like png.c, pngtrans.c, etc.) are used for both reading and writing, and always need to be included. The progressive reader is in pngpread.c If you are creating or distributing a dynamically linked library (a .so or DLL file), you should not remove or disable any parts of the library, as this will cause applications linked with different versions of the library to fail if they call functions not available in your library. The size of the library itself should not be an issue, because only those sections that are actually used will be loaded into memory. XIV. Changes to the build and configuration of libpng in libpng-1.5.x Details of internal changes to the library code can be found in the CHANGES file and in the GIT repository logs. These will be of no concern to the vast majority of library users or builders; however, the few who configure libpng to a non-default feature set may need to change how this is done. There should be no need for library builders to alter build scripts if these use the distributed build support - configure or the makefiles - however, users of the makefiles may care to update their build scripts to build pnglibconf.h where the corresponding makefile does not do so. Building libpng with a non-default configuration has changed completely. The old method using pngusr.h should still work correctly even though the way pngusr.h is used in the build has been changed; however, library builders will probably want to examine the changes to take advantage of new capabilities and to simplify their build system. A. Specific changes to library configuration capabilities The exact mechanism used to control attributes of API functions has changed. A single set of operating system independent macro definitions is used and operating system specific directives are defined in pnglibconf.h As part of this the mechanism used to choose procedure call standards on those systems that allow a choice has been changed. At present this only affects certain Microsoft (DOS, Windows) and IBM (OS/2) operating systems running on Intel processors. As before, PNGAPI is defined where required to control the exported API functions; however, two new macros, PNGCBAPI and PNGCAPI, are used instead for callback functions (PNGCBAPI) and (PNGCAPI) for functions that must match a C library prototype (currently only png_longjmp_ptr, which must match the C longjmp function.) The new approach is documented in pngconf.h Despite these changes, libpng 1.5.0 only supports the native C function calling standard on those platforms tested so far ("__cdecl" on Microsoft Windows). This is because the support requirements for alternative calling conventions seem to no longer exist. Developers who find it necessary to set PNG_API_RULE to 1 should advise the mailing list (png-mng-implement) of this and library builders who use Openwatcom and therefore set PNG_API_RULE to 2 should also contact the mailing list. B. Changes to the configuration mechanism Prior to libpng-1.5.0 library builders who needed to configure libpng had either to modify the exported pngconf.h header file to add system specific configuration or had to write feature selection macros into pngusr.h and cause this to be included into pngconf.h by defining PNG_USER_CONFIG. The latter mechanism had the disadvantage that an application built without PNG_USER_CONFIG defined would see the unmodified, default, libpng API and thus would probably fail to link. These mechanisms still work in the configure build and in any makefile build that builds pnglibconf.h, although the feature selection macros have changed somewhat as described above. In 1.5.0, however, pngusr.h is processed only once, at the time the exported header file pnglibconf.h is built. pngconf.h no longer includes pngusr.h; therefore, pngusr.h is ignored after the build of pnglibconf.h and it is never included in an application build. The formerly used alternative of adding a list of feature macros to the CPPFLAGS setting in the build also still works; however, the macros will be copied to pnglibconf.h and this may produce macro redefinition warnings when the individual C files are compiled. All configuration now only works if pnglibconf.h is built from scripts/pnglibconf.dfa. This requires the program awk. Brian Kernighan (the original author of awk) maintains C source code of that awk and this and all known later implementations (often called by subtly different names - nawk and gawk for example) are adequate to build pnglibconf.h. The Sun Microsystems (now Oracle) program 'awk' is an earlier version and does not work; this may also apply to other systems that have a functioning awk called 'nawk'. Configuration options are now documented in scripts/pnglibconf.dfa. This file also includes dependency information that ensures a configuration is consistent; that is, if a feature is switched off, dependent features are also switched off. As a recommended alternative to using feature macros in pngusr.h a system builder may also define equivalent options in pngusr.dfa (or, indeed, any file) and add that to the configuration by setting DFA_XTRA to the file name. The makefiles in contrib/pngminim illustrate how to do this, and also illustrate a case where pngusr.h is still required. After you have built libpng, the definitions that were recorded in pnglibconf.h are available to your application (pnglibconf.h is included in png.h and gets installed alongside png.h and pngconf.h in your $PREFIX/include directory). Do not edit pnglibconf.h after you have built libpng, because than the settings would not accurately reflect the settings that were used to build libpng. XV. Setjmp/longjmp issues Libpng uses setjmp()/longjmp() for error handling. Unfortunately setjmp() is known to be not thread-safe on some platforms and we don't know of any platform where it is guaranteed to be thread-safe. Therefore, if your application is going to be using multiple threads, you should configure libpng with PNG_NO_SETJMP in your pngusr.dfa file, with -DPNG_NO_SETJMP on your compile line, or with #undef PNG_SETJMP_SUPPORTED in your pnglibconf.h or pngusr.h. Starting with libpng-1.6.0, the library included a "simplified API". This requires setjmp/longjmp, so you must either build the library with PNG_SETJMP_SUPPORTED defined, or with PNG_SIMPLIFIED_READ_SUPPORTED and PNG_SIMPLIFIED_WRITE_SUPPORTED undefined. XVI. Common linking failures If your application fails to find libpng or zlib entries while linking: Be sure "-lz" appears after "-lpng" on your linking command. Be sure you have built libpng, zlib, and your application for the same platform (e.g., 32-bit or 64-bit). If you are using the vstudio project, observe the WARNING in project/vstudio/README.txt. XVII. Other sources of information about libpng: Further information can be found in the README and libpng-manual.txt files, in the individual makefiles, in png.h, and the manual pages libpng.3 and png.5. Copyright (c) 1998-2002,2006-2016 Glenn Randers-Pehrson This document is released under the libpng license. For conditions of distribution and use, see the disclaimer and license in png.h. ================================================ FILE: tess-two/jni/libpng/LICENSE ================================================ This copy of the libpng notices is provided for your convenience. In case of any discrepancy between this copy and the notices in the file png.h that is included in the libpng distribution, the latter shall prevail. COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: If you modify libpng you may insert additional notices immediately following this sentence. This code is released under the libpng license. libpng versions 1.0.7, July 1, 2000 through 1.6.25, September 1, 2016 are Copyright (c) 2000-2002, 2004, 2006-2016 Glenn Randers-Pehrson, are derived from libpng-1.0.6, and are distributed according to the same disclaimer and license as libpng-1.0.6 with the following individuals added to the list of Contributing Authors: Simon-Pierre Cadieux Eric S. Raymond Mans Rullgard Cosmin Truta Gilles Vollant James Yu and with the following additions to the disclaimer: There is no warranty against interference with your enjoyment of the library or against infringement. There is no warranty that our efforts or the library will fulfill any of your particular purposes or needs. This library is provided with all faults, and the entire risk of satisfactory quality, performance, accuracy, and effort is with the user. Some files in the "contrib" directory and some configure-generated files that are distributed with libpng have other copyright owners and are released under other open source licenses. libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from libpng-0.96, and are distributed according to the same disclaimer and license as libpng-0.96, with the following individuals added to the list of Contributing Authors: Tom Lane Glenn Randers-Pehrson Willem van Schaik libpng versions 0.89, June 1996, through 0.96, May 1997, are Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, and are distributed according to the same disclaimer and license as libpng-0.88, with the following individuals added to the list of Contributing Authors: John Bowler Kevin Bracey Sam Bushell Magnus Holmgren Greg Roelofs Tom Tanner Some files in the "scripts" directory have other copyright owners but are released under this license. libpng versions 0.5, May 1995, through 0.88, January 1996, are Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. For the purposes of this copyright and license, "Contributing Authors" is defined as the following set of individuals: Andreas Dilger Dave Martindale Guy Eric Schalnat Paul Schmidt Tim Wegner The PNG Reference Library is supplied "AS IS". The Contributing Authors and Group 42, Inc. disclaim all warranties, expressed or implied, including, without limitation, the warranties of merchantability and of fitness for any purpose. The Contributing Authors and Group 42, Inc. assume no liability for direct, indirect, incidental, special, exemplary, or consequential damages, which may result from the use of the PNG Reference Library, even if advised of the possibility of such damage. Permission is hereby granted to use, copy, modify, and distribute this source code, or portions hereof, for any purpose, without fee, subject to the following restrictions: 1. The origin of this source code must not be misrepresented. 2. Altered versions must be plainly marked as such and must not be misrepresented as being the original source. 3. This Copyright notice may not be removed or altered from any source or altered source distribution. The Contributing Authors and Group 42, Inc. specifically permit, without fee, and encourage the use of this source code as a component to supporting the PNG file format in commercial products. If you use this source code in a product, acknowledgment is not required but would be appreciated. END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE. TRADEMARK: The name "libpng" has not been registered by the Copyright owner as a trademark in any jurisdiction. However, because libpng has been distributed and maintained world-wide, continually since 1995, the Copyright owner claims "common-law trademark protection" in any jurisdiction where common-law trademark is recognized. OSI CERTIFICATION: Libpng is OSI Certified Open Source Software. OSI Certified Open Source is a certification mark of the Open Source Initiative. OSI has not addressed the additional disclaimers inserted at version 1.0.7. EXPORT CONTROL: The Copyright owner believes that the Export Control Classification Number (ECCN) for libpng is EAR99, which means not subject to export controls or International Traffic in Arms Regulations (ITAR) because it is open source, publicly available software, that does not contain any encryption software. See the EAR, paragraphs 734.3(b)(3) and 734.7(b). Glenn Randers-Pehrson glennrp at users.sourceforge.net September 1, 2016 ================================================ FILE: tess-two/jni/libpng/MODULE_LICENSE_BSD_LIKE ================================================ ================================================ FILE: tess-two/jni/libpng/Makefile.am ================================================ # Makefile.am, the source file for Makefile.in (and hence Makefile), is # # Copyright (c) 2004-2016 Glenn Randers-Pehrson # Last changed in libpng 1.6.25 [September 1, 2016] # # This code is released under the libpng license. # For conditions of distribution and use, see the disclaimer # and license in png.h PNGLIB_BASENAME= libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@ ACLOCAL_AMFLAGS = -I scripts # test programs - run on make check, make distcheck check_PROGRAMS= pngtest pngunknown pngstest pngvalid pngimage pngcp if HAVE_CLOCK_GETTIME check_PROGRAMS += timepng endif # Utilities - installed bin_PROGRAMS= pngfix png-fix-itxt # This ensures that pnglibconf.h gets built at the start of 'make all' or # 'make check', but it does not add dependencies to the individual programs, # this is done below. # # IMPORTANT: always add the object modules of new programs to the list below # because otherwise the sequence 'configure; make new-program' will *sometimes* # result in the installed (system) pnglibconf.h being used and the result is # always wrong and always very confusing. BUILT_SOURCES = pnglibconf.h pngtest_SOURCES = pngtest.c pngtest_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la pngvalid_SOURCES = contrib/libtests/pngvalid.c pngvalid_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la pngstest_SOURCES = contrib/libtests/pngstest.c pngstest_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la pngunknown_SOURCES = contrib/libtests/pngunknown.c pngunknown_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la pngimage_SOURCES = contrib/libtests/pngimage.c pngimage_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la timepng_SOURCES = contrib/libtests/timepng.c timepng_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la pngfix_SOURCES = contrib/tools/pngfix.c pngfix_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la png_fix_itxt_SOURCES = contrib/tools/png-fix-itxt.c pngcp_SOURCES = contrib/tools/pngcp.c pngcp_LDADD = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la # Generally these are single line shell scripts to run a test with a particular # set of parameters: TESTS =\ tests/pngtest\ tests/pngvalid-gamma-16-to-8 tests/pngvalid-gamma-alpha-mode\ tests/pngvalid-gamma-background tests/pngvalid-gamma-expand16-alpha-mode\ tests/pngvalid-gamma-expand16-background\ tests/pngvalid-gamma-expand16-transform tests/pngvalid-gamma-sbit\ tests/pngvalid-gamma-threshold tests/pngvalid-gamma-transform\ tests/pngvalid-progressive-size\ tests/pngvalid-progressive-interlace-standard\ tests/pngvalid-transform\ tests/pngvalid-progressive-standard tests/pngvalid-standard\ tests/pngstest-1.8 tests/pngstest-1.8-alpha tests/pngstest-linear\ tests/pngstest-linear-alpha tests/pngstest-none tests/pngstest-none-alpha\ tests/pngstest-sRGB tests/pngstest-sRGB-alpha tests/pngunknown-IDAT\ tests/pngunknown-discard tests/pngunknown-if-safe tests/pngunknown-sAPI\ tests/pngunknown-sTER tests/pngunknown-save tests/pngunknown-vpAg\ tests/pngimage-quick tests/pngimage-full # man pages dist_man_MANS= libpng.3 libpngpf.3 png.5 # generate the -config scripts if required binconfigs= libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@-config EXTRA_SCRIPTS= libpng-config libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@-config bin_SCRIPTS= @binconfigs@ # rules to build libpng, only build the old library on request lib_LTLIBRARIES=libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.la # EXTRA_LTLIBRARIES= libpng.la libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES = png.c pngerror.c\ pngget.c pngmem.c pngpread.c pngread.c pngrio.c pngrtran.c pngrutil.c\ pngset.c pngtrans.c pngwio.c pngwrite.c pngwtran.c pngwutil.c\ png.h pngconf.h pngdebug.h pnginfo.h pngpriv.h pngstruct.h pngusr.dfa if PNG_ARM_NEON libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES += arm/arm_init.c\ arm/filter_neon.S arm/filter_neon_intrinsics.c endif if PNG_MIPS_MSA libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES += mips/mips_init.c\ mips/filter_msa_intrinsics.c endif if PNG_INTEL_SSE libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES += contrib/intel/intel_init.c\ contrib/intel/filter_sse2_intrinsics.c endif nodist_libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES = pnglibconf.h libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_LDFLAGS = -no-undefined -export-dynamic \ -version-number @PNGLIB_MAJOR@@PNGLIB_MINOR@:@PNGLIB_RELEASE@:0 if HAVE_LD_VERSION_SCRIPT # Versioned symbols and restricted exports if HAVE_SOLARIS_LD libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_LDFLAGS += -Wl,-M -Wl,libpng.vers else libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_LDFLAGS += -Wl,--version-script=libpng.vers endif libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_DEPENDENCIES = libpng.vers else # Only restricted exports when possible libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_LDFLAGS += -export-symbols libpng.sym libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_DEPENDENCIES = libpng.sym endif #distribute headers in /usr/include/libpng/* pkgincludedir= $(includedir)/$(PNGLIB_BASENAME) pkginclude_HEADERS= png.h pngconf.h nodist_pkginclude_HEADERS= pnglibconf.h # pkg-config stuff, note that libpng.pc is always required in order # to get the correct library pkgconfigdir = @pkgconfigdir@ pkgconfig_DATA = libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.pc # Extra source distribution files, '${srcdir}' is used below to stop build files # from those directories being included. This only works if the configure is # not done in the source directory! EXTRA_DIST= \ ANNOUNCE CHANGES INSTALL LICENSE README TODO \ pngtest.png pngbar.png pngnow.png pngbar.jpg autogen.sh \ ${srcdir}/contrib ${srcdir}/projects ${srcdir}/scripts \ $(TESTS) $(XFAIL_TESTS) tests/pngstest \ CMakeLists.txt example.c libpng-manual.txt SCRIPT_CLEANFILES=scripts/*.out scripts/*.chk CLEANFILES= *.tf? pngout.png libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@.pc \ libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@-config libpng.vers libpng.sym \ check.new pnglibconf.h pngprefix.h symbols.new pngtest-log.txt \ pnglibconf.out pnglibconf.c pnglibconf.pre pnglibconf.dfn \ $(SCRIPT_CLEANFILES) MAINTAINERCLEANFILES = Makefile.in aclocal.m4 config.guess config.h.in \ config.sub configure depcomp install-sh ltmain.sh missing # PNG_COPTS give extra options for the C compiler to be used on all compilation # steps (unless targe_CFLAGS is specified; that will take precedence over # AM_CFLAGS) PNG_COPTS = @PNG_COPTS@ AM_CFLAGS = ${PNG_COPTS} # DFNCPP is normally just CPP - the C preprocessor - but on Solaris and maybe # other operating systems (NeXT?) the C preprocessor selected by configure # checks input tokens for validity - effectively it performs part of the ANSI-C # parsing - and therefore fails with the .df files. configure.ac has special # checks for this and sets DFNCPP appropriately. DFNCPP = @DFNCPP@ SUFFIXES = .chk .out $(PNGLIB_BASENAME).pc: libpng.pc cp libpng.pc $@ $(PNGLIB_BASENAME)-config: libpng-config cp libpng-config $@ scripts/sym.out scripts/vers.out: png.h pngconf.h pnglibconf.h scripts/prefix.out: png.h pngconf.h pnglibconf.out scripts/symbols.out: png.h pngconf.h $(srcdir)/scripts/pnglibconf.h.prebuilt scripts/intprefix.out: pnglibconf.h libpng.sym: scripts/sym.out rm -f $@ cp $? $@ libpng.vers: scripts/vers.out rm -f $@ cp $? $@ if DO_PNG_PREFIX # Rename functions in scripts/prefix.out with a PNG_PREFIX prefix. # Rename macros in scripts/macro.lst from PNG_PREFIXpng_ to PNG_ (the actual # implementation of the macro). pnglibconf.h: pnglibconf.out scripts/prefix.out scripts/macro.lst rm -f $@ $(AWK) 's==0 && NR>1{print prev}\ s==0{prev=$$0}\ s==1{print "#define", $$1, "@PNG_PREFIX@" $$1}\ s==2{print "#define @PNG_PREFIX@png_" $$1, "PNG_" $$1}\ END{print prev}' s=0 pnglibconf.out s=1 scripts/prefix.out\ s=2 ${srcdir}/scripts/macro.lst >pnglibconf.tf8 mv pnglibconf.tf8 $@ pngprefix.h: scripts/intprefix.out rm -f pngprefix.tf1 $(AWK) '{print "#define", $$1, "@PNG_PREFIX@" $$1}' $? >pngprefix.tf1 mv pngprefix.tf1 $@ else pnglibconf.h: pnglibconf.out rm -f $@ cp $? $@ pngprefix.h: # is empty :>$@ endif $(srcdir)/scripts/pnglibconf.h.prebuilt: @echo "Attempting to build $@" >&2 @echo "This is a machine generated file, but if you want to make" >&2 @echo "a new one simply make 'scripts/pnglibconf.out', copy that" >&2 @echo "AND set PNG_ZLIB_VERNUM to 0 (you MUST do this)" >&2 @exit 1 # The following is necessary to ensure that the local pnglibconf.h is used, not # an installed one (this can happen immediately after on a clean system if # 'make test' is the first thing the user does.) Only files which include # one of the png source files (typically png.h or pngpriv.h) need to be listed # here: pngtest.o: pnglibconf.h contrib/libtests/makepng.o: pnglibconf.h contrib/libtests/pngstest.o: pnglibconf.h contrib/libtests/pngunknown.o: pnglibconf.h contrib/libtests/pngimage.o: pnglibconf.h contrib/libtests/pngvalid.o: pnglibconf.h contrib/libtests/readpng.o: pnglibconf.h contrib/libtests/tarith.o: pnglibconf.h contrib/libtests/timepng.o: pnglibconf.h contrib/tools/makesRGB.o: pnglibconf.h contrib/tools/pngfix.o: pnglibconf.h contrib/tools/pngcp.o: pnglibconf.h # We must use -DPNG_NO_USE_READ_MACROS here even when the library may actually # be built with PNG_USE_READ_MACROS; this prevents the read macros from # interfering with the symbol file format. SYMBOL_CFLAGS = -DPNGLIB_LIBNAME='PNG@PNGLIB_MAJOR@@PNGLIB_MINOR@_0'\ -DPNGLIB_VERSION='@PNGLIB_VERSION@'\ -DSYMBOL_PREFIX='$(SYMBOL_PREFIX)'\ -DPNG_NO_USE_READ_MACROS -DPNG_BUILDING_SYMBOL_TABLE if DO_PNG_PREFIX SYMBOL_CFLAGS += -DPNG_PREFIX='@PNG_PREFIX@' endif .c.out: rm -f $@ $*.tf[12] test -d scripts || mkdir scripts || test -d scripts $(DFNCPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES)\ $(CPPFLAGS) $(SYMBOL_CFLAGS) $< > $*.tf1 $(AWK) -f "${srcdir}/scripts/dfn.awk" out="$*.tf2" $*.tf1 1>&2 rm -f $*.tf1 mv $*.tf2 $@ # The .c file for pnglibconf.h is machine generated pnglibconf.c: scripts/pnglibconf.dfa scripts/options.awk pngconf.h pngusr.dfa $(DFA_XTRA) rm -f $@ $*.tf[45] $(AWK) -f ${srcdir}/scripts/options.awk out=$*.tf4 version=search\ ${srcdir}/pngconf.h ${srcdir}/scripts/pnglibconf.dfa\ ${srcdir}/pngusr.dfa $(DFA_XTRA) 1>&2 $(AWK) -f ${srcdir}/scripts/options.awk out=$*.tf5 $*.tf4 1>&2 rm $*.tf4 mv $*.tf5 $@ # Symbol checks (.def and .out files should match) scripts/symbols.chk: scripts/checksym.awk scripts/symbols.def scripts/symbols.out .out.chk: rm -f $@ $*.new $(AWK) -f ${srcdir}/scripts/checksym.awk ${srcdir}/scripts/${*F}.def\ of="$*.new" $< >&2 mv $*.new $@ # used on demand to regenerate the standard header, CPPFLAGS should # be empty - no non-standard defines scripts/pnglibconf.c: scripts/pnglibconf.dfa scripts/options.awk pngconf.h rm -f $@ pnglibconf.tf[67] test -z "$(CPPFLAGS)" echo "com @PNGLIB_VERSION@ STANDARD API DEFINITION" |\ $(AWK) -f ${srcdir}/scripts/options.awk out=pnglibconf.tf6\ logunsupported=1 version=search ${srcdir}/pngconf.h -\ ${srcdir}/scripts/pnglibconf.dfa 1>&2 $(AWK) -f ${srcdir}/scripts/options.awk out=pnglibconf.tf7\ pnglibconf.tf6 1>&2 rm pnglibconf.tf6 mv pnglibconf.tf7 $@ $(libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_OBJECTS): png.h pngconf.h \ pnglibconf.h pngpriv.h pngdebug.h pnginfo.h pngstruct.h pngprefix.h test: check-am # Extra checks check: scripts/symbols.chk # Don't distribute the generated script files dist-hook: cd '$(top_distdir)'; rm -f $(SCRIPT_CLEANFILES) # Make links between installed files with release-specific names and the generic # file names. If this install rule is run the generic names will be deleted and # recreated - this has obvious issues for systems with multiple installations. install-header-links: @set -ex; cd '$(DESTDIR)$(includedir)'; for f in $(HEADERS); do \ rm -f "$$f"; $(LN_S) "$(PNGLIB_BASENAME)/$$f" "$$f"; done uninstall-header-links: cd '$(DESTDIR)$(includedir)'; rm -f $(HEADERS) install-libpng-pc: @set -ex; cd '$(DESTDIR)$(pkgconfigdir)'; rm -f libpng.pc; \ $(LN_S) '$(PNGLIB_BASENAME).pc' libpng.pc uninstall-libpng-pc: rm -f '$(DESTDIR)$(pkgconfigdir)/libpng.pc' # EXT_LIST is a list of the possibly library directory extensions, this exists # because we can't find a good way of discovering the file extensions that are # actually installed on a given system, so instead we check for every extension # we have seen. EXT_LIST = a dll.a so so.@PNGLIB_MAJOR@@PNGLIB_MINOR@.@PNGLIB_RELEASE@ la sl dylib install-library-links: @set -x; cd '$(DESTDIR)$(libdir)';\ for ext in $(EXT_LIST); do\ rm -f "libpng.$$ext";\ if test -f "$(PNGLIB_BASENAME).$$ext"; then\ $(LN_S) "$(PNGLIB_BASENAME).$$ext" "libpng.$$ext" || exit 1;\ fi;\ done uninstall-library-links: @set -x; cd '$(DESTDIR)$(libdir)'; for ext in $(EXT_LIST); do\ rm -f "libpng.$$ext"; done install-libpng-config: @set -ex; cd '$(DESTDIR)$(bindir)'; rm -f libpng-config; \ $(LN_S) '$(PNGLIB_BASENAME)-config' libpng-config uninstall-libpng-config: rm -f '$(DESTDIR)$(bindir)/libpng-config' if DO_INSTALL_LINKS # If --enable-unversioned-links is specified the header and lib file links # will be automatically made on a 'make install': install-data-hook: install-header-links uninstall-hook: uninstall-header-links install-exec-hook: install-library-links uninstall-hook: uninstall-library-links endif if DO_INSTALL_LIBPNG_PC # Likewise, --install-pc causes libpng.pc to be constructed: install-data-hook: install-libpng-pc uninstall-hook: uninstall-libpng-pc endif if DO_INSTALL_LIBPNG_CONFIG # And --install-config: install-exec-hook: install-libpng-config uninstall-hook: uninstall-libpng-config endif # The following addition ensures that 'make all' always builds the test programs # too. It used to, but some change either in libpng or configure stopped this # working. all-am: $(check_PROGRAMS) ================================================ FILE: tess-two/jni/libpng/README ================================================ README for libpng version 1.6.25 - September 1, 2016 (shared library 16.0) See the note about version numbers near the top of png.h See INSTALL for instructions on how to install libpng. Libpng comes in several distribution formats. Get libpng-*.tar.gz or libpng-*.tar.xz or if you want UNIX-style line endings in the text files, or lpng*.7z or lpng*.zip if you want DOS-style line endings. Version 0.89 was the first official release of libpng. Don't let the fact that it's the first release fool you. The libpng library has been in extensive use and testing since mid-1995. By late 1997 it had finally gotten to the stage where there hadn't been significant changes to the API in some time, and people have a bad feeling about libraries with versions < 1.0. Version 1.0.0 was released in March 1998. **** Note that some of the changes to the png_info structure render this version of the library binary incompatible with libpng-0.89 or earlier versions if you are using a shared library. The type of the "filler" parameter for png_set_filler() has changed from png_byte to png_uint_32, which will affect shared-library applications that use this function. To avoid problems with changes to the internals of png info_struct, new APIs have been made available in 0.95 to avoid direct application access to info_ptr. These functions are the png_set_ and png_get_ functions. These functions should be used when accessing/storing the info_struct data, rather than manipulating it directly, to avoid such problems in the future. It is important to note that the APIs did not make current programs that access the info struct directly incompatible with the new library, through libpng-1.2.x. In libpng-1.4.x, which was meant to be a transitional release, members of the png_struct and the info_struct can still be accessed, but the compiler will issue a warning about deprecated usage. Since libpng-1.5.0, direct access to these structs is not allowed, and the definitions of the structs reside in private pngstruct.h and pnginfo.h header files that are not accessible to applications. It is strongly suggested that new programs use the new APIs (as shown in example.c and pngtest.c), and older programs be converted to the new format, to facilitate upgrades in the future. **** Additions since 0.90 include the ability to compile libpng as a Windows DLL, and new APIs for accessing data in the info struct. Experimental functions include the ability to set weighting and cost factors for row filter selection, direct reads of integers from buffers on big-endian processors that support misaligned data access, faster methods of doing alpha composition, and more accurate 16->8 bit color conversion. The additions since 0.89 include the ability to read from a PNG stream which has had some (or all) of the signature bytes read by the calling application. This also allows the reading of embedded PNG streams that do not have the PNG file signature. As well, it is now possible to set the library action on the detection of chunk CRC errors. It is possible to set different actions based on whether the CRC error occurred in a critical or an ancillary chunk. The changes made to the library, and bugs fixed are based on discussions on the PNG-implement mailing list and not on material submitted privately to Guy, Andreas, or Glenn. They will forward any good suggestions to the list. For a detailed description on using libpng, read libpng-manual.txt. For examples of libpng in a program, see example.c and pngtest.c. For usage information and restrictions (what little they are) on libpng, see png.h. For a description on using zlib (the compression library used by libpng) and zlib's restrictions, see zlib.h I have included a general makefile, as well as several machine and compiler specific ones, but you may have to modify one for your own needs. You should use zlib 1.0.4 or later to run this, but it MAY work with versions as old as zlib 0.95. Even so, there are bugs in older zlib versions which can cause the output of invalid compression streams for some images. You will definitely need zlib 1.0.4 or later if you are taking advantage of the MS-DOS "far" structure allocation for the small and medium memory models. You should also note that zlib is a compression library that is useful for more things than just PNG files. You can use zlib as a drop-in replacement for fread() and fwrite() if you are so inclined. zlib should be available at the same place that libpng is, or at zlib.net. You may also want a copy of the PNG specification. It is available as an RFC, a W3C Recommendation, and an ISO/IEC Standard. You can find these at http://www.libpng.org/pub/png/documents/ This code is currently being archived at libpng.sf.net in the [DOWNLOAD] area, and at ftp://ftp.simplesystems.org. If you can't find it in any of those places, e-mail me, and I'll help you find it. I am not a lawyer, but I believe that the Export Control Classification Number (ECCN) for libpng is EAR99, which means not subject to export controls or International Traffic in Arms Regulations (ITAR) because it is open source, publicly available software, that does not contain any encryption software. See the EAR, paragraphs 734.3(b)(3) and 734.7(b). If you have any code changes, requests, problems, etc., please e-mail them to me. Also, I'd appreciate any make files or project files, and any modifications you needed to make to get libpng to compile, along with a #define variable to tell what compiler/system you are on. If you needed to add transformations to libpng, or wish libpng would provide the image in a different way, drop me a note (and code, if possible), so I can consider supporting the transformation. Finally, if you get any warning messages when compiling libpng (note: not zlib), and they are easy to fix, I'd appreciate the fix. Please mention "libpng" somewhere in the subject line. Thanks. This release was created and will be supported by myself (of course based in a large way on Guy's and Andreas' earlier work), and the PNG development group. Send comments/corrections/commendations to png-mng-implement at lists.sourceforge.net (subscription required; visit https://lists.sourceforge.net/lists/listinfo/png-mng-implement to subscribe) or to glennrp at users.sourceforge.net You can't reach Guy, the original libpng author, at the addresses given in previous versions of this document. He and Andreas will read mail addressed to the png-implement list, however. Please do not send general questions about PNG. Send them to png-mng-misc at lists.sf.net (subscription required; visit https://lists.sourceforge.net/lists/listinfo/png-mng-misc to subscribe). If you have a question about something in the PNG specification that is related to using libpng, send it to me. Send me any questions that start with "I was using libpng, and ...". If in doubt, send questions to me. I'll bounce them to others, if necessary. Please do not send suggestions on how to change PNG. We have been discussing PNG for twenty years now, and it is official and finished. If you have suggestions for libpng, however, I'll gladly listen. Even if your suggestion is not used immediately, it may be used later. Files in this distribution: ANNOUNCE => Announcement of this version, with recent changes CHANGES => Description of changes between libpng versions KNOWNBUG => List of known bugs and deficiencies LICENSE => License to use and redistribute libpng README => This file TODO => Things not implemented in the current library Y2KINFO => Statement of Y2K compliance example.c => Example code for using libpng functions libpng.3 => manual page for libpng (includes libpng-manual.txt) libpng-manual.txt => Description of libpng and its functions libpngpf.3 => manual page for libpng's private functions png.5 => manual page for the PNG format png.c => Basic interface functions common to library png.h => Library function and interface declarations (public) pngpriv.h => Library function and interface declarations (private) pngconf.h => System specific library configuration (public) pngstruct.h => png_struct declaration (private) pnginfo.h => png_info struct declaration (private) pngdebug.h => debugging macros (private) pngerror.c => Error/warning message I/O functions pngget.c => Functions for retrieving info from struct pngmem.c => Memory handling functions pngbar.png => PNG logo, 88x31 pngnow.png => PNG logo, 98x31 pngpread.c => Progressive reading functions pngread.c => Read data/helper high-level functions pngrio.c => Lowest-level data read I/O functions pngrtran.c => Read data transformation functions pngrutil.c => Read data utility functions pngset.c => Functions for storing data into the info_struct pngtest.c => Library test program pngtest.png => Library test sample image pngtrans.c => Common data transformation functions pngwio.c => Lowest-level write I/O functions pngwrite.c => High-level write functions pngwtran.c => Write data transformations pngwutil.c => Write utility functions arm => Contains optimized code for the ARM platform contrib => Contributions arm-neon => Optimized code for ARM-NEON platform examples => Example programs gregbook => source code for PNG reading and writing, from Greg Roelofs' "PNG: The Definitive Guide", O'Reilly, 1999 intel => Optimized code for INTEL-SSE2 platform libtests => Test programs pngminim => Minimal decoder, encoder, and progressive decoder programs demonstrating use of pngusr.dfa pngminus => Simple pnm2png and png2pnm programs pngsuite => Test images testpngs tools => Various tools visupng => Contains a MSVC workspace for VisualPng projects => Contains project files and workspaces for building a DLL owatcom => Contains a WATCOM project for building libpng visualc71 => Contains a Microsoft Visual C++ (MSVC) workspace for building libpng and zlib vstudio => Contains a Microsoft Visual C++ (MSVC) workspace for building libpng and zlib scripts => Directory containing scripts for building libpng: (see scripts/README.txt for the list of scripts) Good luck, and happy coding. -Glenn Randers-Pehrson (current maintainer, since 1998) Internet: glennrp at users.sourceforge.net -Andreas Eric Dilger (former maintainer, 1996-1997) Internet: adilger at enel.ucalgary.ca Web: http://www-mddsp.enel.ucalgary.ca/People/adilger/ -Guy Eric Schalnat (original author and former maintainer, 1995-1996) (formerly of Group 42, Inc) Internet: gschal at infinet.com ================================================ FILE: tess-two/jni/libpng/README.android ================================================ Any Android specific modifications to upstream libpng (1.6.25) should be listed here: (1) Android has added the following files. pngusr.h Android.mk CleanSpec.mk MODULE_LICENSE_BSD_LIKE README.version (2) pnglibconf.h This is copied from scripts/pnglibconf.h.prebuilt. Android has undefined PNG_WARNINGS_SUPPORTED. (3) Removed contrib/testpngs/ There is no reason to check in all of these files if we won't be using them. (4) Applied the Intel SSE patch Upstream places the patch for SSE support in contrib/intel/intel_sse.patch. The patch was applied using the following command: 'patch -i contrib/intel/intel_sse.patch -p1' ================================================ FILE: tess-two/jni/libpng/README.version ================================================ URL: https://sourceforge.net/projects/libpng/files/libpng16/1.6.25/libpng-1.6.25.tar.gz/download Version: 1.6.25 BugComponent: 87896 ================================================ FILE: tess-two/jni/libpng/TODO ================================================ /* TODO - list of things to do for libpng: Final bug fixes. Better C++ wrapper/full C++ implementation? Fix problem with C++ and EXTERN "C". cHRM transformation. Remove setjmp/longjmp usage in favor of returning error codes. As a start on this, minimize the use of png_error(), replacing them with png_warning(); return(0; or similar. Palette creation. Add "grayscale->palette" transformation and "palette->grayscale" detection. Improved dithering. Multi-lingual error and warning message support. Complete sRGB transformation (presently it simply uses gamma=0.45455). Man pages for function calls. Better documentation. Better filter selection (counting huffman bits/precompression? filter inertia? filter costs?). Histogram creation. Text conversion between different code pages (Latin-1 -> Mac and DOS). Avoid building gamma tables whenever possible. Use greater precision when changing to linear gamma for compositing against background and doing rgb-to-gray transformation. Investigate pre-incremented loop counters and other loop constructions. Add interpolated method of handling interlacing. Switch to the simpler zlib (zlib/libpng) license if legally possible. Extend pngvalid.c to validate more of the libpng transformations. */ ================================================ FILE: tess-two/jni/libpng/arm/arm_init.c ================================================ /* arm_init.c - NEON optimised filter functions * * Copyright (c) 2014,2016 Glenn Randers-Pehrson * Written by Mans Rullgard, 2011. * Last changed in libpng 1.6.22 [May 26, 2016] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h */ /* Below, after checking __linux__, various non-C90 POSIX 1003.1 functions are * called. */ #define _POSIX_SOURCE 1 #include "../pngpriv.h" #ifdef PNG_READ_SUPPORTED #if PNG_ARM_NEON_OPT > 0 #ifdef PNG_ARM_NEON_CHECK_SUPPORTED /* Do run-time checks */ /* WARNING: it is strongly recommended that you do not build libpng with * run-time checks for CPU features if at all possible. In the case of the ARM * NEON instructions there is no processor-specific way of detecting the * presence of the required support, therefore run-time detection is extremely * OS specific. * * You may set the macro PNG_ARM_NEON_FILE to the file name of file containing * a fragment of C source code which defines the png_have_neon function. There * are a number of implementations in contrib/arm-neon, but the only one that * has partial support is contrib/arm-neon/linux.c - a generic Linux * implementation which reads /proc/cpufino. */ #ifndef PNG_ARM_NEON_FILE # ifdef __linux__ # define PNG_ARM_NEON_FILE "contrib/arm-neon/linux.c" # endif #endif #ifdef PNG_ARM_NEON_FILE #include /* for sig_atomic_t */ static int png_have_neon(png_structp png_ptr); #include PNG_ARM_NEON_FILE #else /* PNG_ARM_NEON_FILE */ # error "PNG_ARM_NEON_FILE undefined: no support for run-time ARM NEON checks" #endif /* PNG_ARM_NEON_FILE */ #endif /* PNG_ARM_NEON_CHECK_SUPPORTED */ #ifndef PNG_ALIGNED_MEMORY_SUPPORTED # error "ALIGNED_MEMORY is required; set: -DPNG_ALIGNED_MEMORY_SUPPORTED" #endif void png_init_filter_functions_neon(png_structp pp, unsigned int bpp) { /* The switch statement is compiled in for ARM_NEON_API, the call to * png_have_neon is compiled in for ARM_NEON_CHECK. If both are defined * the check is only performed if the API has not set the NEON option on * or off explicitly. In this case the check controls what happens. * * If the CHECK is not compiled in and the option is UNSET the behavior prior * to 1.6.7 was to use the NEON code - this was a bug caused by having the * wrong order of the 'ON' and 'default' cases. UNSET now defaults to OFF, * as documented in png.h */ png_debug(1, "in png_init_filter_functions_neon"); #ifdef PNG_ARM_NEON_API_SUPPORTED switch ((pp->options >> PNG_ARM_NEON) & 3) { case PNG_OPTION_UNSET: /* Allow the run-time check to execute if it has been enabled - * thus both API and CHECK can be turned on. If it isn't supported * this case will fall through to the 'default' below, which just * returns. */ #endif /* PNG_ARM_NEON_API_SUPPORTED */ #ifdef PNG_ARM_NEON_CHECK_SUPPORTED { static volatile sig_atomic_t no_neon = -1; /* not checked */ if (no_neon < 0) no_neon = !png_have_neon(pp); if (no_neon) return; } #ifdef PNG_ARM_NEON_API_SUPPORTED break; #endif #endif /* PNG_ARM_NEON_CHECK_SUPPORTED */ #ifdef PNG_ARM_NEON_API_SUPPORTED default: /* OFF or INVALID */ return; case PNG_OPTION_ON: /* Option turned on */ break; } #endif /* IMPORTANT: any new external functions used here must be declared using * PNG_INTERNAL_FUNCTION in ../pngpriv.h. This is required so that the * 'prefix' option to configure works: * * ./configure --with-libpng-prefix=foobar_ * * Verify you have got this right by running the above command, doing a build * and examining pngprefix.h; it must contain a #define for every external * function you add. (Notice that this happens automatically for the * initialization function.) */ pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up_neon; if (bpp == 3) { pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub3_neon; pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg3_neon; pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth3_neon; } else if (bpp == 4) { pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub4_neon; pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg4_neon; pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth4_neon; } } #endif /* PNG_ARM_NEON_OPT > 0 */ #endif /* READ */ ================================================ FILE: tess-two/jni/libpng/arm/filter_neon.S ================================================ /* filter_neon.S - NEON optimised filter functions * * Copyright (c) 2014 Glenn Randers-Pehrson * Written by Mans Rullgard, 2011. * Last changed in libpng 1.6.16 [December 22, 2014] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h */ /* This is required to get the symbol renames, which are #defines, and the * definitions (or not) of PNG_ARM_NEON_OPT and PNG_ARM_NEON_IMPLEMENTATION. */ #define PNG_VERSION_INFO_ONLY #include "../pngpriv.h" #if defined(__linux__) && defined(__ELF__) .section .note.GNU-stack,"",%progbits /* mark stack as non-executable */ #endif #ifdef PNG_READ_SUPPORTED /* Assembler NEON support - only works for 32-bit ARM (i.e. it does not work for * ARM64). The code in arm/filter_neon_intrinsics.c supports ARM64, however it * only works if -mfpu=neon is specified on the GCC command line. See pngpriv.h * for the logic which sets PNG_USE_ARM_NEON_ASM: */ #if PNG_ARM_NEON_IMPLEMENTATION == 2 /* hand-coded assembler */ #if PNG_ARM_NEON_OPT > 0 #ifdef __ELF__ # define ELF #else # define ELF @ #endif .arch armv7-a .fpu neon .macro func name, export=0 .macro endfunc ELF .size \name, . - \name .endfunc .purgem endfunc .endm .text /* Explicitly specifying alignment here because some versions of * GAS don't align code correctly. This is harmless in correctly * written versions of GAS. */ .align 2 .if \export .global \name .endif ELF .type \name, STT_FUNC .func \name \name: .endm func png_read_filter_row_sub4_neon, export=1 ldr r3, [r0, #4] @ rowbytes vmov.i8 d3, #0 1: vld4.32 {d4[],d5[],d6[],d7[]}, [r1,:128] vadd.u8 d0, d3, d4 vadd.u8 d1, d0, d5 vadd.u8 d2, d1, d6 vadd.u8 d3, d2, d7 vst4.32 {d0[0],d1[0],d2[0],d3[0]},[r1,:128]! subs r3, r3, #16 bgt 1b bx lr endfunc func png_read_filter_row_sub3_neon, export=1 ldr r3, [r0, #4] @ rowbytes vmov.i8 d3, #0 mov r0, r1 mov r2, #3 mov r12, #12 vld1.8 {q11}, [r0], r12 1: vext.8 d5, d22, d23, #3 vadd.u8 d0, d3, d22 vext.8 d6, d22, d23, #6 vadd.u8 d1, d0, d5 vext.8 d7, d23, d23, #1 vld1.8 {q11}, [r0], r12 vst1.32 {d0[0]}, [r1,:32], r2 vadd.u8 d2, d1, d6 vst1.32 {d1[0]}, [r1], r2 vadd.u8 d3, d2, d7 vst1.32 {d2[0]}, [r1], r2 vst1.32 {d3[0]}, [r1], r2 subs r3, r3, #12 bgt 1b bx lr endfunc func png_read_filter_row_up_neon, export=1 ldr r3, [r0, #4] @ rowbytes 1: vld1.8 {q0}, [r1,:128] vld1.8 {q1}, [r2,:128]! vadd.u8 q0, q0, q1 vst1.8 {q0}, [r1,:128]! subs r3, r3, #16 bgt 1b bx lr endfunc func png_read_filter_row_avg4_neon, export=1 ldr r12, [r0, #4] @ rowbytes vmov.i8 d3, #0 1: vld4.32 {d4[],d5[],d6[],d7[]}, [r1,:128] vld4.32 {d16[],d17[],d18[],d19[]},[r2,:128]! vhadd.u8 d0, d3, d16 vadd.u8 d0, d0, d4 vhadd.u8 d1, d0, d17 vadd.u8 d1, d1, d5 vhadd.u8 d2, d1, d18 vadd.u8 d2, d2, d6 vhadd.u8 d3, d2, d19 vadd.u8 d3, d3, d7 vst4.32 {d0[0],d1[0],d2[0],d3[0]},[r1,:128]! subs r12, r12, #16 bgt 1b bx lr endfunc func png_read_filter_row_avg3_neon, export=1 push {r4,lr} ldr r12, [r0, #4] @ rowbytes vmov.i8 d3, #0 mov r0, r1 mov r4, #3 mov lr, #12 vld1.8 {q11}, [r0], lr 1: vld1.8 {q10}, [r2], lr vext.8 d5, d22, d23, #3 vhadd.u8 d0, d3, d20 vext.8 d17, d20, d21, #3 vadd.u8 d0, d0, d22 vext.8 d6, d22, d23, #6 vhadd.u8 d1, d0, d17 vext.8 d18, d20, d21, #6 vadd.u8 d1, d1, d5 vext.8 d7, d23, d23, #1 vld1.8 {q11}, [r0], lr vst1.32 {d0[0]}, [r1,:32], r4 vhadd.u8 d2, d1, d18 vst1.32 {d1[0]}, [r1], r4 vext.8 d19, d21, d21, #1 vadd.u8 d2, d2, d6 vhadd.u8 d3, d2, d19 vst1.32 {d2[0]}, [r1], r4 vadd.u8 d3, d3, d7 vst1.32 {d3[0]}, [r1], r4 subs r12, r12, #12 bgt 1b pop {r4,pc} endfunc .macro paeth rx, ra, rb, rc vaddl.u8 q12, \ra, \rb @ a + b vaddl.u8 q15, \rc, \rc @ 2*c vabdl.u8 q13, \rb, \rc @ pa vabdl.u8 q14, \ra, \rc @ pb vabd.u16 q15, q12, q15 @ pc vcle.u16 q12, q13, q14 @ pa <= pb vcle.u16 q13, q13, q15 @ pa <= pc vcle.u16 q14, q14, q15 @ pb <= pc vand q12, q12, q13 @ pa <= pb && pa <= pc vmovn.u16 d28, q14 vmovn.u16 \rx, q12 vbsl d28, \rb, \rc vbsl \rx, \ra, d28 .endm func png_read_filter_row_paeth4_neon, export=1 ldr r12, [r0, #4] @ rowbytes vmov.i8 d3, #0 vmov.i8 d20, #0 1: vld4.32 {d4[],d5[],d6[],d7[]}, [r1,:128] vld4.32 {d16[],d17[],d18[],d19[]},[r2,:128]! paeth d0, d3, d16, d20 vadd.u8 d0, d0, d4 paeth d1, d0, d17, d16 vadd.u8 d1, d1, d5 paeth d2, d1, d18, d17 vadd.u8 d2, d2, d6 paeth d3, d2, d19, d18 vmov d20, d19 vadd.u8 d3, d3, d7 vst4.32 {d0[0],d1[0],d2[0],d3[0]},[r1,:128]! subs r12, r12, #16 bgt 1b bx lr endfunc func png_read_filter_row_paeth3_neon, export=1 push {r4,lr} ldr r12, [r0, #4] @ rowbytes vmov.i8 d3, #0 vmov.i8 d4, #0 mov r0, r1 mov r4, #3 mov lr, #12 vld1.8 {q11}, [r0], lr 1: vld1.8 {q10}, [r2], lr paeth d0, d3, d20, d4 vext.8 d5, d22, d23, #3 vadd.u8 d0, d0, d22 vext.8 d17, d20, d21, #3 paeth d1, d0, d17, d20 vst1.32 {d0[0]}, [r1,:32], r4 vext.8 d6, d22, d23, #6 vadd.u8 d1, d1, d5 vext.8 d18, d20, d21, #6 paeth d2, d1, d18, d17 vext.8 d7, d23, d23, #1 vld1.8 {q11}, [r0], lr vst1.32 {d1[0]}, [r1], r4 vadd.u8 d2, d2, d6 vext.8 d19, d21, d21, #1 paeth d3, d2, d19, d18 vst1.32 {d2[0]}, [r1], r4 vmov d4, d19 vadd.u8 d3, d3, d7 vst1.32 {d3[0]}, [r1], r4 subs r12, r12, #12 bgt 1b pop {r4,pc} endfunc #endif /* PNG_ARM_NEON_OPT > 0 */ #endif /* PNG_ARM_NEON_IMPLEMENTATION == 2 (assembler) */ #endif /* READ */ ================================================ FILE: tess-two/jni/libpng/arm/filter_neon_intrinsics.c ================================================ /* filter_neon_intrinsics.c - NEON optimised filter functions * * Copyright (c) 2014,2016 Glenn Randers-Pehrson * Written by James Yu , October 2013. * Based on filter_neon.S, written by Mans Rullgard, 2011. * * Last changed in libpng 1.6.22 [May 26, 2016] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h */ #include "../pngpriv.h" #ifdef PNG_READ_SUPPORTED /* This code requires -mfpu=neon on the command line: */ #if PNG_ARM_NEON_IMPLEMENTATION == 1 /* intrinsics code from pngpriv.h */ #include /* libpng row pointers are not necessarily aligned to any particular boundary, * however this code will only work with appropriate alignment. arm/arm_init.c * checks for this (and will not compile unless it is done). This code uses * variants of png_aligncast to avoid compiler warnings. */ #define png_ptr(type,pointer) png_aligncast(type *,pointer) #define png_ptrc(type,pointer) png_aligncastconst(const type *,pointer) /* The following relies on a variable 'temp_pointer' being declared with type * 'type'. This is written this way just to hide the GCC strict aliasing * warning; note that the code is safe because there never is an alias between * the input and output pointers. */ #define png_ldr(type,pointer)\ (temp_pointer = png_ptr(type,pointer), *temp_pointer) #if PNG_ARM_NEON_OPT > 0 void png_read_filter_row_up_neon(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp = row; png_bytep rp_stop = row + row_info->rowbytes; png_const_bytep pp = prev_row; png_debug(1, "in png_read_filter_row_up_neon"); for (; rp < rp_stop; rp += 16, pp += 16) { uint8x16_t qrp, qpp; qrp = vld1q_u8(rp); qpp = vld1q_u8(pp); qrp = vaddq_u8(qrp, qpp); vst1q_u8(rp, qrp); } } void png_read_filter_row_sub3_neon(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp = row; png_bytep rp_stop = row + row_info->rowbytes; uint8x16_t vtmp = vld1q_u8(rp); uint8x8x2_t *vrpt = png_ptr(uint8x8x2_t, &vtmp); uint8x8x2_t vrp = *vrpt; uint8x8x4_t vdest; vdest.val[3] = vdup_n_u8(0); png_debug(1, "in png_read_filter_row_sub3_neon"); for (; rp < rp_stop;) { uint8x8_t vtmp1, vtmp2; uint32x2_t *temp_pointer; vtmp1 = vext_u8(vrp.val[0], vrp.val[1], 3); vdest.val[0] = vadd_u8(vdest.val[3], vrp.val[0]); vtmp2 = vext_u8(vrp.val[0], vrp.val[1], 6); vdest.val[1] = vadd_u8(vdest.val[0], vtmp1); vtmp1 = vext_u8(vrp.val[1], vrp.val[1], 1); vdest.val[2] = vadd_u8(vdest.val[1], vtmp2); vdest.val[3] = vadd_u8(vdest.val[2], vtmp1); vtmp = vld1q_u8(rp + 12); vrpt = png_ptr(uint8x8x2_t, &vtmp); vrp = *vrpt; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[0]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[1]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[2]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[3]), 0); rp += 3; } PNG_UNUSED(prev_row) } void png_read_filter_row_sub4_neon(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp = row; png_bytep rp_stop = row + row_info->rowbytes; uint8x8x4_t vdest; vdest.val[3] = vdup_n_u8(0); png_debug(1, "in png_read_filter_row_sub4_neon"); for (; rp < rp_stop; rp += 16) { uint32x2x4_t vtmp = vld4_u32(png_ptr(uint32_t,rp)); uint8x8x4_t *vrpt = png_ptr(uint8x8x4_t,&vtmp); uint8x8x4_t vrp = *vrpt; uint32x2x4_t *temp_pointer; vdest.val[0] = vadd_u8(vdest.val[3], vrp.val[0]); vdest.val[1] = vadd_u8(vdest.val[0], vrp.val[1]); vdest.val[2] = vadd_u8(vdest.val[1], vrp.val[2]); vdest.val[3] = vadd_u8(vdest.val[2], vrp.val[3]); vst4_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2x4_t,&vdest), 0); } PNG_UNUSED(prev_row) } void png_read_filter_row_avg3_neon(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp = row; png_const_bytep pp = prev_row; png_bytep rp_stop = row + row_info->rowbytes; uint8x16_t vtmp; uint8x8x2_t *vrpt; uint8x8x2_t vrp; uint8x8x4_t vdest; vdest.val[3] = vdup_n_u8(0); vtmp = vld1q_u8(rp); vrpt = png_ptr(uint8x8x2_t,&vtmp); vrp = *vrpt; png_debug(1, "in png_read_filter_row_avg3_neon"); for (; rp < rp_stop; pp += 12) { uint8x8_t vtmp1, vtmp2, vtmp3; uint8x8x2_t *vppt; uint8x8x2_t vpp; uint32x2_t *temp_pointer; vtmp = vld1q_u8(pp); vppt = png_ptr(uint8x8x2_t,&vtmp); vpp = *vppt; vtmp1 = vext_u8(vrp.val[0], vrp.val[1], 3); vdest.val[0] = vhadd_u8(vdest.val[3], vpp.val[0]); vdest.val[0] = vadd_u8(vdest.val[0], vrp.val[0]); vtmp2 = vext_u8(vpp.val[0], vpp.val[1], 3); vtmp3 = vext_u8(vrp.val[0], vrp.val[1], 6); vdest.val[1] = vhadd_u8(vdest.val[0], vtmp2); vdest.val[1] = vadd_u8(vdest.val[1], vtmp1); vtmp2 = vext_u8(vpp.val[0], vpp.val[1], 6); vtmp1 = vext_u8(vrp.val[1], vrp.val[1], 1); vtmp = vld1q_u8(rp + 12); vrpt = png_ptr(uint8x8x2_t,&vtmp); vrp = *vrpt; vdest.val[2] = vhadd_u8(vdest.val[1], vtmp2); vdest.val[2] = vadd_u8(vdest.val[2], vtmp3); vtmp2 = vext_u8(vpp.val[1], vpp.val[1], 1); vdest.val[3] = vhadd_u8(vdest.val[2], vtmp2); vdest.val[3] = vadd_u8(vdest.val[3], vtmp1); vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[0]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[1]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[2]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[3]), 0); rp += 3; } } void png_read_filter_row_avg4_neon(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp = row; png_bytep rp_stop = row + row_info->rowbytes; png_const_bytep pp = prev_row; uint8x8x4_t vdest; vdest.val[3] = vdup_n_u8(0); png_debug(1, "in png_read_filter_row_avg4_neon"); for (; rp < rp_stop; rp += 16, pp += 16) { uint32x2x4_t vtmp; uint8x8x4_t *vrpt, *vppt; uint8x8x4_t vrp, vpp; uint32x2x4_t *temp_pointer; vtmp = vld4_u32(png_ptr(uint32_t,rp)); vrpt = png_ptr(uint8x8x4_t,&vtmp); vrp = *vrpt; vtmp = vld4_u32(png_ptrc(uint32_t,pp)); vppt = png_ptr(uint8x8x4_t,&vtmp); vpp = *vppt; vdest.val[0] = vhadd_u8(vdest.val[3], vpp.val[0]); vdest.val[0] = vadd_u8(vdest.val[0], vrp.val[0]); vdest.val[1] = vhadd_u8(vdest.val[0], vpp.val[1]); vdest.val[1] = vadd_u8(vdest.val[1], vrp.val[1]); vdest.val[2] = vhadd_u8(vdest.val[1], vpp.val[2]); vdest.val[2] = vadd_u8(vdest.val[2], vrp.val[2]); vdest.val[3] = vhadd_u8(vdest.val[2], vpp.val[3]); vdest.val[3] = vadd_u8(vdest.val[3], vrp.val[3]); vst4_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2x4_t,&vdest), 0); } } static uint8x8_t paeth(uint8x8_t a, uint8x8_t b, uint8x8_t c) { uint8x8_t d, e; uint16x8_t p1, pa, pb, pc; p1 = vaddl_u8(a, b); /* a + b */ pc = vaddl_u8(c, c); /* c * 2 */ pa = vabdl_u8(b, c); /* pa */ pb = vabdl_u8(a, c); /* pb */ pc = vabdq_u16(p1, pc); /* pc */ p1 = vcleq_u16(pa, pb); /* pa <= pb */ pa = vcleq_u16(pa, pc); /* pa <= pc */ pb = vcleq_u16(pb, pc); /* pb <= pc */ p1 = vandq_u16(p1, pa); /* pa <= pb && pa <= pc */ d = vmovn_u16(pb); e = vmovn_u16(p1); d = vbsl_u8(d, b, c); e = vbsl_u8(e, a, d); return e; } void png_read_filter_row_paeth3_neon(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp = row; png_const_bytep pp = prev_row; png_bytep rp_stop = row + row_info->rowbytes; uint8x16_t vtmp; uint8x8x2_t *vrpt; uint8x8x2_t vrp; uint8x8_t vlast = vdup_n_u8(0); uint8x8x4_t vdest; vdest.val[3] = vdup_n_u8(0); vtmp = vld1q_u8(rp); vrpt = png_ptr(uint8x8x2_t,&vtmp); vrp = *vrpt; png_debug(1, "in png_read_filter_row_paeth3_neon"); for (; rp < rp_stop; pp += 12) { uint8x8x2_t *vppt; uint8x8x2_t vpp; uint8x8_t vtmp1, vtmp2, vtmp3; uint32x2_t *temp_pointer; vtmp = vld1q_u8(pp); vppt = png_ptr(uint8x8x2_t,&vtmp); vpp = *vppt; vdest.val[0] = paeth(vdest.val[3], vpp.val[0], vlast); vdest.val[0] = vadd_u8(vdest.val[0], vrp.val[0]); vtmp1 = vext_u8(vrp.val[0], vrp.val[1], 3); vtmp2 = vext_u8(vpp.val[0], vpp.val[1], 3); vdest.val[1] = paeth(vdest.val[0], vtmp2, vpp.val[0]); vdest.val[1] = vadd_u8(vdest.val[1], vtmp1); vtmp1 = vext_u8(vrp.val[0], vrp.val[1], 6); vtmp3 = vext_u8(vpp.val[0], vpp.val[1], 6); vdest.val[2] = paeth(vdest.val[1], vtmp3, vtmp2); vdest.val[2] = vadd_u8(vdest.val[2], vtmp1); vtmp1 = vext_u8(vrp.val[1], vrp.val[1], 1); vtmp2 = vext_u8(vpp.val[1], vpp.val[1], 1); vtmp = vld1q_u8(rp + 12); vrpt = png_ptr(uint8x8x2_t,&vtmp); vrp = *vrpt; vdest.val[3] = paeth(vdest.val[2], vtmp2, vtmp3); vdest.val[3] = vadd_u8(vdest.val[3], vtmp1); vlast = vtmp2; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[0]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[1]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[2]), 0); rp += 3; vst1_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2_t,&vdest.val[3]), 0); rp += 3; } } void png_read_filter_row_paeth4_neon(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp = row; png_bytep rp_stop = row + row_info->rowbytes; png_const_bytep pp = prev_row; uint8x8_t vlast = vdup_n_u8(0); uint8x8x4_t vdest; vdest.val[3] = vdup_n_u8(0); png_debug(1, "in png_read_filter_row_paeth4_neon"); for (; rp < rp_stop; rp += 16, pp += 16) { uint32x2x4_t vtmp; uint8x8x4_t *vrpt, *vppt; uint8x8x4_t vrp, vpp; uint32x2x4_t *temp_pointer; vtmp = vld4_u32(png_ptr(uint32_t,rp)); vrpt = png_ptr(uint8x8x4_t,&vtmp); vrp = *vrpt; vtmp = vld4_u32(png_ptrc(uint32_t,pp)); vppt = png_ptr(uint8x8x4_t,&vtmp); vpp = *vppt; vdest.val[0] = paeth(vdest.val[3], vpp.val[0], vlast); vdest.val[0] = vadd_u8(vdest.val[0], vrp.val[0]); vdest.val[1] = paeth(vdest.val[0], vpp.val[1], vpp.val[0]); vdest.val[1] = vadd_u8(vdest.val[1], vrp.val[1]); vdest.val[2] = paeth(vdest.val[1], vpp.val[2], vpp.val[1]); vdest.val[2] = vadd_u8(vdest.val[2], vrp.val[2]); vdest.val[3] = paeth(vdest.val[2], vpp.val[3], vpp.val[2]); vdest.val[3] = vadd_u8(vdest.val[3], vrp.val[3]); vlast = vpp.val[3]; vst4_lane_u32(png_ptr(uint32_t,rp), png_ldr(uint32x2x4_t,&vdest), 0); } } #endif /* PNG_ARM_NEON_OPT > 0 */ #endif /* PNG_ARM_NEON_IMPLEMENTATION == 1 (intrinsics) */ #endif /* READ */ ================================================ FILE: tess-two/jni/libpng/autogen.sh ================================================ #! /bin/sh # # Run 'autoreconf' to build 'configure', 'Makefile.in' and other configure # control files. # # The first time this is run on a GIT checkout the only files that exist are # configure.ac and Makefile.am; all of the autotools support scripts are # missing. They are instantiated with autoreconf --force --install. # # For regular ("tarball") distributions all the files should exist. We do not # want them to be updated *under any circumstances*. It should never be # necessary to run autogen.sh because ./configure --enable-maintainer-mode says # what to do if Makefile.am or configure.ac are changed. # # It is *probably* OK to update the files on a GIT checkout, because they have # come from the local tools, but leave that to the user who is assumed to know # whether it is ok or required. # # This script is intended to work without arguments, there are, however, hidden # arguments (a) for use while testing the script and (b) to fix up systems that # have been broken. If (b) is required the script prompts for the correct # options. For this reason the options are *NOT* documented in the help; this # is deliberate; UTSL. # clean= maintainer= while test $# -gt 0 do case "$1" in --maintainer) maintainer=1;; --clean) clean=1;; *) exec >&2 echo "$0: usage: ./autogen.sh" if test -d .git then echo " ./autogen.sh generates the configure script and" echo " Makefile.in, or refreshes them after changes to Makefile.am" echo " or configure.ac. You may prefer to just run autoreconf." elif test -z "$maintainer" then echo " DO NOT RUN THIS SCRIPT." echo " If you need to change Makefile.am or configure.ac then you" echo " also need to run ./configure --enable-maintainer-mode and" echo " use the appropriate autotools, *NOT* this script, to update" echo " everything, please check the documentation of autoreconf." echo " WARNING: libpng is intentionally generated with a known," echo " fixed, set of autotools. It is known *NOT* to work with" echo " the collection of autotools distributed on highly reputable" echo " operating systems." echo " Remember: autotools is GNU software, you are expected to" echo " pay for support." else echo " You have run autogen.sh with --maintainer enabled and you" echo " are not using a GIT distribution, then you have given an" echo " unrecognized argument. This is not good. --maintainer" echo " switches off any assumptions that you might not know what" echo " you are doing." fi exit 1;; esac shift done # # First check for a set of the autotools files; if absent then this is assumed # to be a GIT version and the local autotools must be used. If present this # is a tarball distribution and the script should not be used. If partially # present bad things are happening. # # The autotools generated files: libpng_autotools_files="Makefile.in aclocal.m4 config.guess config.h.in config.sub configure depcomp install-sh ltmain.sh missing\ test-driver" # # Files generated by versions of configue >2.68 or automake >1.13 (i.e. later # versions than those required by configure.ac): libpng_autotools_extra="compile config.h.in~" # # These are separate because 'maintainer-clean' does not remove them. libpng_libtool_files="scripts/libtool.m4 scripts/ltoptions.m4\ scripts/ltsugar.m4 scripts/ltversion.m4 scripts/lt~obsolete.m4" libpng_autotools_dirs="autom4te.cache" # not required # # The configure generated files: libpng_configure_files="Makefile config.h config.log config.status\ libpng-config libpng.pc libtool stamp-h1" libpng_configure_dirs=".deps" # # We must remove the configure generated files as well as the autotools # generated files if autotools are regenerated because otherwise if configure # has been run without "--enable-maintainer-mode" make can do a partial update # of Makefile. These functions do the two bits of cleaning. clean_autotools(){ rm -rf $libpng_autotools_files $libpng_libtool_files $libpng_autotools_dirs rm -rf $libpng_autotools_extra } clean_configure(){ rm -rf $libpng_configure_files $libpng_configure_dirs } # # Clean: remove everything (this is to help with testing) if test -n "$clean" then clean_configure if test -n "$maintainer" then clean_autotools fi exit 0 fi # # Validate the distribution. libpng_autotools_file_found= libpng_autotools_file_missing= for file in $libpng_autotools_files do if test -f "$file" then libpng_autotools_file_found=1 else libpng_autotools_file_missing=1 fi done # # Presence of one of these does not *invalidate* missing, but absence # invalidates found. for file in $libpng_libtool_files do if test ! -f "$file" then libpng_autotools_file_missing=1 fi done # # The cache directory doesn't matter - it will be regenerated and does not exist # anyway in a tarball. # # Either everything is missing or everything is there, the --maintainer option # just changes this so that the mode is set to generate all the files. mode= if test -z "$libpng_autotools_file_found" -o -n "$maintainer" then mode="autoreconf" else if test -n "$libpng_autotools_file_missing" then mode="broken" else mode="configure" fi fi # # So: case "$mode" in autoreconf) # Clean in case configure files exist clean_configure clean_autotools # Everything must be initialized, so use --force if autoreconf --warnings=all --force --install then missing= for file in $libpng_autotools_files do test -f "$file" || missing=1 done # ignore the cache directory test -z "$missing" || { exec >&2 echo "autoreconf was run, but did not produce all the expected" echo "files. It is likely that your autotools installation is" echo "not compatible with that expected by libpng." exit 1 } else exec >&2 echo "autoreconf failed: your version of autotools is incompatible" echo "with this libpng version. Please use a distributed archive" echo "(which includes the autotools generated files) and run configure" echo "instead." exit 1 fi;; configure) if test -d .git then exec >&2 echo "ERROR: running autoreconf on an initialized sytem" echo " This is not necessary; it is only necessary to remake the" echo " autotools generated files if Makefile.am or configure.ac" echo " change and make does the right thing with:" echo echo " ./configure --enable-maintainer-mode." echo echo " You can run autoreconf yourself if you don't like maintainer" echo " mode and you can also just run autoreconf -f -i to initialize" echo " everything in the first place; this script is only for" echo " compatibility with prior releases." exit 1 else exec >&2 echo "autogen.sh is intended only to generate 'configure' on systems" echo "that do not have it. You have a complete 'configure', if you" echo "need to change Makefile.am or configure.ac you also need to" echo "run configure with the --enable-maintainer-mode option." exit 1 fi;; broken) exec >&2 echo "Your system has a partial set of autotools generated files." echo "autogen.sh is unable to proceed. The full set of files is" echo "contained in the libpng 'tar' distribution archive and you do" echo "not need to run autogen.sh if you use it." exit 1;; esac ================================================ FILE: tess-two/jni/libpng/configure.ac ================================================ # configure.ac # Copyright (c) 2004-2016 Glenn Randers-Pehrson # Last changed in libpng 1.6.25 [September 1, 2016] # This code is released under the libpng license. # For conditions of distribution and use, see the disclaimer # and license in png.h dnl Process this file with autoconf to produce a configure script. dnl dnl Minor upgrades (compatible ABI): increment the package version dnl (third field in two places below) and set the PNGLIB_RELEASE dnl variable. dnl dnl Major upgrades (incompatible ABI): increment the package major dnl version (second field, or first if desired), set the minor dnl to 0, set PNGLIB_MAJOR below *and* follow the instructions in dnl Makefile.am to upgrade the package name. dnl This is here to prevent earlier autoconf from being used, it dnl should not be necessary to regenerate configure if the time dnl stamps are correct AC_PREREQ([2.68]) dnl Version number stuff here: AC_INIT([libpng],[1.6.25],[png-mng-implement@lists.sourceforge.net]) AC_CONFIG_MACRO_DIR([scripts]) # libpng does not follow GNU file name conventions (hence 'foreign') # color-tests requires automake 1.11 or later # silent-rules requires automake 1.11 or later # dist-xz requires automake 1.11 or later # 1.12.2 fixes a security issue in 1.11.2 and 1.12.1 # 1.13 is required for parallel tests AM_INIT_AUTOMAKE([1.13 foreign dist-xz color-tests silent-rules subdir-objects]) # The following line causes --disable-maintainer-mode to be the default to # configure. This is necessary because libpng distributions cannot rely on the # time stamps of the autotools generated files being correct AM_MAINTAINER_MODE dnl configure.ac and Makefile.am expect automake 1.11.2 or a compatible later dnl version; aclocal.m4 will generate a failure if you use a prior version of dnl automake, so the following is not necessary (and is not defined anyway): dnl AM_PREREQ([1.11.2]) dnl stop configure from automagically running automake PNGLIB_VERSION=1.6.25 PNGLIB_MAJOR=1 PNGLIB_MINOR=6 PNGLIB_RELEASE=25 dnl End of version number stuff AC_CONFIG_SRCDIR([pngget.c]) AC_CONFIG_HEADERS([config.h]) # Checks for programs. AC_LANG([C]) AC_PROG_CC AM_PROG_AS LT_PATH_LD AC_PROG_CPP AC_PROG_AWK AC_PROG_INSTALL AC_PROG_LN_S AC_PROG_MAKE_SET dnl libtool/libtoolize; version 2.4.2 is the tested version. This or any dnl compatible later version may be used LT_INIT([win32-dll]) LT_PREREQ([2.4.2]) # Some awks crash when confronted with pnglibconf.dfa, do a test run now # to make sure this doesn't happen AC_MSG_CHECKING([that AWK works]) if ${AWK} -f ${srcdir}/scripts/options.awk out="/dev/null" version=search\ ${srcdir}/pngconf.h ${srcdir}/scripts/pnglibconf.dfa\ ${srcdir}/pngusr.dfa 1>&2 then AC_MSG_RESULT([ok]) else AC_MSG_FAILURE([failed], 1) fi # This is a remnant of the old cc -E validation, where it may have been # necessary to use a different preprocessor for .dfn files DFNCPP="$CPP" AC_SUBST(DFNCPP) # -Werror cannot be passed to GCC in CFLAGS because configure will fail (it # checks the compiler with a program that generates a warning), add the # following option to deal with this AC_ARG_VAR(PNG_COPTS, [additional flags for the C compiler, use this for options that would] [cause configure itself to fail]) AC_ARG_ENABLE(werror, AS_HELP_STRING([[[--enable-werror[=OPT]]]], [Pass -Werror or the given argument to the compiler if it is supported]), [test "$enable_werror" = "yes" && enable_werror="-Werror" if test "$enable_werror" != "no"; then sav_CFLAGS="$CFLAGS" CFLAGS="$enable_werror $CFLAGS" AC_MSG_CHECKING([if the compiler allows $enable_werror]) AC_COMPILE_IFELSE( [AC_LANG_SOURCE([ [int main(int argc, char **argv){] [return argv[argc-1][0];] [}]])], AC_MSG_RESULT(yes) PNG_COPTS="$PNG_COPTS $enable_werror", AC_MSG_RESULT(no)) CFLAGS="$sav_CFLAGS" fi],) # For GCC 5 the default mode for C is -std=gnu11 instead of -std=gnu89 # In pngpriv.h we request just the POSIX 1003.1 and C89 APIs by defining _POSIX_SOURCE to 1 # This is incompatible with the new default mode, so we test for that and force the # "-std=c89" compiler option: AC_MSG_CHECKING([if we need to force back C standard to C89]) AC_COMPILE_IFELSE( [AC_LANG_PROGRAM([ [#define _POSIX_SOURCE 1] [#include ] ])], AC_MSG_RESULT(no),[ if test "x$GCC" != "xyes"; then AC_MSG_ERROR( [Forcing back to C89 is required but the flags are only known for GCC]) fi AC_MSG_RESULT(yes) CFLAGS="$CFLAGS -std=c89" ]) # Checks for header files. AC_HEADER_STDC # Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_SIZE_T AC_STRUCT_TM AC_C_RESTRICT # Checks for library functions. AC_FUNC_STRTOD AC_CHECK_FUNCS([memset], , AC_MSG_ERROR(memset not found in libc)) AC_CHECK_FUNCS([pow], , AC_CHECK_LIB(m, pow, , AC_MSG_ERROR(cannot find pow)) ) # Some later POSIX 1003.1 functions are required for test programs, failure here # is soft (the corresponding test program is not built). AC_CHECK_FUNC([clock_gettime],,[AC_MSG_WARN([not building timepng])]) AM_CONDITIONAL([HAVE_CLOCK_GETTIME], [test "$ac_cv_func_clock_gettime" = "yes"]) AC_ARG_WITH(zlib-prefix, AS_HELP_STRING([[[--with-zlib-prefix]]], [prefix that may have been used in installed zlib]), [ZPREFIX=${withval}], [ZPREFIX='z_']) AC_CHECK_LIB(z, zlibVersion, , AC_CHECK_LIB(z, ${ZPREFIX}zlibVersion, , AC_MSG_ERROR(zlib not installed))) # The following is for pngvalid, to ensure it catches FP errors even on # platforms that don't enable FP exceptions, the function appears in the math # library (typically), it's not an error if it is not found. AC_CHECK_LIB([m], [feenableexcept]) AC_CHECK_FUNCS([feenableexcept]) AC_MSG_CHECKING([if using Solaris linker]) SLD=`$LD --version 2>&1 | grep Solaris` if test "$SLD"; then have_solaris_ld=yes AC_MSG_RESULT(yes) else have_solaris_ld=no AC_MSG_RESULT(no) fi AM_CONDITIONAL(HAVE_SOLARIS_LD, test "$have_solaris_ld" = "yes") AC_MSG_CHECKING([if libraries can be versioned]) # Special case for PE/COFF platforms: ld reports # support for version-script, but doesn't actually # DO anything with it. case $host in *cygwin* | *mingw32* | *interix* ) have_ld_version_script=no AC_MSG_RESULT(no) ;; * ) if test "$have_solaris_ld" = "yes"; then GLD=`$LD --help < /dev/null 2>&1 | grep 'M mapfile'` else GLD=`$LD --help < /dev/null 2>/dev/null | grep version-script` fi if test "$GLD"; then have_ld_version_script=yes AC_MSG_RESULT(yes) else have_ld_version_script=no AC_MSG_RESULT(no) AC_MSG_WARN(*** You have not enabled versioned symbols.) fi ;; esac AM_CONDITIONAL(HAVE_LD_VERSION_SCRIPT, test "$have_ld_version_script" = "yes") if test "$have_ld_version_script" = "yes"; then AC_MSG_CHECKING([for symbol prefix]) SYMBOL_PREFIX=`echo "PREFIX=__USER_LABEL_PREFIX__" \ | ${CPP-${CC-gcc} -E} - 2>&1 \ | ${EGREP-grep} "^PREFIX=" \ | ${SED-sed} -e "s:^PREFIX=::" -e "s:__USER_LABEL_PREFIX__::"` AC_SUBST(SYMBOL_PREFIX) AC_MSG_RESULT($SYMBOL_PREFIX) fi # Substitutions for .in files AC_SUBST(PNGLIB_VERSION) AC_SUBST(PNGLIB_MAJOR) AC_SUBST(PNGLIB_MINOR) AC_SUBST(PNGLIB_RELEASE) # Additional arguments (and substitutions) # Allow the pkg-config directory to be set AC_ARG_WITH(pkgconfigdir, AS_HELP_STRING([[[--with-pkgconfigdir]]], [Use the specified pkgconfig dir (default is libdir/pkgconfig)]), [pkgconfigdir=${withval}], [pkgconfigdir='${libdir}/pkgconfig']) AC_SUBST([pkgconfigdir]) AC_MSG_NOTICE([[pkgconfig directory is ${pkgconfigdir}]]) # Make the *-config binary config scripts optional AC_ARG_WITH(binconfigs, AS_HELP_STRING([[[--with-binconfigs]]], [Generate shell libpng-config scripts as well as pkg-config data] [@<:@default=yes@:>@]), [if test "${withval}" = no; then binconfigs= AC_MSG_NOTICE([[libpng-config scripts will not be built]]) else binconfigs='${binconfigs}' fi], [binconfigs='${binconfigs}']) AC_SUBST([binconfigs]) # Support for prefixes to the API function names; this will generate defines # at the start of the build to rename exported library functions AC_ARG_WITH(libpng-prefix, AS_HELP_STRING([[[--with-libpng-prefix]]], [prefix libpng exported function (API) names with the given value]), [if test "${withval:-no}" != "no"; then AC_SUBST([PNG_PREFIX], [${withval}]) fi]) AM_CONDITIONAL([DO_PNG_PREFIX], [test "${with_libpng_prefix:-no}" != "no"]) # Control over what links are made for installed files. Versioned files are # always installed, when the following options are turned on corresponding # unversioned links are also created (normally as symbolic links): AC_ARG_ENABLE([unversioned-links], AS_HELP_STRING([[[--enable-unversioned-links]]], [Installed libpng header files are placed in a versioned subdirectory] [and installed libpng library (including DLL) files are versioned.] [If this option is enabled unversioned links will be created pointing to] [the corresponding installed files. If you use libpng.pc or] [libpng-config for all builds you do not need these links, but if you] [compile programs directly they will typically #include and] [link with -lpng; in that case you need the links.] [The links can be installed manually using 'make install-header-links'] [and 'make install-library-links' and can be removed using the] [corresponding uninstall- targets. If you do enable this option every] [libpng 'make install' will recreate the links to point to the just] [installed version of libpng. The default is to create the links;] [use --disable-unversioned-links to change this])) # The AM_CONDITIONAL test is written so that the default is enabled; # --disable-unversioned-links must be given to turn the option off. AM_CONDITIONAL([DO_INSTALL_LINKS],[test "$enable_unversioned_links" != "no"]) AC_ARG_ENABLE([unversioned-libpng-pc], AS_HELP_STRING([[[--enable-unversioned-libpng-pc]]], [Install the configuration file 'libpng.pc' as a link to the versioned] [version. This is done by default - use --disable-unversioned-libpng-pc] [to change this.])) AM_CONDITIONAL([DO_INSTALL_LIBPNG_PC], [test "$enable_unversioned_libpng_pc" != "no"]) AC_ARG_ENABLE([unversioned-libpng-config], AS_HELP_STRING([[[--enable-unversioned-libpng-config]]], [Install the configuration file 'libpng-config' as a link to the] [versioned version. This is done by default - use] [--disable-unversioned-libpng-config to change this.])) AM_CONDITIONAL([DO_INSTALL_LIBPNG_CONFIG], [test "$enable_unversioned_libpng_config" != "no"]) # HOST SPECIFIC OPTIONS # ===================== # # ARM # === # # ARM NEON (SIMD) support. AC_ARG_ENABLE([arm-neon], AS_HELP_STRING([[[--enable-arm-neon]]], [Enable ARM NEON optimizations: =no/off, check, api, yes/on:] [no/off: disable the optimizations; check: use internal checking code] [(deprecated and poorly supported); api: disable by default, enable by] [a call to png_set_option; yes/on: turn on unconditionally.] [If not specified: determined by the compiler.]), [case "$enableval" in no|off) # disable the default enabling on __ARM_NEON__ systems: AC_DEFINE([PNG_ARM_NEON], [], [ARM NEON support]) AC_DEFINE([PNG_ARM_NEON_OPT], [0], [Disable ARM Neon optimizations]) # Prevent inclusion of the assembler files below: enable_arm_neon=no;; check) AC_DEFINE([PNG_ARM_NEON], [], [ARM NEON support]) AC_DEFINE([PNG_ARM_NEON_CHECK_SUPPORTED], [], [Check for ARM Neon support at run-time]);; api) AC_DEFINE([PNG_ARM_NEON], [], [ARM NEON support]) AC_DEFINE([PNG_ARM_NEON_API_SUPPORTED], [], [Turn on ARM Neon optimizations at run-time]);; yes|on) AC_DEFINE([PNG_ARM_NEON], [], [ARM NEON support]) AC_DEFINE([PNG_ARM_NEON_OPT], [2], [Enable ARM Neon optimizations]) AC_MSG_WARN([--enable-arm-neon: please specify 'check' or 'api', if] [you want the optimizations unconditionally pass -mfpu=neon] [to the compiler.]);; *) AC_MSG_ERROR([--enable-arm-neon=${enable_arm_neon}: invalid value]) esac]) # Add ARM specific files to all builds where the host_cpu is arm ('arm*') or # where ARM optimizations were explicitly requested (this allows a fallback if a # future host CPU does not match 'arm*') AM_CONDITIONAL([PNG_ARM_NEON], [test "$enable_arm_neon" != 'no' && case "$host_cpu" in arm*|aarch64*) :;; *) test "$enable_arm_neon" != '';; esac]) # MIPS # === # # MIPS MSA (SIMD) support. AC_ARG_ENABLE([mips-msa], AS_HELP_STRING([[[--enable-mips-msa]]], [Enable MIPS MSA optimizations: =no/off, check, api, yes/on:] [no/off: disable the optimizations; check: use internal checking code] [(deprecated and poorly supported); api: disable by default, enable by] [a call to png_set_option; yes/on: turn on unconditionally.] [If not specified: determined by the compiler.]), [case "$enableval" in no|off) # disable the default enabling on __mips_msa systems: AC_DEFINE([PNG_MIPS_MSA_OPT], [0], [Disable MIPS MSA optimizations]) # Prevent inclusion of the assembler files below: enable_mips_msa=no;; check) AC_DEFINE([PNG_MIPS_MSA_CHECK_SUPPORTED], [], [Check for MIPS MSA support at run-time]);; api) AC_DEFINE([PNG_MIPS_MSA_API_SUPPORTED], [], [Turn on MIPS MSA optimizations at run-time]);; yes|on) AC_DEFINE([PNG_MIPS_MSA_OPT], [2], [Enable MIPS MSA optimizations]) AC_MSG_WARN([--enable-mips-msa: please specify 'check' or 'api', if] [you want the optimizations unconditionally pass '-mmsa -mfp64'] [to the compiler.]);; *) AC_MSG_ERROR([--enable-mips-msa=${enable_mips_msa}: invalid value]) esac]) # Add MIPS specific files to all builds where the host_cpu is mips ('mips*') or # where MIPS optimizations were explicitly requested (this allows a fallback if a # future host CPU does not match 'mips*') AM_CONDITIONAL([PNG_MIPS_MSA], [test "$enable_mips_msa" != 'no' && case "$host_cpu" in mipsel*|mips64el*) :;; esac]) # INTEL # ===== # # INTEL SSE (SIMD) support. AC_ARG_ENABLE([intel-sse], AS_HELP_STRING([[[--enable-intel-sse]]], [Enable Intel SSE optimizations: =no/off, yes/on:] [no/off: disable the optimizations;] [yes/on: enable the optimizations.] [If not specified: determined by the compiler.]), [case "$enableval" in no|off) # disable the default enabling: AC_DEFINE([PNG_INTEL_SSE_OPT], [0], [Disable Intel SSE optimizations]) # Prevent inclusion of the assembler files below: enable_intel_sse=no;; yes|on) AC_DEFINE([PNG_INTEL_SSE_OPT], [1], [Enable Intel SSE optimizations]);; *) AC_MSG_ERROR([--enable-intel-sse=${enable_intel_sse}: invalid value]) esac]) # Add Intel specific files to all builds where the host_cpu is Intel ('x86*') # or where Intel optimizations were explicitly requested (this allows a # fallback if a future host CPU does not match 'x86*') AM_CONDITIONAL([PNG_INTEL_SSE], [test "$enable_intel_sse" != 'no' && case "$host_cpu" in i?86|x86_64) :;; *) test "$enable_intel_sse" != '';; esac]) AC_MSG_NOTICE([[Extra options for compiler: $PNG_COPTS]]) # Config files, substituting as above AC_CONFIG_FILES([Makefile libpng.pc:libpng.pc.in]) AC_CONFIG_FILES([libpng-config:libpng-config.in], [chmod +x libpng-config]) AC_OUTPUT ================================================ FILE: tess-two/jni/libpng/contrib/README.txt ================================================ This "contrib" directory contains contributions which are not necessarily under the libpng license, although all are open source. They are not part of libpng proper and are not used for building the library, although some are used for testing the library via "make check". ================================================ FILE: tess-two/jni/libpng/contrib/arm-neon/README ================================================ OPERATING SYSTEM SPECIFIC ARM NEON DETECTION -------------------------------------------- Detection of the ability to execute ARM NEON on an ARM processor requires operating system support. (The information is not available in user mode.) HOW TO USE THIS --------------- This directory contains C code fragments that can be included in arm/arm_init.c by setting the macro PNG_ARM_NEON_FILE to the file name in "" or <> at build time. This setting is not recorded in pnglibconf.h and can be changed simply by rebuilding arm/arm_init.o with the required macro definition. For any of this code to be used the ARM NEON code must be enabled and run time checks must be supported. I.e.: #if PNG_ARM_NEON_OPT > 0 #ifdef PNG_ARM_NEON_CHECK_SUPPORTED This is done in a 'configure' build by passing configure the argument: --enable-arm-neon=check Apart from the basic Linux implementation in contrib/arm-neon/linux.c this code is unsupported. That means that it is not even compiled on a regular basis and may be broken in any given minor release. FILE FORMAT ----------- Each file documents its testing status as of the last time it was tested (which may have been a long time ago): STATUS: one of: SUPPORTED: This indicates that the file is included in the regularly performed test builds and bugs are fixed when discovered. COMPILED: This indicates that the code did compile at least once. See the more detailed description for the extent to which the result was successful. TESTED: This means the code was fully compiled into the libpng test programs and these were run at least once. BUG REPORTS: an email address to which to send reports of problems The file is a fragment of C code. It should not define any 'extern' symbols; everything should be static. It must define the function: static int png_have_neon(png_structp png_ptr); That function must return 1 if ARM NEON instructions are supported, 0 if not. It must not execute png_error unless it detects a bug. A png_error will prevent the reading of the PNG and in the future, writing too. BUG REPORTS ----------- If you mail a bug report for any file that is not SUPPORTED there may only be limited response. Consider fixing it and sending a patch to fix the problem - this is more likely to result in action. CONTRIBUTIONS ------------- You may send contributions of new implementations to png-mng-implement@sourceforge.net. Please write code in strict C90 C where possible. Obviously OS dependencies are to be expected. If you submit code you must have the authors permission and it must have a license that is acceptable to the current maintainer; in particular that license must permit modification and redistribution. Please try to make the contribution a single file and give the file a clear and unambiguous name that identifies the target OS. If multiple files really are required put them all in a sub-directory. You must also be prepared to handle bug reports from users of the code, either by joining the png-mng-implement mailing list or by providing an email for the "BUG REPORTS" entry or both. Please make sure that the header of the file contains the STATUS and BUG REPORTS fields as above. Please list the OS requirements as precisely as possible. Ideally you should also list the environment in which the code has been tested and certainly list any environments where you suspect it might not work. ================================================ FILE: tess-two/jni/libpng/contrib/arm-neon/android-ndk.c ================================================ /* contrib/arm-neon/android-ndk.c * * Copyright (c) 2014 Glenn Randers-Pehrson * Written by John Bowler, 2014. * Last changed in libpng 1.6.10 [March 6, 2014] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * SEE contrib/arm-neon/README before reporting bugs * * STATUS: COMPILED, UNTESTED * BUG REPORTS: png-mng-implement@sourceforge.net * * png_have_neon implemented for the Android NDK, see: * * Documentation: * http://www.kandroid.org/ndk/docs/CPU-ARM-NEON.html * http://code.google.com/p/android/issues/detail?id=49065 * * NOTE: this requires that libpng is built against the Android NDK and linked * with an implementation of the Android ARM 'cpu-features' library. The code * has been compiled only, not linked: no version of the library has been found, * only the header files exist in the NDK. */ #include static int png_have_neon(png_structp png_ptr) { /* This is a whole lot easier than the linux code, however it is probably * implemented as below, therefore it is better to cache the result (these * function calls may be slow!) */ PNG_UNUSED(png_ptr) return android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM && (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0; } ================================================ FILE: tess-two/jni/libpng/contrib/arm-neon/linux-auxv.c ================================================ /* contrib/arm-neon/linux-auxv.c * * Copyright (c) 2014 Glenn Randers-Pehrson * Written by Mans Rullgard, 2011. * Last changed in libpng 1.6.10 [March 6, 2014] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * SEE contrib/arm-neon/README before reporting bugs * * STATUS: COMPILED, TESTED * BUG REPORTS: png-mng-implement@sourceforge.net * * png_have_neon implemented for Linux versions which allow access to * /proc/self/auxv. This is probably faster, cleaner and safer than the code to * read /proc/cpuinfo in contrib/arm-neon/linux, however it is yet another piece * of potentially untested code and has more complex dependencies than the code * to read cpuinfo. * * This generic __linux__ implementation requires reading /proc/self/auxv and * looking at each element for one that records NEON capabilities. */ #include /* for POSIX 1003.1 */ #include /* for EINTR */ #include #include #include #include #include /* A read call may be interrupted, in which case it returns -1 and sets errno to * EINTR if nothing was done, otherwise (if something was done) a partial read * may result. */ static size_t safe_read(png_structp png_ptr, int fd, void *buffer_in, size_t nbytes) { size_t ntotal = 0; char *buffer = png_voidcast(char*, buffer_in); while (nbytes > 0) { unsigned int nread; int iread; /* Passing nread > INT_MAX to read is implementation defined in POSIX * 1003.1, therefore despite the unsigned argument portable code must * limit the value to INT_MAX! */ if (nbytes > INT_MAX) nread = INT_MAX; else nread = (unsigned int)/*SAFE*/nbytes; iread = read(fd, buffer, nread); if (iread == -1) { /* This is the devil in the details, a read can terminate early with 0 * bytes read because of EINTR, yet it still returns -1 otherwise end * of file cannot be distinguished. */ if (errno != EINTR) { png_warning(png_ptr, "/proc read failed"); return 0; /* I.e., a permanent failure */ } } else if (iread < 0) { /* Not a valid 'read' result: */ png_warning(png_ptr, "OS /proc read bug"); return 0; } else if (iread > 0) { /* Continue reading until a permanent failure, or EOF */ buffer += iread; nbytes -= (unsigned int)/*SAFE*/iread; ntotal += (unsigned int)/*SAFE*/iread; } else return ntotal; } return ntotal; /* nbytes == 0 */ } static int png_have_neon(png_structp png_ptr) { int fd = open("/proc/self/auxv", O_RDONLY); Elf32_auxv_t aux; /* Failsafe: failure to open means no NEON */ if (fd == -1) { png_warning(png_ptr, "/proc/self/auxv open failed"); return 0; } while (safe_read(png_ptr, fd, &aux, sizeof aux) == sizeof aux) { if (aux.a_type == AT_HWCAP && (aux.a_un.a_val & HWCAP_NEON) != 0) { close(fd); return 1; } } close(fd); return 0; } ================================================ FILE: tess-two/jni/libpng/contrib/arm-neon/linux.c ================================================ /* contrib/arm-neon/linux.c * * Copyright (c) 2014 Glenn Randers-Pehrson * Written by John Bowler, 2014. * Last changed in libpng 1.6.16 [December 22, 2014] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * SEE contrib/arm-neon/README before reporting bugs * * STATUS: SUPPORTED * BUG REPORTS: png-mng-implement@sourceforge.net * * png_have_neon implemented for Linux by reading the widely available * pseudo-file /proc/cpuinfo. * * This code is strict ANSI-C and is probably moderately portable; it does * however use and it assumes that /proc/cpuinfo is never localized. */ #include static int png_have_neon(png_structp png_ptr) { FILE *f = fopen("/proc/cpuinfo", "rb"); if (f != NULL) { /* This is a simple state machine which reads the input byte-by-byte until * it gets a match on the 'neon' feature or reaches the end of the stream. */ static const char ch_feature[] = { 70, 69, 65, 84, 85, 82, 69, 83 }; static const char ch_neon[] = { 78, 69, 79, 78 }; enum { StartLine, Feature, Colon, StartTag, Neon, HaveNeon, SkipTag, SkipLine } state; int counter; for (state=StartLine, counter=0;;) { int ch = fgetc(f); if (ch == EOF) { /* EOF means error or end-of-file, return false; neon at EOF is * assumed to be a mistake. */ fclose(f); return 0; } switch (state) { case StartLine: /* Match spaces at the start of line */ if (ch <= 32) /* skip control characters and space */ break; counter=0; state = Feature; /* FALL THROUGH */ case Feature: /* Match 'FEATURE', ASCII case insensitive. */ if ((ch & ~0x20) == ch_feature[counter]) { if (++counter == (sizeof ch_feature)) state = Colon; break; } /* did not match 'feature' */ state = SkipLine; /* FALL THROUGH */ case SkipLine: skipLine: /* Skip everything until we see linefeed or carriage return */ if (ch != 10 && ch != 13) break; state = StartLine; break; case Colon: /* Match any number of space or tab followed by ':' */ if (ch == 32 || ch == 9) break; if (ch == 58) /* i.e. ':' */ { state = StartTag; break; } /* Either a bad line format or a 'feature' prefix followed by * other characters. */ state = SkipLine; goto skipLine; case StartTag: /* Skip space characters before a tag */ if (ch == 32 || ch == 9) break; state = Neon; counter = 0; /* FALL THROUGH */ case Neon: /* Look for 'neon' tag */ if ((ch & ~0x20) == ch_neon[counter]) { if (++counter == (sizeof ch_neon)) state = HaveNeon; break; } state = SkipTag; /* FALL THROUGH */ case SkipTag: /* Skip non-space characters */ if (ch == 10 || ch == 13) state = StartLine; else if (ch == 32 || ch == 9) state = StartTag; break; case HaveNeon: /* Have seen a 'neon' prefix, but there must be a space or new * line character to terminate it. */ if (ch == 10 || ch == 13 || ch == 32 || ch == 9) { fclose(f); return 1; } state = SkipTag; break; default: png_error(png_ptr, "png_have_neon: internal error (bug)"); } } } #ifdef PNG_WARNINGS_SUPPORTED else png_warning(png_ptr, "/proc/cpuinfo open failed"); #endif return 0; } ================================================ FILE: tess-two/jni/libpng/contrib/conftest/README ================================================ This directory contains test configuration files, currently always '.dfa' files intended to be used in the build by setting the make macro DFA_XTRA to the name of the file. These files are used in release validation of the 'configure' builds of libpng by building 'make check', or 'make all-am' for cross-builds, with each .dfa file. The files in this directory may change between minor releases, however contributions describing specific builds of libpng are welcomed. There is no guarantee that libpng will continue to build with such configurations; support for given configurations can be, and has been, dropped between successive minor releases. However if a .dfa file describing a configuration is not in this directory it is very unlikely that it will be tested before a minor release! You can use these .dfa files as the basis of new configurations. Files in this directory should not have any use restrictions or restrictive licenses. This directory is not included in the .zip and .7z distributions, which do not contain 'configure' scripts. DOCUMENTATION ============= Examples: ${srcdir}/pngusr.dfa ${srcdir}/contrib/pngminim/*/pngusr.dfa Documentation of the options: ${srcdir}/scripts/pnglibconf.dfa Documentation of the file format: ${srcdir}/scripts/options.awk FILE NAMING =========== File names in this directory may NOT contain any of the five characters: - , + * ? Neither may they contain any space character. While other characters may be used it is strongly suggested that file names be limited to lower case Latiin alphabetic characters (a-z), digits (0-9) and, if necessary the underscore (_) character. File names should be about 8 characters long (excluding the .dfa extension). Submitted .dfa files should have names between 7 and 16 characters long, shorter names (6 characters or less) are reserved for standard tests. ================================================ FILE: tess-two/jni/libpng/contrib/conftest/pngcp.dfa ================================================ # pngcp.dfa # Build time configuration of libpng # # Author: John Bowler # Copyright: (c) John Bowler, 2016 # Usage rights: # To the extent possible under law, the author has waived all copyright and # related or neighboring rights to this work. This work is published from: # United States. # # Build libpng with support for pngcp. This means just png_read_png, # png_write_png and small number of configuration settings. # everything = off # This option is specific to this configuration; it adds a #define to the # generated pnglibconf.h which turns on the (not portable) timing option for # pngcp. Note that any option is automatically preceded by PNG_; there is no # way round this and this is deliberate. option PNGCP_TIMING # Because of the everything off above the option must also be turned on. This # may not be done in one step because it is safer and avoids mis-spelled options # in user .dfa files to error out if an unrecognized option is turned on. option PNGCP_TIMING on # Options to turn on png_read_png and png_write_png: option INFO_IMAGE on option SEQUENTIAL_READ on option EASY_ACCESS on option WRITE on option WRITE_16BIT on option WRITE_FILTER on # pngcp needs this to preserve unknown chunks, switching all these on means that # pngcp can work without explicit known chunk reading suppport option UNKNOWN_CHUNKS on option SET_UNKNOWN_CHUNKS on option HANDLE_AS_UNKNOWN on option SAVE_UNKNOWN_CHUNKS on option WRITE_UNKNOWN_CHUNKS on # pngcp needs this to handle palette files with invalid indices: option CHECK_FOR_INVALID_INDEX on option GET_PALETTE_MAX on # Pre-libpng 1.7 pngcp has to stash text chunks manually, post 1.7 without this # text chunks should be handled as unknown ok. option TEXT on # this is used to turn off limits: option USER_LIMITS on option SET_USER_LIMITS on # these are are just required for specific customizations option WRITE_CUSTOMIZE_ZTXT_COMPRESSION on option WRITE_CUSTOMIZE_COMPRESSION on ================================================ FILE: tess-two/jni/libpng/contrib/conftest/read.dfa ================================================ # read.dfa # Build time configuration of libpng # # Author: John Bowler # Copyright: (c) John Bowler, 2013 # Usage rights: # To the extent possible under law, the author has waived all copyright and # related or neighboring rights to this work. This work is published from: # United States. # # Build libpng with basic read support. This enables the lowest level libpng # read API - the one where the calling code has to use a loop to read each row. # At present this is the API used by most programs. # # Support is enabled only for those chunks and transformations that are # typically required - others can be added easily. # everything = off # The sequential read code is enabled here; the progressive code can be used # instead but there is no point enabling both. option SEQUENTIAL_READ on # Likewise it is pointless enabling both fixed and floating point APIs. Choose # one or the other for both the API and the internal math. #Fixed point: #option FIXED_POINT on #option FLOATING_ARITHMETIC off #Floating point: option FLOATING_POINT on option FLOATING_ARITHMETIC on # Basic error handling, IO and user memory support. The latter allows the # application program to provide its own implementations of 'malloc' and 'free'. option SETJMP on option STDIO on option USER_MEM on # To read the full set of PNG images correctly interlace, transparency and # 16-bit support is required. The application can implement interlace itself, # but very few do and it's no longer possible to disable it when READ is # enabled. option READ_tRNS on option READ_16BIT on # Everything else is application dependent. This file assumes the app handles # all the native PNG bit layouts, so it doesn't need any of layout change # transforms, but needs libpng to perform gamma correction. It doesn't do any # colorspace stuff and ignores the 'significant bit' information. # # If your app always expands the image to a limited set of bit layouts you # probably want to consider using the simplified API instead of the low level # one - see png.h and s_read.dfa. option READ_GAMMA on ================================================ FILE: tess-two/jni/libpng/contrib/conftest/s_read.dfa ================================================ # s_read.dfa # Build time configuration of libpng # # Author: John Bowler # Copyright: (c) John Bowler, 2013 # Usage rights: # To the extent possible under law, the author has waived all copyright and # related or neighboring rights to this work. This work is published from: # United States. # # Build libpng with simplified read support (only). This builds a minimal # libpng able to read all PNG formats and convert them into a small number of # well understood memory formats. # everything = off option SIMPLIFIED_READ on # It isn't necessary to chose fixed or floating point for the APIs because the # simplified API doesn't need fixed or floating point numbers. It is necessary # to chose an internal math implementation. The default (because of 'everything # = off') is fixed point - turn the floating point implementation on if you have # hardware floating point or prefer your software floating point implementation. option FLOATING_ARITHMETIC on # This is not strictly necessary, but without it the message strings in the API # will not be filled in option ERROR_TEXT on # Switching these options on enables the 'AFIRST' and 'BGR' formats - you don't # need this if you don't use them, they just allow the in-memory layout to be # changed to match common hardware formats. option SIMPLIFIED_READ_AFIRST on option SIMPLIFIED_READ_BGR on ================================================ FILE: tess-two/jni/libpng/contrib/conftest/s_write.dfa ================================================ # s_write.dfa # Build time configuration of libpng # # Author: John Bowler # Copyright: (c) John Bowler, 2013 # Usage rights: # To the extent possible under law, the author has waived all copyright and # related or neighboring rights to this work. This work is published from: # United States. # # Build libpng with (just) simplified write support # everything = off option SIMPLIFIED_WRITE on # It isn't necessary to chose fixed or floating point for the APIs because the # simplified API doesn't need fixed or floating point numbers. It is necessary # to chose an internal math implementation. The default (because of 'everything # = off') is fixed point - turn the floating point implementation on if you have # hardware floating point or prefer your software floating point implementation. option FLOATING_ARITHMETIC on # This is not strictly necessary, but without it the message strings in the API # will not be filled in option ERROR_TEXT on # Switching these options on enables the 'AFIRST' and 'BGR' formats - you don't # need this if you don't use them, they just allow the in-memory layout to be # changed to match common hardware formats. option SIMPLIFIED_WRITE_AFIRST on option SIMPLIFIED_WRITE_BGR on ================================================ FILE: tess-two/jni/libpng/contrib/conftest/simple.dfa ================================================ # simple.dfa # Build time configuration of libpng # # Author: John Bowler # Copyright: (c) John Bowler, 2013 # Usage rights: # To the extent possible under law, the author has waived all copyright and # related or neighboring rights to this work. This work is published from: # United States. # # Build libpng with just the simplified APIs (read and write). # everything = off option SIMPLIFIED_WRITE on option SIMPLIFIED_READ on # It isn't necessary to chose fixed or floating point for the APIs because the # simplified API doesn't need fixed or floating point numbers. It is necessary # to chose an internal math implementation. The default (because of 'everything # = off') is fixed point - turn the floating point implementation on if you have # hardware floating point or prefer your software floating point implementation. option FLOATING_ARITHMETIC on # This is not strictly necessary, but without it the message strings in the API # will not be filled in option ERROR_TEXT on # Switching these options on enables the 'AFIRST' and 'BGR' formats - you don't # need this if you don't use them, they just allow the in-memory layout to be # changed to match common hardware formats. option SIMPLIFIED_READ_AFIRST on option SIMPLIFIED_READ_BGR on option SIMPLIFIED_WRITE_AFIRST on option SIMPLIFIED_WRITE_BGR on ================================================ FILE: tess-two/jni/libpng/contrib/conftest/write.dfa ================================================ # write.dfa # Build time configuration of libpng # # Author: John Bowler # Copyright: (c) John Bowler, 2013 # Usage rights: # To the extent possible under law, the author has waived all copyright and # related or neighboring rights to this work. This work is published from: # United States. # # Build libpng with no read support and minimal write support. # everything = off # Switch on the write code - this makes a minimalist encoder option WRITE on # Choose fixed or floating point APIs and arithmetic. The choices are # independent but normally they will match. It is typically better to use the # floating point if you have floating point hardware. If you don't know, or # (perhaps) to make libpng smaller used fixed point throughout. #Fixed point: #option FIXED_POINT on #option FLOATING_ARITHMETIC off #Floating point: option FLOATING_POINT on option FLOATING_ARITHMETIC on # Basic error handling, IO and user memory support. The latter allows the # application program to provide its own implementations of 'malloc' and 'free'. option SETJMP on option STDIO on option USER_MEM on # Everything else is optional. Unlike the read code in libpng the write code # does not need to deal with arbitrary formats, so only add support for things # you really do write! For example you might only write sRGB images, sometimes # with transparency and never write 16 bit images, so: option WRITE_sRGB on option WRITE_tRNS on #option WRITE_16BIT off (this is the default with 'everything = off') ================================================ FILE: tess-two/jni/libpng/contrib/examples/README.txt ================================================ This directory (contrib/examples) contains examples of libpng usage. NO COPYRIGHT RIGHTS ARE CLAIMED TO ANY OF THE FILES IN THIS DIRECTORY. To the extent possible under law, the authors have waived all copyright and related or neighboring rights to this work. This work is published from: United States. The files may be used freely in any way. The intention is that appropriate parts of the files be used in other libpng-using programs without any need for the authors of the using code to seek copyright or license from the original authors. The source code and comments in this directory are the original work of the people named below. No other person or organization has made contributions to the work in this directory. ORIGINAL AUTHORS The following people have contributed to the code in this directory. None of the people below claim any rights with regard to the contents of this directory. John Bowler ================================================ FILE: tess-two/jni/libpng/contrib/examples/iccfrompng.c ================================================ /*- iccfrompng * * COPYRIGHT: Written by John Cunningham Bowler, 2011. * To the extent possible under law, the author has waived all copyright and * related or neighboring rights to this work. This work is published from: * United States. * * Extract any icc profiles found in the given PNG files. This is a simple * example of a program that extracts information from the header of a PNG file * without processing the image. Notice that some header information may occur * after the image data. Textual data and comments are an example; the approach * in this file won't work reliably for such data because it only looks for the * information in the section of the file that preceeds the image data. * * Compile and link against libpng and zlib, plus anything else required on the * system you use. * * To use supply a list of PNG files containing iCCP chunks, the chunks will be * extracted to a similarly named file with the extension replaced by 'icc', * which will be overwritten without warning. */ #include #include #include #include #include #if defined(PNG_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED) && \ defined (PNG_iCCP_SUPPORTED) static int verbose = 1; static png_byte no_profile[] = "no profile"; static png_bytep extract(FILE *fp, png_uint_32 *proflen) { png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0); png_infop info_ptr = NULL; png_bytep result = NULL; /* Initialize for error or no profile: */ *proflen = 0; if (png_ptr == NULL) { fprintf(stderr, "iccfrompng: version library mismatch?\n"); return 0; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 0; } png_init_io(png_ptr, fp); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); png_read_info(png_ptr, info_ptr); { png_charp name; int compression_type; png_bytep profile; if (png_get_iCCP(png_ptr, info_ptr, &name, &compression_type, &profile, proflen) & PNG_INFO_iCCP) { result = malloc(*proflen); if (result != NULL) memcpy(result, profile, *proflen); else png_error(png_ptr, "OOM allocating profile buffer"); } else result = no_profile; } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return result; } static int extract_one_file(const char *filename) { int result = 0; FILE *fp = fopen(filename, "rb"); if (fp != NULL) { png_uint_32 proflen = 0; png_bytep profile = extract(fp, &proflen); if (profile != NULL && profile != no_profile) { size_t len; char *output; { const char *ep = strrchr(filename, '.'); if (ep != NULL) len = ep-filename; else len = strlen(filename); } output = malloc(len + 5); if (output != NULL) { FILE *of; memcpy(output, filename, len); strcpy(output+len, ".icc"); of = fopen(output, "wb"); if (of != NULL) { if (fwrite(profile, proflen, 1, of) == 1 && fflush(of) == 0 && fclose(of) == 0) { if (verbose) printf("%s -> %s\n", filename, output); /* Success return */ result = 1; } else { fprintf(stderr, "%s: error writing profile\n", output); if (remove(output)) fprintf(stderr, "%s: could not remove file\n", output); } } else fprintf(stderr, "%s: failed to open output file\n", output); free(output); } else fprintf(stderr, "%s: OOM allocating string!\n", filename); free(profile); } else if (verbose && profile == no_profile) printf("%s has no profile\n", filename); } else fprintf(stderr, "%s: could not open file\n", filename); return result; } int main(int argc, char **argv) { int i; int extracted = 0; for (i=1; i #include #include /* required for error handling */ /* Normally use here to get the installed libpng, but this is done to * ensure the code picks up the local libpng implementation: */ #include "../../png.h" #if defined(PNG_READ_SUPPORTED) && defined(PNG_SEQUENTIAL_READ_SUPPORTED) /* Return component 'c' of pixel 'x' from the given row. */ static unsigned int component(png_const_bytep row, png_uint_32 x, unsigned int c, unsigned int bit_depth, unsigned int channels) { /* PNG images can be up to 2^31 pixels wide, but this means they can be up to * 2^37 bits wide (for a 64-bit pixel - the largest possible) and hence 2^34 * bytes wide. Since the row fitted into memory, however, the following must * work: */ png_uint_32 bit_offset_hi = bit_depth * ((x >> 6) * channels); png_uint_32 bit_offset_lo = bit_depth * ((x & 0x3f) * channels + c); row = (png_const_bytep)(((PNG_CONST png_byte (*)[8])row) + bit_offset_hi); row += bit_offset_lo >> 3; bit_offset_lo &= 0x07; /* PNG pixels are packed into bytes to put the first pixel in the highest * bits of the byte and into two bytes for 16-bit values with the high 8 bits * first, so: */ switch (bit_depth) { case 1: return (row[0] >> (7-bit_offset_lo)) & 0x01; case 2: return (row[0] >> (6-bit_offset_lo)) & 0x03; case 4: return (row[0] >> (4-bit_offset_lo)) & 0x0f; case 8: return row[0]; case 16: return (row[0] << 8) + row[1]; default: /* This should never happen; it indicates a bug in this program or in * libpng itself: */ fprintf(stderr, "pngpixel: invalid bit depth %u\n", bit_depth); exit(1); } } /* Print a pixel from a row returned by libpng; determine the row format, find * the pixel, and print the relevant information to stdout. */ static void print_pixel(png_structp png_ptr, png_infop info_ptr, png_const_bytep row, png_uint_32 x) { PNG_CONST unsigned int bit_depth = png_get_bit_depth(png_ptr, info_ptr); switch (png_get_color_type(png_ptr, info_ptr)) { case PNG_COLOR_TYPE_GRAY: printf("GRAY %u\n", component(row, x, 0, bit_depth, 1)); return; /* The palette case is slightly more difficult - the palette and, if * present, the tRNS ('transparency', though the values are really * opacity) data must be read to give the full picture: */ case PNG_COLOR_TYPE_PALETTE: { PNG_CONST int index = component(row, x, 0, bit_depth, 1); png_colorp palette = NULL; int num_palette = 0; if ((png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette) & PNG_INFO_PLTE) && num_palette > 0 && palette != NULL) { png_bytep trans_alpha = NULL; int num_trans = 0; if ((png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, NULL) & PNG_INFO_tRNS) && num_trans > 0 && trans_alpha != NULL) printf("INDEXED %u = %d %d %d %d\n", index, palette[index].red, palette[index].green, palette[index].blue, index < num_trans ? trans_alpha[index] : 255); else /* no transparency */ printf("INDEXED %u = %d %d %d\n", index, palette[index].red, palette[index].green, palette[index].blue); } else printf("INDEXED %u = invalid index\n", index); } return; case PNG_COLOR_TYPE_RGB: printf("RGB %u %u %u\n", component(row, x, 0, bit_depth, 3), component(row, x, 1, bit_depth, 3), component(row, x, 2, bit_depth, 3)); return; case PNG_COLOR_TYPE_GRAY_ALPHA: printf("GRAY+ALPHA %u %u\n", component(row, x, 0, bit_depth, 2), component(row, x, 1, bit_depth, 2)); return; case PNG_COLOR_TYPE_RGB_ALPHA: printf("RGBA %u %u %u %u\n", component(row, x, 0, bit_depth, 4), component(row, x, 1, bit_depth, 4), component(row, x, 2, bit_depth, 4), component(row, x, 3, bit_depth, 4)); return; default: png_error(png_ptr, "pngpixel: invalid color type"); } } int main(int argc, const char **argv) { /* This program uses the default, based, libpng error handling * mechanism, therefore any local variable that exists before the call to * setjmp and is changed after the call to setjmp returns successfully must * be declared with 'volatile' to ensure that their values don't get * destroyed by longjmp: */ volatile int result = 1/*fail*/; if (argc == 4) { long x = atol(argv[1]); long y = atol(argv[2]); FILE *f = fopen(argv[3], "rb"); volatile png_bytep row = NULL; if (f != NULL) { /* libpng requires a callback function for handling errors; this * callback must not return. The default callback function uses a * stored style jmp_buf which is held in a png_struct and * writes error messages to stderr. Creating the png_struct is a * little tricky; just copy the following code. */ png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr != NULL) { png_infop info_ptr = png_create_info_struct(png_ptr); if (info_ptr != NULL) { /* Declare stack variables to hold pointers to locally allocated * data. */ /* Initialize the error control buffer: */ if (setjmp(png_jmpbuf(png_ptr)) == 0) { png_uint_32 width, height; int bit_depth, color_type, interlace_method, compression_method, filter_method; png_bytep row_tmp; /* Now associate the recently opened (FILE*) with the default * libpng initialization functions. Sometimes libpng is * compiled without stdio support (it can be difficult to do * in some environments); in that case you will have to write * your own read callback to read data from the (FILE*). */ png_init_io(png_ptr, f); /* And read the first part of the PNG file - the header and * all the information up to the first pixel. */ png_read_info(png_ptr, info_ptr); /* This fills in enough information to tell us the width of * each row in bytes, allocate the appropriate amount of * space. In this case png_malloc is used - it will not * return if memory isn't available. */ row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); /* To avoid the overhead of using a volatile auto copy row_tmp * to a local here - just use row for the png_free below. */ row_tmp = row; /* All the information we need is in the header is returned by * png_get_IHDR, if this fails we can now use 'png_error' to * signal the error and return control to the setjmp above. */ if (png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_method, &compression_method, &filter_method)) { int passes, pass; /* png_set_interlace_handling returns the number of * passes required as well as turning on libpng's * handling, but since we do it ourselves this is * necessary: */ switch (interlace_method) { case PNG_INTERLACE_NONE: passes = 1; break; case PNG_INTERLACE_ADAM7: passes = PNG_INTERLACE_ADAM7_PASSES; break; default: png_error(png_ptr, "pngpixel: unknown interlace"); } /* Now read the pixels, pass-by-pass, row-by-row: */ png_start_read_image(png_ptr); for (pass=0; pass #include #include #include /* Normally use here to get the installed libpng, but this is done to * ensure the code picks up the local libpng implementation: */ #include "../../png.h" #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && \ defined(PNG_SIMPLIFIED_WRITE_SUPPORTED) int main(int argc, const char **argv) { int result = 1; if (argc == 3) { png_image image; /* Only the image structure version number needs to be set. */ memset(&image, 0, sizeof image); image.version = PNG_IMAGE_VERSION; if (png_image_begin_read_from_file(&image, argv[1])) { png_bytep buffer; /* Change this to try different formats! If you set a colormap format * then you must also supply a colormap below. */ image.format = PNG_FORMAT_RGBA; buffer = malloc(PNG_IMAGE_SIZE(image)); if (buffer != NULL) { if (png_image_finish_read(&image, NULL/*background*/, buffer, 0/*row_stride*/, NULL/*colormap for PNG_FORMAT_FLAG_COLORMAP */)) { if (png_image_write_to_file(&image, argv[2], 0/*convert_to_8bit*/, buffer, 0/*row_stride*/, NULL/*colormap*/)) result = 0; else fprintf(stderr, "pngtopng: write %s: %s\n", argv[2], image.message); free(buffer); } else { fprintf(stderr, "pngtopng: read %s: %s\n", argv[1], image.message); /* This is the only place where a 'free' is required; libpng does * the cleanup on error and success, but in this case we couldn't * complete the read because of running out of memory. */ png_image_free(&image); } } else fprintf(stderr, "pngtopng: out of memory: %lu bytes\n", (unsigned long)PNG_IMAGE_SIZE(image)); } else /* Failed to read the first argument: */ fprintf(stderr, "pngtopng: %s: %s\n", argv[1], image.message); } else /* Wrong number of arguments */ fprintf(stderr, "pngtopng: usage: pngtopng input-file output-file\n"); return result; } #endif /* READ && WRITE */ ================================================ FILE: tess-two/jni/libpng/contrib/examples/simpleover.c ================================================ /*- simpleover * * COPYRIGHT: Written by John Cunningham Bowler, 2015. * To the extent possible under law, the author has waived all copyright and * related or neighboring rights to this work. This work is published from: * United States. * * Read several PNG files, which should have an alpha channel or transparency * information, and composite them together to produce one or more 16-bit linear * RGBA intermediates. This involves doing the correct 'over' composition to * combine the alpha channels and corresponding data. * * Finally read an output (background) PNG using the 24-bit RGB format (the * PNG will be composited on green (#00ff00) by default if it has an alpha * channel), and apply the intermediate image generated above to specified * locations in the image. * * The command line has the general format: * * simpleover [output.png] * {--sprite=width,height,name {[--at=x,y] {sprite.png}}} * {--add=name {x,y}} * * The --sprite and --add options may occur multiple times. They are executed * in order. --add may refer to any sprite already read. * * This code is intended to show how to composite multiple images together * correctly. Apart from the libpng Simplified API the only work done in here * is to combine multiple input PNG images into a single sprite; this involves * a Porter-Duff 'over' operation and the input PNG images may, as a result, * be regarded as being layered one on top of the other with the first (leftmost * on the command line) being at the bottom and the last on the top. */ #include #include #include #include #include /* Normally use here to get the installed libpng, but this is done to * ensure the code picks up the local libpng implementation, so long as this * file is linked against a sufficiently recent libpng (1.6+) it is ok to * change this to : */ #include "../../png.h" #ifdef PNG_SIMPLIFIED_READ_SUPPORTED #define sprite_name_chars 15 struct sprite { FILE *file; png_uint_16p buffer; unsigned int width; unsigned int height; char name[sprite_name_chars+1]; }; #if 0 /* div by 65535 test program */ #include #include int main(void) { double err = 0; unsigned int xerr = 0; unsigned int r = 32769; { unsigned int x = 0; do { unsigned int t = x + (x >> 16) /*+ (x >> 31)*/ + r; double v = x, errtest; if (t < x) { fprintf(stderr, "overflow: %u+%u -> %u\n", x, r, t); return 1; } v /= 65535; errtest = v; t >>= 16; errtest -= t; if (errtest > err) { err = errtest; xerr = x; if (errtest >= .5) { fprintf(stderr, "error: %u/65535 = %f, not %u, error %f\n", x, v, t, errtest); return 0; } } } while (++x <= 65535U*65535U); } printf("error %f @ %u\n", err, xerr); return 0; } #endif /* div by 65535 test program */ static void sprite_op(const struct sprite *sprite, int x_offset, int y_offset, png_imagep image, const png_uint_16 *buffer) { /* This is where the Porter-Duff 'Over' operator is evaluated; change this * code to change the operator (this could be parameterized). Any other * image processing operation could be used here. */ /* Check for an x or y offset that pushes any part of the image beyond the * right or bottom of the sprite: */ if ((y_offset < 0 || (unsigned)/*SAFE*/y_offset < sprite->height) && (x_offset < 0 || (unsigned)/*SAFE*/x_offset < sprite->width)) { unsigned int y = 0; if (y_offset < 0) y = -y_offset; /* Skip to first visible row */ do { unsigned int x = 0; if (x_offset < 0) x = -x_offset; do { /* In and out are RGBA values, so: */ const png_uint_16 *in_pixel = buffer + (y * image->width + x)*4; png_uint_32 in_alpha = in_pixel[3]; /* This is the optimized Porter-Duff 'Over' operation, when the * input alpha is 0 the output is not changed. */ if (in_alpha > 0) { png_uint_16 *out_pixel = sprite->buffer + ((y+y_offset) * sprite->width + (x+x_offset))*4; /* This is the weight to apply to the output: */ in_alpha = 65535-in_alpha; if (in_alpha > 0) { /* The input must be composed onto the output. This means * multiplying the current output pixel value by the inverse * of the input alpha (1-alpha). A division is required but * it is by the constant 65535. Approximate this as: * * (x + (x >> 16) + 32769) >> 16; * * This is exact (and does not overflow) for all values of * x in the range 0..65535*65535. (Note that the calculation * produces the closest integer; the maximum error is <0.5). */ png_uint_32 tmp; # define compose(c)\ tmp = out_pixel[c] * in_alpha;\ tmp = (tmp + (tmp >> 16) + 32769) >> 16;\ out_pixel[c] = tmp + in_pixel[c] /* The following is very vectorizable... */ compose(0); compose(1); compose(2); compose(3); } else out_pixel[0] = in_pixel[0], out_pixel[1] = in_pixel[1], out_pixel[2] = in_pixel[2], out_pixel[3] = in_pixel[3]; } } while (++x < image->width); } while (++y < image->height); } } static int create_sprite(struct sprite *sprite, int *argc, const char ***argv) { /* Read the arguments and create this sprite. The sprite buffer has already * been allocated. This reads the input PNGs one by one in linear format, * composes them onto the sprite buffer (the code in the function above) * then saves the result, converting it on the fly to PNG RGBA 8-bit format. */ while (*argc > 0) { char tombstone; int x = 0, y = 0; if ((*argv)[0][0] == '-' && (*argv)[0][1] == '-') { /* The only supported option is --at. */ if (sscanf((*argv)[0], "--at=%d,%d%c", &x, &y, &tombstone) != 2) break; /* success; caller will parse this option */ ++*argv, --*argc; } else { /* The argument has to be a file name */ png_image image; image.version = PNG_IMAGE_VERSION; image.opaque = NULL; if (png_image_begin_read_from_file(&image, (*argv)[0])) { png_uint_16p buffer; image.format = PNG_FORMAT_LINEAR_RGB_ALPHA; buffer = malloc(PNG_IMAGE_SIZE(image)); if (buffer != NULL) { if (png_image_finish_read(&image, NULL/*background*/, buffer, 0/*row_stride*/, NULL/*colormap for PNG_FORMAT_FLAG_COLORMAP*/)) { /* This is the place where the Porter-Duff 'Over' operator * needs to be done by this code. In fact, any image * processing required can be done here; the data is in * the correct format (linear, 16-bit) and source and * destination are in memory. */ sprite_op(sprite, x, y, &image, buffer); free(buffer); ++*argv, --*argc; /* And continue to the next argument */ continue; } else { free(buffer); fprintf(stderr, "simpleover: read %s: %s\n", (*argv)[0], image.message); } } else { fprintf(stderr, "simpleover: out of memory: %lu bytes\n", (unsigned long)PNG_IMAGE_SIZE(image)); /* png_image_free must be called if we abort the Simplified API * read because of a problem detected in this code. If problems * are detected in the Simplified API it cleans up itself. */ png_image_free(&image); } } else { /* Failed to read the first argument: */ fprintf(stderr, "simpleover: %s: %s\n", (*argv)[0], image.message); } return 0; /* failure */ } } /* All the sprite operations have completed successfully. Save the RGBA * buffer as a PNG using the simplified write API. */ sprite->file = tmpfile(); if (sprite->file != NULL) { png_image save; memset(&save, 0, sizeof save); save.version = PNG_IMAGE_VERSION; save.opaque = NULL; save.width = sprite->width; save.height = sprite->height; save.format = PNG_FORMAT_LINEAR_RGB_ALPHA; save.flags = PNG_IMAGE_FLAG_FAST; save.colormap_entries = 0; if (png_image_write_to_stdio(&save, sprite->file, 1/*convert_to_8_bit*/, sprite->buffer, 0/*row_stride*/, NULL/*colormap*/)) { /* Success; the buffer is no longer needed: */ free(sprite->buffer); sprite->buffer = NULL; return 1; /* ok */ } else fprintf(stderr, "simpleover: write sprite %s: %s\n", sprite->name, save.message); } else fprintf(stderr, "simpleover: sprite %s: could not allocate tmpfile: %s\n", sprite->name, strerror(errno)); return 0; /* fail */ } static int add_sprite(png_imagep output, png_bytep out_buf, struct sprite *sprite, int *argc, const char ***argv) { /* Given a --add argument naming this sprite, perform the operations listed * in the following arguments. The arguments are expected to have the form * (x,y), which is just an offset at which to add the sprite to the * output. */ while (*argc > 0) { char tombstone; int x, y; if ((*argv)[0][0] == '-' && (*argv)[0][1] == '-') return 1; /* success */ if (sscanf((*argv)[0], "%d,%d%c", &x, &y, &tombstone) == 2) { /* Now add the new image into the sprite data, but only if it * will fit. */ if (x < 0 || y < 0 || (unsigned)/*SAFE*/x >= output->width || (unsigned)/*SAFE*/y >= output->height || sprite->width > output->width-x || sprite->height > output->height-y) { fprintf(stderr, "simpleover: sprite %s @ (%d,%d) outside image\n", sprite->name, x, y); /* Could just skip this, but for the moment it is an error */ return 0; /* error */ } else { /* Since we know the sprite fits we can just read it into the * output using the simplified API. */ png_image in; in.version = PNG_IMAGE_VERSION; rewind(sprite->file); if (png_image_begin_read_from_stdio(&in, sprite->file)) { in.format = PNG_FORMAT_RGB; /* force compose */ if (png_image_finish_read(&in, NULL/*background*/, out_buf + (y*output->width + x)*3/*RGB*/, output->width*3/*row_stride*/, NULL/*colormap for PNG_FORMAT_FLAG_COLORMAP*/)) { ++*argv, --*argc; continue; } } /* The read failed: */ fprintf(stderr, "simpleover: add sprite %s: %s\n", sprite->name, in.message); return 0; /* error */ } } else { fprintf(stderr, "simpleover: --add='%s': invalid position %s\n", sprite->name, (*argv)[0]); return 0; /* error */ } } return 1; /* ok */ } static int simpleover_process(png_imagep output, png_bytep out_buf, int argc, const char **argv) { int result = 1; /* success */ # define csprites 10/*limit*/ # define str(a) #a int nsprites = 0; struct sprite sprites[csprites]; while (argc > 0) { result = 0; /* fail */ if (strncmp(argv[0], "--sprite=", 9) == 0) { char tombstone; if (nsprites < csprites) { int n; sprites[nsprites].width = sprites[nsprites].height = 0; sprites[nsprites].name[0] = 0; n = sscanf(argv[0], "--sprite=%u,%u,%" str(sprite_name_chars) "s%c", &sprites[nsprites].width, &sprites[nsprites].height, sprites[nsprites].name, &tombstone); if ((n == 2 || n == 3) && sprites[nsprites].width > 0 && sprites[nsprites].height > 0) { size_t buf_size, tmp; /* Default a name if not given. */ if (sprites[nsprites].name[0] == 0) sprintf(sprites[nsprites].name, "sprite-%d", nsprites+1); /* Allocate a buffer for the sprite and calculate the buffer * size: */ buf_size = sizeof (png_uint_16 [4]); buf_size *= sprites[nsprites].width; buf_size *= sprites[nsprites].height; /* This can overflow a (size_t); check for this: */ tmp = buf_size; tmp /= sprites[nsprites].width; tmp /= sprites[nsprites].height; if (tmp == sizeof (png_uint_16 [4])) { sprites[nsprites].buffer = malloc(buf_size); /* This buffer must be initialized to transparent: */ memset(sprites[nsprites].buffer, 0, buf_size); if (sprites[nsprites].buffer != NULL) { sprites[nsprites].file = NULL; ++argv, --argc; if (create_sprite(sprites+nsprites++, &argc, &argv)) { result = 1; /* still ok */ continue; } break; /* error */ } } /* Overflow, or OOM */ fprintf(stderr, "simpleover: %s: sprite too large\n", argv[0]); break; } else { fprintf(stderr, "simpleover: %s: invalid sprite (%u,%u)\n", argv[0], sprites[nsprites].width, sprites[nsprites].height); break; } } else { fprintf(stderr, "simpleover: %s: too many sprites\n", argv[0]); break; } } else if (strncmp(argv[0], "--add=", 6) == 0) { const char *name = argv[0]+6; int isprite = nsprites; ++argv, --argc; while (--isprite >= 0) { if (strcmp(sprites[isprite].name, name) == 0) { if (!add_sprite(output, out_buf, sprites+isprite, &argc, &argv)) goto out; /* error in add_sprite */ break; } } if (isprite < 0) /* sprite not found */ { fprintf(stderr, "simpleover: --add='%s': sprite not found\n", name); break; } } else { fprintf(stderr, "simpleover: %s: unrecognized operation\n", argv[0]); break; } result = 1; /* ok */ } /* Clean up the cache of sprites: */ out: while (--nsprites >= 0) { if (sprites[nsprites].buffer != NULL) free(sprites[nsprites].buffer); if (sprites[nsprites].file != NULL) (void)fclose(sprites[nsprites].file); } return result; } int main(int argc, const char **argv) { int result = 1; /* default to fail */ if (argc >= 2) { int argi = 2; const char *output = NULL; png_image image; if (argc > 2 && argv[2][0] != '-'/*an operation*/) { output = argv[2]; argi = 3; } image.version = PNG_IMAGE_VERSION; image.opaque = NULL; if (png_image_begin_read_from_file(&image, argv[1])) { png_bytep buffer; image.format = PNG_FORMAT_RGB; /* 24-bit RGB */ buffer = malloc(PNG_IMAGE_SIZE(image)); if (buffer != NULL) { png_color background = {0, 0xff, 0}; /* fully saturated green */ if (png_image_finish_read(&image, &background, buffer, 0/*row_stride*/, NULL/*colormap for PNG_FORMAT_FLAG_COLORMAP */)) { /* At this point png_image_finish_read has cleaned up the * allocated data in png_image, and only the buffer needs to be * freed. * * Perform the remaining operations: */ if (simpleover_process(&image, buffer, argc-argi, argv+argi)) { /* Write the output: */ if ((output != NULL && png_image_write_to_file(&image, output, 0/*convert_to_8bit*/, buffer, 0/*row_stride*/, NULL/*colormap*/)) || (output == NULL && png_image_write_to_stdio(&image, stdout, 0/*convert_to_8bit*/, buffer, 0/*row_stride*/, NULL/*colormap*/))) result = 0; else fprintf(stderr, "simpleover: write %s: %s\n", output == NULL ? "stdout" : output, image.message); } /* else simpleover_process writes an error message */ } else fprintf(stderr, "simpleover: read %s: %s\n", argv[1], image.message); free(buffer); } else { fprintf(stderr, "simpleover: out of memory: %lu bytes\n", (unsigned long)PNG_IMAGE_SIZE(image)); /* This is the only place where a 'free' is required; libpng does * the cleanup on error and success, but in this case we couldn't * complete the read because of running out of memory. */ png_image_free(&image); } } else { /* Failed to read the first argument: */ fprintf(stderr, "simpleover: %s: %s\n", argv[1], image.message); } } else { /* Usage message */ fprintf(stderr, "simpleover: usage: simpleover background.png [output.png]\n" " Output 'background.png' as a 24-bit RGB PNG file in 'output.png'\n" " or, if not given, stdout. 'background.png' will be composited\n" " on fully saturated green.\n" "\n" " Optionally, before output, process additional PNG files:\n" "\n" " --sprite=width,height,name {[--at=x,y] {sprite.png}}\n" " Produce a transparent sprite of size (width,height) and with\n" " name 'name'.\n" " For each sprite.png composite it using a Porter-Duff 'Over'\n" " operation at offset (x,y) in the sprite (defaulting to (0,0)).\n" " Input PNGs will be truncated to the area of the sprite.\n" "\n" " --add='name' {x,y}\n" " Optionally, before output, composite a sprite, 'name', which\n" " must have been previously produced using --sprite, at each\n" " offset (x,y) in the output image. Each sprite must fit\n" " completely within the output image.\n" "\n" " PNG files are processed in the order they occur on the command\n" " line and thus the first PNG processed appears as the bottommost\n" " in the output image.\n"); } return result; } #endif /* SIMPLIFIED_READ */ ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/COPYING ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/LICENSE ================================================ --------------------------------------------------------------------------- Copyright (c) 1998-2008 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --------------------------------------------------------------------------- ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/Makefile.mingw32 ================================================ # Sample makefile for rpng-win / rpng2-win / wpng using mingw32-gcc and make. # Greg Roelofs # Last modified: 2 June 2007 # # The programs built by this makefile are described in the book, # "PNG: The Definitive Guide," by Greg Roelofs (O'Reilly and # Associates, 1999). Go buy a copy, eh? Well, OK, it's not # generally for sale anymore, but it's the thought that counts, # right? (Hint: http://www.libpng.org/pub/png/book/ ) # # Invoke this makefile from a DOS-prompt window via: # # make -f Makefile.mingw32 # # This makefile assumes libpng and zlib have already been built or downloaded # and are in subdirectories at the same level as the current subdirectory # (as indicated by the PNGDIR and ZDIR macros below). It makes no assumptions # at all about the mingw32 installation tree (W32DIR). Edit as appropriate. # # Note that the names of the dynamic and static libpng and zlib libraries # used below may change in later releases of the libraries. This makefile # builds both statically and dynamically linked executables by default. # (You need only one set, but for testing it can be handy to have both.) # macros -------------------------------------------------------------------- #PNGDIR = ../..# for libpng-x.y.z/contrib/gregbook builds PNGDIR = ../libpng-win32 PNGINC = -I$(PNGDIR) PNGLIBd = $(PNGDIR)/libpng.dll.a # dynamically linked PNGLIBs = $(PNGDIR)/libpng.a # statically linked, local libpng #ZDIR = ../../../zlib-win32# for libpng-x.y.z/contrib/gregbook builds ZDIR = ../zlib-win32 ZINC = -I$(ZDIR) ZLIBd = $(ZDIR)/libzdll.a ZLIBs = $(ZDIR)/libz.a # change this to be the path where mingw32 installs its stuff: W32DIR = #W32DIR = /usr/local/cross-tools/i386-mingw32msvc W32INC = -I$(W32DIR)/include W32LIB = $(W32DIR)/lib/libuser32.a $(W32DIR)/lib/libgdi32.a CC = gcc #CC = i386-mingw32msvc-gcc # e.g., Linux -> Win32 cross-compilation LD = $(CC) RM = rm -f CPPFLAGS = $(INCS) CFLAGS = -O -Wall $(MINGW_CCFLAGS) # [note that -Wall is a gcc-specific compilation flag ("most warnings on")] # [-ansi, -pedantic and -W can also be used] LDFLAGS = $(MINGW_LDFLAGS) O = .o E = .exe INCS = $(PNGINC) $(ZINC) $(W32INC) RLIBSd = $(PNGLIBd) $(ZLIBd) $(W32LIB) -lm RLIBSs = $(PNGLIBs) $(ZLIBs) $(W32LIB) -lm WLIBSd = $(PNGLIBd) $(ZLIBd) WLIBSs = $(PNGLIBs) $(ZLIBs) RPNG = rpng-win RPNG2 = rpng2-win WPNG = wpng ROBJSd = $(RPNG)$(O) readpng.pic$(O) ROBJS2d = $(RPNG2)$(O) readpng2.pic$(O) WOBJSd = $(WPNG)$(O) writepng.pic$(O) RPNGs = $(RPNG)-static RPNG2s = $(RPNG2)-static WPNGs = $(WPNG)-static ROBJSs = $(RPNG)$(O) readpng$(O) ROBJS2s = $(RPNG2)$(O) readpng2$(O) WOBJSs = $(WPNG)$(O) writepng$(O) STATIC_EXES = $(RPNGs)$(E) $(RPNG2s)$(E) $(WPNGs)$(E) DYNAMIC_EXES = $(RPNG)$(E) $(RPNG2)$(E) $(WPNG)$(E) EXES = $(STATIC_EXES) $(DYNAMIC_EXES) # implicit make rules ------------------------------------------------------- .c$(O): $(CC) -c $(CPPFLAGS) $(CFLAGS) $< %.pic$(O): %.c $(CC) -c $(CPPFLAGS) $(CFLAGS) -DPNG_BUILD_DLL -o $@ $< # dependencies -------------------------------------------------------------- all: $(EXES) $(RPNGs)$(E): $(ROBJSs) $(LD) $(LDFLAGS) -o $@ $(ROBJSs) $(RLIBSs) $(RPNG)$(E): $(ROBJSd) $(LD) $(LDFLAGS) -o $@ $(ROBJSd) $(RLIBSd) $(RPNG2s)$(E): $(ROBJS2s) $(LD) $(LDFLAGS) -o $@ $(ROBJS2s) $(RLIBSs) $(RPNG2)$(E): $(ROBJS2d) $(LD) $(LDFLAGS) -o $@ $(ROBJS2d) $(RLIBSd) $(WPNGs)$(E): $(WOBJSs) $(LD) $(LDFLAGS) -o $@ $(WOBJSs) $(WLIBSs) $(WPNG)$(E): $(WOBJSd) $(LD) $(LDFLAGS) -o $@ $(WOBJSd) $(WLIBSd) $(RPNG)$(O): $(RPNG).c readpng.h $(RPNG2)$(O): $(RPNG2).c readpng2.h $(WPNG)$(O): $(WPNG).c writepng.h readpng$(O) readpng.pic$(O): readpng.c readpng.h readpng2$(O) readpng2.pic$(O): readpng2.c readpng2.h writepng$(O) writepng.pic$(O): writepng.c writepng.h # maintenance --------------------------------------------------------------- clean: $(RM) $(EXES) $(RM) $(ROBJSs) $(ROBJS2s) $(WOBJSs) $(RM) $(ROBJSd) $(ROBJS2d) $(WOBJSd) ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/Makefile.sgi ================================================ # Sample makefile for rpng-x / rpng2-x / wpng for SGI using cc and make. # Greg Roelofs # Last modified: 7 March 2002 # # The programs built by this makefile are described in the book, # "PNG: The Definitive Guide," by Greg Roelofs (O'Reilly and # Associates, 1999). Go buy a copy, eh? Buy some for friends # and family, too. (Not that this is a blatant plug or anything.) # # Invoke this makefile from a shell prompt in the usual way; for example: # # make -f Makefile.sgi # # This makefile assumes libpng and zlib have already been built or downloaded # and are both installed in /usr/local/{include,lib} (as indicated by the # PNG* and Z* macros below). Edit as appropriate--choose only ONE each of # the PNGINC, PNGLIB, ZINC and ZLIB lines. # # This makefile builds dynamically linked executables (against libpng and zlib, # that is), but that can be changed by uncommenting the appropriate PNGLIB and # ZLIB lines. # macros -------------------------------------------------------------------- PNGINC = -I/usr/local/include/libpng16 PNGLIB = -L/usr/local/lib -lpng16 # dynamically linked against libpng #PNGLIB = /usr/local/lib/libpng16.a # statically linked against libpng # or: #PNGINC = -I../.. #PNGLIB = -L../.. -lpng #PNGLIB = ../../libpng.a ZINC = -I/usr/local/include ZLIB = -L/usr/local/lib -lz # dynamically linked against zlib #ZLIB = /usr/local/lib/libz.a # statically linked against zlib #ZINC = -I../zlib #ZLIB = -L../zlib -lz #ZLIB = ../../../zlib/libz.a XINC = -I/usr/include/X11 # old-style, stock X distributions XLIB = -L/usr/lib/X11 -lX11 #XINC = -I/usr/openwin/include # Sun workstations (OpenWindows) #XLIB = -L/usr/openwin/lib -lX11 #XINC = -I/usr/X11R6/include # new X distributions (XFree86, etc.) #XLIB = -L/usr/X11R6/lib -lX11 INCS = $(PNGINC) $(ZINC) $(XINC) RLIBS = $(PNGLIB) $(ZLIB) $(XLIB) -lm WLIBS = $(PNGLIB) $(ZLIB) CC = cc LD = cc RM = rm -f # ABI must be the same as that used to build libpng. ABI = CPPFLAGS = CFLAGS = $(ABI) -O -fullwarn $(INCS) LDFLAGS = $(ABI) O = .o E = RPNG = rpng-x RPNG2 = rpng2-x WPNG = wpng ROBJS = $(RPNG)$(O) readpng$(O) ROBJS2 = $(RPNG2)$(O) readpng2$(O) WOBJS = $(WPNG)$(O) writepng$(O) EXES = $(RPNG)$(E) $(RPNG2)$(E) $(WPNG)$(E) # implicit make rules ------------------------------------------------------- .c$(O): $(CC) -c $(CPPFLAGS) $(CFLAGS) $< # dependencies -------------------------------------------------------------- all: $(EXES) $(RPNG)$(E): $(ROBJS) $(LD) $(LDFLAGS) -o $@ $(ROBJS) $(RLIBS) $(RPNG2)$(E): $(ROBJS2) $(LD) $(LDFLAGS) -o $@ $(ROBJS2) $(RLIBS) $(WPNG)$(E): $(WOBJS) $(LD) $(LDFLAGS) -o $@ $(WOBJS) $(WLIBS) $(RPNG)$(O): $(RPNG).c readpng.h $(RPNG2)$(O): $(RPNG2).c readpng2.h $(WPNG)$(O): $(WPNG).c writepng.h readpng$(O): readpng.c readpng.h readpng2$(O): readpng2.c readpng2.h writepng$(O): writepng.c writepng.h # maintenance --------------------------------------------------------------- clean: $(RM) $(EXES) $(ROBJS) $(ROBJS2) $(WOBJS) ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/Makefile.unx ================================================ # Sample makefile for rpng-x / rpng2-x / wpng using gcc and make. # Greg Roelofs # Last modified: 2 June 2007 # # The programs built by this makefile are described in the book, # "PNG: The Definitive Guide," by Greg Roelofs (O'Reilly and # Associates, 1999). Go buy a copy, eh? Well, OK, it's not # generally for sale anymore, but it's the thought that counts, # right? (Hint: http://www.libpng.org/pub/png/book/ ) # # Invoke this makefile from a shell prompt in the usual way; for example: # # make -f Makefile.unx # # This makefile assumes libpng and zlib have already been built or downloaded # and are installed in /usr/local/{include,lib} or as otherwise indicated by # the PNG* and Z* macros below. Edit as appropriate--choose only ONE each of # the PNGINC, PNGLIBd, PNGLIBs, ZINC, ZLIBd and ZLIBs lines. # # This makefile builds both dynamically and statically linked executables # (against libpng and zlib, that is), but that can be changed by modifying # the "EXES =" line. (You need only one set, but for testing it can be handy # to have both.) # macros -------------------------------------------------------------------- #PNGDIR = /usr/local/lib #PNGINC = -I/usr/local/include/libpng16 #PNGLIBd = -L$(PNGDIR) -lpng16 # dynamically linked, installed libpng #PNGLIBs = $(PNGDIR)/libpng16.a # statically linked, installed libpng # or: PNGDIR = ../..# this one is for libpng-x.y.z/contrib/gregbook builds #PNGDIR = ../libpng PNGINC = -I$(PNGDIR) PNGLIBd = -Wl,-rpath,$(PNGDIR) -L$(PNGDIR) -lpng16 # dynamically linked PNGLIBs = $(PNGDIR)/libpng.a # statically linked, local libpng ZDIR = /usr/local/lib #ZDIR = /usr/lib64 ZINC = -I/usr/local/include ZLIBd = -L$(ZDIR) -lz # dynamically linked against zlib ZLIBs = $(ZDIR)/libz.a # statically linked against zlib # or: #ZDIR = ../zlib #ZINC = -I$(ZDIR) #ZLIBd = -Wl,-rpath,$(ZDIR) -L$(ZDIR) -lz # -rpath allows in-place testing #ZLIBs = $(ZDIR)/libz.a #XINC = -I/usr/include # old-style, stock X distributions #XLIB = -L/usr/lib/X11 -lX11 # (including SGI IRIX) #XINC = -I/usr/openwin/include # Sun workstations (OpenWindows) #XLIB = -L/usr/openwin/lib -lX11 XINC = -I/usr/X11R6/include # new X distributions (X.org, etc.) XLIB = -L/usr/X11R6/lib -lX11 #XLIB = -L/usr/X11R6/lib64 -lX11 # e.g., Red Hat on AMD64 INCS = $(PNGINC) $(ZINC) $(XINC) RLIBSd = $(PNGLIBd) $(ZLIBd) $(XLIB) -lm RLIBSs = $(PNGLIBs) $(ZLIBs) $(XLIB) -lm WLIBSd = $(PNGLIBd) $(ZLIBd) -lm WLIBSs = $(PNGLIBs) $(ZLIBs) -lm CC = gcc LD = gcc RM = rm -f CPPFLAGS = $(INCS) -DFEATURE_LOOP CFLAGS = -O -Wall #CFLAGS = -O -W -Wall -Wextra -pedantic -ansi # [note that -Wall is a gcc-specific compilation flag ("most warnings on")] # [-ansi, -pedantic, -Wextra, and -W can also be used] LDFLAGS = O = .o E = RPNG = rpng-x RPNG2 = rpng2-x WPNG = wpng RPNGs = $(RPNG)-static RPNG2s = $(RPNG2)-static WPNGs = $(WPNG)-static ROBJS = $(RPNG)$(O) readpng$(O) ROBJS2 = $(RPNG2)$(O) readpng2$(O) WOBJS = $(WPNG)$(O) writepng$(O) STATIC_EXES = $(RPNGs)$(E) $(RPNG2s)$(E) $(WPNGs)$(E) DYNAMIC_EXES = $(RPNG)$(E) $(RPNG2)$(E) $(WPNG)$(E) EXES = $(STATIC_EXES) $(DYNAMIC_EXES) # implicit make rules ------------------------------------------------------- .c$(O): $(CC) -c $(CPPFLAGS) $(CFLAGS) $< # dependencies -------------------------------------------------------------- all: $(EXES) $(RPNGs)$(E): $(ROBJS) $(LD) $(LDFLAGS) -o $@ $(ROBJS) $(RLIBSs) $(RPNG)$(E): $(ROBJS) $(LD) $(LDFLAGS) -o $@ $(ROBJS) $(RLIBSd) $(RPNG2s)$(E): $(ROBJS2) $(LD) $(LDFLAGS) -o $@ $(ROBJS2) $(RLIBSs) $(RPNG2)$(E): $(ROBJS2) $(LD) $(LDFLAGS) -o $@ $(ROBJS2) $(RLIBSd) $(WPNGs)$(E): $(WOBJS) $(LD) $(LDFLAGS) -o $@ $(WOBJS) $(WLIBSs) $(WPNG)$(E): $(WOBJS) $(LD) $(LDFLAGS) -o $@ $(WOBJS) $(WLIBSd) $(RPNG)$(O): $(RPNG).c readpng.h $(RPNG2)$(O): $(RPNG2).c readpng2.h $(WPNG)$(O): $(WPNG).c writepng.h readpng$(O): readpng.c readpng.h readpng2$(O): readpng2.c readpng2.h writepng$(O): writepng.c writepng.h # maintenance --------------------------------------------------------------- clean: $(RM) $(EXES) $(ROBJS) $(ROBJS2) $(WOBJS) ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/Makefile.w32 ================================================ # Sample makefile for rpng-win / rpng2-win / wpng using MSVC and NMAKE. # Greg Roelofs # Last modified: 2 June 2007 # # The programs built by this makefile are described in the book, # "PNG: The Definitive Guide," by Greg Roelofs (O'Reilly and # Associates, 1999). Go buy a copy, eh? Well, OK, it's not # generally for sale anymore, but it's the thought that counts, # right? (Hint: http://www.libpng.org/pub/png/book/ ) # # Invoke this makefile from a DOS prompt window via: # # %devstudio%\vc\bin\vcvars32.bat # nmake -nologo -f Makefile.w32 # # where %devstudio% is the installation directory for MSVC / DevStudio. If # you get "environment out of space" errors, create a desktop shortcut with # "c:\windows\command.com /e:4096" as the program command line and set the # working directory to this directory. Then double-click to open the new # DOS-prompt window with a bigger environment and retry the commands above. # # This makefile assumes libpng and zlib have already been built or downloaded # and are in subdirectories at the same level as the current subdirectory # (as indicated by the PNGPATH and ZPATH macros below). Edit as appropriate. # # Note that the names of the dynamic and static libpng and zlib libraries # used below may change in later releases of the libraries. This makefile # builds statically linked executables, but that can be changed by uncom- # menting the appropriate PNGLIB and ZLIB lines. !include # macros -------------------------------------------------------------------- PNGPATH = ../libpng PNGINC = -I$(PNGPATH) #PNGLIB = $(PNGPATH)/pngdll.lib PNGLIB = $(PNGPATH)/libpng.lib ZPATH = ../zlib ZINC = -I$(ZPATH) #ZLIB = $(ZPATH)/zlibdll.lib ZLIB = $(ZPATH)/zlibstat.lib WINLIBS = -defaultlib:user32.lib gdi32.lib # ["real" apps may also need comctl32.lib, comdlg32.lib, winmm.lib, etc.] INCS = $(PNGINC) $(ZINC) RLIBS = $(PNGLIB) $(ZLIB) $(WINLIBS) WLIBS = $(PNGLIB) $(ZLIB) CC = cl LD = link RM = del CPPFLAGS = $(INCS) CFLAGS = -nologo -O -W3 $(cvars) # [note that -W3 is an MSVC-specific compilation flag ("all warnings on")] # [see %devstudio%\vc\include\win32.mak for cvars macro definition] O = .obj E = .exe RLDFLAGS = -nologo -subsystem:windows WLDFLAGS = -nologo RPNG = rpng-win RPNG2 = rpng2-win WPNG = wpng ROBJS = $(RPNG)$(O) readpng$(O) ROBJS2 = $(RPNG2)$(O) readpng2$(O) WOBJS = $(WPNG)$(O) writepng$(O) EXES = $(RPNG)$(E) $(RPNG2)$(E) $(WPNG)$(E) # implicit make rules ------------------------------------------------------- .c$(O): $(CC) -c $(CPPFLAGS) $(CFLAGS) $< # dependencies -------------------------------------------------------------- all: $(EXES) $(RPNG)$(E): $(ROBJS) $(LD) $(RLDFLAGS) -out:$@ $(ROBJS) $(RLIBS) $(RPNG2)$(E): $(ROBJS2) $(LD) $(RLDFLAGS) -out:$@ $(ROBJS2) $(RLIBS) $(WPNG)$(E): $(WOBJS) $(LD) $(WLDFLAGS) -out:$@ $(WOBJS) $(WLIBS) $(RPNG)$(O): $(RPNG).c readpng.h $(RPNG2)$(O): $(RPNG2).c readpng2.h $(WPNG)$(O): $(WPNG).c writepng.h readpng$(O): readpng.c readpng.h readpng2$(O): readpng2.c readpng2.h writepng$(O): writepng.c writepng.h # maintenance --------------------------------------------------------------- clean: # ideally we could just do this: # $(RM) $(EXES) $(ROBJS) $(ROBJS2) $(WOBJS) # ...but the Windows "DEL" command is none too bright, so: $(RM) r*$(E) $(RM) w*$(E) $(RM) r*$(O) $(RM) w*$(O) ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/README ================================================ =========================== PNG: The Definitive Guide =========================== Source Code Chapters 13, 14 and 15 of "PNG: The Definitive Guide" discuss three free, cross-platform demo programs that show how to use the libpng reference library: rpng, rpng2 and wpng. rpng and rpng2 are viewers; the first is a very simple example that that shows how a standard file-viewer might use libpng, while the second is designed to process streaming data and shows how a web browser might be written. wpng is a simple command-line program that reads binary PGM and PPM files (the ``raw'' grayscale and RGB subsets of PBMPLUS/NetPBM) and converts them to PNG. The source code for all three demo programs currently compiles under Unix, OpenVMS, and 32-bit Windows. (Special thanks to Martin Zinser, zinser@decus.de, for making the necessary changes for OpenVMS and for providing an appropriate build script.) Build instructions can be found below. Files: README this file LICENSE terms of distribution and reuse (BSD-like or GNU GPL) COPYING GNU General Public License (GPL) Makefile.unx Unix makefile Makefile.w32 Windows (MSVC) makefile makevms.com OpenVMS build script rpng-win.c Windows front end for the basic viewer rpng-x.c X Window System (Unix, OpenVMS) front end readpng.c generic back end for the basic viewer readpng.h header file for the basic viewer rpng2-win.c Windows front end for the progressive viewer rpng2-x.c X front end for the progressive viewer readpng2.c generic back end for the progressive viewer readpng2.h header file for the progressive viewer wpng.c generic (text) front end for the converter writepng.c generic back end for the converter writepng.h header file for the converter toucan.png transparent PNG for testing (by Stefan Schneider) Note that, although the programs are designed to be functional, their primary purpose is to illustrate how to use libpng to add PNG support to other programs. As such, their user interfaces are crude and definitely are not intended for everyday use. Please see http://www.libpng.org/pub/png/pngbook.html for further infor- mation and links to the latest version of the source code, and Chapters 13-15 of the book for detailed discussion of the three programs. Greg Roelofs http://pobox.com/~newt/greg_contact.html 16 March 2008 BUILD INSTRUCTIONS - Prerequisites (in order of compilation): - zlib http://zlib.net/ - libpng http://www.libpng.org/pub/png/libpng.html - pngbook http://www.libpng.org/pub/png/book/sources.html The pngbook demo programs are explicitly designed to demonstrate proper coding techniques for using the libpng reference library. As a result, you need to download and build both zlib (on which libpng depends) and libpng. A common build setup is to place the zlib, libpng and pngbook subdirectory trees ("folders") in the same parent directory. Then the libpng build can refer to files in ../zlib (or ..\zlib or [-.zlib]), and similarly for the pngbook build. Note that all three packages are designed to be built from a command line by default; those who wish to use a graphical or other integrated development environments are on their own. - Unix: Unpack the latest pngbook sources (which should correspond to this README file) into a directory and change into that directory. Copy Makefile.unx to Makefile and edit the PNG* and Z* variables appropriately (possibly also the X* variables if necessary). make There is no "install" target, so copy the three executables somewhere in your path or run them from the current directory. All three will print a basic usage screen when run without any command-line arguments; see the book for more details. - Windows: Unpack the latest pngbook sources (which should correspond to this README file) into a folder, open a "DOS shell" or "command prompt" or equivalent command-line window, and cd into the folder where you unpacked the source code. For MSVC, set up the necessary environment variables by invoking %devstudio%\vc\bin\vcvars32.bat where where %devstudio% is the installation directory for MSVC / DevStudio. If you get "environment out of space" errors under 95/98, create a desktop shortcut with "c:\windows\command.com /e:4096" as the program command line and set the working directory to the pngbook directory. Then double-click to open the new DOS-prompt window with a bigger environment and retry the commands above. Copy Makefile.w32 to Makefile and edit the PNGPATH and ZPATH variables appropriately (possibly also the "INC" and "LIB" variables if needed). Note that the names of the dynamic and static libpng and zlib libraries used in the makefile may change in later releases of the libraries. Also note that, as of libpng version 1.0.5, MSVC DLL builds do not work. This makefile therefore builds statically linked executables, but if the DLL problems ever get fixed, uncommenting the appropriate PNGLIB and ZLIB lines will build dynamically linked executables instead. Do the build by typing nmake The result should be three executables: rpng-win.exe, rpng2-win.exe, and wpng.exe. Copy them somewhere in your PATH or run them from the current folder. Like the Unix versions, the two windowed programs (rpng and rpng2) now display a usage screen in a console window when invoked without command-line arguments; this is new behavior as of the June 2001 release. Note that the programs use the Unix-style "-" character to specify options, instead of the more common DOS/Windows "/" character. (For example: "rpng2-win -bgpat 4 foo.png", not "rpng2-win /bgpat 4 foo.png") - OpenVMS: Unpack the pngbook sources into a subdirectory and change into that subdirectory. Edit makevms.com appropriately, specifically the zpath and pngpath variables. @makevms To run the programs, they probably first need to be set up as "foreign symbols," with "disk" and "dir" set appropriately: $ rpng == "$disk:[dir]rpng-x.exe" $ rpng2 == "$disk:[dir]rpng2-x.exe" $ wpng == "$disk:[dir]wpng.exe" All three will print a basic usage screen when run without any command- line arguments; see the book for more details. Note that the options style is Unix-like, i.e., preceded by "-" rather than "/". RUNNING THE PROGRAMS: (VERY) BRIEF INTRO rpng is a simple PNG viewer that can display transparent PNGs with a specified background color; for example, rpng -bgcolor \#ff0000 toucan.png would display the image with a red background. rpng2 is a progressive viewer that simulates a web browser in some respects; it can display images against either a background color or a dynamically generated background image. For example: rpng2 -bgpat 16 toucan.png wpng is a purely command-line image converter from binary PBMPLUS/NetPBM format (.pgm or .ppm) to PNG; for example, wpng -time < toucan-notrans.ppm > toucan-notrans.png would convert the specified PPM file (using redirection) to PNG, auto- matically setting the PNG modification-time chunk. All options can be abbreviated to the shortest unique value; for example, "-bgc" for -bgcolor (versus "-bgp" for -bgpat), or "-g" for -gamma. ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/makevms.com ================================================ $!------------------------------------------------------------------------------ $! make "PNG: The Definitive Guide" demo programs (for X) under OpenVMS $! $! Script created by Martin Zinser for libpng; modified by Greg Roelofs $! for standalone pngbook source distribution. $! $! $! Set locations where zlib and libpng sources live. $! $ zpath = "" $ pngpath = "" $! $ if f$search("[---.zlib]zlib.h").nes."" then zpath = "[---.zlib]" $ if f$search("[--]png.h").nes."" then pngpath = "[--]" $! $ if f$search("[-.zlib]zlib.h").nes."" then zpath = "[-.zlib]" $ if f$search("[-.libpng]png.h").nes."" then pngpath = "[-.libpng]" $! $ if zpath .eqs. "" $ then $ write sys$output "zlib include not found. Exiting..." $ exit 2 $ endif $! $ if pngpath .eqs. "" $ then $ write sys$output "libpng include not found. Exiting..." $ exit 2 $ endif $! $! Look for the compiler used. $! $ ccopt="/include=(''zpath',''pngpath')" $ if f$getsyi("HW_MODEL").ge.1024 $ then $ ccopt = "/prefix=all"+ccopt $ comp = "__decc__=1" $ if f$trnlnm("SYS").eqs."" then define sys sys$library: $ else $ if f$search("SYS$SYSTEM:DECC$COMPILER.EXE").eqs."" $ then $ if f$trnlnm("SYS").eqs."" then define sys sys$library: $ if f$search("SYS$SYSTEM:VAXC.EXE").eqs."" $ then $ comp = "__gcc__=1" $ CC :== GCC $ else $ comp = "__vaxc__=1" $ endif $ else $ if f$trnlnm("SYS").eqs."" then define sys decc$library_include: $ ccopt = "/decc/prefix=all"+ccopt $ comp = "__decc__=1" $ endif $ endif $ open/write lopt lib.opt $ write lopt "''pngpath'libpng.olb/lib" $ write lopt "''zpath'libz.olb/lib" $ close lopt $ open/write xopt x11.opt $ write xopt "sys$library:decw$xlibshr.exe/share" $ close xopt $! $! Build 'em. $! $ write sys$output "Compiling PNG book programs ..." $ CALL MAKE readpng.OBJ "cc ''CCOPT' readpng" - readpng.c readpng.h $ CALL MAKE readpng2.OBJ "cc ''CCOPT' readpng2" - readpng2.c readpng2.h $ CALL MAKE writepng.OBJ "cc ''CCOPT' writepng" - writepng.c writepng.h $ write sys$output "Building rpng-x..." $ CALL MAKE rpng-x.OBJ "cc ''CCOPT' rpng-x" - rpng-x.c readpng.h $ call make rpng-x.exe - "LINK rpng-x,readpng,lib.opt/opt,x11.opt/opt" - rpng-x.obj readpng.obj $ write sys$output "Building rpng2-x..." $ CALL MAKE rpng2-x.OBJ "cc ''CCOPT' rpng2-x" - rpng2-x.c readpng2.h $ call make rpng2-x.exe - "LINK rpng2-x,readpng2,lib.opt/opt,x11.opt/opt" - rpng2-x.obj readpng2.obj $ write sys$output "Building wpng..." $ CALL MAKE wpng.OBJ "cc ''CCOPT' wpng" - wpng.c writepng.h $ call make wpng.exe - "LINK wpng,writepng,lib.opt/opt" - wpng.obj writepng.obj $ exit $! $! $MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES $ V = 'F$Verify(0) $! P1 = What we are trying to make $! P2 = Command to make it $! P3 - P8 What it depends on $ $ If F$Search(P1) .Eqs. "" Then Goto Makeit $ Time = F$CvTime(F$File(P1,"RDT")) $arg=3 $Loop: $ Argument = P'arg $ If Argument .Eqs. "" Then Goto Exit $ El=0 $Loop2: $ File = F$Element(El," ",Argument) $ If File .Eqs. " " Then Goto Endl $ AFile = "" $Loop3: $ OFile = AFile $ AFile = F$Search(File) $ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl $ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit $ Goto Loop3 $NextEL: $ El = El + 1 $ Goto Loop2 $EndL: $ arg=arg+1 $ If arg .Le. 8 Then Goto Loop $ Goto Exit $ $Makeit: $ VV=F$VERIFY(0) $ write sys$output P2 $ 'P2 $ VV='F$Verify(VV) $Exit: $ If V Then Set Verify $ENDSUBROUTINE ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/readpng.c ================================================ /*--------------------------------------------------------------------------- rpng - simple PNG display program readpng.c --------------------------------------------------------------------------- Copyright (c) 1998-2007 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #include #include #include #include "png.h" /* libpng header */ #include "readpng.h" /* typedefs, common macros, public prototypes */ /* future versions of libpng will provide this macro: */ #ifndef png_jmpbuf # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf) #endif static png_structp png_ptr = NULL; static png_infop info_ptr = NULL; png_uint_32 width, height; int bit_depth, color_type; uch *image_data = NULL; void readpng_version_info(void) { fprintf(stderr, " Compiled with libpng %s; using libpng %s.\n", PNG_LIBPNG_VER_STRING, png_libpng_ver); fprintf(stderr, " Compiled with zlib %s; using zlib %s.\n", ZLIB_VERSION, zlib_version); } /* return value = 0 for success, 1 for bad sig, 2 for bad IHDR, 4 for no mem */ int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight) { uch sig[8]; /* first do a quick check that the file really is a PNG image; could * have used slightly more general png_sig_cmp() function instead */ fread(sig, 1, 8, infile); if (png_sig_cmp(sig, 0, 8)) return 1; /* bad signature */ /* could pass pointers to user-defined error handlers instead of NULLs: */ png_ptr = png_create_read_struct(png_get_libpng_ver(NULL), NULL, NULL, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } png_init_io(png_ptr, infile); png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */ png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); *pWidth = width; *pHeight = height; /* OK, that's all we need for now; return happy */ return 0; } /* returns 0 if succeeds, 1 if fails due to no bKGD chunk, 2 if libpng error; * scales values to 8-bit if necessary */ int readpng_get_bgcolor(uch *red, uch *green, uch *blue) { png_color_16p pBackground; /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD)) return 1; /* it is not obvious from the libpng documentation, but this function * takes a pointer to a pointer, and it always returns valid red, green * and blue values, regardless of color_type: */ png_get_bKGD(png_ptr, info_ptr, &pBackground); /* however, it always returns the raw bKGD data, regardless of any * bit-depth transformations, so check depth and adjust if necessary */ if (bit_depth == 16) { *red = pBackground->red >> 8; *green = pBackground->green >> 8; *blue = pBackground->blue >> 8; } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { if (bit_depth == 1) *red = *green = *blue = pBackground->gray? 255 : 0; else if (bit_depth == 2) *red = *green = *blue = (255/3) * pBackground->gray; else /* bit_depth == 4 */ *red = *green = *blue = (255/15) * pBackground->gray; } else { *red = (uch)pBackground->red; *green = (uch)pBackground->green; *blue = (uch)pBackground->blue; } return 0; } /* display_exponent == LUT_exponent * CRT_exponent */ uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes) { double gamma; png_uint_32 i, rowbytes; png_bytepp row_pointers = NULL; /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(png_jmpbuf(png_ptr))) { free(image_data); image_data = NULL; free(row_pointers); row_pointers = NULL; png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return NULL; } /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); #ifdef PNG_READ_16_TO_8_SUPPORTED if (bit_depth == 16) # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_set_scale_16(png_ptr); # else png_set_strip_16(png_ptr); # endif #endif if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); /* unlike the example in the libpng documentation, we have *no* idea where * this file may have come from--so if it doesn't have a file gamma, don't * do any correction ("do no harm") */ if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, display_exponent, gamma); /* all transformations have been registered; now update info_ptr data, * get rowbytes and channels, and allocate image memory */ png_read_update_info(png_ptr, info_ptr); *pRowbytes = rowbytes = png_get_rowbytes(png_ptr, info_ptr); *pChannels = (int)png_get_channels(png_ptr, info_ptr); if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return NULL; } if ((row_pointers = (png_bytepp)malloc(height*sizeof(png_bytep))) == NULL) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); free(image_data); image_data = NULL; return NULL; } Trace((stderr, "readpng_get_image: channels = %d, rowbytes = %ld, height = %ld\n", *pChannels, rowbytes, height)); /* set the individual row_pointers to point at the correct offsets */ for (i = 0; i < height; ++i) row_pointers[i] = image_data + i*rowbytes; /* now we can go ahead and just read the whole image */ png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) */ free(row_pointers); row_pointers = NULL; png_read_end(png_ptr, NULL); return image_data; } void readpng_cleanup(int free_image_data) { if (free_image_data && image_data) { free(image_data); image_data = NULL; } if (png_ptr && info_ptr) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); png_ptr = NULL; info_ptr = NULL; } } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/readpng.h ================================================ /*--------------------------------------------------------------------------- rpng - simple PNG display program readpng.h --------------------------------------------------------------------------- Copyright (c) 1998-2007 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #ifndef TRUE # define TRUE 1 # define FALSE 0 #endif #ifndef MAX # define MAX(a,b) ((a) > (b)? (a) : (b)) # define MIN(a,b) ((a) < (b)? (a) : (b)) #endif #ifdef DEBUG # define Trace(x) {fprintf x ; fflush(stderr); fflush(stdout);} #else # define Trace(x) ; #endif typedef unsigned char uch; typedef unsigned short ush; typedef unsigned long ulg; /* prototypes for public functions in readpng.c */ void readpng_version_info(void); int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight); int readpng_get_bgcolor(uch *bg_red, uch *bg_green, uch *bg_blue); uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes); void readpng_cleanup(int free_image_data); ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/readpng2.c ================================================ /*--------------------------------------------------------------------------- rpng2 - progressive-model PNG display program readpng2.c --------------------------------------------------------------------------- Copyright (c) 1998-2015 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --------------------------------------------------------------------------- Changelog: 2015-11-12 - Check return value of png_get_bKGD() (Glenn R-P) ---------------------------------------------------------------------------*/ #include /* for exit() prototype */ #include #include #include "png.h" /* libpng header from the local directory */ #include "readpng2.h" /* typedefs, common macros, public prototypes */ /* local prototypes */ static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr); static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row, png_uint_32 row_num, int pass); static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr); static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg); static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg); void readpng2_version_info(void) { fprintf(stderr, " Compiled with libpng %s; using libpng %s\n", PNG_LIBPNG_VER_STRING, png_libpng_ver); fprintf(stderr, " and with zlib %s; using zlib %s.\n", ZLIB_VERSION, zlib_version); } int readpng2_check_sig(uch *sig, int num) { return !png_sig_cmp(sig, 0, num); } /* returns 0 for success, 2 for libpng problem, 4 for out of memory */ int readpng2_init(mainprog_info *mainprog_ptr) { png_structp png_ptr; /* note: temporary variables! */ png_infop info_ptr; /* could also replace libpng warning-handler (final NULL), but no need: */ png_ptr = png_create_read_struct(png_get_libpng_ver(NULL), mainprog_ptr, readpng2_error_handler, readpng2_warning_handler); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function, unless an alternate error handler was installed-- * but compatible error handlers must either use longjmp() themselves * (as in this program) or exit immediately, so here we are: */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED /* prepare the reader to ignore all recognized chunks whose data won't be * used, i.e., all chunks recognized by libpng except for IHDR, PLTE, IDAT, * IEND, tRNS, bKGD, gAMA, and sRGB (small performance improvement) */ { /* These byte strings were copied from png.h. If a future version * of readpng2.c recognizes more chunks, add them to this list. */ static PNG_CONST png_byte chunks_to_process[] = { 98, 75, 71, 68, '\0', /* bKGD */ 103, 65, 77, 65, '\0', /* gAMA */ 115, 82, 71, 66, '\0', /* sRGB */ }; /* Ignore all chunks except for IHDR, PLTE, tRNS, IDAT, and IEND */ png_set_keep_unknown_chunks(png_ptr, -1 /* PNG_HANDLE_CHUNK_NEVER */, NULL, -1); /* But do not ignore chunks in the "chunks_to_process" list */ png_set_keep_unknown_chunks(png_ptr, 0 /* PNG_HANDLE_CHUNK_AS_DEFAULT */, chunks_to_process, sizeof(chunks_to_process)/5); } #endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */ /* instead of doing png_init_io() here, now we set up our callback * functions for progressive decoding */ png_set_progressive_read_fn(png_ptr, mainprog_ptr, readpng2_info_callback, readpng2_row_callback, readpng2_end_callback); /* make sure we save our pointers for use in readpng2_decode_data() */ mainprog_ptr->png_ptr = png_ptr; mainprog_ptr->info_ptr = info_ptr; /* and that's all there is to initialization */ return 0; } /* returns 0 for success, 2 for libpng (longjmp) problem */ int readpng2_decode_data(mainprog_info *mainprog_ptr, uch *rawbuf, ulg length) { png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr; /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; return 2; } /* hand off the next chunk of input data to libpng for decoding */ png_process_data(png_ptr, info_ptr, rawbuf, length); return 0; } static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; int color_type, bit_depth; png_uint_32 width, height; #ifdef PNG_FLOATING_POINT_SUPPORTED double gamma; #else png_fixed_point gamma; #endif /* setjmp() doesn't make sense here, because we'd either have to exit(), * longjmp() ourselves, or return control to libpng, which doesn't want * to see us again. By not doing anything here, libpng will instead jump * to readpng2_decode_data(), which can return an error value to the main * program. */ /* retrieve the pointer to our special-purpose struct, using the png_ptr * that libpng passed back to us (i.e., not a global this time--there's * no real difference for a single image, but for a multithreaded browser * decoding several PNG images at the same time, one needs to avoid mixing * up different images' structs) */ mainprog_ptr = png_get_progressive_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we be hosed */ fprintf(stderr, "readpng2 error: main struct not recoverable in info_callback.\n"); fflush(stderr); return; /* * Alternatively, we could call our error-handler just like libpng * does, which would effectively terminate the program. Since this * can only happen if png_ptr gets redirected somewhere odd or the * main PNG struct gets wiped, we're probably toast anyway. (If * png_ptr itself is NULL, we would not have been called.) */ } /* this is just like in the non-progressive case */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); mainprog_ptr->width = (ulg)width; mainprog_ptr->height = (ulg)height; /* since we know we've read all of the PNG file's "header" (i.e., up * to IDAT), we can check for a background color here */ if (mainprog_ptr->need_bgcolor) { png_color_16p pBackground; /* it is not obvious from the libpng documentation, but this function * takes a pointer to a pointer, and it always returns valid red, * green and blue values, regardless of color_type: */ if (png_get_bKGD(png_ptr, info_ptr, &pBackground)) { /* however, it always returns the raw bKGD data, regardless of any * bit-depth transformations, so check depth and adjust if necessary */ if (bit_depth == 16) { mainprog_ptr->bg_red = pBackground->red >> 8; mainprog_ptr->bg_green = pBackground->green >> 8; mainprog_ptr->bg_blue = pBackground->blue >> 8; } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { if (bit_depth == 1) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = pBackground->gray? 255 : 0; else if (bit_depth == 2) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/3) * pBackground->gray; else /* bit_depth == 4 */ mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/15) * pBackground->gray; } else { mainprog_ptr->bg_red = (uch)pBackground->red; mainprog_ptr->bg_green = (uch)pBackground->green; mainprog_ptr->bg_blue = (uch)pBackground->blue; } } } /* as before, let libpng expand palette images to RGB, low-bit-depth * grayscale images to 8 bits, transparency chunks to full alpha channel; * strip 16-bit-per-sample images to 8 bits per sample; and convert * grayscale to RGB[A] */ if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); #ifdef PNG_READ_16_TO_8_SUPPORTED if (bit_depth == 16) # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_set_scale_16(png_ptr); # else png_set_strip_16(png_ptr); # endif #endif if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); /* Unlike the basic viewer, which was designed to operate on local files, * this program is intended to simulate a web browser--even though we * actually read from a local file, too. But because we are pretending * that most of the images originate on the Internet, we follow the recom- * mendation of the sRGB proposal and treat unlabelled images (no gAMA * chunk) as existing in the sRGB color space. That is, we assume that * such images have a file gamma of 0.45455, which corresponds to a PC-like * display system. This change in assumptions will have no effect on a * PC-like system, but on a Mac, SGI, NeXT or other system with a non- * identity lookup table, it will darken unlabelled images, which effec- * tively favors images from PC-like systems over those originating on * the local platform. Note that mainprog_ptr->display_exponent is the * "gamma" value for the entire display system, i.e., the product of * LUT_exponent and CRT_exponent. */ #ifdef PNG_FLOATING_POINT_SUPPORTED if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma); else png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455); #else if (png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), gamma); else png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), 45455); #endif /* we'll let libpng expand interlaced images, too */ mainprog_ptr->passes = png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data and * then get rowbytes and channels */ png_read_update_info(png_ptr, info_ptr); mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr); mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr); /* Call the main program to allocate memory for the image buffer and * initialize windows and whatnot. (The old-style function-pointer * invocation is used for compatibility with a few supposedly ANSI * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */ (*mainprog_ptr->mainprog_init)(); /* and that takes care of initialization */ return; } static void readpng2_row_callback(png_structp png_ptr, png_bytep new_row, png_uint_32 row_num, int pass) { mainprog_info *mainprog_ptr; /* first check whether the row differs from the previous pass; if not, * nothing to combine or display */ if (!new_row) return; /* retrieve the pointer to our special-purpose struct so we can access * the old rows and image-display callback function */ mainprog_ptr = png_get_progressive_ptr(png_ptr); /* save the pass number for optional use by the front end */ mainprog_ptr->pass = pass; /* have libpng either combine the new row data with the existing row data * from previous passes (if interlaced) or else just copy the new row * into the main program's image buffer */ png_progressive_combine_row(png_ptr, mainprog_ptr->row_pointers[row_num], new_row); /* finally, call the display routine in the main program with the number * of the row we just updated */ (*mainprog_ptr->mainprog_display_row)(row_num); /* and we're ready for more */ return; } static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; /* retrieve the pointer to our special-purpose struct */ mainprog_ptr = png_get_progressive_ptr(png_ptr); /* let the main program know that it should flush any buffered image * data to the display now and set a "done" flag or whatever, but note * that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do * NOT call readpng2_cleanup() either here or in the finish_display() * routine; wait until control returns to the main program via * readpng2_decode_data() */ (*mainprog_ptr->mainprog_finish_display)(); /* all done */ (void)info_ptr; /* Unused */ return; } void readpng2_cleanup(mainprog_info *mainprog_ptr) { png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr; if (png_ptr && info_ptr) png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; } static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg) { fprintf(stderr, "readpng2 libpng warning: %s\n", msg); fflush(stderr); (void)png_ptr; /* Unused */ } static void readpng2_error_handler(png_structp png_ptr, png_const_charp msg) { mainprog_info *mainprog_ptr; /* This function, aside from the extra step of retrieving the "error * pointer" (below) and the fact that it exists within the application * rather than within libpng, is essentially identical to libpng's * default error handler. The second point is critical: since both * setjmp() and longjmp() are called from the same code, they are * guaranteed to have compatible notions of how big a jmp_buf is, * regardless of whether _BSD_SOURCE or anything else has (or has not) * been defined. */ fprintf(stderr, "readpng2 libpng error: %s\n", msg); fflush(stderr); mainprog_ptr = png_get_error_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we are completely hosed now */ fprintf(stderr, "readpng2 severe error: jmpbuf not recoverable; terminating.\n"); fflush(stderr); exit(99); } /* Now we have our data structure we can use the information in it * to return control to our own higher level code (all the points * where 'setjmp' is called in this file.) This will work with other * error handling mechanisms as well - libpng always calls png_error * when it can proceed no further, thus, so long as the error handler * is intercepted, application code can do its own error recovery. */ longjmp(mainprog_ptr->jmpbuf, 1); } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/readpng2.h ================================================ /*--------------------------------------------------------------------------- rpng2 - progressive-model PNG display program readpng2.h --------------------------------------------------------------------------- Copyright (c) 1998-2008 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #ifndef TRUE # define TRUE 1 # define FALSE 0 #endif #ifndef MAX # define MAX(a,b) ((a) > (b)? (a) : (b)) # define MIN(a,b) ((a) < (b)? (a) : (b)) #endif #ifdef DEBUG # define Trace(x) {fprintf x ; fflush(stderr); fflush(stdout);} #else # define Trace(x) ; #endif enum rpng2_states { kPreInit = 0, kWindowInit, kDone }; typedef unsigned char uch; typedef unsigned short ush; typedef unsigned long ulg; typedef struct _mainprog_info { double display_exponent; ulg width; ulg height; void *png_ptr; void *info_ptr; void (*mainprog_init)(void); void (*mainprog_display_row)(ulg row_num); void (*mainprog_finish_display)(void); uch *image_data; uch **row_pointers; jmp_buf jmpbuf; int passes; /* not used */ int pass; int rowbytes; int channels; int need_bgcolor; int state; uch bg_red; uch bg_green; uch bg_blue; } mainprog_info; /* prototypes for public functions in readpng2.c */ void readpng2_version_info(void); int readpng2_check_sig(uch *sig, int num); int readpng2_init(mainprog_info *mainprog_ptr); int readpng2_decode_data(mainprog_info *mainprog_ptr, uch *rawbuf, ulg length); void readpng2_cleanup(mainprog_info *mainprog_ptr); ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/readppm.c ================================================ /*--------------------------------------------------------------------------- rpng - simple PNG display program readppm.c --------------------------------------------------------------------------- This is a special-purpose replacement for readpng.c that allows binary PPM files to be used in place of PNG images. --------------------------------------------------------------------------- Copyright (c) 1998-2007 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #include #include #include "readpng.h" /* typedefs, common macros, public prototypes */ ulg width, height; int bit_depth, color_type, channels; uch *image_data = NULL; FILE *saved_infile; void readpng_version_info() { fprintf(stderr, " Compiled without libpng, zlib or PBMPLUS/NetPBM.\n"); } /* return value = 0 for success, 1 for bad sig, 2 for bad IHDR, 4 for no mem */ int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight) { static uch ppmline[256]; int maxval; saved_infile = infile; fgets(ppmline, 256, infile); if (ppmline[0] != 'P' || ppmline[1] != '6') { fprintf(stderr, "ERROR: not a PPM file\n"); return 1; } /* possible color types: P5 = grayscale (0), P6 = RGB (2), P8 = RGBA (6) */ if (ppmline[1] == '6') { color_type = 2; channels = 3; } else if (ppmline[1] == '8') { color_type = 6; channels = 4; } else /* if (ppmline[1] == '5') */ { color_type = 0; channels = 1; } do { fgets(ppmline, 256, infile); } while (ppmline[0] == '#'); sscanf(ppmline, "%lu %lu", &width, &height); do { fgets(ppmline, 256, infile); } while (ppmline[0] == '#'); sscanf(ppmline, "%d", &maxval); if (maxval != 255) { fprintf(stderr, "ERROR: maxval = %d\n", maxval); return 2; } bit_depth = 8; *pWidth = width; *pHeight = height; return 0; } /* returns 0 if succeeds, 1 if fails due to no bKGD chunk, 2 if libpng error; * scales values to 8-bit if necessary */ int readpng_get_bgcolor(uch *red, uch *green, uch *blue) { return 1; } /* display_exponent == LUT_exponent * CRT_exponent */ uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes) { ulg rowbytes; /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ /* GRR WARNING: grayscale needs to be expanded and channels reset! */ *pRowbytes = rowbytes = channels*width; *pChannels = channels; if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) { return NULL; } Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height)); /* now we can go ahead and just read the whole image */ if (fread(image_data, 1L, rowbytes*height, saved_infile) < rowbytes*height) { free (image_data); image_data = NULL; return NULL; } return image_data; } void readpng_cleanup(int free_image_data) { if (free_image_data && image_data) { free(image_data); image_data = NULL; } } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/rpng-win.c ================================================ /*--------------------------------------------------------------------------- rpng - simple PNG display program rpng-win.c This program decodes and displays PNG images, with gamma correction and optionally with a user-specified background color (in case the image has transparency). It is very nearly the most basic PNG viewer possible. This version is for 32-bit Windows; it may compile under 16-bit Windows with a little tweaking (or maybe not). to do: - handle quoted command-line args (especially filenames with spaces) - have minimum window width: oh well - use %.1023s to simplify truncation of title-bar string? --------------------------------------------------------------------------- Changelog: - 1.00: initial public release - 1.01: modified to allow abbreviated options; fixed long/ulong mis- match; switched to png_jmpbuf() macro - 1.02: added extra set of parentheses to png_jmpbuf() macro; fixed command-line parsing bug - 1.10: enabled "message window"/console (thanks to David Geldreich) - 2.00: dual-licensed (added GNU GPL) - 2.01: fixed improper display of usage screen on PNG error(s) --------------------------------------------------------------------------- Copyright (c) 1998-2008 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #define PROGNAME "rpng-win" #define LONGNAME "Simple PNG Viewer for Windows" #define VERSION "2.01 of 16 March 2008" #include #include #include #include #include #ifdef __CYGWIN__ /* getch replacement. Turns out, we don't really need this, * but leave it here if we ever enable any of the uses of * _getch in the main code */ #include #include #include int repl_getch( void ) { char ch; int fd = fileno(stdin); struct termio old_tty, new_tty; ioctl(fd, TCGETA, &old_tty); new_tty = old_tty; new_tty.c_lflag &= ~(ICANON | ECHO | ISIG); ioctl(fd, TCSETA, &new_tty); fread(&ch, 1, sizeof(ch), stdin); ioctl(fd, TCSETA, &old_tty); return ch; } #define _getch repl_getch #else #include /* only for _getch() */ #endif /* #define DEBUG : this enables the Trace() macros */ #include "readpng.h" /* typedefs, common macros, readpng prototypes */ /* could just include png.h, but this macro is the only thing we need * (name and typedefs changed to local versions); note that side effects * only happen with alpha (which could easily be avoided with * "ush acopy = (alpha);") */ #define alpha_composite(composite, fg, alpha, bg) { \ ush temp = ((ush)(fg)*(ush)(alpha) + \ (ush)(bg)*(ush)(255 - (ush)(alpha)) + (ush)128); \ (composite) = (uch)((temp + (temp >> 8)) >> 8); \ } /* local prototypes */ static int rpng_win_create_window(HINSTANCE hInst, int showmode); static int rpng_win_display_image(void); static void rpng_win_cleanup(void); LRESULT CALLBACK rpng_win_wndproc(HWND, UINT, WPARAM, LPARAM); static char titlebar[1024]; static char *progname = PROGNAME; static char *appname = LONGNAME; static char *filename; static FILE *infile; static char *bgstr; static uch bg_red=0, bg_green=0, bg_blue=0; static double display_exponent; static ulg image_width, image_height, image_rowbytes; static int image_channels; static uch *image_data; /* Windows-specific variables */ static ulg wimage_rowbytes; static uch *dib; static uch *wimage_data; static BITMAPINFOHEADER *bmih; static HWND global_hwnd; int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, PSTR cmd, int showmode) { char *args[1024]; /* arbitrary limit, but should suffice */ char *p, *q, **argv = args; int argc = 0; int rc, alen, flen; int error = 0; int have_bg = FALSE; double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ MSG msg; filename = (char *)NULL; #ifndef __CYGWIN__ /* First reenable console output, which normally goes to the bit bucket * for windowed apps. Closing the console window will terminate the * app. Thanks to David.Geldreich@realviz.com for supplying the magical * incantation. */ AllocConsole(); freopen("CONOUT$", "a", stderr); freopen("CONOUT$", "a", stdout); #endif /* Next set the default value for our display-system exponent, i.e., * the product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. And * yes, these ifdefs are completely wasted in a Windows program... */ #if defined(NeXT) LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to get the * "gamma" value, so we do it the hard way */ infile = fopen("/etc/config/system.glGammaVal", "r"); if (infile) { double sgi_gamma; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) display_exponent = atof(p); else display_exponent = default_display_exponent; /* Windows really hates command lines, so we have to set up our own argv. * Note that we do NOT bother with quoted arguments here, so don't use * filenames with spaces in 'em! */ argv[argc++] = PROGNAME; p = cmd; for (;;) { if (*p == ' ') while (*++p == ' ') ; /* now p points at the first non-space after some spaces */ if (*p == '\0') break; /* nothing after the spaces: done */ argv[argc++] = q = p; while (*q && *q != ' ') ++q; /* now q points at a space or the end of the string */ if (*q == '\0') break; /* last argv already terminated; quit */ *q = '\0'; /* change space to terminator */ p = q + 1; } argv[argc] = NULL; /* terminate the argv array itself */ /* Now parse the command line for options and the PNG filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { display_exponent = atof(*argv); if (display_exponent <= 0.0) ++error; } } else if (!strncmp(*argv, "-bgcolor", 2)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else have_bg = TRUE; } } else { if (**argv != '-') { filename = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } if (!filename) ++error; /* print usage screen if any errors up to this point */ if (error) { #ifndef __CYGWIN__ int ch; #endif fprintf(stderr, "\n%s %s: %s\n\n", PROGNAME, VERSION, appname); readpng_version_info(); fprintf(stderr, "\n" "Usage: %s [-gamma exp] [-bgcolor bg] file.png\n" " exp \ttransfer-function exponent (``gamma'') of the display\n" "\t\t system in floating-point format (e.g., ``%.1f''); equal\n" "\t\t to the product of the lookup-table exponent (varies)\n" "\t\t and the CRT exponent (usually 2.2); must be positive\n" " bg \tdesired background color in 7-character hex RGB format\n" "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n" "\t\t used with transparent images\n" "\nPress Q, Esc or mouse button 1 after image is displayed to quit.\n" #ifndef __CYGWIN__ "Press Q or Esc to quit this usage screen.\n" #endif "\n", PROGNAME, default_display_exponent); #ifndef __CYGWIN__ do ch = _getch(); while (ch != 'q' && ch != 'Q' && ch != 0x1B); #endif exit(1); } if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename); ++error; } else { if ((rc = readpng_init(infile, &image_width, &image_height)) != 0) { switch (rc) { case 1: fprintf(stderr, PROGNAME ": [%s] is not a PNG file: incorrect signature\n", filename); break; case 2: fprintf(stderr, PROGNAME ": [%s] has bad IHDR (libpng longjmp)\n", filename); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; default: fprintf(stderr, PROGNAME ": unknown readpng_init() error\n"); break; } ++error; } if (error) fclose(infile); } if (error) { #ifndef __CYGWIN__ int ch; #endif fprintf(stderr, PROGNAME ": aborting.\n"); #ifndef __CYGWIN__ do ch = _getch(); while (ch != 'q' && ch != 'Q' && ch != 0x1B); #endif exit(2); } else { fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, appname); #ifndef __CYGWIN__ fprintf(stderr, "\n [console window: closing this window will terminate %s]\n\n", PROGNAME); #endif } /* set the title-bar string, but make sure buffer doesn't overflow */ alen = strlen(appname); flen = strlen(filename); if (alen + flen + 3 > 1023) sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023)); else sprintf(titlebar, "%s: %s", appname, filename); /* if the user didn't specify a background color on the command line, * check for one in the PNG file--if not, the initialized values of 0 * (black) will be used */ if (have_bg) { unsigned r, g, b; /* this approach quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); bg_red = (uch)r; bg_green = (uch)g; bg_blue = (uch)b; } else if (readpng_get_bgcolor(&bg_red, &bg_green, &bg_blue) > 1) { readpng_cleanup(TRUE); fprintf(stderr, PROGNAME ": libpng error while checking for background color\n"); exit(2); } /* do the basic Windows initialization stuff, make the window and fill it * with the background color */ if (rpng_win_create_window(hInst, showmode)) exit(2); /* decode the image, all at once */ Trace((stderr, "calling readpng_get_image()\n")) image_data = readpng_get_image(display_exponent, &image_channels, &image_rowbytes); Trace((stderr, "done with readpng_get_image()\n")) /* done with PNG file, so clean up to minimize memory usage (but do NOT * nuke image_data!) */ readpng_cleanup(FALSE); fclose(infile); if (!image_data) { fprintf(stderr, PROGNAME ": unable to decode PNG image\n"); exit(3); } /* display image (composite with background if requested) */ Trace((stderr, "calling rpng_win_display_image()\n")) if (rpng_win_display_image()) { free(image_data); exit(4); } Trace((stderr, "done with rpng_win_display_image()\n")) /* wait for the user to tell us when to quit */ printf( #ifndef __CYGWIN__ "Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n" #else "Done. Press mouse button 1 (within image window) to quit.\n" #endif ); fflush(stdout); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } /* OK, we're done: clean up all image and Windows resources and go away */ rpng_win_cleanup(); return msg.wParam; } static int rpng_win_create_window(HINSTANCE hInst, int showmode) { uch *dest; int extra_width, extra_height; ulg i, j; WNDCLASSEX wndclass; /*--------------------------------------------------------------------------- Allocate memory for the display-specific version of the image (round up to multiple of 4 for Windows DIB). ---------------------------------------------------------------------------*/ wimage_rowbytes = ((3*image_width + 3L) >> 2) << 2; if (!(dib = (uch *)malloc(sizeof(BITMAPINFOHEADER) + wimage_rowbytes*image_height))) { return 4; /* fail */ } /*--------------------------------------------------------------------------- Initialize the DIB. Negative height means to use top-down BMP ordering (must be uncompressed, but that's what we want). Bit count of 1, 4 or 8 implies a colormap of RGBX quads, but 24-bit BMPs just use B,G,R values directly => wimage_data begins immediately after BMP header. ---------------------------------------------------------------------------*/ memset(dib, 0, sizeof(BITMAPINFOHEADER)); bmih = (BITMAPINFOHEADER *)dib; bmih->biSize = sizeof(BITMAPINFOHEADER); bmih->biWidth = image_width; bmih->biHeight = -((long)image_height); bmih->biPlanes = 1; bmih->biBitCount = 24; bmih->biCompression = 0; wimage_data = dib + sizeof(BITMAPINFOHEADER); /*--------------------------------------------------------------------------- Fill in background color (black by default); data are in BGR order. ---------------------------------------------------------------------------*/ for (j = 0; j < image_height; ++j) { dest = wimage_data + j*wimage_rowbytes; for (i = image_width; i > 0; --i) { *dest++ = bg_blue; *dest++ = bg_green; *dest++ = bg_red; } } /*--------------------------------------------------------------------------- Set the window parameters. ---------------------------------------------------------------------------*/ memset(&wndclass, 0, sizeof(wndclass)); wndclass.cbSize = sizeof(wndclass); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = rpng_win_wndproc; wndclass.hInstance = hInst; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = progname; wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); RegisterClassEx(&wndclass); /*--------------------------------------------------------------------------- Finally, create the window. ---------------------------------------------------------------------------*/ extra_width = 2*(GetSystemMetrics(SM_CXBORDER) + GetSystemMetrics(SM_CXDLGFRAME)); extra_height = 2*(GetSystemMetrics(SM_CYBORDER) + GetSystemMetrics(SM_CYDLGFRAME)) + GetSystemMetrics(SM_CYCAPTION); global_hwnd = CreateWindow(progname, titlebar, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, image_width+extra_width, image_height+extra_height, NULL, NULL, hInst, NULL); ShowWindow(global_hwnd, showmode); UpdateWindow(global_hwnd); return 0; } /* end function rpng_win_create_window() */ static int rpng_win_display_image() { uch *src, *dest; uch r, g, b, a; ulg i, row, lastrow; RECT rect; Trace((stderr, "beginning display loop (image_channels == %d)\n", image_channels)) Trace((stderr, "(width = %ld, rowbytes = %ld, wimage_rowbytes = %d)\n", image_width, image_rowbytes, wimage_rowbytes)) /*--------------------------------------------------------------------------- Blast image data to buffer. This whole routine takes place before the message loop begins, so there's no real point in any pseudo-progressive display... ---------------------------------------------------------------------------*/ for (lastrow = row = 0; row < image_height; ++row) { src = image_data + row*image_rowbytes; dest = wimage_data + row*wimage_rowbytes; if (image_channels == 3) { for (i = image_width; i > 0; --i) { r = *src++; g = *src++; b = *src++; *dest++ = b; *dest++ = g; /* note reverse order */ *dest++ = r; } } else /* if (image_channels == 4) */ { for (i = image_width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (a == 255) { *dest++ = b; *dest++ = g; *dest++ = r; } else if (a == 0) { *dest++ = bg_blue; *dest++ = bg_green; *dest++ = bg_red; } else { /* this macro (copied from png.h) composites the * foreground and background values and puts the * result into the first argument; there are no * side effects with the first argument */ alpha_composite(*dest++, b, a, bg_blue); alpha_composite(*dest++, g, a, bg_green); alpha_composite(*dest++, r, a, bg_red); } } } /* display after every 16 lines */ if (((row+1) & 0xf) == 0) { rect.left = 0L; rect.top = (LONG)lastrow; rect.right = (LONG)image_width; /* possibly off by one? */ rect.bottom = (LONG)lastrow + 16L; /* possibly off by one? */ InvalidateRect(global_hwnd, &rect, FALSE); UpdateWindow(global_hwnd); /* similar to XFlush() */ lastrow = row + 1; } } Trace((stderr, "calling final image-flush routine\n")) if (lastrow < image_height) { rect.left = 0L; rect.top = (LONG)lastrow; rect.right = (LONG)image_width; /* possibly off by one? */ rect.bottom = (LONG)image_height; /* possibly off by one? */ InvalidateRect(global_hwnd, &rect, FALSE); UpdateWindow(global_hwnd); /* similar to XFlush() */ } /* last param determines whether or not background is wiped before paint InvalidateRect(global_hwnd, NULL, TRUE); UpdateWindow(global_hwnd); */ return 0; } static void rpng_win_cleanup() { if (image_data) { free(image_data); image_data = NULL; } if (dib) { free(dib); dib = NULL; } } LRESULT CALLBACK rpng_win_wndproc(HWND hwnd, UINT iMsg, WPARAM wP, LPARAM lP) { HDC hdc; PAINTSTRUCT ps; int rc; switch (iMsg) { case WM_CREATE: /* one-time processing here, if any */ return 0; case WM_PAINT: hdc = BeginPaint(hwnd, &ps); /* dest */ rc = StretchDIBits(hdc, 0, 0, image_width, image_height, /* source */ 0, 0, image_width, image_height, wimage_data, (BITMAPINFO *)bmih, /* iUsage: no clue */ 0, SRCCOPY); EndPaint(hwnd, &ps); return 0; /* wait for the user to tell us when to quit */ case WM_CHAR: switch (wP) { /* only need one, so ignore repeat count */ case 'q': case 'Q': case 0x1B: /* Esc key */ PostQuitMessage(0); } return 0; case WM_LBUTTONDOWN: /* another way of quitting */ case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, iMsg, wP, lP); } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/rpng-x.c ================================================ /*--------------------------------------------------------------------------- rpng - simple PNG display program rpng-x.c This program decodes and displays PNG images, with gamma correction and optionally with a user-specified background color (in case the image has transparency). It is very nearly the most basic PNG viewer possible. This version is for the X Window System (tested by author under Unix and by Martin Zinser under OpenVMS; may work under OS/2 with some tweaking). to do: - 8-bit (colormapped) X support - use %.1023s to simplify truncation of title-bar string? --------------------------------------------------------------------------- Changelog: - 1.01: initial public release - 1.02: modified to allow abbreviated options; fixed long/ulong mis- match; switched to png_jmpbuf() macro - 1.10: added support for non-default visuals; fixed X pixel-conversion - 1.11: added extra set of parentheses to png_jmpbuf() macro; fixed command-line parsing bug - 1.12: fixed some small X memory leaks (thanks to Franois Petitjean) - 1.13: fixed XFreeGC() crash bug (thanks to Patrick Welche) - 1.14: added support for X resources (thanks to Gerhard Niklasch) - 2.00: dual-licensed (added GNU GPL) - 2.01: fixed improper display of usage screen on PNG error(s) - 2.02: Added "void(argc);" statement to quiet pedantic compiler warnings about unused variable (GR-P) --------------------------------------------------------------------------- Copyright (c) 1998-2008 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #define PROGNAME "rpng-x" #define LONGNAME "Simple PNG Viewer for X" #define VERSION "2.02 of 15 June 2014" #define RESNAME "rpng" /* our X resource application name */ #define RESCLASS "Rpng" /* our X resource class name */ #include #include #include #include #include #include #include #include /* #define DEBUG : this enables the Trace() macros */ #include "readpng.h" /* typedefs, common macros, readpng prototypes */ /* could just include png.h, but this macro is the only thing we need * (name and typedefs changed to local versions); note that side effects * only happen with alpha (which could easily be avoided with * "ush acopy = (alpha);") */ #define alpha_composite(composite, fg, alpha, bg) { \ ush temp = ((ush)(fg)*(ush)(alpha) + \ (ush)(bg)*(ush)(255 - (ush)(alpha)) + (ush)128); \ (composite) = (uch)((temp + (temp >> 8)) >> 8); \ } /* local prototypes */ static int rpng_x_create_window(void); static int rpng_x_display_image(void); static void rpng_x_cleanup(void); static int rpng_x_msb(ulg u32val); static char titlebar[1024], *window_name = titlebar; static char *appname = LONGNAME; static char *icon_name = PROGNAME; static char *res_name = RESNAME; static char *res_class = RESCLASS; static char *filename; static FILE *infile; static char *bgstr; static uch bg_red=0, bg_green=0, bg_blue=0; static double display_exponent; static ulg image_width, image_height, image_rowbytes; static int image_channels; static uch *image_data; /* X-specific variables */ static char *displayname; static XImage *ximage; static Display *display; static int depth; static Visual *visual; static XVisualInfo *visual_list; static int RShift, GShift, BShift; static ulg RMask, GMask, BMask; static Window window; static GC gc; static Colormap colormap; static int have_nondefault_visual = FALSE; static int have_colormap = FALSE; static int have_window = FALSE; static int have_gc = FALSE; /* ulg numcolors=0, pixels[256]; ush reds[256], greens[256], blues[256]; */ int main(int argc, char **argv) { #ifdef sgi char tmpline[80]; #endif char *p; int rc, alen, flen; int error = 0; int have_bg = FALSE; double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ XEvent e; KeySym k; displayname = (char *)NULL; filename = (char *)NULL; /* First set the default value for our display-system exponent, i.e., * the product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. */ #if defined(NeXT) LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to get the * "gamma" value, so we do it the hard way */ infile = fopen("/etc/config/system.glGammaVal", "r"); if (infile) { double sgi_gamma; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) display_exponent = atof(p); else display_exponent = default_display_exponent; /* Now parse the command line for options and the PNG filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-display", 2)) { if (!*++argv) ++error; else displayname = *argv; } else if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { display_exponent = atof(*argv); if (display_exponent <= 0.0) ++error; } } else if (!strncmp(*argv, "-bgcolor", 2)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else have_bg = TRUE; } } else { if (**argv != '-') { filename = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } if (!filename) ++error; /* print usage screen if any errors up to this point */ if (error) { fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, appname); readpng_version_info(); fprintf(stderr, "\n" "Usage: %s [-display xdpy] [-gamma exp] [-bgcolor bg] file.png\n" " xdpy\tname of the target X display (e.g., ``hostname:0'')\n" " exp \ttransfer-function exponent (``gamma'') of the display\n" "\t\t system in floating-point format (e.g., ``%.1f''); equal\n", PROGNAME, default_display_exponent); fprintf(stderr, "\n" "\t\t to the product of the lookup-table exponent (varies)\n" "\t\t and the CRT exponent (usually 2.2); must be positive\n" " bg \tdesired background color in 7-character hex RGB format\n" "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n" "\t\t used with transparent images\n" "\nPress Q, Esc or mouse button 1 (within image window, after image\n" "is displayed) to quit.\n"); exit(1); } if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename); ++error; } else { if ((rc = readpng_init(infile, &image_width, &image_height)) != 0) { switch (rc) { case 1: fprintf(stderr, PROGNAME ": [%s] is not a PNG file: incorrect signature\n", filename); break; case 2: fprintf(stderr, PROGNAME ": [%s] has bad IHDR (libpng longjmp)\n", filename); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; default: fprintf(stderr, PROGNAME ": unknown readpng_init() error\n"); break; } ++error; } else { display = XOpenDisplay(displayname); if (!display) { readpng_cleanup(TRUE); fprintf(stderr, PROGNAME ": can't open X display [%s]\n", displayname? displayname : "default"); ++error; } } if (error) fclose(infile); } if (error) { fprintf(stderr, PROGNAME ": aborting.\n"); exit(2); } /* set the title-bar string, but make sure buffer doesn't overflow */ alen = strlen(appname); flen = strlen(filename); if (alen + flen + 3 > 1023) sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023)); else sprintf(titlebar, "%s: %s", appname, filename); /* if the user didn't specify a background color on the command line, * check for one in the PNG file--if not, the initialized values of 0 * (black) will be used */ if (have_bg) { unsigned r, g, b; /* this approach quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); bg_red = (uch)r; bg_green = (uch)g; bg_blue = (uch)b; } else if (readpng_get_bgcolor(&bg_red, &bg_green, &bg_blue) > 1) { readpng_cleanup(TRUE); fprintf(stderr, PROGNAME ": libpng error while checking for background color\n"); exit(2); } /* do the basic X initialization stuff, make the window and fill it * with the background color */ if (rpng_x_create_window()) exit(2); /* decode the image, all at once */ Trace((stderr, "calling readpng_get_image()\n")) image_data = readpng_get_image(display_exponent, &image_channels, &image_rowbytes); Trace((stderr, "done with readpng_get_image()\n")) /* done with PNG file, so clean up to minimize memory usage (but do NOT * nuke image_data!) */ readpng_cleanup(FALSE); fclose(infile); if (!image_data) { fprintf(stderr, PROGNAME ": unable to decode PNG image\n"); exit(3); } /* display image (composite with background if requested) */ Trace((stderr, "calling rpng_x_display_image()\n")) if (rpng_x_display_image()) { free(image_data); exit(4); } Trace((stderr, "done with rpng_x_display_image()\n")) /* wait for the user to tell us when to quit */ printf( "Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n"); fflush(stdout); do XNextEvent(display, &e); while (!(e.type == ButtonPress && e.xbutton.button == Button1) && !(e.type == KeyPress && /* v--- or 1 for shifted keys */ ((k = XLookupKeysym(&e.xkey, 0)) == XK_q || k == XK_Escape) )); /* OK, we're done: clean up all image and X resources and go away */ rpng_x_cleanup(); (void)argc; /* Unused */ return 0; } static int rpng_x_create_window(void) { uch *xdata; int need_colormap = FALSE; int screen, pad; ulg bg_pixel = 0L; ulg attrmask; Window root; XEvent e; XGCValues gcvalues; XSetWindowAttributes attr; XTextProperty windowName, *pWindowName = &windowName; XTextProperty iconName, *pIconName = &iconName; XVisualInfo visual_info; XSizeHints *size_hints; XWMHints *wm_hints; XClassHint *class_hints; screen = DefaultScreen(display); depth = DisplayPlanes(display, screen); root = RootWindow(display, screen); #ifdef DEBUG XSynchronize(display, True); #endif #if 0 /* GRR: add 8-bit support */ if (/* depth != 8 && */ depth != 16 && depth != 24 && depth != 32) { fprintf(stderr, "screen depth %d not supported (only 16-, 24- or 32-bit TrueColor)\n", depth); return 2; } XMatchVisualInfo(display, screen, depth, (depth == 8)? PseudoColor : TrueColor, &visual_info); visual = visual_info.visual; #else if (depth != 16 && depth != 24 && depth != 32) { int visuals_matched = 0; Trace((stderr, "default depth is %d: checking other visuals\n", depth)) /* 24-bit first */ visual_info.screen = screen; visual_info.depth = 24; visual_list = XGetVisualInfo(display, VisualScreenMask | VisualDepthMask, &visual_info, &visuals_matched); if (visuals_matched == 0) { /* GRR: add 15-, 16- and 32-bit TrueColor visuals (also DirectColor?) */ fprintf(stderr, "default screen depth %d not supported, and no" " 24-bit visuals found\n", depth); return 2; } Trace((stderr, "XGetVisualInfo() returned %d 24-bit visuals\n", visuals_matched)) visual = visual_list[0].visual; depth = visual_list[0].depth; /* colormap_size = visual_list[0].colormap_size; visual_class = visual->class; visualID = XVisualIDFromVisual(visual); */ have_nondefault_visual = TRUE; need_colormap = TRUE; } else { XMatchVisualInfo(display, screen, depth, TrueColor, &visual_info); visual = visual_info.visual; } #endif RMask = visual->red_mask; GMask = visual->green_mask; BMask = visual->blue_mask; /* GRR: add/check 8-bit support */ if (depth == 8 || need_colormap) { colormap = XCreateColormap(display, root, visual, AllocNone); if (!colormap) { fprintf(stderr, "XCreateColormap() failed\n"); return 2; } have_colormap = TRUE; } if (depth == 15 || depth == 16) { RShift = 15 - rpng_x_msb(RMask); /* these are right-shifts */ GShift = 15 - rpng_x_msb(GMask); BShift = 15 - rpng_x_msb(BMask); } else if (depth > 16) { #define NO_24BIT_MASKS #ifdef NO_24BIT_MASKS RShift = rpng_x_msb(RMask) - 7; /* these are left-shifts */ GShift = rpng_x_msb(GMask) - 7; BShift = rpng_x_msb(BMask) - 7; #else RShift = 7 - rpng_x_msb(RMask); /* these are right-shifts, too */ GShift = 7 - rpng_x_msb(GMask); BShift = 7 - rpng_x_msb(BMask); #endif } if (depth >= 15 && (RShift < 0 || GShift < 0 || BShift < 0)) { fprintf(stderr, "rpng internal logic error: negative X shift(s)!\n"); return 2; } /*--------------------------------------------------------------------------- Finally, create the window. ---------------------------------------------------------------------------*/ attr.backing_store = Always; attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask; attrmask = CWBackingStore | CWEventMask; if (have_nondefault_visual) { attr.colormap = colormap; attr.background_pixel = 0; attr.border_pixel = 1; attrmask |= CWColormap | CWBackPixel | CWBorderPixel; } window = XCreateWindow(display, root, 0, 0, image_width, image_height, 0, depth, InputOutput, visual, attrmask, &attr); if (window == None) { fprintf(stderr, "XCreateWindow() failed\n"); return 2; } else have_window = TRUE; if (depth == 8) XSetWindowColormap(display, window, colormap); if (!XStringListToTextProperty(&window_name, 1, pWindowName)) pWindowName = NULL; if (!XStringListToTextProperty(&icon_name, 1, pIconName)) pIconName = NULL; /* OK if any hints allocation fails; XSetWMProperties() allows NULLs */ if ((size_hints = XAllocSizeHints()) != NULL) { /* window will not be resizable */ size_hints->flags = PMinSize | PMaxSize; size_hints->min_width = size_hints->max_width = (int)image_width; size_hints->min_height = size_hints->max_height = (int)image_height; } if ((wm_hints = XAllocWMHints()) != NULL) { wm_hints->initial_state = NormalState; wm_hints->input = True; /* wm_hints->icon_pixmap = icon_pixmap; */ wm_hints->flags = StateHint | InputHint /* | IconPixmapHint */ ; } if ((class_hints = XAllocClassHint()) != NULL) { class_hints->res_name = res_name; class_hints->res_class = res_class; } XSetWMProperties(display, window, pWindowName, pIconName, NULL, 0, size_hints, wm_hints, class_hints); /* various properties and hints no longer needed; free memory */ if (pWindowName) XFree(pWindowName->value); if (pIconName) XFree(pIconName->value); if (size_hints) XFree(size_hints); if (wm_hints) XFree(wm_hints); if (class_hints) XFree(class_hints); XMapWindow(display, window); gc = XCreateGC(display, window, 0, &gcvalues); have_gc = TRUE; /*--------------------------------------------------------------------------- Fill window with the specified background color. ---------------------------------------------------------------------------*/ if (depth == 24 || depth == 32) { bg_pixel = ((ulg)bg_red << RShift) | ((ulg)bg_green << GShift) | ((ulg)bg_blue << BShift); } else if (depth == 16) { bg_pixel = ((((ulg)bg_red << 8) >> RShift) & RMask) | ((((ulg)bg_green << 8) >> GShift) & GMask) | ((((ulg)bg_blue << 8) >> BShift) & BMask); } else /* depth == 8 */ { /* GRR: add 8-bit support */ } XSetForeground(display, gc, bg_pixel); XFillRectangle(display, window, gc, 0, 0, image_width, image_height); /*--------------------------------------------------------------------------- Wait for first Expose event to do any drawing, then flush. ---------------------------------------------------------------------------*/ do XNextEvent(display, &e); while (e.type != Expose || e.xexpose.count); XFlush(display); /*--------------------------------------------------------------------------- Allocate memory for the X- and display-specific version of the image. ---------------------------------------------------------------------------*/ if (depth == 24 || depth == 32) { xdata = (uch *)malloc(4*image_width*image_height); pad = 32; } else if (depth == 16) { xdata = (uch *)malloc(2*image_width*image_height); pad = 16; } else /* depth == 8 */ { xdata = (uch *)malloc(image_width*image_height); pad = 8; } if (!xdata) { fprintf(stderr, PROGNAME ": unable to allocate image memory\n"); return 4; } ximage = XCreateImage(display, visual, depth, ZPixmap, 0, (char *)xdata, image_width, image_height, pad, 0); if (!ximage) { fprintf(stderr, PROGNAME ": XCreateImage() failed\n"); free(xdata); return 3; } /* to avoid testing the byte order every pixel (or doubling the size of * the drawing routine with a giant if-test), we arbitrarily set the byte * order to MSBFirst and let Xlib worry about inverting things on little- * endian machines (like Linux/x86, old VAXen, etc.)--this is not the most * efficient approach (the giant if-test would be better), but in the * interest of clarity, we take the easy way out... */ ximage->byte_order = MSBFirst; return 0; } /* end function rpng_x_create_window() */ static int rpng_x_display_image(void) { uch *src; char *dest; uch r, g, b, a; ulg i, row, lastrow = 0; ulg pixel; int ximage_rowbytes = ximage->bytes_per_line; /* int bpp = ximage->bits_per_pixel; */ Trace((stderr, "beginning display loop (image_channels == %d)\n", image_channels)) Trace((stderr, " (width = %ld, rowbytes = %ld, ximage_rowbytes = %d)\n", image_width, image_rowbytes, ximage_rowbytes)) Trace((stderr, " (bpp = %d)\n", ximage->bits_per_pixel)) Trace((stderr, " (byte_order = %s)\n", ximage->byte_order == MSBFirst? "MSBFirst" : (ximage->byte_order == LSBFirst? "LSBFirst" : "unknown"))) if (depth == 24 || depth == 32) { ulg red, green, blue; for (lastrow = row = 0; row < image_height; ++row) { src = image_data + row*image_rowbytes; dest = ximage->data + row*ximage_rowbytes; if (image_channels == 3) { for (i = image_width; i > 0; --i) { red = *src++; green = *src++; blue = *src++; #ifdef NO_24BIT_MASKS pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ /* GRR BUG: this assumes bpp == 32, but may be 24: */ *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); #else red = (RShift < 0)? red << (-RShift) : red >> RShift; green = (GShift < 0)? green << (-GShift) : green >> GShift; blue = (BShift < 0)? blue << (-BShift) : blue >> BShift; pixel = (red & RMask) | (green & GMask) | (blue & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); #endif } } else /* if (image_channels == 4) */ { for (i = image_width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (a == 255) { red = r; green = g; blue = b; } else if (a == 0) { red = bg_red; green = bg_green; blue = bg_blue; } else { /* this macro (from png.h) composites the foreground * and background values and puts the result into the * first argument */ alpha_composite(red, r, a, bg_red); alpha_composite(green, g, a, bg_green); alpha_composite(blue, b, a, bg_blue); } pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } /* display after every 16 lines */ if (((row+1) & 0xf) == 0) { XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0, (int)lastrow, image_width, 16); XFlush(display); lastrow = row + 1; } } } else if (depth == 16) { ush red, green, blue; for (lastrow = row = 0; row < image_height; ++row) { src = image_data + row*image_rowbytes; dest = ximage->data + row*ximage_rowbytes; if (image_channels == 3) { for (i = image_width; i > 0; --i) { red = ((ush)(*src) << 8); ++src; green = ((ush)(*src) << 8); ++src; blue = ((ush)(*src) << 8); ++src; pixel = ((red >> RShift) & RMask) | ((green >> GShift) & GMask) | ((blue >> BShift) & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } else /* if (image_channels == 4) */ { for (i = image_width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (a == 255) { red = ((ush)r << 8); green = ((ush)g << 8); blue = ((ush)b << 8); } else if (a == 0) { red = ((ush)bg_red << 8); green = ((ush)bg_green << 8); blue = ((ush)bg_blue << 8); } else { /* this macro (from png.h) composites the foreground * and background values and puts the result back into * the first argument (== fg byte here: safe) */ alpha_composite(r, r, a, bg_red); alpha_composite(g, g, a, bg_green); alpha_composite(b, b, a, bg_blue); red = ((ush)r << 8); green = ((ush)g << 8); blue = ((ush)b << 8); } pixel = ((red >> RShift) & RMask) | ((green >> GShift) & GMask) | ((blue >> BShift) & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } /* display after every 16 lines */ if (((row+1) & 0xf) == 0) { XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0, (int)lastrow, image_width, 16); XFlush(display); lastrow = row + 1; } } } else /* depth == 8 */ { /* GRR: add 8-bit support */ } Trace((stderr, "calling final XPutImage()\n")) if (lastrow < image_height) { XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0, (int)lastrow, image_width, image_height-lastrow); XFlush(display); } return 0; } static void rpng_x_cleanup(void) { if (image_data) { free(image_data); image_data = NULL; } if (ximage) { if (ximage->data) { free(ximage->data); /* we allocated it, so we free it */ ximage->data = (char *)NULL; /* instead of XDestroyImage() */ } XDestroyImage(ximage); ximage = NULL; } if (have_gc) XFreeGC(display, gc); if (have_window) XDestroyWindow(display, window); if (have_colormap) XFreeColormap(display, colormap); if (have_nondefault_visual) XFree(visual_list); } static int rpng_x_msb(ulg u32val) { int i; for (i = 31; i >= 0; --i) { if (u32val & 0x80000000L) break; u32val <<= 1; } return i; } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/rpng2-win.c ================================================ /*--------------------------------------------------------------------------- rpng2 - progressive-model PNG display program rpng2-win.c This program decodes and displays PNG files progressively, as if it were a web browser (though the front end is only set up to read from files). It supports gamma correction, user-specified background colors, and user- specified background patterns (for transparent images). This version is for 32-bit Windows; it may compile under 16-bit Windows with a little tweaking (or maybe not). Thanks to Adam Costello and Pieter S. van der Meulen for the "diamond" and "radial waves" patterns, respectively. to do (someday, maybe): - handle quoted command-line args (especially filenames with spaces) - finish resizable checkerboard-gradient (sizes 4-128?) - use %.1023s to simplify truncation of title-bar string? - have minimum window width: oh well --------------------------------------------------------------------------- Changelog: - 1.01: initial public release - 1.02: fixed cut-and-paste error in usage screen (oops...) - 1.03: modified to allow abbreviated options - 1.04: removed bogus extra argument from usage fprintf() [Glenn R-P?]; fixed command-line parsing bug - 1.10: enabled "message window"/console (thanks to David Geldreich) - 1.20: added runtime MMX-enabling/disabling and new -mmx* options - 1.21: made minor tweak to usage screen to fit within 25-line console - 1.22: added AMD64/EM64T support (__x86_64__) - 2.00: dual-licensed (added GNU GPL) - 2.01: fixed 64-bit typo in readpng2.c - 2.02: fixed improper display of usage screen on PNG error(s); fixed unexpected-EOF and file-read-error cases - 2.03: removed runtime MMX-enabling/disabling and obsolete -mmx* options - 2.04: (GR-P) --------------------------------------------------------------------------- Copyright (c) 1998-2008 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #define PROGNAME "rpng2-win" #define LONGNAME "Progressive PNG Viewer for Windows" #define VERSION "2.02 of 16 March 2008" #include #include #include #include /* for jmpbuf declaration in readpng2.h */ #include #include /* only for PvdM background code */ #include #ifdef __CYGWIN__ /* getch replacement. Turns out, we don't really need this, * but leave it here if we ever enable any of the uses of * _getch in the main code */ #include #include #include int repl_getch( void ) { char ch; int fd = fileno(stdin); struct termio old_tty, new_tty; ioctl(fd, TCGETA, &old_tty); new_tty = old_tty; new_tty.c_lflag &= ~(ICANON | ECHO | ISIG); ioctl(fd, TCSETA, &new_tty); fread(&ch, 1, sizeof(ch), stdin); ioctl(fd, TCSETA, &old_tty); return ch; } #define _getch repl_getch #else #include /* only for _getch() */ #endif /* all for PvdM background code: */ #ifndef PI # define PI 3.141592653589793238 #endif #define PI_2 (PI*0.5) #define INV_PI_360 (360.0 / PI) #define MAX(a,b) (a>b?a:b) #define MIN(a,b) (a> 8)) >> 8); \ } #define INBUFSIZE 4096 /* with pseudo-timing on (1 sec delay/block), this * block size corresponds roughly to a download * speed 10% faster than theoretical 33.6K maximum * (assuming 8 data bits, 1 stop bit and no other * overhead) */ /* local prototypes */ static void rpng2_win_init(void); static int rpng2_win_create_window(void); static int rpng2_win_load_bg_image(void); static void rpng2_win_display_row(ulg row); static void rpng2_win_finish_display(void); static void rpng2_win_cleanup(void); LRESULT CALLBACK rpng2_win_wndproc(HWND, UINT, WPARAM, LPARAM); static char titlebar[1024]; static char *progname = PROGNAME; static char *appname = LONGNAME; static char *filename; static FILE *infile; static mainprog_info rpng2_info; static uch inbuf[INBUFSIZE]; static int incount; static int pat = 6; /* must be less than num_bgpat */ static int bg_image = 0; static int bgscale = 16; static ulg bg_rowbytes; static uch *bg_data; static struct rgb_color { uch r, g, b; } rgb[] = { { 0, 0, 0}, /* 0: black */ {255, 255, 255}, /* 1: white */ {173, 132, 57}, /* 2: tan */ { 64, 132, 0}, /* 3: medium green */ {189, 117, 1}, /* 4: gold */ {253, 249, 1}, /* 5: yellow */ { 0, 0, 255}, /* 6: blue */ { 0, 0, 120}, /* 7: medium blue */ {255, 0, 255}, /* 8: magenta */ { 64, 0, 64}, /* 9: dark magenta */ {255, 0, 0}, /* 10: red */ { 64, 0, 0}, /* 11: dark red */ {255, 127, 0}, /* 12: orange */ {192, 96, 0}, /* 13: darker orange */ { 24, 60, 0}, /* 14: dark green-yellow */ { 85, 125, 200} /* 15: ice blue */ }; /* not used for now, but should be for error-checking: static int num_rgb = sizeof(rgb) / sizeof(struct rgb_color); */ /* This whole struct is a fairly cheesy way to keep the number of command-line options to a minimum. The radial-waves background type is a particularly poor fit to the integer elements of the struct...but a few macros and a little fixed-point math will do wonders for ya. type bits: F E D C B A 9 8 7 6 5 4 3 2 1 0 | | | | | | | +-+-+-- 0 = sharp-edged checkerboard | | 1 = soft diamonds | | 2 = radial waves | | 3-7 = undefined | +-- gradient #2 inverted? +-- alternating columns inverted? */ static struct background_pattern { ush type; int rgb1_max, rgb1_min; /* or bg_freq, bg_gray */ int rgb2_max, rgb2_min; /* or bg_bsat, bg_brot (both scaled by 10)*/ } bg[] = { {0+8, 2,0, 1,15}, /* checkered: tan/black vs. white/ice blue */ {0+24, 2,0, 1,0}, /* checkered: tan/black vs. white/black */ {0+8, 4,5, 0,2}, /* checkered: gold/yellow vs. black/tan */ {0+8, 4,5, 0,6}, /* checkered: gold/yellow vs. black/blue */ {0, 7,0, 8,9}, /* checkered: deep blue/black vs. magenta */ {0+8, 13,0, 5,14}, /* checkered: orange/black vs. yellow */ {0+8, 12,0, 10,11}, /* checkered: orange/black vs. red */ {1, 7,0, 8,0}, /* diamonds: deep blue/black vs. magenta */ {1, 12,0, 11,0}, /* diamonds: orange vs. dark red */ {1, 10,0, 7,0}, /* diamonds: red vs. medium blue */ {1, 4,0, 5,0}, /* diamonds: gold vs. yellow */ {1, 3,0, 0,0}, /* diamonds: medium green vs. black */ {2, 16, 100, 20, 0}, /* radial: ~hard radial color-beams */ {2, 18, 100, 10, 2}, /* radial: soft, curved radial color-beams */ {2, 16, 256, 100, 250}, /* radial: very tight spiral */ {2, 10000, 256, 11, 0} /* radial: dipole-moire' (almost fractal) */ }; static int num_bgpat = sizeof(bg) / sizeof(struct background_pattern); /* Windows-specific global variables (could go in struct, but messy...) */ static ulg wimage_rowbytes; static uch *dib; static uch *wimage_data; static BITMAPINFOHEADER *bmih; static HWND global_hwnd; static HINSTANCE global_hInst; static int global_showmode; int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, PSTR cmd, int showmode) { char *args[1024]; /* arbitrary limit, but should suffice */ char **argv = args; char *p, *q, *bgstr = NULL; int argc = 0; int rc, alen, flen; int error = 0; int timing = FALSE; int have_bg = FALSE; double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ MSG msg; /* First initialize a few things, just to be sure--memset takes care of * default background color (black), booleans (FALSE), pointers (NULL), * etc. */ global_hInst = hInst; global_showmode = showmode; filename = (char *)NULL; memset(&rpng2_info, 0, sizeof(mainprog_info)); #ifndef __CYGWIN__ /* Next reenable console output, which normally goes to the bit bucket * for windowed apps. Closing the console window will terminate the * app. Thanks to David.Geldreich@realviz.com for supplying the magical * incantation. */ AllocConsole(); freopen("CONOUT$", "a", stderr); freopen("CONOUT$", "a", stdout); #endif /* Set the default value for our display-system exponent, i.e., the * product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. And * yes, these ifdefs are completely wasted in a Windows program... */ #if defined(NeXT) /* third-party utilities can modify the default LUT exponent */ LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to * get the "gamma" value, so we do it the hard way */ infile = fopen("/etc/config/system.glGammaVal", "r"); if (infile) { double sgi_gamma; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) rpng2_info.display_exponent = atof(p); else rpng2_info.display_exponent = default_display_exponent; /* Windows really hates command lines, so we have to set up our own argv. * Note that we do NOT bother with quoted arguments here, so don't use * filenames with spaces in 'em! */ argv[argc++] = PROGNAME; p = cmd; for (;;) { if (*p == ' ') while (*++p == ' ') ; /* now p points at the first non-space after some spaces */ if (*p == '\0') break; /* nothing after the spaces: done */ argv[argc++] = q = p; while (*q && *q != ' ') ++q; /* now q points at a space or the end of the string */ if (*q == '\0') break; /* last argv already terminated; quit */ *q = '\0'; /* change space to terminator */ p = q + 1; } argv[argc] = NULL; /* terminate the argv array itself */ /* Now parse the command line for options and the PNG filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { rpng2_info.display_exponent = atof(*argv); if (rpng2_info.display_exponent <= 0.0) ++error; } } else if (!strncmp(*argv, "-bgcolor", 4)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else { have_bg = TRUE; bg_image = FALSE; } } } else if (!strncmp(*argv, "-bgpat", 4)) { if (!*++argv) ++error; else { pat = atoi(*argv) - 1; if (pat < 0 || pat >= num_bgpat) ++error; else { bg_image = TRUE; have_bg = FALSE; } } } else if (!strncmp(*argv, "-timing", 2)) { timing = TRUE; } else { if (**argv != '-') { filename = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } if (!filename) ++error; /* print usage screen if any errors up to this point */ if (error) { #ifndef __CYGWIN__ int ch; #endif fprintf(stderr, "\n%s %s: %s\n\n", PROGNAME, VERSION, appname); readpng2_version_info(); fprintf(stderr, "\n" "Usage: %s [-gamma exp] [-bgcolor bg | -bgpat pat] [-timing]\n" " %*s file.png\n\n" " exp \ttransfer-function exponent (``gamma'') of the display\n" "\t\t system in floating-point format (e.g., ``%.1f''); equal\n" "\t\t to the product of the lookup-table exponent (varies)\n" "\t\t and the CRT exponent (usually 2.2); must be positive\n" " bg \tdesired background color in 7-character hex RGB format\n" "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n" "\t\t used with transparent images; overrides -bgpat option\n" " pat \tdesired background pattern number (1-%d); used with\n" "\t\t transparent images; overrides -bgcolor option\n" " -timing\tenables delay for every block read, to simulate modem\n" "\t\t download of image (~36 Kbps)\n" "\nPress Q, Esc or mouse button 1 after image is displayed to quit.\n" #ifndef __CYGWIN__ "Press Q or Esc to quit this usage screen. ", #else , #endif PROGNAME, #if (defined(__i386__) || defined(_M_IX86) || defined(__x86_64__)) && \ !(defined(__CYGWIN__) || defined(__MINGW32__)) (int)strlen(PROGNAME), " ", #endif (int)strlen(PROGNAME), " ", default_display_exponent, num_bgpat); fflush(stderr); #ifndef __CYGWIN__ do ch = _getch(); while (ch != 'q' && ch != 'Q' && ch != 0x1B); #endif exit(1); } if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename); ++error; } else { incount = fread(inbuf, 1, INBUFSIZE, infile); if (incount < 8 || !readpng2_check_sig(inbuf, 8)) { fprintf(stderr, PROGNAME ": [%s] is not a PNG file: incorrect signature\n", filename); ++error; } else if ((rc = readpng2_init(&rpng2_info)) != 0) { switch (rc) { case 2: fprintf(stderr, PROGNAME ": [%s] has bad IHDR (libpng longjmp)\n", filename); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; default: fprintf(stderr, PROGNAME ": unknown readpng2_init() error\n"); break; } ++error; } if (error) fclose(infile); } if (error) { #ifndef __CYGWIN__ int ch; #endif fprintf(stderr, PROGNAME ": aborting.\n"); #ifndef __CYGWIN__ do ch = _getch(); while (ch != 'q' && ch != 'Q' && ch != 0x1B); #endif exit(2); } else { fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, appname); #ifndef __CYGWIN__ fprintf(stderr, "\n [console window: closing this window will terminate %s]\n\n", PROGNAME); #endif fflush(stderr); } /* set the title-bar string, but make sure buffer doesn't overflow */ alen = strlen(appname); flen = strlen(filename); if (alen + flen + 3 > 1023) sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023)); else sprintf(titlebar, "%s: %s", appname, filename); /* set some final rpng2_info variables before entering main data loop */ if (have_bg) { unsigned r, g, b; /* this approach quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); rpng2_info.bg_red = (uch)r; rpng2_info.bg_green = (uch)g; rpng2_info.bg_blue = (uch)b; } else rpng2_info.need_bgcolor = TRUE; rpng2_info.state = kPreInit; rpng2_info.mainprog_init = rpng2_win_init; rpng2_info.mainprog_display_row = rpng2_win_display_row; rpng2_info.mainprog_finish_display = rpng2_win_finish_display; /* OK, this is the fun part: call readpng2_decode_data() at the start of * the loop to deal with our first buffer of data (read in above to verify * that the file is a PNG image), then loop through the file and continue * calling the same routine to handle each chunk of data. It in turn * passes the data to libpng, which will invoke one or more of our call- * backs as decoded data become available. We optionally call Sleep() for * one second per iteration to simulate downloading the image via an analog * modem. */ for (;;) { Trace((stderr, "about to call readpng2_decode_data()\n")) if (readpng2_decode_data(&rpng2_info, inbuf, incount)) ++error; Trace((stderr, "done with readpng2_decode_data()\n")) if (error || incount != INBUFSIZE || rpng2_info.state == kDone) { if (rpng2_info.state == kDone) { Trace((stderr, "done decoding PNG image\n")) } else if (ferror(infile)) { fprintf(stderr, PROGNAME ": error while reading PNG image file\n"); exit(3); } else if (feof(infile)) { fprintf(stderr, PROGNAME ": end of file reached " "(unexpectedly) while reading PNG image file\n"); exit(3); } else /* if (error) */ { /* will print error message below */ } break; } if (timing) Sleep(1000L); incount = fread(inbuf, 1, INBUFSIZE, infile); } /* clean up PNG stuff and report any decoding errors */ fclose(infile); Trace((stderr, "about to call readpng2_cleanup()\n")) readpng2_cleanup(&rpng2_info); if (error) { fprintf(stderr, PROGNAME ": libpng error while decoding PNG image\n"); exit(3); } /* wait for the user to tell us when to quit */ while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } /* we're done: clean up all image and Windows resources and go away */ Trace((stderr, "about to call rpng2_win_cleanup()\n")) rpng2_win_cleanup(); return msg.wParam; } /* this function is called by readpng2_info_callback() in readpng2.c, which * in turn is called by libpng after all of the pre-IDAT chunks have been * read and processed--i.e., we now have enough info to finish initializing */ static void rpng2_win_init() { ulg i; ulg rowbytes = rpng2_info.rowbytes; Trace((stderr, "beginning rpng2_win_init()\n")) Trace((stderr, " rowbytes = %d\n", rpng2_info.rowbytes)) Trace((stderr, " width = %ld\n", rpng2_info.width)) Trace((stderr, " height = %ld\n", rpng2_info.height)) rpng2_info.image_data = (uch *)malloc(rowbytes * rpng2_info.height); if (!rpng2_info.image_data) { readpng2_cleanup(&rpng2_info); return; } rpng2_info.row_pointers = (uch **)malloc(rpng2_info.height * sizeof(uch *)); if (!rpng2_info.row_pointers) { free(rpng2_info.image_data); rpng2_info.image_data = NULL; readpng2_cleanup(&rpng2_info); return; } for (i = 0; i < rpng2_info.height; ++i) rpng2_info.row_pointers[i] = rpng2_info.image_data + i*rowbytes; /*--------------------------------------------------------------------------- Do the basic Windows initialization stuff, make the window, and fill it with the user-specified, file-specified or default background color. ---------------------------------------------------------------------------*/ if (rpng2_win_create_window()) { readpng2_cleanup(&rpng2_info); return; } rpng2_info.state = kWindowInit; } static int rpng2_win_create_window() { uch bg_red = rpng2_info.bg_red; uch bg_green = rpng2_info.bg_green; uch bg_blue = rpng2_info.bg_blue; uch *dest; int extra_width, extra_height; ulg i, j; WNDCLASSEX wndclass; RECT rect; /*--------------------------------------------------------------------------- Allocate memory for the display-specific version of the image (round up to multiple of 4 for Windows DIB). ---------------------------------------------------------------------------*/ wimage_rowbytes = ((3*rpng2_info.width + 3L) >> 2) << 2; if (!(dib = (uch *)malloc(sizeof(BITMAPINFOHEADER) + wimage_rowbytes*rpng2_info.height))) { return 4; /* fail */ } /*--------------------------------------------------------------------------- Initialize the DIB. Negative height means to use top-down BMP ordering (must be uncompressed, but that's what we want). Bit count of 1, 4 or 8 implies a colormap of RGBX quads, but 24-bit BMPs just use B,G,R values directly => wimage_data begins immediately after BMP header. ---------------------------------------------------------------------------*/ memset(dib, 0, sizeof(BITMAPINFOHEADER)); bmih = (BITMAPINFOHEADER *)dib; bmih->biSize = sizeof(BITMAPINFOHEADER); bmih->biWidth = rpng2_info.width; bmih->biHeight = -((long)rpng2_info.height); bmih->biPlanes = 1; bmih->biBitCount = 24; bmih->biCompression = 0; wimage_data = dib + sizeof(BITMAPINFOHEADER); /*--------------------------------------------------------------------------- Fill window with the specified background color (default is black), but defer loading faked "background image" until window is displayed (may be slow to compute). Data are in BGR order. ---------------------------------------------------------------------------*/ if (bg_image) { /* just fill with black for now */ memset(wimage_data, 0, wimage_rowbytes*rpng2_info.height); } else { for (j = 0; j < rpng2_info.height; ++j) { dest = wimage_data + j*wimage_rowbytes; for (i = rpng2_info.width; i > 0; --i) { *dest++ = bg_blue; *dest++ = bg_green; *dest++ = bg_red; } } } /*--------------------------------------------------------------------------- Set the window parameters. ---------------------------------------------------------------------------*/ memset(&wndclass, 0, sizeof(wndclass)); wndclass.cbSize = sizeof(wndclass); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = rpng2_win_wndproc; wndclass.hInstance = global_hInst; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = progname; wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); RegisterClassEx(&wndclass); /*--------------------------------------------------------------------------- Finally, create the window. ---------------------------------------------------------------------------*/ extra_width = 2*(GetSystemMetrics(SM_CXBORDER) + GetSystemMetrics(SM_CXDLGFRAME)); extra_height = 2*(GetSystemMetrics(SM_CYBORDER) + GetSystemMetrics(SM_CYDLGFRAME)) + GetSystemMetrics(SM_CYCAPTION); global_hwnd = CreateWindow(progname, titlebar, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rpng2_info.width+extra_width, rpng2_info.height+extra_height, NULL, NULL, global_hInst, NULL); ShowWindow(global_hwnd, global_showmode); UpdateWindow(global_hwnd); /*--------------------------------------------------------------------------- Now compute the background image and display it. If it fails (memory allocation), revert to a plain background color. ---------------------------------------------------------------------------*/ if (bg_image) { static const char *msg = "Computing background image..."; int x, y, len = strlen(msg); HDC hdc = GetDC(global_hwnd); TEXTMETRIC tm; GetTextMetrics(hdc, &tm); x = (rpng2_info.width - len*tm.tmAveCharWidth)/2; y = (rpng2_info.height - tm.tmHeight)/2; SetBkMode(hdc, TRANSPARENT); SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT)); /* this can still begin out of bounds even if x is positive (???): */ TextOut(hdc, ((x < 0)? 0 : x), ((y < 0)? 0 : y), msg, len); ReleaseDC(global_hwnd, hdc); rpng2_win_load_bg_image(); /* resets bg_image if fails */ } if (!bg_image) { for (j = 0; j < rpng2_info.height; ++j) { dest = wimage_data + j*wimage_rowbytes; for (i = rpng2_info.width; i > 0; --i) { *dest++ = bg_blue; *dest++ = bg_green; *dest++ = bg_red; } } } rect.left = 0L; rect.top = 0L; rect.right = (LONG)rpng2_info.width; /* possibly off by one? */ rect.bottom = (LONG)rpng2_info.height; /* possibly off by one? */ InvalidateRect(global_hwnd, &rect, FALSE); UpdateWindow(global_hwnd); /* similar to XFlush() */ return 0; } /* end function rpng2_win_create_window() */ static int rpng2_win_load_bg_image() { uch *src, *dest; uch r1, r2, g1, g2, b1, b2; uch r1_inv, r2_inv, g1_inv, g2_inv, b1_inv, b2_inv; int k, hmax, max; int xidx, yidx, yidx_max = (bgscale-1); int even_odd_vert, even_odd_horiz, even_odd; int invert_gradient2 = (bg[pat].type & 0x08); int invert_column; ulg i, row; /*--------------------------------------------------------------------------- Allocate buffer for fake background image to be used with transparent images; if this fails, revert to plain background color. ---------------------------------------------------------------------------*/ bg_rowbytes = 3 * rpng2_info.width; bg_data = (uch *)malloc(bg_rowbytes * rpng2_info.height); if (!bg_data) { fprintf(stderr, PROGNAME ": unable to allocate memory for background image\n"); bg_image = 0; return 1; } /*--------------------------------------------------------------------------- Vertical gradients (ramps) in NxN squares, alternating direction and colors (N == bgscale). ---------------------------------------------------------------------------*/ if ((bg[pat].type & 0x07) == 0) { uch r1_min = rgb[bg[pat].rgb1_min].r; uch g1_min = rgb[bg[pat].rgb1_min].g; uch b1_min = rgb[bg[pat].rgb1_min].b; uch r2_min = rgb[bg[pat].rgb2_min].r; uch g2_min = rgb[bg[pat].rgb2_min].g; uch b2_min = rgb[bg[pat].rgb2_min].b; int r1_diff = rgb[bg[pat].rgb1_max].r - r1_min; int g1_diff = rgb[bg[pat].rgb1_max].g - g1_min; int b1_diff = rgb[bg[pat].rgb1_max].b - b1_min; int r2_diff = rgb[bg[pat].rgb2_max].r - r2_min; int g2_diff = rgb[bg[pat].rgb2_max].g - g2_min; int b2_diff = rgb[bg[pat].rgb2_max].b - b2_min; for (row = 0; row < rpng2_info.height; ++row) { yidx = row % bgscale; even_odd_vert = (row / bgscale) & 1; r1 = r1_min + (r1_diff * yidx) / yidx_max; g1 = g1_min + (g1_diff * yidx) / yidx_max; b1 = b1_min + (b1_diff * yidx) / yidx_max; r1_inv = r1_min + (r1_diff * (yidx_max-yidx)) / yidx_max; g1_inv = g1_min + (g1_diff * (yidx_max-yidx)) / yidx_max; b1_inv = b1_min + (b1_diff * (yidx_max-yidx)) / yidx_max; r2 = r2_min + (r2_diff * yidx) / yidx_max; g2 = g2_min + (g2_diff * yidx) / yidx_max; b2 = b2_min + (b2_diff * yidx) / yidx_max; r2_inv = r2_min + (r2_diff * (yidx_max-yidx)) / yidx_max; g2_inv = g2_min + (g2_diff * (yidx_max-yidx)) / yidx_max; b2_inv = b2_min + (b2_diff * (yidx_max-yidx)) / yidx_max; dest = bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { even_odd_horiz = (i / bgscale) & 1; even_odd = even_odd_vert ^ even_odd_horiz; invert_column = (even_odd_horiz && (bg[pat].type & 0x10)); if (even_odd == 0) { /* gradient #1 */ if (invert_column) { *dest++ = r1_inv; *dest++ = g1_inv; *dest++ = b1_inv; } else { *dest++ = r1; *dest++ = g1; *dest++ = b1; } } else { /* gradient #2 */ if ((invert_column && invert_gradient2) || (!invert_column && !invert_gradient2)) { *dest++ = r2; /* not inverted or */ *dest++ = g2; /* doubly inverted */ *dest++ = b2; } else { *dest++ = r2_inv; *dest++ = g2_inv; /* singly inverted */ *dest++ = b2_inv; } } } } /*--------------------------------------------------------------------------- Soft gradient-diamonds with scale = bgscale. Code contributed by Adam M. Costello. ---------------------------------------------------------------------------*/ } else if ((bg[pat].type & 0x07) == 1) { hmax = (bgscale-1)/2; /* half the max weight of a color */ max = 2*hmax; /* the max weight of a color */ r1 = rgb[bg[pat].rgb1_max].r; g1 = rgb[bg[pat].rgb1_max].g; b1 = rgb[bg[pat].rgb1_max].b; r2 = rgb[bg[pat].rgb2_max].r; g2 = rgb[bg[pat].rgb2_max].g; b2 = rgb[bg[pat].rgb2_max].b; for (row = 0; row < rpng2_info.height; ++row) { yidx = row % bgscale; if (yidx > hmax) yidx = bgscale-1 - yidx; dest = bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { xidx = i % bgscale; if (xidx > hmax) xidx = bgscale-1 - xidx; k = xidx + yidx; *dest++ = (k*r1 + (max-k)*r2) / max; *dest++ = (k*g1 + (max-k)*g2) / max; *dest++ = (k*b1 + (max-k)*b2) / max; } } /*--------------------------------------------------------------------------- Radial "starburst" with azimuthal sinusoids; [eventually number of sinu- soids will equal bgscale?]. This one is slow but very cool. Code con- tributed by Pieter S. van der Meulen (originally in Smalltalk). ---------------------------------------------------------------------------*/ } else if ((bg[pat].type & 0x07) == 2) { uch ch; int ii, x, y, hw, hh, grayspot; double freq, rotate, saturate, gray, intensity; double angle=0.0, aoffset=0.0, maxDist, dist; double red=0.0, green=0.0, blue=0.0, hue, s, v, f, p, q, t; fprintf(stderr, "%s: computing radial background...", PROGNAME); fflush(stderr); hh = rpng2_info.height / 2; hw = rpng2_info.width / 2; /* variables for radial waves: * aoffset: number of degrees to rotate hue [CURRENTLY NOT USED] * freq: number of color beams originating from the center * grayspot: size of the graying center area (anti-alias) * rotate: rotation of the beams as a function of radius * saturate: saturation of beams' shape azimuthally */ angle = CLIP(angle, 0.0, 360.0); grayspot = CLIP(bg[pat].bg_gray, 1, (hh + hw)); freq = MAX((double)bg[pat].bg_freq, 0.0); saturate = (double)bg[pat].bg_bsat * 0.1; rotate = (double)bg[pat].bg_brot * 0.1; gray = 0.0; intensity = 0.0; maxDist = (double)((hw*hw) + (hh*hh)); for (row = 0; row < rpng2_info.height; ++row) { y = row - hh; dest = bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { x = i - hw; angle = (x == 0)? PI_2 : atan((double)y / (double)x); gray = (double)MAX(ABS(y), ABS(x)) / grayspot; gray = MIN(1.0, gray); dist = (double)((x*x) + (y*y)) / maxDist; intensity = cos((angle+(rotate*dist*PI)) * freq) * gray * saturate; intensity = (MAX(MIN(intensity,1.0),-1.0) + 1.0) * 0.5; hue = (angle + PI) * INV_PI_360 + aoffset; s = gray * ((double)(ABS(x)+ABS(y)) / (double)(hw + hh)); s = MIN(MAX(s,0.0), 1.0); v = MIN(MAX(intensity,0.0), 1.0); if (s == 0.0) { ch = (uch)(v * 255.0); *dest++ = ch; *dest++ = ch; *dest++ = ch; } else { if ((hue < 0.0) || (hue >= 360.0)) hue -= (((int)(hue / 360.0)) * 360.0); hue /= 60.0; ii = (int)hue; f = hue - (double)ii; p = (1.0 - s) * v; q = (1.0 - (s * f)) * v; t = (1.0 - (s * (1.0 - f))) * v; if (ii == 0) { red = v; green = t; blue = p; } else if (ii == 1) { red = q; green = v; blue = p; } else if (ii == 2) { red = p; green = v; blue = t; } else if (ii == 3) { red = p; green = q; blue = v; } else if (ii == 4) { red = t; green = p; blue = v; } else if (ii == 5) { red = v; green = p; blue = q; } *dest++ = (uch)(red * 255.0); *dest++ = (uch)(green * 255.0); *dest++ = (uch)(blue * 255.0); } } } fprintf(stderr, "done.\n"); fflush(stderr); } /*--------------------------------------------------------------------------- Blast background image to display buffer before beginning PNG decode; calling function will handle invalidation and UpdateWindow() call. ---------------------------------------------------------------------------*/ for (row = 0; row < rpng2_info.height; ++row) { src = bg_data + row*bg_rowbytes; dest = wimage_data + row*wimage_rowbytes; for (i = rpng2_info.width; i > 0; --i) { r1 = *src++; g1 = *src++; b1 = *src++; *dest++ = b1; *dest++ = g1; /* note reverse order */ *dest++ = r1; } } return 0; } /* end function rpng2_win_load_bg_image() */ static void rpng2_win_display_row(ulg row) { uch bg_red = rpng2_info.bg_red; uch bg_green = rpng2_info.bg_green; uch bg_blue = rpng2_info.bg_blue; uch *src, *src2=NULL, *dest; uch r, g, b, a; ulg i; static int rows=0; static ulg firstrow; /*--------------------------------------------------------------------------- rows and firstrow simply track how many rows (and which ones) have not yet been displayed; alternatively, we could call InvalidateRect() for every row and not bother with the records-keeping. ---------------------------------------------------------------------------*/ Trace((stderr, "beginning rpng2_win_display_row()\n")) if (rows == 0) firstrow = row; /* first row not yet displayed */ ++rows; /* count of rows received but not yet displayed */ /*--------------------------------------------------------------------------- Aside from the use of the rpng2_info struct and the lack of an outer loop (over rows), this routine is identical to rpng_win_display_image() in the non-progressive version of the program. ---------------------------------------------------------------------------*/ src = rpng2_info.image_data + row*rpng2_info.rowbytes; if (bg_image) src2 = bg_data + row*bg_rowbytes; dest = wimage_data + row*wimage_rowbytes; if (rpng2_info.channels == 3) { for (i = rpng2_info.width; i > 0; --i) { r = *src++; g = *src++; b = *src++; *dest++ = b; *dest++ = g; /* note reverse order */ *dest++ = r; } } else /* if (rpng2_info.channels == 4) */ { for (i = rpng2_info.width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (bg_image) { bg_red = *src2++; bg_green = *src2++; bg_blue = *src2++; } if (a == 255) { *dest++ = b; *dest++ = g; *dest++ = r; } else if (a == 0) { *dest++ = bg_blue; *dest++ = bg_green; *dest++ = bg_red; } else { /* this macro (copied from png.h) composites the * foreground and background values and puts the * result into the first argument; there are no * side effects with the first argument */ alpha_composite(*dest++, b, a, bg_blue); alpha_composite(*dest++, g, a, bg_green); alpha_composite(*dest++, r, a, bg_red); } } } /*--------------------------------------------------------------------------- Display after every 16 rows or when on last row. (Region may include previously displayed lines due to interlacing--i.e., not contiguous.) ---------------------------------------------------------------------------*/ if ((rows & 0xf) == 0 || row == rpng2_info.height-1) { RECT rect; rect.left = 0L; rect.top = (LONG)firstrow; rect.right = (LONG)rpng2_info.width; /* possibly off by one? */ rect.bottom = (LONG)row + 1L; /* possibly off by one? */ InvalidateRect(global_hwnd, &rect, FALSE); UpdateWindow(global_hwnd); /* similar to XFlush() */ rows = 0; } } /* end function rpng2_win_display_row() */ static void rpng2_win_finish_display() { Trace((stderr, "beginning rpng2_win_finish_display()\n")) /* last row has already been displayed by rpng2_win_display_row(), so * we have nothing to do here except set a flag and let the user know * that the image is done */ rpng2_info.state = kDone; printf( #ifndef __CYGWIN__ "Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n" #else "Done. Press mouse button 1 (within image window) to quit.\n" #endif ); fflush(stdout); } static void rpng2_win_cleanup() { if (bg_image && bg_data) { free(bg_data); bg_data = NULL; } if (rpng2_info.image_data) { free(rpng2_info.image_data); rpng2_info.image_data = NULL; } if (rpng2_info.row_pointers) { free(rpng2_info.row_pointers); rpng2_info.row_pointers = NULL; } if (dib) { free(dib); dib = NULL; } } LRESULT CALLBACK rpng2_win_wndproc(HWND hwnd, UINT iMsg, WPARAM wP, LPARAM lP) { HDC hdc; PAINTSTRUCT ps; int rc; switch (iMsg) { case WM_CREATE: /* one-time processing here, if any */ return 0; case WM_PAINT: hdc = BeginPaint(hwnd, &ps); rc = StretchDIBits(hdc, 0, 0, rpng2_info.width, rpng2_info.height, 0, 0, rpng2_info.width, rpng2_info.height, wimage_data, (BITMAPINFO *)bmih, 0, SRCCOPY); EndPaint(hwnd, &ps); return 0; /* wait for the user to tell us when to quit */ case WM_CHAR: switch (wP) { /* only need one, so ignore repeat count */ case 'q': case 'Q': case 0x1B: /* Esc key */ PostQuitMessage(0); } return 0; case WM_LBUTTONDOWN: /* another way of quitting */ case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, iMsg, wP, lP); } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/rpng2-x.c ================================================ /*--------------------------------------------------------------------------- rpng2 - progressive-model PNG display program rpng2-x.c This program decodes and displays PNG files progressively, as if it were a web browser (though the front end is only set up to read from files). It supports gamma correction, user-specified background colors, and user- specified background patterns (for transparent images). This version is for the X Window System (tested by the author under Unix and by Martin Zinser under OpenVMS; may work under OS/2 with a little tweaking). Thanks to Adam Costello and Pieter S. van der Meulen for the "diamond" and "radial waves" patterns, respectively. to do (someday, maybe): - fix expose/redraw code: don't draw entire row if only part exposed - 8-bit (colormapped) X support - finish resizable checkerboard-gradient (sizes 4-128?) - use %.1023s to simplify truncation of title-bar string? --------------------------------------------------------------------------- Changelog: - 1.01: initial public release - 1.02: modified to allow abbreviated options; fixed char/uchar mismatch - 1.10: added support for non-default visuals; fixed X pixel-conversion - 1.11: added -usleep option for demos; fixed command-line parsing bug - 1.12: added -pause option for demos and testing - 1.20: added runtime MMX-enabling/disabling and new -mmx* options - 1.21: fixed some small X memory leaks (thanks to Franois Petitjean) - 1.22: fixed XFreeGC() crash bug (thanks to Patrick Welche) - 1.23: added -bgpat 0 mode (std white/gray checkerboard, 8x8 squares) - 1.30: added -loop option for -bgpat (ifdef FEATURE_LOOP); fixed bpp = 24; added support for X resources (thanks to Gerhard Niklasch) - 1.31: added code to skip unused chunks (thanks to Glenn Randers-Pehrson) - 1.32: added AMD64/EM64T support (__x86_64__); added basic expose/redraw handling - 2.00: dual-licensed (added GNU GPL) - 2.01: fixed 64-bit typo in readpng2.c; fixed -pause usage description - 2.02: fixed improper display of usage screen on PNG error(s); fixed unexpected-EOF and file-read-error cases; fixed Trace() cut-and- paste bugs - 2.03: deleted runtime MMX-enabling/disabling and obsolete -mmx* options - 2.04: Added "void(foo);" statements to quiet pedantic compiler warnings about unused variables (GR-P) - 2.05: Use nanosleep() instead of usleep(), which is deprecated (GR-P). --------------------------------------------------------------------------- Copyright (c) 1998-2010, 2014-2015 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #define PROGNAME "rpng2-x" #define LONGNAME "Progressive PNG Viewer for X" #define VERSION "2.04 of 15 June 2014" #define RESNAME "rpng2" /* our X resource application name */ #define RESCLASS "Rpng" /* our X resource class name */ #include #include #include #include #include /* for jmpbuf declaration in readpng2.h */ #include #include /* only for PvdM background code */ #include #include #include #include /* defines XK_* macros */ #if _POSIX_C_SOURCE >= 199309L /* have nanosleep() */ # undef usleep # define usleep(usec) { \ struct timespec ts; \ ts.tv_sec = 0; \ ts.tv_nsec = (usec) * 1000; \ nanosleep(&ts, NULL); } # endif #ifndef usleep /* have neither nanosleep() nor usleep() */ # define usleep(x) sleep(((x)+499999)/1000000) #endif #ifdef VMS # include #endif /* all for PvdM background code: */ #ifndef PI # define PI 3.141592653589793238 #endif #define PI_2 (PI*0.5) #define INV_PI_360 (360.0 / PI) #define MAX(a,b) (a>b?a:b) #define MIN(a,b) (a> 8)) >> 8); \ } #define INBUFSIZE 4096 /* with pseudo-timing on (1 sec delay/block), this * block size corresponds roughly to a download * speed 10% faster than theoretical 33.6K maximum * (assuming 8 data bits, 1 stop bit and no other * overhead) */ /* local prototypes */ static void rpng2_x_init (void); static int rpng2_x_create_window (void); static int rpng2_x_load_bg_image (void); static void rpng2_x_display_row (ulg row); static void rpng2_x_finish_display (void); static void rpng2_x_redisplay_image (ulg startcol, ulg startrow, ulg width, ulg height); #ifdef FEATURE_LOOP static void rpng2_x_reload_bg_image (void); static int is_number (char *p); #endif static void rpng2_x_cleanup (void); static int rpng2_x_msb (ulg u32val); static char titlebar[1024], *window_name = titlebar; static char *appname = LONGNAME; static char *icon_name = PROGNAME; static char *res_name = RESNAME; static char *res_class = RESCLASS; static char *filename; static FILE *infile; static mainprog_info rpng2_info; static uch inbuf[INBUFSIZE]; static int incount; static int pat = 6; /* must be less than num_bgpat */ static int bg_image = 0; static int bgscale, bgscale_default = 16; static ulg bg_rowbytes; static uch *bg_data; int pause_after_pass = FALSE; int demo_timing = FALSE; ulg usleep_duration = 0L; static struct rgb_color { uch r, g, b; } rgb[] = { { 0, 0, 0}, /* 0: black */ {255, 255, 255}, /* 1: white */ {173, 132, 57}, /* 2: tan */ { 64, 132, 0}, /* 3: medium green */ {189, 117, 1}, /* 4: gold */ {253, 249, 1}, /* 5: yellow */ { 0, 0, 255}, /* 6: blue */ { 0, 0, 120}, /* 7: medium blue */ {255, 0, 255}, /* 8: magenta */ { 64, 0, 64}, /* 9: dark magenta */ {255, 0, 0}, /* 10: red */ { 64, 0, 0}, /* 11: dark red */ {255, 127, 0}, /* 12: orange */ {192, 96, 0}, /* 13: darker orange */ { 24, 60, 0}, /* 14: dark green-yellow */ { 85, 125, 200}, /* 15: ice blue */ {192, 192, 192} /* 16: Netscape/Mosaic gray */ }; /* not used for now, but should be for error-checking: static int num_rgb = sizeof(rgb) / sizeof(struct rgb_color); */ /* This whole struct is a fairly cheesy way to keep the number of command-line options to a minimum. The radial-waves background type is a particularly poor fit to the integer elements of the struct...but a few macros and a little fixed-point math will do wonders for ya. type bits: F E D C B A 9 8 7 6 5 4 3 2 1 0 | | | | | | | +-+-+-- 0 = sharp-edged checkerboard | | 1 = soft diamonds | | 2 = radial waves | | 3-7 = undefined | +-- gradient #2 inverted? +-- alternating columns inverted? */ static struct background_pattern { ush type; int rgb1_max, rgb1_min; /* or bg_freq, bg_gray */ int rgb2_max, rgb2_min; /* or bg_bsat, bg_brot (both scaled by 10)*/ } bg[] = { {0, 1,1, 16,16}, /* checkered: white vs. light gray (basic) */ {0+8, 2,0, 1,15}, /* checkered: tan/black vs. white/ice blue */ {0+24, 2,0, 1,0}, /* checkered: tan/black vs. white/black */ {0+8, 4,5, 0,2}, /* checkered: gold/yellow vs. black/tan */ {0+8, 4,5, 0,6}, /* checkered: gold/yellow vs. black/blue */ {0, 7,0, 8,9}, /* checkered: deep blue/black vs. magenta */ {0+8, 13,0, 5,14}, /* checkered: orange/black vs. yellow */ {0+8, 12,0, 10,11}, /* checkered: orange/black vs. red */ {1, 7,0, 8,0}, /* diamonds: deep blue/black vs. magenta */ {1, 12,0, 11,0}, /* diamonds: orange vs. dark red */ {1, 10,0, 7,0}, /* diamonds: red vs. medium blue */ {1, 4,0, 5,0}, /* diamonds: gold vs. yellow */ {1, 3,0, 0,0}, /* diamonds: medium green vs. black */ {2, 16, 100, 20, 0}, /* radial: ~hard radial color-beams */ {2, 18, 100, 10, 2}, /* radial: soft, curved radial color-beams */ {2, 16, 256, 100, 250}, /* radial: very tight spiral */ {2, 10000, 256, 11, 0} /* radial: dipole-moire' (almost fractal) */ }; static int num_bgpat = sizeof(bg) / sizeof(struct background_pattern); /* X-specific variables */ static char *displayname; static XImage *ximage; static Display *display; static int depth; static Visual *visual; static XVisualInfo *visual_list; static int RShift, GShift, BShift; static ulg RMask, GMask, BMask; static Window window; static GC gc; static Colormap colormap; static int have_nondefault_visual = FALSE; static int have_colormap = FALSE; static int have_window = FALSE; static int have_gc = FALSE; int main(int argc, char **argv) { #ifdef sgi char tmpline[80]; #endif char *p, *bgstr = NULL; int rc, alen, flen; int error = 0; int timing = FALSE; int have_bg = FALSE; #ifdef FEATURE_LOOP int loop = FALSE; long loop_interval = -1; /* seconds (100,000 max) */ #endif double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ XEvent e; KeySym k; /* First initialize a few things, just to be sure--memset takes care of * default background color (black), booleans (FALSE), pointers (NULL), * etc. */ displayname = (char *)NULL; filename = (char *)NULL; memset(&rpng2_info, 0, sizeof(mainprog_info)); /* Set the default value for our display-system exponent, i.e., the * product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. This is not an * exhaustive list of LUT values (e.g., OpenStep has a lot of weird * ones), but it should cover 99% of the current possibilities. */ #if defined(NeXT) /* third-party utilities can modify the default LUT exponent */ LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to * get the "gamma" value, so we do it the hard way */ infile = fopen("/etc/config/system.glGammaVal", "r"); if (infile) { double sgi_gamma; fgets(tmpline, 80, infile); fclose(infile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) rpng2_info.display_exponent = atof(p); else rpng2_info.display_exponent = default_display_exponent; /* Now parse the command line for options and the PNG filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-display", 2)) { if (!*++argv) ++error; else displayname = *argv; } else if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { rpng2_info.display_exponent = atof(*argv); if (rpng2_info.display_exponent <= 0.0) ++error; } } else if (!strncmp(*argv, "-bgcolor", 4)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else { have_bg = TRUE; bg_image = FALSE; } } } else if (!strncmp(*argv, "-bgpat", 4)) { if (!*++argv) ++error; else { pat = atoi(*argv); if (pat >= 0 && pat < num_bgpat) { bg_image = TRUE; have_bg = FALSE; } else ++error; } } else if (!strncmp(*argv, "-usleep", 2)) { if (!*++argv) ++error; else { usleep_duration = (ulg)atol(*argv); demo_timing = TRUE; } } else if (!strncmp(*argv, "-pause", 2)) { pause_after_pass = TRUE; } else if (!strncmp(*argv, "-timing", 2)) { timing = TRUE; #ifdef FEATURE_LOOP } else if (!strncmp(*argv, "-loop", 2)) { loop = TRUE; if (!argv[1] || !is_number(argv[1])) loop_interval = 2; else { ++argv; loop_interval = atol(*argv); if (loop_interval < 0) loop_interval = 2; else if (loop_interval > 100000) /* bit more than one day */ loop_interval = 100000; } #endif } else { if (**argv != '-') { filename = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } if (!filename) ++error; /* print usage screen if any errors up to this point */ if (error) { fprintf(stderr, "\n%s %s: %s\n\n", PROGNAME, VERSION, appname); readpng2_version_info(); fprintf(stderr, "\n" "Usage: "); fprintf(stderr, "%s [-display xdpy] [-gamma exp] [-bgcolor bg | -bgpat pat]\n" " %*s [-usleep dur | -timing] [-pause]\n", PROGNAME, (int)strlen(PROGNAME), " "); fprintf(stderr, #ifdef FEATURE_LOOP " [-loop [sec]]" #endif " file.png\n\n"); fprintf(stderr, " xdpy\tname of the target X display (e.g., ``hostname:0'')\n" " exp \ttransfer-function exponent (``gamma'') of the display\n" "\t\t system in floating-point format (e.g., ``%.1f''); equal\n" "\t\t to the product of the lookup-table exponent (varies)\n", default_display_exponent); fprintf(stderr, "\t\t and the CRT exponent (usually 2.2); must be positive\n" " bg \tdesired background color in 7-character hex RGB format\n" "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n" "\t\t used with transparent images; overrides -bgpat\n" " pat \tdesired background pattern number (0-%d); used with\n" "\t\t transparent images; overrides -bgcolor\n", num_bgpat-1); #ifdef FEATURE_LOOP fprintf(stderr, " -loop\tloops through background images after initial display\n" "\t\t is complete (depends on -bgpat)\n" " sec \tseconds to display each background image (default = 2)\n"); #endif fprintf(stderr, " dur \tduration in microseconds to wait after displaying each\n" "\t\t row (for demo purposes)\n" " -timing\tenables delay for every block read, to simulate modem\n" "\t\t download of image (~36 Kbps)\n" " -pause\tpauses after displaying each pass until mouse clicked\n" "\nPress Q, Esc or mouse button 1 (within image window, after image\n" "is displayed) to quit.\n"); exit(1); } if (!(infile = fopen(filename, "rb"))) { fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename); ++error; } else { incount = fread(inbuf, 1, INBUFSIZE, infile); if (incount < 8 || !readpng2_check_sig(inbuf, 8)) { fprintf(stderr, PROGNAME ": [%s] is not a PNG file: incorrect signature\n", filename); ++error; } else if ((rc = readpng2_init(&rpng2_info)) != 0) { switch (rc) { case 2: fprintf(stderr, PROGNAME ": [%s] has bad IHDR (libpng longjmp)\n", filename); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; default: fprintf(stderr, PROGNAME ": unknown readpng2_init() error\n"); break; } ++error; } else { Trace((stderr, "about to call XOpenDisplay()\n")) display = XOpenDisplay(displayname); if (!display) { readpng2_cleanup(&rpng2_info); fprintf(stderr, PROGNAME ": can't open X display [%s]\n", displayname? displayname : "default"); ++error; } } if (error) fclose(infile); } if (error) { fprintf(stderr, PROGNAME ": aborting.\n"); exit(2); } /* set the title-bar string, but make sure buffer doesn't overflow */ alen = strlen(appname); flen = strlen(filename); if (alen + flen + 3 > 1023) sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023)); else sprintf(titlebar, "%s: %s", appname, filename); /* set some final rpng2_info variables before entering main data loop */ if (have_bg) { unsigned r, g, b; /* this approach quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); rpng2_info.bg_red = (uch)r; rpng2_info.bg_green = (uch)g; rpng2_info.bg_blue = (uch)b; } else rpng2_info.need_bgcolor = TRUE; rpng2_info.state = kPreInit; rpng2_info.mainprog_init = rpng2_x_init; rpng2_info.mainprog_display_row = rpng2_x_display_row; rpng2_info.mainprog_finish_display = rpng2_x_finish_display; /* OK, this is the fun part: call readpng2_decode_data() at the start of * the loop to deal with our first buffer of data (read in above to verify * that the file is a PNG image), then loop through the file and continue * calling the same routine to handle each chunk of data. It in turn * passes the data to libpng, which will invoke one or more of our call- * backs as decoded data become available. We optionally call sleep() for * one second per iteration to simulate downloading the image via an analog * modem. */ for (;;) { Trace((stderr, "about to call readpng2_decode_data()\n")) if (readpng2_decode_data(&rpng2_info, inbuf, incount)) ++error; Trace((stderr, "done with readpng2_decode_data()\n")) if (error || incount != INBUFSIZE || rpng2_info.state == kDone) { if (rpng2_info.state == kDone) { Trace((stderr, "done decoding PNG image\n")) } else if (ferror(infile)) { fprintf(stderr, PROGNAME ": error while reading PNG image file\n"); exit(3); } else if (feof(infile)) { fprintf(stderr, PROGNAME ": end of file reached " "(unexpectedly) while reading PNG image file\n"); exit(3); } else /* if (error) */ { /* will print error message below */ } break; } if (timing) sleep(1); incount = fread(inbuf, 1, INBUFSIZE, infile); } /* clean up PNG stuff and report any decoding errors */ fclose(infile); Trace((stderr, "about to call readpng2_cleanup()\n")) readpng2_cleanup(&rpng2_info); if (error) { fprintf(stderr, PROGNAME ": libpng error while decoding PNG image\n"); exit(3); } #ifdef FEATURE_LOOP if (loop && bg_image) { Trace((stderr, "entering -loop loop (FEATURE_LOOP)\n")) for (;;) { int i, use_sleep; struct timeval now, then; /* get current time and add loop_interval to get target time */ if (gettimeofday(&then, NULL) == 0) { then.tv_sec += loop_interval; use_sleep = FALSE; } else use_sleep = TRUE; /* do quick check for a quit event but don't wait for it */ /* GRR BUG: should also check for Expose events and redraw... */ if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e)) if (QUIT(e,k)) break; /* generate next background image */ if (++pat >= num_bgpat) pat = 0; rpng2_x_reload_bg_image(); /* wait for timeout, using whatever means are available */ if (use_sleep || gettimeofday(&now, NULL) != 0) { for (i = loop_interval; i > 0; --i) { sleep(1); /* GRR BUG: also need to check for Expose (and redraw!) */ if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e) && QUIT(e,k)) break; } } else { /* Y2038 BUG! */ if (now.tv_sec < then.tv_sec || (now.tv_sec == then.tv_sec && now.tv_usec < then.tv_usec)) { int quit = FALSE; long seconds_to_go = then.tv_sec - now.tv_sec; long usleep_usec; /* basically chew up most of remaining loop-interval with * calls to sleep(1) interleaved with checks for quit * events, but also recalc time-to-go periodically; when * done, clean up any remaining time with usleep() call * (could also use SIGALRM, but signals are a pain...) */ while (seconds_to_go-- > 1) { int seconds_done = 0; for (i = seconds_to_go; i > 0 && !quit; --i) { sleep(1); /* GRR BUG: need to check for Expose and redraw */ if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e) && QUIT(e,k)) quit = TRUE; if (++seconds_done > 1000) break; /* time to redo seconds_to_go meas. */ } if (quit) break; /* OK, more than 1000 seconds since last check: * correct the time-to-go measurement for drift */ if (gettimeofday(&now, NULL) == 0) { if (now.tv_sec >= then.tv_sec) break; seconds_to_go = then.tv_sec - now.tv_sec; } else ++seconds_to_go; /* restore what we subtracted */ } if (quit) break; /* breaks outer do-loop, skips redisplay */ /* since difference between "now" and "then" is already * eaten up to within a couple of seconds, don't need to * worry about overflow--but might have overshot (neg.) */ if (gettimeofday(&now, NULL) == 0) { usleep_usec = 1000000L*(then.tv_sec - now.tv_sec) + then.tv_usec - now.tv_usec; if (usleep_usec > 0) usleep((ulg)usleep_usec); } } } /* composite image against new background and display (note that * we do not take into account the time spent doing this...) */ rpng2_x_redisplay_image (0, 0, rpng2_info.width, rpng2_info.height); } } else /* FALL THROUGH and do the normal thing */ #endif /* FEATURE_LOOP */ /* wait for the user to tell us when to quit */ if (rpng2_info.state >= kWindowInit) { Trace((stderr, "entering final wait-for-quit-event loop\n")) do { XNextEvent(display, &e); if (e.type == Expose) { XExposeEvent *ex = (XExposeEvent *)&e; rpng2_x_redisplay_image (ex->x, ex->y, ex->width, ex->height); } } while (!QUIT(e,k)); } else { fprintf(stderr, PROGNAME ": init callback never called: probable " "libpng error while decoding PNG metadata\n"); exit(4); } /* we're done: clean up all image and X resources and go away */ Trace((stderr, "about to call rpng2_x_cleanup()\n")) rpng2_x_cleanup(); (void)argc; /* Unused */ return 0; } /* this function is called by readpng2_info_callback() in readpng2.c, which * in turn is called by libpng after all of the pre-IDAT chunks have been * read and processed--i.e., we now have enough info to finish initializing */ static void rpng2_x_init(void) { ulg i; ulg rowbytes = rpng2_info.rowbytes; Trace((stderr, "beginning rpng2_x_init()\n")) Trace((stderr, " rowbytes = %d\n", rpng2_info.rowbytes)) Trace((stderr, " width = %ld\n", rpng2_info.width)) Trace((stderr, " height = %ld\n", rpng2_info.height)) rpng2_info.image_data = (uch *)malloc(rowbytes * rpng2_info.height); if (!rpng2_info.image_data) { readpng2_cleanup(&rpng2_info); return; } rpng2_info.row_pointers = (uch **)malloc(rpng2_info.height * sizeof(uch *)); if (!rpng2_info.row_pointers) { free(rpng2_info.image_data); rpng2_info.image_data = NULL; readpng2_cleanup(&rpng2_info); return; } for (i = 0; i < rpng2_info.height; ++i) rpng2_info.row_pointers[i] = rpng2_info.image_data + i*rowbytes; /* do the basic X initialization stuff, make the window, and fill it with * the user-specified, file-specified or default background color or * pattern */ if (rpng2_x_create_window()) { /* GRR TEMPORARY HACK: this is fundamentally no different from cases * above; libpng should call our error handler to longjmp() back to us * when png_ptr goes away. If we/it segfault instead, seems like a * libpng bug... */ /* we're here via libpng callback, so if window fails, clean and bail */ readpng2_cleanup(&rpng2_info); rpng2_x_cleanup(); exit(2); } rpng2_info.state = kWindowInit; } static int rpng2_x_create_window(void) { ulg bg_red = rpng2_info.bg_red; ulg bg_green = rpng2_info.bg_green; ulg bg_blue = rpng2_info.bg_blue; ulg bg_pixel = 0L; ulg attrmask; int need_colormap = FALSE; int screen, pad; uch *xdata; Window root; XEvent e; XGCValues gcvalues; XSetWindowAttributes attr; XTextProperty windowName, *pWindowName = &windowName; XTextProperty iconName, *pIconName = &iconName; XVisualInfo visual_info; XSizeHints *size_hints; XWMHints *wm_hints; XClassHint *class_hints; Trace((stderr, "beginning rpng2_x_create_window()\n")) screen = DefaultScreen(display); depth = DisplayPlanes(display, screen); root = RootWindow(display, screen); #ifdef DEBUG XSynchronize(display, True); #endif if (depth != 16 && depth != 24 && depth != 32) { int visuals_matched = 0; Trace((stderr, "default depth is %d: checking other visuals\n", depth)) /* 24-bit first */ visual_info.screen = screen; visual_info.depth = 24; visual_list = XGetVisualInfo(display, VisualScreenMask | VisualDepthMask, &visual_info, &visuals_matched); if (visuals_matched == 0) { /* GRR: add 15-, 16- and 32-bit TrueColor visuals (also DirectColor?) */ fprintf(stderr, "default screen depth %d not supported, and no" " 24-bit visuals found\n", depth); return 2; } Trace((stderr, "XGetVisualInfo() returned %d 24-bit visuals\n", visuals_matched)) visual = visual_list[0].visual; depth = visual_list[0].depth; /* colormap_size = visual_list[0].colormap_size; visual_class = visual->class; visualID = XVisualIDFromVisual(visual); */ have_nondefault_visual = TRUE; need_colormap = TRUE; } else { XMatchVisualInfo(display, screen, depth, TrueColor, &visual_info); visual = visual_info.visual; } RMask = visual->red_mask; GMask = visual->green_mask; BMask = visual->blue_mask; /* GRR: add/check 8-bit support */ if (depth == 8 || need_colormap) { colormap = XCreateColormap(display, root, visual, AllocNone); if (!colormap) { fprintf(stderr, "XCreateColormap() failed\n"); return 2; } have_colormap = TRUE; if (depth == 8) bg_image = FALSE; /* gradient just wastes palette entries */ } if (depth == 15 || depth == 16) { RShift = 15 - rpng2_x_msb(RMask); /* these are right-shifts */ GShift = 15 - rpng2_x_msb(GMask); BShift = 15 - rpng2_x_msb(BMask); } else if (depth > 16) { RShift = rpng2_x_msb(RMask) - 7; /* these are left-shifts */ GShift = rpng2_x_msb(GMask) - 7; BShift = rpng2_x_msb(BMask) - 7; } if (depth >= 15 && (RShift < 0 || GShift < 0 || BShift < 0)) { fprintf(stderr, "rpng2 internal logic error: negative X shift(s)!\n"); return 2; } /*--------------------------------------------------------------------------- Finally, create the window. ---------------------------------------------------------------------------*/ attr.backing_store = Always; attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask; attrmask = CWBackingStore | CWEventMask; if (have_nondefault_visual) { attr.colormap = colormap; attr.background_pixel = 0; attr.border_pixel = 1; attrmask |= CWColormap | CWBackPixel | CWBorderPixel; } window = XCreateWindow(display, root, 0, 0, rpng2_info.width, rpng2_info.height, 0, depth, InputOutput, visual, attrmask, &attr); if (window == None) { fprintf(stderr, "XCreateWindow() failed\n"); return 2; } else have_window = TRUE; if (depth == 8) XSetWindowColormap(display, window, colormap); if (!XStringListToTextProperty(&window_name, 1, pWindowName)) pWindowName = NULL; if (!XStringListToTextProperty(&icon_name, 1, pIconName)) pIconName = NULL; /* OK if either hints allocation fails; XSetWMProperties() allows NULLs */ if ((size_hints = XAllocSizeHints()) != NULL) { /* window will not be resizable */ size_hints->flags = PMinSize | PMaxSize; size_hints->min_width = size_hints->max_width = (int)rpng2_info.width; size_hints->min_height = size_hints->max_height = (int)rpng2_info.height; } if ((wm_hints = XAllocWMHints()) != NULL) { wm_hints->initial_state = NormalState; wm_hints->input = True; /* wm_hints->icon_pixmap = icon_pixmap; */ wm_hints->flags = StateHint | InputHint /* | IconPixmapHint */ ; } if ((class_hints = XAllocClassHint()) != NULL) { class_hints->res_name = res_name; class_hints->res_class = res_class; } XSetWMProperties(display, window, pWindowName, pIconName, NULL, 0, size_hints, wm_hints, class_hints); /* various properties and hints no longer needed; free memory */ if (pWindowName) XFree(pWindowName->value); if (pIconName) XFree(pIconName->value); if (size_hints) XFree(size_hints); if (wm_hints) XFree(wm_hints); if (class_hints) XFree(class_hints); XMapWindow(display, window); gc = XCreateGC(display, window, 0, &gcvalues); have_gc = TRUE; /*--------------------------------------------------------------------------- Allocate memory for the X- and display-specific version of the image. ---------------------------------------------------------------------------*/ if (depth == 24 || depth == 32) { xdata = (uch *)malloc(4*rpng2_info.width*rpng2_info.height); pad = 32; } else if (depth == 16) { xdata = (uch *)malloc(2*rpng2_info.width*rpng2_info.height); pad = 16; } else /* depth == 8 */ { xdata = (uch *)malloc(rpng2_info.width*rpng2_info.height); pad = 8; } if (!xdata) { fprintf(stderr, PROGNAME ": unable to allocate image memory\n"); return 4; } ximage = XCreateImage(display, visual, depth, ZPixmap, 0, (char *)xdata, rpng2_info.width, rpng2_info.height, pad, 0); if (!ximage) { fprintf(stderr, PROGNAME ": XCreateImage() failed\n"); free(xdata); return 3; } /* to avoid testing the byte order every pixel (or doubling the size of * the drawing routine with a giant if-test), we arbitrarily set the byte * order to MSBFirst and let Xlib worry about inverting things on little- * endian machines (e.g., Linux/x86, old VAXen, etc.)--this is not the * most efficient approach (the giant if-test would be better), but in * the interest of clarity, we'll take the easy way out... */ ximage->byte_order = MSBFirst; /*--------------------------------------------------------------------------- Fill window with the specified background color (default is black) or faked "background image" (but latter is disabled if 8-bit; gradients just waste palette entries). ---------------------------------------------------------------------------*/ if (bg_image) rpng2_x_load_bg_image(); /* resets bg_image if fails */ if (!bg_image) { if (depth == 24 || depth == 32) { bg_pixel = (bg_red << RShift) | (bg_green << GShift) | (bg_blue << BShift); } else if (depth == 16) { bg_pixel = (((bg_red << 8) >> RShift) & RMask) | (((bg_green << 8) >> GShift) & GMask) | (((bg_blue << 8) >> BShift) & BMask); } else /* depth == 8 */ { /* GRR: add 8-bit support */ } XSetForeground(display, gc, bg_pixel); XFillRectangle(display, window, gc, 0, 0, rpng2_info.width, rpng2_info.height); } /*--------------------------------------------------------------------------- Wait for first Expose event to do any drawing, then flush and return. ---------------------------------------------------------------------------*/ do XNextEvent(display, &e); while (e.type != Expose || e.xexpose.count); XFlush(display); return 0; } /* end function rpng2_x_create_window() */ static int rpng2_x_load_bg_image(void) { uch *src; char *dest; uch r1, r2, g1, g2, b1, b2; uch r1_inv, r2_inv, g1_inv, g2_inv, b1_inv, b2_inv; int k, hmax, max; int xidx, yidx, yidx_max; int even_odd_vert, even_odd_horiz, even_odd; int invert_gradient2 = (bg[pat].type & 0x08); int invert_column; int ximage_rowbytes = ximage->bytes_per_line; ulg i, row; ulg pixel; /*--------------------------------------------------------------------------- Allocate buffer for fake background image to be used with transparent images; if this fails, revert to plain background color. ---------------------------------------------------------------------------*/ bg_rowbytes = 3 * rpng2_info.width; bg_data = (uch *)malloc(bg_rowbytes * rpng2_info.height); if (!bg_data) { fprintf(stderr, PROGNAME ": unable to allocate memory for background image\n"); bg_image = 0; return 1; } bgscale = (pat == 0)? 8 : bgscale_default; yidx_max = bgscale - 1; /*--------------------------------------------------------------------------- Vertical gradients (ramps) in NxN squares, alternating direction and colors (N == bgscale). ---------------------------------------------------------------------------*/ if ((bg[pat].type & 0x07) == 0) { uch r1_min = rgb[bg[pat].rgb1_min].r; uch g1_min = rgb[bg[pat].rgb1_min].g; uch b1_min = rgb[bg[pat].rgb1_min].b; uch r2_min = rgb[bg[pat].rgb2_min].r; uch g2_min = rgb[bg[pat].rgb2_min].g; uch b2_min = rgb[bg[pat].rgb2_min].b; int r1_diff = rgb[bg[pat].rgb1_max].r - r1_min; int g1_diff = rgb[bg[pat].rgb1_max].g - g1_min; int b1_diff = rgb[bg[pat].rgb1_max].b - b1_min; int r2_diff = rgb[bg[pat].rgb2_max].r - r2_min; int g2_diff = rgb[bg[pat].rgb2_max].g - g2_min; int b2_diff = rgb[bg[pat].rgb2_max].b - b2_min; for (row = 0; row < rpng2_info.height; ++row) { yidx = (int)(row % bgscale); even_odd_vert = (int)((row / bgscale) & 1); r1 = r1_min + (r1_diff * yidx) / yidx_max; g1 = g1_min + (g1_diff * yidx) / yidx_max; b1 = b1_min + (b1_diff * yidx) / yidx_max; r1_inv = r1_min + (r1_diff * (yidx_max-yidx)) / yidx_max; g1_inv = g1_min + (g1_diff * (yidx_max-yidx)) / yidx_max; b1_inv = b1_min + (b1_diff * (yidx_max-yidx)) / yidx_max; r2 = r2_min + (r2_diff * yidx) / yidx_max; g2 = g2_min + (g2_diff * yidx) / yidx_max; b2 = b2_min + (b2_diff * yidx) / yidx_max; r2_inv = r2_min + (r2_diff * (yidx_max-yidx)) / yidx_max; g2_inv = g2_min + (g2_diff * (yidx_max-yidx)) / yidx_max; b2_inv = b2_min + (b2_diff * (yidx_max-yidx)) / yidx_max; dest = (char *)bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { even_odd_horiz = (int)((i / bgscale) & 1); even_odd = even_odd_vert ^ even_odd_horiz; invert_column = (even_odd_horiz && (bg[pat].type & 0x10)); if (even_odd == 0) { /* gradient #1 */ if (invert_column) { *dest++ = r1_inv; *dest++ = g1_inv; *dest++ = b1_inv; } else { *dest++ = r1; *dest++ = g1; *dest++ = b1; } } else { /* gradient #2 */ if ((invert_column && invert_gradient2) || (!invert_column && !invert_gradient2)) { *dest++ = r2; /* not inverted or */ *dest++ = g2; /* doubly inverted */ *dest++ = b2; } else { *dest++ = r2_inv; *dest++ = g2_inv; /* singly inverted */ *dest++ = b2_inv; } } } } /*--------------------------------------------------------------------------- Soft gradient-diamonds with scale = bgscale. Code contributed by Adam M. Costello. ---------------------------------------------------------------------------*/ } else if ((bg[pat].type & 0x07) == 1) { hmax = (bgscale-1)/2; /* half the max weight of a color */ max = 2*hmax; /* the max weight of a color */ r1 = rgb[bg[pat].rgb1_max].r; g1 = rgb[bg[pat].rgb1_max].g; b1 = rgb[bg[pat].rgb1_max].b; r2 = rgb[bg[pat].rgb2_max].r; g2 = rgb[bg[pat].rgb2_max].g; b2 = rgb[bg[pat].rgb2_max].b; for (row = 0; row < rpng2_info.height; ++row) { yidx = (int)(row % bgscale); if (yidx > hmax) yidx = bgscale-1 - yidx; dest = (char *)bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { xidx = (int)(i % bgscale); if (xidx > hmax) xidx = bgscale-1 - xidx; k = xidx + yidx; *dest++ = (k*r1 + (max-k)*r2) / max; *dest++ = (k*g1 + (max-k)*g2) / max; *dest++ = (k*b1 + (max-k)*b2) / max; } } /*--------------------------------------------------------------------------- Radial "starburst" with azimuthal sinusoids; [eventually number of sinu- soids will equal bgscale?]. This one is slow but very cool. Code con- tributed by Pieter S. van der Meulen (originally in Smalltalk). ---------------------------------------------------------------------------*/ } else if ((bg[pat].type & 0x07) == 2) { uch ch; int ii, x, y, hw, hh, grayspot; double freq, rotate, saturate, gray, intensity; double angle=0.0, aoffset=0.0, maxDist, dist; double red=0.0, green=0.0, blue=0.0, hue, s, v, f, p, q, t; fprintf(stderr, "%s: computing radial background...", PROGNAME); fflush(stderr); hh = (int)(rpng2_info.height / 2); hw = (int)(rpng2_info.width / 2); /* variables for radial waves: * aoffset: number of degrees to rotate hue [CURRENTLY NOT USED] * freq: number of color beams originating from the center * grayspot: size of the graying center area (anti-alias) * rotate: rotation of the beams as a function of radius * saturate: saturation of beams' shape azimuthally */ angle = CLIP(angle, 0.0, 360.0); grayspot = CLIP(bg[pat].bg_gray, 1, (hh + hw)); freq = MAX((double)bg[pat].bg_freq, 0.0); saturate = (double)bg[pat].bg_bsat * 0.1; rotate = (double)bg[pat].bg_brot * 0.1; gray = 0.0; intensity = 0.0; maxDist = (double)((hw*hw) + (hh*hh)); for (row = 0; row < rpng2_info.height; ++row) { y = (int)(row - hh); dest = (char *)bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { x = (int)(i - hw); angle = (x == 0)? PI_2 : atan((double)y / (double)x); gray = (double)MAX(ABS(y), ABS(x)) / grayspot; gray = MIN(1.0, gray); dist = (double)((x*x) + (y*y)) / maxDist; intensity = cos((angle+(rotate*dist*PI)) * freq) * gray * saturate; intensity = (MAX(MIN(intensity,1.0),-1.0) + 1.0) * 0.5; hue = (angle + PI) * INV_PI_360 + aoffset; s = gray * ((double)(ABS(x)+ABS(y)) / (double)(hw + hh)); s = MIN(MAX(s,0.0), 1.0); v = MIN(MAX(intensity,0.0), 1.0); if (s == 0.0) { ch = (uch)(v * 255.0); *dest++ = ch; *dest++ = ch; *dest++ = ch; } else { if ((hue < 0.0) || (hue >= 360.0)) hue -= (((int)(hue / 360.0)) * 360.0); hue /= 60.0; ii = (int)hue; f = hue - (double)ii; p = (1.0 - s) * v; q = (1.0 - (s * f)) * v; t = (1.0 - (s * (1.0 - f))) * v; if (ii == 0) { red = v; green = t; blue = p; } else if (ii == 1) { red = q; green = v; blue = p; } else if (ii == 2) { red = p; green = v; blue = t; } else if (ii == 3) { red = p; green = q; blue = v; } else if (ii == 4) { red = t; green = p; blue = v; } else if (ii == 5) { red = v; green = p; blue = q; } *dest++ = (uch)(red * 255.0); *dest++ = (uch)(green * 255.0); *dest++ = (uch)(blue * 255.0); } } } fprintf(stderr, "done.\n"); fflush(stderr); } /*--------------------------------------------------------------------------- Blast background image to display buffer before beginning PNG decode. ---------------------------------------------------------------------------*/ if (depth == 24 || depth == 32) { ulg red, green, blue; int bpp = ximage->bits_per_pixel; for (row = 0; row < rpng2_info.height; ++row) { src = bg_data + row*bg_rowbytes; dest = ximage->data + row*ximage_rowbytes; if (bpp == 32) { /* slightly optimized version */ for (i = rpng2_info.width; i > 0; --i) { red = *src++; green = *src++; blue = *src++; pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } else { for (i = rpng2_info.width; i > 0; --i) { red = *src++; green = *src++; blue = *src++; pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ /* GRR BUG? this assumes bpp == 24 & bits are packed low */ /* (probably need to use RShift, RMask, etc.) */ *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } } } else if (depth == 16) { ush red, green, blue; for (row = 0; row < rpng2_info.height; ++row) { src = bg_data + row*bg_rowbytes; dest = ximage->data + row*ximage_rowbytes; for (i = rpng2_info.width; i > 0; --i) { red = ((ush)(*src) << 8); ++src; green = ((ush)(*src) << 8); ++src; blue = ((ush)(*src) << 8); ++src; pixel = ((red >> RShift) & RMask) | ((green >> GShift) & GMask) | ((blue >> BShift) & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } } else /* depth == 8 */ { /* GRR: add 8-bit support */ } XPutImage(display, window, gc, ximage, 0, 0, 0, 0, rpng2_info.width, rpng2_info.height); return 0; } /* end function rpng2_x_load_bg_image() */ static void rpng2_x_display_row(ulg row) { uch bg_red = rpng2_info.bg_red; uch bg_green = rpng2_info.bg_green; uch bg_blue = rpng2_info.bg_blue; uch *src, *src2=NULL; char *dest; uch r, g, b, a; int ximage_rowbytes = ximage->bytes_per_line; ulg i, pixel; static int rows=0, prevpass=(-1); static ulg firstrow; /*--------------------------------------------------------------------------- rows and firstrow simply track how many rows (and which ones) have not yet been displayed; alternatively, we could call XPutImage() for every row and not bother with the records-keeping. ---------------------------------------------------------------------------*/ Trace((stderr, "beginning rpng2_x_display_row()\n")) if (rpng2_info.pass != prevpass) { if (pause_after_pass && rpng2_info.pass > 0) { XEvent e; KeySym k; fprintf(stderr, "%s: end of pass %d of 7; click in image window to continue\n", PROGNAME, prevpass + 1); do XNextEvent(display, &e); while (!QUIT(e,k)); } fprintf(stderr, "%s: pass %d of 7\r", PROGNAME, rpng2_info.pass + 1); fflush(stderr); prevpass = rpng2_info.pass; } if (rows == 0) firstrow = row; /* first row that is not yet displayed */ ++rows; /* count of rows received but not yet displayed */ /*--------------------------------------------------------------------------- Aside from the use of the rpng2_info struct, the lack of an outer loop (over rows) and moving the XPutImage() call outside the "if (depth)" tests, this routine is identical to rpng_x_display_image() in the non- progressive version of the program. ---------------------------------------------------------------------------*/ if (depth == 24 || depth == 32) { ulg red, green, blue; int bpp = ximage->bits_per_pixel; src = rpng2_info.image_data + row*rpng2_info.rowbytes; if (bg_image) src2 = bg_data + row*bg_rowbytes; dest = ximage->data + row*ximage_rowbytes; if (rpng2_info.channels == 3) { for (i = rpng2_info.width; i > 0; --i) { red = *src++; green = *src++; blue = *src++; pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ if (bpp == 32) { *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } else { /* GRR BUG? this assumes bpp == 24 & bits are packed low */ /* (probably need to use RShift, RMask, etc.) */ *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } } else /* if (rpng2_info.channels == 4) */ { for (i = rpng2_info.width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (bg_image) { bg_red = *src2++; bg_green = *src2++; bg_blue = *src2++; } if (a == 255) { red = r; green = g; blue = b; } else if (a == 0) { red = bg_red; green = bg_green; blue = bg_blue; } else { /* this macro (from png.h) composites the foreground * and background values and puts the result into the * first argument */ alpha_composite(red, r, a, bg_red); alpha_composite(green, g, a, bg_green); alpha_composite(blue, b, a, bg_blue); } pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ if (bpp == 32) { *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } else { /* GRR BUG? this assumes bpp == 24 & bits are packed low */ /* (probably need to use RShift, RMask, etc.) */ *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } } } else if (depth == 16) { ush red, green, blue; src = rpng2_info.row_pointers[row]; if (bg_image) src2 = bg_data + row*bg_rowbytes; dest = ximage->data + row*ximage_rowbytes; if (rpng2_info.channels == 3) { for (i = rpng2_info.width; i > 0; --i) { red = ((ush)(*src) << 8); ++src; green = ((ush)(*src) << 8); ++src; blue = ((ush)(*src) << 8); ++src; pixel = ((red >> RShift) & RMask) | ((green >> GShift) & GMask) | ((blue >> BShift) & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } else /* if (rpng2_info.channels == 4) */ { for (i = rpng2_info.width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (bg_image) { bg_red = *src2++; bg_green = *src2++; bg_blue = *src2++; } if (a == 255) { red = ((ush)r << 8); green = ((ush)g << 8); blue = ((ush)b << 8); } else if (a == 0) { red = ((ush)bg_red << 8); green = ((ush)bg_green << 8); blue = ((ush)bg_blue << 8); } else { /* this macro (from png.h) composites the foreground * and background values and puts the result back into * the first argument (== fg byte here: safe) */ alpha_composite(r, r, a, bg_red); alpha_composite(g, g, a, bg_green); alpha_composite(b, b, a, bg_blue); red = ((ush)r << 8); green = ((ush)g << 8); blue = ((ush)b << 8); } pixel = ((red >> RShift) & RMask) | ((green >> GShift) & GMask) | ((blue >> BShift) & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } } else /* depth == 8 */ { /* GRR: add 8-bit support */ } /*--------------------------------------------------------------------------- Display after every 16 rows or when on one of last two rows. (Region may include previously displayed lines due to interlacing--i.e., not contiguous. Also, second-to-last row is final one in interlaced images with odd number of rows.) For demos, flush (and delay) after every 16th row so "sparse" passes don't go twice as fast. ---------------------------------------------------------------------------*/ if (demo_timing && (row - firstrow >= 16 || row >= rpng2_info.height-2)) { XPutImage(display, window, gc, ximage, 0, (int)firstrow, 0, (int)firstrow, rpng2_info.width, row - firstrow + 1); XFlush(display); rows = 0; usleep(usleep_duration); } else if (!demo_timing && ((rows & 0xf) == 0 || row >= rpng2_info.height-2)) { XPutImage(display, window, gc, ximage, 0, (int)firstrow, 0, (int)firstrow, rpng2_info.width, row - firstrow + 1); XFlush(display); rows = 0; } } static void rpng2_x_finish_display(void) { Trace((stderr, "beginning rpng2_x_finish_display()\n")) /* last row has already been displayed by rpng2_x_display_row(), so we * have nothing to do here except set a flag and let the user know that * the image is done */ rpng2_info.state = kDone; printf( "Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n"); fflush(stdout); } static void rpng2_x_redisplay_image(ulg startcol, ulg startrow, ulg width, ulg height) { uch bg_red = rpng2_info.bg_red; uch bg_green = rpng2_info.bg_green; uch bg_blue = rpng2_info.bg_blue; uch *src, *src2=NULL; char *dest; uch r, g, b, a; ulg i, row, lastrow = 0; ulg pixel; int ximage_rowbytes = ximage->bytes_per_line; Trace((stderr, "beginning display loop (image_channels == %d)\n", rpng2_info.channels)) Trace((stderr, " (width = %ld, rowbytes = %d, ximage_rowbytes = %d)\n", rpng2_info.width, rpng2_info.rowbytes, ximage_rowbytes)) Trace((stderr, " (bpp = %d)\n", ximage->bits_per_pixel)) Trace((stderr, " (byte_order = %s)\n", ximage->byte_order == MSBFirst? "MSBFirst" : (ximage->byte_order == LSBFirst? "LSBFirst" : "unknown"))) /*--------------------------------------------------------------------------- Aside from the use of the rpng2_info struct and of src2 (for background image), this routine is identical to rpng_x_display_image() in the non- progressive version of the program--for the simple reason that redisplay of the image against a new background happens after the image is fully decoded and therefore is, by definition, non-progressive. ---------------------------------------------------------------------------*/ if (depth == 24 || depth == 32) { ulg red, green, blue; int bpp = ximage->bits_per_pixel; for (lastrow = row = startrow; row < startrow+height; ++row) { src = rpng2_info.image_data + row*rpng2_info.rowbytes; if (bg_image) src2 = bg_data + row*bg_rowbytes; dest = ximage->data + row*ximage_rowbytes; if (rpng2_info.channels == 3) { for (i = rpng2_info.width; i > 0; --i) { red = *src++; green = *src++; blue = *src++; #ifdef NO_24BIT_MASKS pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ if (bpp == 32) { *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } else { /* this assumes bpp == 24 & bits are packed low */ /* (probably need to use RShift, RMask, etc.) */ *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } #else red = (RShift < 0)? red << (-RShift) : red >> RShift; green = (GShift < 0)? green << (-GShift) : green >> GShift; blue = (BShift < 0)? blue << (-BShift) : blue >> BShift; pixel = (red & RMask) | (green & GMask) | (blue & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ if (bpp == 32) { *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } else { /* GRR BUG */ /* this assumes bpp == 24 & bits are packed low */ /* (probably need to use RShift/RMask/etc. here, too) */ *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } #endif } } else /* if (rpng2_info.channels == 4) */ { for (i = rpng2_info.width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (bg_image) { bg_red = *src2++; bg_green = *src2++; bg_blue = *src2++; } if (a == 255) { red = r; green = g; blue = b; } else if (a == 0) { red = bg_red; green = bg_green; blue = bg_blue; } else { /* this macro (from png.h) composites the foreground * and background values and puts the result into the * first argument */ alpha_composite(red, r, a, bg_red); alpha_composite(green, g, a, bg_green); alpha_composite(blue, b, a, bg_blue); } #ifdef NO_24BIT_MASKS pixel = (red << RShift) | (green << GShift) | (blue << BShift); /* recall that we set ximage->byte_order = MSBFirst above */ if (bpp == 32) { *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } else { /* this assumes bpp == 24 & bits are packed low */ /* (probably need to use RShift, RMask, etc.) */ *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } #else red = (RShift < 0)? red << (-RShift) : red >> RShift; green = (GShift < 0)? green << (-GShift) : green >> GShift; blue = (BShift < 0)? blue << (-BShift) : blue >> BShift; pixel = (red & RMask) | (green & GMask) | (blue & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ if (bpp == 32) { *dest++ = (char)((pixel >> 24) & 0xff); *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } else { /* GRR BUG */ /* this assumes bpp == 24 & bits are packed low */ /* (probably need to use RShift/RMask/etc. here, too) */ *dest++ = (char)((pixel >> 16) & 0xff); *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } #endif } } /* display after every 16 lines */ if (((row+1) & 0xf) == 0) { XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0, (int)lastrow, rpng2_info.width, 16); XFlush(display); lastrow = row + 1; } } } else if (depth == 16) { ush red, green, blue; for (lastrow = row = startrow; row < startrow+height; ++row) { src = rpng2_info.row_pointers[row]; if (bg_image) src2 = bg_data + row*bg_rowbytes; dest = ximage->data + row*ximage_rowbytes; if (rpng2_info.channels == 3) { for (i = rpng2_info.width; i > 0; --i) { red = ((ush)(*src) << 8); ++src; green = ((ush)(*src) << 8); ++src; blue = ((ush)(*src) << 8); ++src; pixel = ((red >> RShift) & RMask) | ((green >> GShift) & GMask) | ((blue >> BShift) & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } else /* if (rpng2_info.channels == 4) */ { for (i = rpng2_info.width; i > 0; --i) { r = *src++; g = *src++; b = *src++; a = *src++; if (bg_image) { bg_red = *src2++; bg_green = *src2++; bg_blue = *src2++; } if (a == 255) { red = ((ush)r << 8); green = ((ush)g << 8); blue = ((ush)b << 8); } else if (a == 0) { red = ((ush)bg_red << 8); green = ((ush)bg_green << 8); blue = ((ush)bg_blue << 8); } else { /* this macro (from png.h) composites the foreground * and background values and puts the result back into * the first argument (== fg byte here: safe) */ alpha_composite(r, r, a, bg_red); alpha_composite(g, g, a, bg_green); alpha_composite(b, b, a, bg_blue); red = ((ush)r << 8); green = ((ush)g << 8); blue = ((ush)b << 8); } pixel = ((red >> RShift) & RMask) | ((green >> GShift) & GMask) | ((blue >> BShift) & BMask); /* recall that we set ximage->byte_order = MSBFirst above */ *dest++ = (char)((pixel >> 8) & 0xff); *dest++ = (char)( pixel & 0xff); } } /* display after every 16 lines */ if (((row+1) & 0xf) == 0) { XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0, (int)lastrow, rpng2_info.width, 16); XFlush(display); lastrow = row + 1; } } } else /* depth == 8 */ { /* GRR: add 8-bit support */ } Trace((stderr, "calling final XPutImage()\n")) if (lastrow < startrow+height) { XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0, (int)lastrow, rpng2_info.width, rpng2_info.height-lastrow); XFlush(display); } (void)startcol; (void)width; } /* end function rpng2_x_redisplay_image() */ #ifdef FEATURE_LOOP static void rpng2_x_reload_bg_image(void) { char *dest; uch r1, r2, g1, g2, b1, b2; uch r1_inv, r2_inv, g1_inv, g2_inv, b1_inv, b2_inv; int k, hmax, max; int xidx, yidx, yidx_max; int even_odd_vert, even_odd_horiz, even_odd; int invert_gradient2 = (bg[pat].type & 0x08); int invert_column; ulg i, row; bgscale = (pat == 0)? 8 : bgscale_default; yidx_max = bgscale - 1; /*--------------------------------------------------------------------------- Vertical gradients (ramps) in NxN squares, alternating direction and colors (N == bgscale). ---------------------------------------------------------------------------*/ if ((bg[pat].type & 0x07) == 0) { uch r1_min = rgb[bg[pat].rgb1_min].r; uch g1_min = rgb[bg[pat].rgb1_min].g; uch b1_min = rgb[bg[pat].rgb1_min].b; uch r2_min = rgb[bg[pat].rgb2_min].r; uch g2_min = rgb[bg[pat].rgb2_min].g; uch b2_min = rgb[bg[pat].rgb2_min].b; int r1_diff = rgb[bg[pat].rgb1_max].r - r1_min; int g1_diff = rgb[bg[pat].rgb1_max].g - g1_min; int b1_diff = rgb[bg[pat].rgb1_max].b - b1_min; int r2_diff = rgb[bg[pat].rgb2_max].r - r2_min; int g2_diff = rgb[bg[pat].rgb2_max].g - g2_min; int b2_diff = rgb[bg[pat].rgb2_max].b - b2_min; for (row = 0; row < rpng2_info.height; ++row) { yidx = (int)(row % bgscale); even_odd_vert = (int)((row / bgscale) & 1); r1 = r1_min + (r1_diff * yidx) / yidx_max; g1 = g1_min + (g1_diff * yidx) / yidx_max; b1 = b1_min + (b1_diff * yidx) / yidx_max; r1_inv = r1_min + (r1_diff * (yidx_max-yidx)) / yidx_max; g1_inv = g1_min + (g1_diff * (yidx_max-yidx)) / yidx_max; b1_inv = b1_min + (b1_diff * (yidx_max-yidx)) / yidx_max; r2 = r2_min + (r2_diff * yidx) / yidx_max; g2 = g2_min + (g2_diff * yidx) / yidx_max; b2 = b2_min + (b2_diff * yidx) / yidx_max; r2_inv = r2_min + (r2_diff * (yidx_max-yidx)) / yidx_max; g2_inv = g2_min + (g2_diff * (yidx_max-yidx)) / yidx_max; b2_inv = b2_min + (b2_diff * (yidx_max-yidx)) / yidx_max; dest = (char *)bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { even_odd_horiz = (int)((i / bgscale) & 1); even_odd = even_odd_vert ^ even_odd_horiz; invert_column = (even_odd_horiz && (bg[pat].type & 0x10)); if (even_odd == 0) { /* gradient #1 */ if (invert_column) { *dest++ = r1_inv; *dest++ = g1_inv; *dest++ = b1_inv; } else { *dest++ = r1; *dest++ = g1; *dest++ = b1; } } else { /* gradient #2 */ if ((invert_column && invert_gradient2) || (!invert_column && !invert_gradient2)) { *dest++ = r2; /* not inverted or */ *dest++ = g2; /* doubly inverted */ *dest++ = b2; } else { *dest++ = r2_inv; *dest++ = g2_inv; /* singly inverted */ *dest++ = b2_inv; } } } } /*--------------------------------------------------------------------------- Soft gradient-diamonds with scale = bgscale. Code contributed by Adam M. Costello. ---------------------------------------------------------------------------*/ } else if ((bg[pat].type & 0x07) == 1) { hmax = (bgscale-1)/2; /* half the max weight of a color */ max = 2*hmax; /* the max weight of a color */ r1 = rgb[bg[pat].rgb1_max].r; g1 = rgb[bg[pat].rgb1_max].g; b1 = rgb[bg[pat].rgb1_max].b; r2 = rgb[bg[pat].rgb2_max].r; g2 = rgb[bg[pat].rgb2_max].g; b2 = rgb[bg[pat].rgb2_max].b; for (row = 0; row < rpng2_info.height; ++row) { yidx = (int)(row % bgscale); if (yidx > hmax) yidx = bgscale-1 - yidx; dest = (char *)bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { xidx = (int)(i % bgscale); if (xidx > hmax) xidx = bgscale-1 - xidx; k = xidx + yidx; *dest++ = (k*r1 + (max-k)*r2) / max; *dest++ = (k*g1 + (max-k)*g2) / max; *dest++ = (k*b1 + (max-k)*b2) / max; } } /*--------------------------------------------------------------------------- Radial "starburst" with azimuthal sinusoids; [eventually number of sinu- soids will equal bgscale?]. This one is slow but very cool. Code con- tributed by Pieter S. van der Meulen (originally in Smalltalk). ---------------------------------------------------------------------------*/ } else if ((bg[pat].type & 0x07) == 2) { uch ch; int ii, x, y, hw, hh, grayspot; double freq, rotate, saturate, gray, intensity; double angle=0.0, aoffset=0.0, maxDist, dist; double red=0.0, green=0.0, blue=0.0, hue, s, v, f, p, q, t; hh = (int)(rpng2_info.height / 2); hw = (int)(rpng2_info.width / 2); /* variables for radial waves: * aoffset: number of degrees to rotate hue [CURRENTLY NOT USED] * freq: number of color beams originating from the center * grayspot: size of the graying center area (anti-alias) * rotate: rotation of the beams as a function of radius * saturate: saturation of beams' shape azimuthally */ angle = CLIP(angle, 0.0, 360.0); grayspot = CLIP(bg[pat].bg_gray, 1, (hh + hw)); freq = MAX((double)bg[pat].bg_freq, 0.0); saturate = (double)bg[pat].bg_bsat * 0.1; rotate = (double)bg[pat].bg_brot * 0.1; gray = 0.0; intensity = 0.0; maxDist = (double)((hw*hw) + (hh*hh)); for (row = 0; row < rpng2_info.height; ++row) { y = (int)(row - hh); dest = (char *)bg_data + row*bg_rowbytes; for (i = 0; i < rpng2_info.width; ++i) { x = (int)(i - hw); angle = (x == 0)? PI_2 : atan((double)y / (double)x); gray = (double)MAX(ABS(y), ABS(x)) / grayspot; gray = MIN(1.0, gray); dist = (double)((x*x) + (y*y)) / maxDist; intensity = cos((angle+(rotate*dist*PI)) * freq) * gray * saturate; intensity = (MAX(MIN(intensity,1.0),-1.0) + 1.0) * 0.5; hue = (angle + PI) * INV_PI_360 + aoffset; s = gray * ((double)(ABS(x)+ABS(y)) / (double)(hw + hh)); s = MIN(MAX(s,0.0), 1.0); v = MIN(MAX(intensity,0.0), 1.0); if (s == 0.0) { ch = (uch)(v * 255.0); *dest++ = ch; *dest++ = ch; *dest++ = ch; } else { if ((hue < 0.0) || (hue >= 360.0)) hue -= (((int)(hue / 360.0)) * 360.0); hue /= 60.0; ii = (int)hue; f = hue - (double)ii; p = (1.0 - s) * v; q = (1.0 - (s * f)) * v; t = (1.0 - (s * (1.0 - f))) * v; if (ii == 0) { red = v; green = t; blue = p; } else if (ii == 1) { red = q; green = v; blue = p; } else if (ii == 2) { red = p; green = v; blue = t; } else if (ii == 3) { red = p; green = q; blue = v; } else if (ii == 4) { red = t; green = p; blue = v; } else if (ii == 5) { red = v; green = p; blue = q; } *dest++ = (uch)(red * 255.0); *dest++ = (uch)(green * 255.0); *dest++ = (uch)(blue * 255.0); } } } } } /* end function rpng2_x_reload_bg_image() */ static int is_number(char *p) { while (*p) { if (!isdigit(*p)) return FALSE; ++p; } return TRUE; } #endif /* FEATURE_LOOP */ static void rpng2_x_cleanup(void) { if (bg_image && bg_data) { free(bg_data); bg_data = NULL; } if (rpng2_info.image_data) { free(rpng2_info.image_data); rpng2_info.image_data = NULL; } if (rpng2_info.row_pointers) { free(rpng2_info.row_pointers); rpng2_info.row_pointers = NULL; } if (ximage) { if (ximage->data) { free(ximage->data); /* we allocated it, so we free it */ ximage->data = (char *)NULL; /* instead of XDestroyImage() */ } XDestroyImage(ximage); ximage = NULL; } if (have_gc) XFreeGC(display, gc); if (have_window) XDestroyWindow(display, window); if (have_colormap) XFreeColormap(display, colormap); if (have_nondefault_visual) XFree(visual_list); } static int rpng2_x_msb(ulg u32val) { int i; for (i = 31; i >= 0; --i) { if (u32val & 0x80000000L) break; u32val <<= 1; } return i; } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/wpng.c ================================================ /*--------------------------------------------------------------------------- wpng - simple PNG-writing program wpng.c This program converts certain NetPBM binary files (grayscale and RGB, maxval = 255) to PNG. Non-interlaced PNGs are written progressively; interlaced PNGs are read and written in one memory-intensive blast. Thanks to Jean-loup Gailly for providing the necessary trick to read interactive text from the keyboard while stdin is redirected. Thanks to Cosmin Truta for Cygwin fixes. NOTE: includes provisional support for PNM type "8" (portable alphamap) images, presumed to be a 32-bit interleaved RGBA format; no pro- vision for possible interleaved grayscale+alpha (16-bit) format. THIS IS UNLIKELY TO BECOME AN OFFICIAL NETPBM ALPHA FORMAT! to do: - delete output file if quit before calling any writepng routines - process backspace with -text option under DOS/Win? (currently get ^H) --------------------------------------------------------------------------- Changelog: - 1.01: initial public release - 1.02: modified to allow abbreviated options - 1.03: removed extraneous character from usage screen; fixed bug in command-line parsing - 1.04: fixed DOS/OS2/Win32 detection, including partial Cygwin fix (see http://home.att.net/~perlspinr/diffs/GregBook_cygwin.diff) - 2.00: dual-licensed (added GNU GPL) [REPORTED BUG (win32 only): "contrib/gregbook/wpng.c - cmd line dose not work! In order to do something useful I needed to redirect both input and output, with cygwin and with bcc32 as well. Under Linux, the same wpng appears to work fine. I don't know what is the problem."] --------------------------------------------------------------------------- Copyright (c) 1998-2007 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #define PROGNAME "wpng" #define VERSION "2.00 of 2 June 2007" #define APPNAME "Simple PGM/PPM/PAM to PNG Converter" #if defined(__MSDOS__) || defined(__OS2__) # define DOS_OS2_W32 #elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) # ifndef __GNUC__ /* treat Win32 native ports of gcc as Unix environments */ # define DOS_OS2_W32 # endif #endif #include #include #include #include /* for jmpbuf declaration in writepng.h */ #include #ifdef DOS_OS2_W32 # include /* for isatty(), setmode() prototypes */ # include /* O_BINARY for fdopen() without text translation */ # ifdef __EMX__ # ifndef getch # define getch() _read_kbd(0, 1, 0) /* need getche() */ # endif # else /* !__EMX__ */ # ifdef __GO32__ # include # define getch() getkey() /* GRR: need getche() */ # else # include /* for getche() console input */ # endif # endif /* ?__EMX__ */ # define FGETS(buf,len,stream) dos_kbd_gets(buf,len) #else # include /* for isatty() prototype */ # define FGETS fgets #endif /* #define DEBUG : this enables the Trace() macros */ /* #define FORBID_LATIN1_CTRL : this requires the user to re-enter any text that includes control characters discouraged by the PNG spec; text that includes an escape character (27) must be re-entered regardless */ #include "writepng.h" /* typedefs, common macros, writepng prototypes */ /* local prototypes */ static int wpng_isvalid_latin1(uch *p, int len); static void wpng_cleanup(void); #ifdef DOS_OS2_W32 static char *dos_kbd_gets(char *buf, int len); #endif static mainprog_info wpng_info; /* lone global */ int main(int argc, char **argv) { #ifndef DOS_OS2_W32 FILE *keybd; #endif #ifdef sgi FILE *tmpfile; /* or we could just use keybd, since no overlap */ char tmpline[80]; #endif char *inname = NULL, outname[256]; char *p, pnmchar, pnmline[256]; char *bgstr, *textbuf = NULL; ulg rowbytes; int rc, len = 0; int error = 0; int text = FALSE; int maxval; double LUT_exponent; /* just the lookup table */ double CRT_exponent = 2.2; /* just the monitor */ double default_display_exponent; /* whole display system */ double default_gamma = 0.0; wpng_info.infile = NULL; wpng_info.outfile = NULL; wpng_info.image_data = NULL; wpng_info.row_pointers = NULL; wpng_info.filter = FALSE; wpng_info.interlaced = FALSE; wpng_info.have_bg = FALSE; wpng_info.have_time = FALSE; wpng_info.have_text = 0; wpng_info.gamma = 0.0; /* First get the default value for our display-system exponent, i.e., * the product of the CRT exponent and the exponent corresponding to * the frame-buffer's lookup table (LUT), if any. If the PNM image * looks correct on the user's display system, its file gamma is the * inverse of this value. (Note that this is not an exhaustive list * of LUT values--e.g., OpenStep has a lot of weird ones--but it should * cover 99% of the current possibilities. This section must ensure * that default_display_exponent is positive.) */ #if defined(NeXT) /* third-party utilities can modify the default LUT exponent */ LUT_exponent = 1.0 / 2.2; /* if (some_next_function_that_returns_gamma(&next_gamma)) LUT_exponent = 1.0 / next_gamma; */ #elif defined(sgi) LUT_exponent = 1.0 / 1.7; /* there doesn't seem to be any documented function to * get the "gamma" value, so we do it the hard way */ tmpfile = fopen("/etc/config/system.glGammaVal", "r"); if (tmpfile) { double sgi_gamma; fgets(tmpline, 80, tmpfile); fclose(tmpfile); sgi_gamma = atof(tmpline); if (sgi_gamma > 0.0) LUT_exponent = 1.0 / sgi_gamma; } #elif defined(Macintosh) LUT_exponent = 1.8 / 2.61; /* if (some_mac_function_that_returns_gamma(&mac_gamma)) LUT_exponent = mac_gamma / 2.61; */ #else LUT_exponent = 1.0; /* assume no LUT: most PCs */ #endif /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */ default_display_exponent = LUT_exponent * CRT_exponent; /* If the user has set the SCREEN_GAMMA environment variable as suggested * (somewhat imprecisely) in the libpng documentation, use that; otherwise * use the default value we just calculated. Either way, the user may * override this via a command-line option. */ if ((p = getenv("SCREEN_GAMMA")) != NULL) { double exponent = atof(p); if (exponent > 0.0) default_gamma = 1.0 / exponent; } if (default_gamma == 0.0) default_gamma = 1.0 / default_display_exponent; /* Now parse the command line for options and the PNM filename. */ while (*++argv && !error) { if (!strncmp(*argv, "-i", 2)) { wpng_info.interlaced = TRUE; } else if (!strncmp(*argv, "-time", 3)) { wpng_info.modtime = time(NULL); wpng_info.have_time = TRUE; } else if (!strncmp(*argv, "-text", 3)) { text = TRUE; } else if (!strncmp(*argv, "-gamma", 2)) { if (!*++argv) ++error; else { wpng_info.gamma = atof(*argv); if (wpng_info.gamma <= 0.0) ++error; else if (wpng_info.gamma > 1.01) fprintf(stderr, PROGNAME " warning: file gammas are usually less than 1.0\n"); } } else if (!strncmp(*argv, "-bgcolor", 4)) { if (!*++argv) ++error; else { bgstr = *argv; if (strlen(bgstr) != 7 || bgstr[0] != '#') ++error; else { unsigned r, g, b; /* this way quiets compiler warnings */ sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b); wpng_info.bg_red = (uch)r; wpng_info.bg_green = (uch)g; wpng_info.bg_blue = (uch)b; wpng_info.have_bg = TRUE; } } } else { if (**argv != '-') { inname = *argv; if (argv[1]) /* shouldn't be any more args after filename */ ++error; } else ++error; /* not expecting any other options */ } } /* open the input and output files, or register an error and abort */ if (!inname) { if (isatty(0)) { fprintf(stderr, PROGNAME ": must give input filename or provide image data via stdin\n"); ++error; } else { #ifdef DOS_OS2_W32 /* some buggy C libraries require BOTH setmode() and fdopen(bin) */ setmode(fileno(stdin), O_BINARY); setmode(fileno(stdout), O_BINARY); #endif if ((wpng_info.infile = fdopen(fileno(stdin), "rb")) == NULL) { fprintf(stderr, PROGNAME ": unable to reopen stdin in binary mode\n"); ++error; } else if ((wpng_info.outfile = fdopen(fileno(stdout), "wb")) == NULL) { fprintf(stderr, PROGNAME ": unable to reopen stdout in binary mode\n"); fclose(wpng_info.infile); ++error; } else wpng_info.filter = TRUE; } } else if ((len = strlen(inname)) > 250) { fprintf(stderr, PROGNAME ": input filename is too long [%d chars]\n", len); ++error; } else if (!(wpng_info.infile = fopen(inname, "rb"))) { fprintf(stderr, PROGNAME ": can't open input file [%s]\n", inname); ++error; } if (!error) { fgets(pnmline, 256, wpng_info.infile); if (pnmline[0] != 'P' || ((pnmchar = pnmline[1]) != '5' && pnmchar != '6' && pnmchar != '8')) { fprintf(stderr, PROGNAME ": input file [%s] is not a binary PGM, PPM or PAM file\n", inname); ++error; } else { wpng_info.pnmtype = (int)(pnmchar - '0'); if (wpng_info.pnmtype != 8) wpng_info.have_bg = FALSE; /* no need for bg if opaque */ do { fgets(pnmline, 256, wpng_info.infile); /* lose any comments */ } while (pnmline[0] == '#'); sscanf(pnmline, "%ld %ld", &wpng_info.width, &wpng_info.height); do { fgets(pnmline, 256, wpng_info.infile); /* more comment lines */ } while (pnmline[0] == '#'); sscanf(pnmline, "%d", &maxval); if (wpng_info.width <= 0L || wpng_info.height <= 0L || maxval != 255) { fprintf(stderr, PROGNAME ": only positive width/height, maxval == 255 allowed \n"); ++error; } wpng_info.sample_depth = 8; /* <==> maxval 255 */ if (!wpng_info.filter) { /* make outname from inname */ if ((p = strrchr(inname, '.')) == NULL || (p - inname) != (len - 4)) { strcpy(outname, inname); strcpy(outname+len, ".png"); } else { len -= 4; strncpy(outname, inname, len); strcpy(outname+len, ".png"); } /* check if outname already exists; if not, open */ if ((wpng_info.outfile = fopen(outname, "rb")) != NULL) { fprintf(stderr, PROGNAME ": output file exists [%s]\n", outname); fclose(wpng_info.outfile); ++error; } else if (!(wpng_info.outfile = fopen(outname, "wb"))) { fprintf(stderr, PROGNAME ": can't open output file [%s]\n", outname); ++error; } } } if (error) { fclose(wpng_info.infile); wpng_info.infile = NULL; if (wpng_info.filter) { fclose(wpng_info.outfile); wpng_info.outfile = NULL; } } } /* if we had any errors, print usage and die horrible death...arrr! */ if (error) { fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, APPNAME); writepng_version_info(); fprintf(stderr, "\n" "Usage: %s [-gamma exp] [-bgcolor bg] [-text] [-time] [-interlace] pnmfile\n" "or: ... | %s [-gamma exp] [-bgcolor bg] [-text] [-time] [-interlace] | ...\n" " exp \ttransfer-function exponent (``gamma'') of the image in\n" "\t\t floating-point format (e.g., ``%.5f''); if image looks\n" "\t\t correct on given display system, image gamma is equal to\n" "\t\t inverse of display-system exponent, i.e., 1 / (LUT * CRT)\n" "\t\t (where LUT = lookup-table exponent and CRT = CRT exponent;\n" "\t\t first varies, second is usually 2.2, all are positive)\n" " bg \tdesired background color for alpha-channel images, in\n" "\t\t 7-character hex RGB format (e.g., ``#ff7700'' for orange:\n" "\t\t same as HTML colors)\n" " -text\tprompt interactively for text info (tEXt chunks)\n" " -time\tinclude a tIME chunk (last modification time)\n" " -interlace\twrite interlaced PNG image\n" "\n" "pnmfile or stdin must be a binary PGM (`P5'), PPM (`P6') or (extremely\n" "unofficial and unsupported!) PAM (`P8') file. Currently it is required\n" "to have maxval == 255 (i.e., no scaling). If pnmfile is specified, it\n" "is converted to the corresponding PNG file with the same base name but a\n" "``.png'' extension; files read from stdin are converted and sent to stdout.\n" "The conversion is progressive (low memory usage) unless interlacing is\n" "requested; in that case the whole image will be buffered in memory and\n" "written in one call.\n" "\n", PROGNAME, PROGNAME, default_gamma); exit(1); } /* prepare the text buffers for libpng's use; note that even though * PNG's png_text struct includes a length field, we don't have to fill * it out */ if (text && #ifndef DOS_OS2_W32 (keybd = fdopen(fileno(stderr), "r")) != NULL && #endif (textbuf = (char *)malloc((5 + 9)*75)) != NULL) { int i, valid, result; fprintf(stderr, "Enter text info (no more than 72 characters per line);\n"); fprintf(stderr, "to skip a field, hit the key.\n"); /* note: just leaves len == 1 */ do { valid = TRUE; p = textbuf + TEXT_TITLE_OFFSET; fprintf(stderr, " Title: "); fflush(stderr); if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) { if (p[len-1] == '\n') p[--len] = '\0'; wpng_info.title = p; wpng_info.have_text |= TEXT_TITLE; if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) { fprintf(stderr, " " PROGNAME " warning: character code" " %u is %sdiscouraged by the PNG\n specification " "[first occurrence was at character position #%d]\n", (unsigned)p[result], (p[result] == 27)? "strongly " : "", result+1); fflush(stderr); #ifdef FORBID_LATIN1_CTRL wpng_info.have_text &= ~TEXT_TITLE; valid = FALSE; #else if (p[result] == 27) { /* escape character */ wpng_info.have_text &= ~TEXT_TITLE; valid = FALSE; } #endif } } } while (!valid); do { valid = TRUE; p = textbuf + TEXT_AUTHOR_OFFSET; fprintf(stderr, " Author: "); fflush(stderr); if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) { if (p[len-1] == '\n') p[--len] = '\0'; wpng_info.author = p; wpng_info.have_text |= TEXT_AUTHOR; if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) { fprintf(stderr, " " PROGNAME " warning: character code" " %u is %sdiscouraged by the PNG\n specification " "[first occurrence was at character position #%d]\n", (unsigned)p[result], (p[result] == 27)? "strongly " : "", result+1); fflush(stderr); #ifdef FORBID_LATIN1_CTRL wpng_info.have_text &= ~TEXT_AUTHOR; valid = FALSE; #else if (p[result] == 27) { /* escape character */ wpng_info.have_text &= ~TEXT_AUTHOR; valid = FALSE; } #endif } } } while (!valid); do { valid = TRUE; p = textbuf + TEXT_DESC_OFFSET; fprintf(stderr, " Description (up to 9 lines):\n"); for (i = 1; i < 10; ++i) { fprintf(stderr, " [%d] ", i); fflush(stderr); if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) p += len; /* now points at NULL; char before is newline */ else break; } if ((len = p - (textbuf + TEXT_DESC_OFFSET)) > 1) { if (p[-1] == '\n') { p[-1] = '\0'; --len; } wpng_info.desc = textbuf + TEXT_DESC_OFFSET; wpng_info.have_text |= TEXT_DESC; p = textbuf + TEXT_DESC_OFFSET; if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) { fprintf(stderr, " " PROGNAME " warning: character code" " %u is %sdiscouraged by the PNG\n specification " "[first occurrence was at character position #%d]\n", (unsigned)p[result], (p[result] == 27)? "strongly " : "", result+1); fflush(stderr); #ifdef FORBID_LATIN1_CTRL wpng_info.have_text &= ~TEXT_DESC; valid = FALSE; #else if (p[result] == 27) { /* escape character */ wpng_info.have_text &= ~TEXT_DESC; valid = FALSE; } #endif } } } while (!valid); do { valid = TRUE; p = textbuf + TEXT_COPY_OFFSET; fprintf(stderr, " Copyright: "); fflush(stderr); if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) { if (p[len-1] == '\n') p[--len] = '\0'; wpng_info.copyright = p; wpng_info.have_text |= TEXT_COPY; if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) { fprintf(stderr, " " PROGNAME " warning: character code" " %u is %sdiscouraged by the PNG\n specification " "[first occurrence was at character position #%d]\n", (unsigned)p[result], (p[result] == 27)? "strongly " : "", result+1); fflush(stderr); #ifdef FORBID_LATIN1_CTRL wpng_info.have_text &= ~TEXT_COPY; valid = FALSE; #else if (p[result] == 27) { /* escape character */ wpng_info.have_text &= ~TEXT_COPY; valid = FALSE; } #endif } } } while (!valid); do { valid = TRUE; p = textbuf + TEXT_EMAIL_OFFSET; fprintf(stderr, " E-mail: "); fflush(stderr); if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) { if (p[len-1] == '\n') p[--len] = '\0'; wpng_info.email = p; wpng_info.have_text |= TEXT_EMAIL; if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) { fprintf(stderr, " " PROGNAME " warning: character code" " %u is %sdiscouraged by the PNG\n specification " "[first occurrence was at character position #%d]\n", (unsigned)p[result], (p[result] == 27)? "strongly " : "", result+1); fflush(stderr); #ifdef FORBID_LATIN1_CTRL wpng_info.have_text &= ~TEXT_EMAIL; valid = FALSE; #else if (p[result] == 27) { /* escape character */ wpng_info.have_text &= ~TEXT_EMAIL; valid = FALSE; } #endif } } } while (!valid); do { valid = TRUE; p = textbuf + TEXT_URL_OFFSET; fprintf(stderr, " URL: "); fflush(stderr); if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) { if (p[len-1] == '\n') p[--len] = '\0'; wpng_info.url = p; wpng_info.have_text |= TEXT_URL; if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) { fprintf(stderr, " " PROGNAME " warning: character code" " %u is %sdiscouraged by the PNG\n specification " "[first occurrence was at character position #%d]\n", (unsigned)p[result], (p[result] == 27)? "strongly " : "", result+1); fflush(stderr); #ifdef FORBID_LATIN1_CTRL wpng_info.have_text &= ~TEXT_URL; valid = FALSE; #else if (p[result] == 27) { /* escape character */ wpng_info.have_text &= ~TEXT_URL; valid = FALSE; } #endif } } } while (!valid); #ifndef DOS_OS2_W32 fclose(keybd); #endif } else if (text) { fprintf(stderr, PROGNAME ": unable to allocate memory for text\n"); text = FALSE; wpng_info.have_text = 0; } /* allocate libpng stuff, initialize transformations, write pre-IDAT data */ if ((rc = writepng_init(&wpng_info)) != 0) { switch (rc) { case 2: fprintf(stderr, PROGNAME ": libpng initialization problem (longjmp)\n"); break; case 4: fprintf(stderr, PROGNAME ": insufficient memory\n"); break; case 11: fprintf(stderr, PROGNAME ": internal logic error (unexpected PNM type)\n"); break; default: fprintf(stderr, PROGNAME ": unknown writepng_init() error\n"); break; } exit(rc); } /* free textbuf, since it's a completely local variable and all text info * has just been written to the PNG file */ if (text && textbuf) { free(textbuf); textbuf = NULL; } /* calculate rowbytes on basis of image type; note that this becomes much * more complicated if we choose to support PBM type, ASCII PNM types, or * 16-bit-per-sample binary data [currently not an official NetPBM type] */ if (wpng_info.pnmtype == 5) rowbytes = wpng_info.width; else if (wpng_info.pnmtype == 6) rowbytes = wpng_info.width * 3; else /* if (wpng_info.pnmtype == 8) */ rowbytes = wpng_info.width * 4; /* read and write the image, either in its entirety (if writing interlaced * PNG) or row by row (if non-interlaced) */ fprintf(stderr, "Encoding image data...\n"); fflush(stderr); if (wpng_info.interlaced) { long i; ulg bytes; ulg image_bytes = rowbytes * wpng_info.height; /* overflow? */ wpng_info.image_data = (uch *)malloc(image_bytes); wpng_info.row_pointers = (uch **)malloc(wpng_info.height*sizeof(uch *)); if (wpng_info.image_data == NULL || wpng_info.row_pointers == NULL) { fprintf(stderr, PROGNAME ": insufficient memory for image data\n"); writepng_cleanup(&wpng_info); wpng_cleanup(); exit(5); } for (i = 0; i < wpng_info.height; ++i) wpng_info.row_pointers[i] = wpng_info.image_data + i*rowbytes; bytes = fread(wpng_info.image_data, 1, image_bytes, wpng_info.infile); if (bytes != image_bytes) { fprintf(stderr, PROGNAME ": expected %lu bytes, got %lu bytes\n", image_bytes, bytes); fprintf(stderr, " (continuing anyway)\n"); } if (writepng_encode_image(&wpng_info) != 0) { fprintf(stderr, PROGNAME ": libpng problem (longjmp) while writing image data\n"); writepng_cleanup(&wpng_info); wpng_cleanup(); exit(2); } } else /* not interlaced: write progressively (row by row) */ { long j; ulg bytes; wpng_info.image_data = (uch *)malloc(rowbytes); if (wpng_info.image_data == NULL) { fprintf(stderr, PROGNAME ": insufficient memory for row data\n"); writepng_cleanup(&wpng_info); wpng_cleanup(); exit(5); } error = 0; for (j = wpng_info.height; j > 0L; --j) { bytes = fread(wpng_info.image_data, 1, rowbytes, wpng_info.infile); if (bytes != rowbytes) { fprintf(stderr, PROGNAME ": expected %lu bytes, got %lu bytes (row %ld)\n", rowbytes, bytes, wpng_info.height-j); ++error; break; } if (writepng_encode_row(&wpng_info) != 0) { fprintf(stderr, PROGNAME ": libpng problem (longjmp) while writing row %ld\n", wpng_info.height-j); ++error; break; } } if (error) { writepng_cleanup(&wpng_info); wpng_cleanup(); exit(2); } if (writepng_encode_finish(&wpng_info) != 0) { fprintf(stderr, PROGNAME ": error on final libpng call\n"); writepng_cleanup(&wpng_info); wpng_cleanup(); exit(2); } } /* OK, we're done (successfully): clean up all resources and quit */ fprintf(stderr, "Done.\n"); fflush(stderr); writepng_cleanup(&wpng_info); wpng_cleanup(); return 0; } static int wpng_isvalid_latin1(uch *p, int len) { int i, result = -1; for (i = 0; i < len; ++i) { if (p[i] == 10 || (p[i] > 31 && p[i] < 127) || p[i] > 160) continue; /* character is completely OK */ if (result < 0 || (p[result] != 27 && p[i] == 27)) result = i; /* mark location of first questionable one */ } /* or of first escape character (bad) */ return result; } static void wpng_cleanup(void) { if (wpng_info.outfile) { fclose(wpng_info.outfile); wpng_info.outfile = NULL; } if (wpng_info.infile) { fclose(wpng_info.infile); wpng_info.infile = NULL; } if (wpng_info.image_data) { free(wpng_info.image_data); wpng_info.image_data = NULL; } if (wpng_info.row_pointers) { free(wpng_info.row_pointers); wpng_info.row_pointers = NULL; } } #ifdef DOS_OS2_W32 static char *dos_kbd_gets(char *buf, int len) { int ch, count=0; do { buf[count++] = ch = getche(); } while (ch != '\r' && count < len-1); buf[count--] = '\0'; /* terminate string */ if (buf[count] == '\r') /* Enter key makes CR, so change to newline */ buf[count] = '\n'; fprintf(stderr, "\n"); /* Enter key does *not* cause a newline */ fflush(stderr); return buf; } #endif /* DOS_OS2_W32 */ ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/writepng.c ================================================ /*--------------------------------------------------------------------------- wpng - simple PNG-writing program writepng.c --------------------------------------------------------------------------- Copyright (c) 1998-2007 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #include /* for exit() prototype */ #include #include "png.h" /* libpng header, includes setjmp.h */ #include "writepng.h" /* typedefs, common macros, public prototypes */ /* local prototype */ static void writepng_error_handler(png_structp png_ptr, png_const_charp msg); void writepng_version_info(void) { fprintf(stderr, " Compiled with libpng %s; using libpng %s.\n", PNG_LIBPNG_VER_STRING, png_libpng_ver); fprintf(stderr, " Compiled with zlib %s; using zlib %s.\n", ZLIB_VERSION, zlib_version); } /* returns 0 for success, 2 for libpng problem, 4 for out of memory, 11 for * unexpected pnmtype; note that outfile might be stdout */ int writepng_init(mainprog_info *mainprog_ptr) { png_structp png_ptr; /* note: temporary variables! */ png_infop info_ptr; int color_type, interlace_type; /* could also replace libpng warning-handler (final NULL), but no need: */ png_ptr = png_create_write_struct(png_get_libpng_ver(NULL), mainprog_ptr, writepng_error_handler, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, NULL); return 4; /* out of memory */ } /* setjmp() must be called in every function that calls a PNG-writing * libpng function, unless an alternate error handler was installed-- * but compatible error handlers must either use longjmp() themselves * (as in this program) or some other method to return control to * application code, so here we go: */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); return 2; } /* make sure outfile is (re)opened in BINARY mode */ png_init_io(png_ptr, mainprog_ptr->outfile); /* set the compression levels--in general, always want to leave filtering * turned on (except for palette images) and allow all of the filters, * which is the default; want 32K zlib window, unless entire image buffer * is 16K or smaller (unknown here)--also the default; usually want max * compression (NOT the default); and remaining compression flags should * be left alone */ png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); /* >> this is default for no filtering; Z_FILTERED is default otherwise: png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY); >> these are all defaults: png_set_compression_mem_level(png_ptr, 8); png_set_compression_window_bits(png_ptr, 15); png_set_compression_method(png_ptr, 8); */ /* set the image parameters appropriately */ if (mainprog_ptr->pnmtype == 5) color_type = PNG_COLOR_TYPE_GRAY; else if (mainprog_ptr->pnmtype == 6) color_type = PNG_COLOR_TYPE_RGB; else if (mainprog_ptr->pnmtype == 8) color_type = PNG_COLOR_TYPE_RGB_ALPHA; else { png_destroy_write_struct(&png_ptr, &info_ptr); return 11; } interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE; png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height, mainprog_ptr->sample_depth, color_type, interlace_type, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); if (mainprog_ptr->gamma > 0.0) png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma); if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */ png_color_16 background; background.red = mainprog_ptr->bg_red; background.green = mainprog_ptr->bg_green; background.blue = mainprog_ptr->bg_blue; png_set_bKGD(png_ptr, info_ptr, &background); } if (mainprog_ptr->have_time) { png_time modtime; png_convert_from_time_t(&modtime, mainprog_ptr->modtime); png_set_tIME(png_ptr, info_ptr, &modtime); } if (mainprog_ptr->have_text) { png_text text[6]; int num_text = 0; if (mainprog_ptr->have_text & TEXT_TITLE) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Title"; text[num_text].text = mainprog_ptr->title; ++num_text; } if (mainprog_ptr->have_text & TEXT_AUTHOR) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Author"; text[num_text].text = mainprog_ptr->author; ++num_text; } if (mainprog_ptr->have_text & TEXT_DESC) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Description"; text[num_text].text = mainprog_ptr->desc; ++num_text; } if (mainprog_ptr->have_text & TEXT_COPY) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Copyright"; text[num_text].text = mainprog_ptr->copyright; ++num_text; } if (mainprog_ptr->have_text & TEXT_EMAIL) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "E-mail"; text[num_text].text = mainprog_ptr->email; ++num_text; } if (mainprog_ptr->have_text & TEXT_URL) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "URL"; text[num_text].text = mainprog_ptr->url; ++num_text; } png_set_text(png_ptr, info_ptr, text, num_text); } /* write all chunks up to (but not including) first IDAT */ png_write_info(png_ptr, info_ptr); /* if we wanted to write any more text info *after* the image data, we * would set up text struct(s) here and call png_set_text() again, with * just the new data; png_set_tIME() could also go here, but it would * have no effect since we already called it above (only one tIME chunk * allowed) */ /* set up the transformations: for now, just pack low-bit-depth pixels * into bytes (one, two or four pixels per byte) */ png_set_packing(png_ptr); /* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */ /* make sure we save our pointers for use in writepng_encode_image() */ mainprog_ptr->png_ptr = png_ptr; mainprog_ptr->info_ptr = info_ptr; /* OK, that's all we need to do for now; return happy */ return 0; } /* returns 0 for success, 2 for libpng (longjmp) problem */ int writepng_encode_image(mainprog_info *mainprog_ptr) { png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr; /* as always, setjmp() must be called in every function that calls a * PNG-writing libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; return 2; } /* and now we just write the whole image; libpng takes care of interlacing * for us */ png_write_image(png_ptr, mainprog_ptr->row_pointers); /* since that's it, we also close out the end of the PNG file now--if we * had any text or time info to write after the IDATs, second argument * would be info_ptr, but we optimize slightly by sending NULL pointer: */ png_write_end(png_ptr, NULL); return 0; } /* returns 0 if succeeds, 2 if libpng problem */ int writepng_encode_row(mainprog_info *mainprog_ptr) /* NON-interlaced only! */ { png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr; /* as always, setjmp() must be called in every function that calls a * PNG-writing libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; return 2; } /* image_data points at our one row of image data */ png_write_row(png_ptr, mainprog_ptr->image_data); return 0; } /* returns 0 if succeeds, 2 if libpng problem */ int writepng_encode_finish(mainprog_info *mainprog_ptr) /* NON-interlaced! */ { png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr; /* as always, setjmp() must be called in every function that calls a * PNG-writing libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; return 2; } /* close out PNG file; if we had any text or time info to write after * the IDATs, second argument would be info_ptr: */ png_write_end(png_ptr, NULL); return 0; } void writepng_cleanup(mainprog_info *mainprog_ptr) { png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr; if (png_ptr && info_ptr) png_destroy_write_struct(&png_ptr, &info_ptr); } static void writepng_error_handler(png_structp png_ptr, png_const_charp msg) { mainprog_info *mainprog_ptr; /* This function, aside from the extra step of retrieving the "error * pointer" (below) and the fact that it exists within the application * rather than within libpng, is essentially identical to libpng's * default error handler. The second point is critical: since both * setjmp() and longjmp() are called from the same code, they are * guaranteed to have compatible notions of how big a jmp_buf is, * regardless of whether _BSD_SOURCE or anything else has (or has not) * been defined. */ fprintf(stderr, "writepng libpng error: %s\n", msg); fflush(stderr); mainprog_ptr = png_get_error_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we are completely hosed now */ fprintf(stderr, "writepng severe error: jmpbuf not recoverable; terminating.\n"); fflush(stderr); exit(99); } /* Now we have our data structure we can use the information in it * to return control to our own higher level code (all the points * where 'setjmp' is called in this file.) This will work with other * error handling mechanisms as well - libpng always calls png_error * when it can proceed no further, thus, so long as the error handler * is intercepted, application code can do its own error recovery. */ longjmp(mainprog_ptr->jmpbuf, 1); } ================================================ FILE: tess-two/jni/libpng/contrib/gregbook/writepng.h ================================================ /*--------------------------------------------------------------------------- wpng - simple PNG-writing program writepng.h --------------------------------------------------------------------------- Copyright (c) 1998-2007 Greg Roelofs. All rights reserved. This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software. The contents of this file are DUAL-LICENSED. You may modify and/or redistribute this software according to the terms of one of the following two licenses (at your option): LICENSE 1 ("BSD-like with advertising clause"): Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates. LICENSE 2 (GNU GPL v2 or later): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---------------------------------------------------------------------------*/ #ifndef TRUE # define TRUE 1 # define FALSE 0 #endif #ifndef MAX # define MAX(a,b) ((a) > (b)? (a) : (b)) # define MIN(a,b) ((a) < (b)? (a) : (b)) #endif #ifdef DEBUG # define Trace(x) {fprintf x ; fflush(stderr); fflush(stdout);} #else # define Trace(x) ; #endif #define TEXT_TITLE 0x01 #define TEXT_AUTHOR 0x02 #define TEXT_DESC 0x04 #define TEXT_COPY 0x08 #define TEXT_EMAIL 0x10 #define TEXT_URL 0x20 #define TEXT_TITLE_OFFSET 0 #define TEXT_AUTHOR_OFFSET 72 #define TEXT_COPY_OFFSET (2*72) #define TEXT_EMAIL_OFFSET (3*72) #define TEXT_URL_OFFSET (4*72) #define TEXT_DESC_OFFSET (5*72) typedef unsigned char uch; typedef unsigned short ush; typedef unsigned long ulg; typedef struct _mainprog_info { double gamma; long width; long height; time_t modtime; FILE *infile; FILE *outfile; void *png_ptr; void *info_ptr; uch *image_data; uch **row_pointers; char *title; char *author; char *desc; char *copyright; char *email; char *url; int filter; /* command-line-filter flag, not PNG row filter! */ int pnmtype; int sample_depth; int interlaced; int have_bg; int have_time; int have_text; jmp_buf jmpbuf; uch bg_red; uch bg_green; uch bg_blue; } mainprog_info; /* prototypes for public functions in writepng.c */ void writepng_version_info(void); int writepng_init(mainprog_info *mainprog_ptr); int writepng_encode_image(mainprog_info *mainprog_ptr); int writepng_encode_row(mainprog_info *mainprog_ptr); int writepng_encode_finish(mainprog_info *mainprog_ptr); void writepng_cleanup(mainprog_info *mainprog_ptr); ================================================ FILE: tess-two/jni/libpng/contrib/intel/INSTALL ================================================ Enabling SSE support Copyright (c) 2016 Google, Inc. Written by Mike Klein, Matt Sarett This INSTALL file written by Glenn Randers-Pehrson, 2016. If you have moved intel_init.c and filter_sse2_intrinsics.c to a different directory, be sure to update the '#include "../../pngpriv.h"' line in both files if necessary to point to the correct relative location of pngpriv.h with respect to the new location of those files. To enable SSE support in libpng, follow the instructions in I, II, or III, below: I. Using patched "configure" scripts: First, apply intel_sse.patch in your build directory. patch -i contrib/intel/intel_sse.patch -p1 Then, if you are not building in a new GIT clone, e.g., in a tar distribution, remove any existing pre-built configure scripts: ./configure --enable-maintainer-mode make maintainer-clean ./autogen.sh --maintainer --clean Finally, configure libpng with -DPNG_INTEL_SSE in CPPFLAGS: ./autogen.sh --maintainer CPPFLAGS="-DPNG_INTEL_SSE" ./configure [options] make CPPFLAGS="-DPNG_INTEL_SSE" [options] make II. Using a custom makefile: If you are using a custom makefile makefile, you will have to update it manually to include contrib/intel/*.o in the dependencies, and to define PNG_INTEL_SSE. III. Using manually updated "configure" scripts: If you prefer, manually edit pngpriv.h, configure.ac, and Makefile.am, following the instructions below, then follow the instructions in section II of INSTALL in the main libpng directory, then configure libpng with -DPNG_INTEL_SSE in CPPFLAGS. 1. Add the following code to configure.ac under HOST SPECIFIC OPTIONS directly beneath the section for ARM: -----------------cut---------------- # INTEL # ===== # # INTEL SSE (SIMD) support. AC_ARG_ENABLE([intel-sse], AS_HELP_STRING([[[--enable-intel-sse]]], [Enable Intel SSE optimizations: =no/off, yes/on:] [no/off: disable the optimizations;] [yes/on: enable the optimizations.] [If not specified: determined by the compiler.]), [case "$enableval" in no|off) # disable the default enabling: AC_DEFINE([PNG_INTEL_SSE_OPT], [0], [Disable Intel SSE optimizations]) # Prevent inclusion of the assembler files below: enable_intel_sse=no;; yes|on) AC_DEFINE([PNG_INTEL_SSE_OPT], [1], [Enable Intel SSE optimizations]);; *) AC_MSG_ERROR([--enable-intel-sse=${enable_intel_sse}: invalid value]) esac]) # Add Intel specific files to all builds where the host_cpu is Intel ('x86*') # or where Intel optimizations were explicitly requested (this allows a # fallback if a future host CPU does not match 'x86*') AM_CONDITIONAL([PNG_INTEL_SSE], [test "$enable_intel_sse" != 'no' && case "$host_cpu" in i?86|x86_64) :;; *) test "$enable_intel_sse" != '';; esac]) -----------------cut---------------- 2. Add the following code to Makefile.am under HOST SPECIFIC OPTIONS directly beneath the "if PNG_ARM_NEON ... endif" statement: -----------------cut---------------- if PNG_INTEL_SSE libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES += contrib/intel/intel_init.c\ contrib/intel/filter_sse2_intrinsics.c endif -----------------cut---------------- 3. Add the following lines to pngpriv.h, following the PNG_ARM_NEON_OPT code: -----------------cut---------------- #ifndef PNG_INTEL_SSE_OPT # ifdef PNG_INTEL_SSE /* Only check for SSE if the build configuration has been modified to * enable SSE optimizations. This means that these optimizations will * be off by default. See contrib/intel for more details. */ # if defined(__SSE4_1__) || defined(__AVX__) || defined(__SSSE3__) || \ defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) || \ (defined(_M_IX86_FP) && _M_IX86_FP >= 2) # define PNG_INTEL_SSE_OPT 1 # endif # endif #endif #if PNG_INTEL_SSE_OPT > 0 # ifndef PNG_INTEL_SSE_IMPLEMENTATION # if defined(__SSE4_1__) || defined(__AVX__) /* We are not actually using AVX, but checking for AVX is the best way we can detect SSE4.1 and SSSE3 on MSVC. */ # define PNG_INTEL_SSE_IMPLEMENTATION 3 # elif defined(__SSSE3__) # define PNG_INTEL_SSE_IMPLEMENTATION 2 # elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) || \ (defined(_M_IX86_FP) && _M_IX86_FP >= 2) # define PNG_INTEL_SSE_IMPLEMENTATION 1 # else # define PNG_INTEL_SSE_IMPLEMENTATION 0 # endif # endif # if PNG_INTEL_SSE_IMPLEMENTATION > 0 # define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_sse2 # endif #endif -----------------cut---------------- 4. Add the following lines to pngpriv.h, following the prototype for png_read_filter_row_paeth4_neon: -----------------cut---------------- PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub3_sse2,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub4_sse2,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg3_sse2,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg4_sse2,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth3_sse2,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_sse2,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); -----------------cut---------------- ================================================ FILE: tess-two/jni/libpng/contrib/intel/Makefile.am.patch ================================================ # # Copyright (c) 2016 Google, Inc. # # This code is released under the libpng license. # For conditions of distribution and use, see the disclaimer # and license in png.h # # In order to compile Intel SSE optimizations for libpng, please add # the following code to Makefile.am directly beneath the # "if PNG_ARM_NEON ... endif" statement. if PNG_INTEL_SSE libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES += contrib/intel/intel_init.c\ contrib/intel/filter_sse2_intrinsics.c endif ================================================ FILE: tess-two/jni/libpng/contrib/intel/configure.ac.patch ================================================ # # Copyright (c) 2016 Google, Inc. # # This code is released under the libpng license. # For conditions of distribution and use, see the disclaimer # and license in png.h # # In order to compile Intel SSE optimizations for libpng, please add # the following code to configure.ac under HOST SPECIFIC OPTIONS # directly beneath the section for ARM. # INTEL # === # # INTEL SSE (SIMD) support. AC_ARG_ENABLE([intel-sse], AS_HELP_STRING([[[--enable-intel-sse]]], [Enable Intel SSE optimizations: =no/off, yes/on:] [no/off: disable the optimizations;] [yes/on: enable the optimizations.] [If not specified: determined by the compiler.]), [case "$enableval" in no|off) # disable the default enabling: AC_DEFINE([PNG_INTEL_SSE_OPT], [0], [Disable Intel SSE optimizations]) # Prevent inclusion of the assembler files below: enable_intel_sse=no;; yes|on) AC_DEFINE([PNG_INTEL_SSE_OPT], [1], [Enable Intel SSE optimizations]);; *) AC_MSG_ERROR([--enable-intel-sse=${enable_intel_sse}: invalid value]) esac]) # Add Intel specific files to all builds where the host_cpu is Intel ('x86*') # or where Intel optimizations were explicitly requested (this allows a # fallback if a future host CPU does not match 'x86*') AM_CONDITIONAL([PNG_INTEL_SSE], [test "$enable_intel_sse" != 'no' && case "$host_cpu" in i?86|x86_64) :;; *) test "$enable_intel_sse" != '';; esac]) ================================================ FILE: tess-two/jni/libpng/contrib/intel/filter_sse2_intrinsics.c ================================================ /* filter_sse2_intrinsics.c - SSE2 optimized filter functions * * Copyright (c) 2016 Google, Inc. * Written by Mike Klein and Matt Sarett * Derived from arm/filter_neon_intrinsics.c, which was * Copyright (c) 2014,2016 Glenn Randers-Pehrson * * Last changed in libpng 1.6.24 [August 4, 2016] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h */ #include "../../pngpriv.h" #ifdef PNG_READ_SUPPORTED #if PNG_INTEL_SSE_IMPLEMENTATION > 0 #include /* Functions in this file look at most 3 pixels (a,b,c) to predict the 4th (d). * They're positioned like this: * prev: c b * row: a d * The Sub filter predicts d=a, Avg d=(a+b)/2, and Paeth predicts d to be * whichever of a, b, or c is closest to p=a+b-c. */ static __m128i load4(const void* p) { return _mm_cvtsi32_si128(*(const int*)p); } static void store4(void* p, __m128i v) { *(int*)p = _mm_cvtsi128_si32(v); } static __m128i load3(const void* p) { /* We'll load 2 bytes, then 1 byte, * then mask them together, and finally load into SSE. */ const png_uint_16* p01 = p; const png_byte* p2 = (const png_byte*)(p01+1); png_uint_32 v012 = (png_uint_32)(*p01) | (png_uint_32)(*p2) << 16; return load4(&v012); } static void store3(void* p, __m128i v) { /* We'll pull from SSE as a 32-bit int, then write * its bottom two bytes, then its third byte. */ png_uint_32 v012; store4(&v012, v); png_uint_16* p01 = p; png_byte* p2 = (png_byte*)(p01+1); *p01 = v012; *p2 = v012 >> 16; } void png_read_filter_row_sub3_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Sub filter predicts each pixel as the previous pixel, a. * There is no pixel to the left of the first pixel. It's encoded directly. * That works with our main loop if we just say that left pixel was zero. */ png_debug(1, "in png_read_filter_row_sub3_sse2"); __m128i a, d = _mm_setzero_si128(); int rb = row_info->rowbytes; while (rb >= 4) { a = d; d = load4(row); d = _mm_add_epi8(d, a); store3(row, d); row += 3; rb -= 3; } if (rb > 0) { a = d; d = load3(row); d = _mm_add_epi8(d, a); store3(row, d); row += 3; rb -= 3; } } void png_read_filter_row_sub4_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Sub filter predicts each pixel as the previous pixel, a. * There is no pixel to the left of the first pixel. It's encoded directly. * That works with our main loop if we just say that left pixel was zero. */ png_debug(1, "in png_read_filter_row_sub4_sse2"); __m128i a, d = _mm_setzero_si128(); int rb = row_info->rowbytes; while (rb > 0) { a = d; d = load4(row); d = _mm_add_epi8(d, a); store4(row, d); row += 4; rb -= 4; } } void png_read_filter_row_avg3_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Avg filter predicts each pixel as the (truncated) average of a and b. * There's no pixel to the left of the first pixel. Luckily, it's * predicted to be half of the pixel above it. So again, this works * perfectly with our loop if we make sure a starts at zero. */ png_debug(1, "in png_read_filter_row_avg3_sse2"); const __m128i zero = _mm_setzero_si128(); __m128i b; __m128i a, d = zero; int rb = row_info->rowbytes; while (rb >= 4) { b = load4(prev); a = d; d = load4(row ); /* PNG requires a truncating average, so we can't just use _mm_avg_epu8 */ __m128i avg = _mm_avg_epu8(a,b); /* ...but we can fix it up by subtracting off 1 if it rounded up. */ avg = _mm_sub_epi8(avg, _mm_and_si128(_mm_xor_si128(a,b), _mm_set1_epi8(1))); d = _mm_add_epi8(d, avg); store3(row, d); prev += 3; row += 3; rb -= 3; } if (rb > 0) { b = load3(prev); a = d; d = load3(row ); /* PNG requires a truncating average, so we can't just use _mm_avg_epu8 */ __m128i avg = _mm_avg_epu8(a,b); /* ...but we can fix it up by subtracting off 1 if it rounded up. */ avg = _mm_sub_epi8(avg, _mm_and_si128(_mm_xor_si128(a,b), _mm_set1_epi8(1))); d = _mm_add_epi8(d, avg); store3(row, d); prev += 3; row += 3; rb -= 3; } } void png_read_filter_row_avg4_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Avg filter predicts each pixel as the (truncated) average of a and b. * There's no pixel to the left of the first pixel. Luckily, it's * predicted to be half of the pixel above it. So again, this works * perfectly with our loop if we make sure a starts at zero. */ png_debug(1, "in png_read_filter_row_avg4_sse2"); const __m128i zero = _mm_setzero_si128(); __m128i b; __m128i a, d = zero; int rb = row_info->rowbytes; while (rb > 0) { b = load4(prev); a = d; d = load4(row ); /* PNG requires a truncating average, so we can't just use _mm_avg_epu8 */ __m128i avg = _mm_avg_epu8(a,b); /* ...but we can fix it up by subtracting off 1 if it rounded up. */ avg = _mm_sub_epi8(avg, _mm_and_si128(_mm_xor_si128(a,b), _mm_set1_epi8(1))); d = _mm_add_epi8(d, avg); store4(row, d); prev += 4; row += 4; rb -= 4; } } /* Returns |x| for 16-bit lanes. */ static __m128i abs_i16(__m128i x) { #if PNG_INTEL_SSE_IMPLEMENTATION >= 2 return _mm_abs_epi16(x); #else /* Read this all as, return x<0 ? -x : x. * To negate two's complement, you flip all the bits then add 1. */ __m128i is_negative = _mm_cmplt_epi16(x, _mm_setzero_si128()); /* Flip negative lanes. */ x = _mm_xor_si128(x, is_negative); /* +1 to negative lanes, else +0. */ x = _mm_sub_epi16(x, is_negative); return x; #endif } /* Bytewise c ? t : e. */ static __m128i if_then_else(__m128i c, __m128i t, __m128i e) { #if PNG_INTEL_SSE_IMPLEMENTATION >= 3 return _mm_blendv_epi8(e,t,c); #else return _mm_or_si128(_mm_and_si128(c, t), _mm_andnot_si128(c, e)); #endif } void png_read_filter_row_paeth3_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* Paeth tries to predict pixel d using the pixel to the left of it, a, * and two pixels from the previous row, b and c: * prev: c b * row: a d * The Paeth function predicts d to be whichever of a, b, or c is nearest to * p=a+b-c. * * The first pixel has no left context, and so uses an Up filter, p = b. * This works naturally with our main loop's p = a+b-c if we force a and c * to zero. * Here we zero b and d, which become c and a respectively at the start of * the loop. */ png_debug(1, "in png_read_filter_row_paeth3_sse2"); const __m128i zero = _mm_setzero_si128(); __m128i c, b = zero, a, d = zero; int rb = row_info->rowbytes; while (rb >= 4) { /* It's easiest to do this math (particularly, deal with pc) with 16-bit * intermediates. */ c = b; b = _mm_unpacklo_epi8(load4(prev), zero); a = d; d = _mm_unpacklo_epi8(load4(row ), zero); /* (p-a) == (a+b-c - a) == (b-c) */ __m128i pa = _mm_sub_epi16(b,c); /* (p-b) == (a+b-c - b) == (a-c) */ __m128i pb = _mm_sub_epi16(a,c); /* (p-c) == (a+b-c - c) == (a+b-c-c) == (b-c)+(a-c) */ __m128i pc = _mm_add_epi16(pa,pb); pa = abs_i16(pa); /* |p-a| */ pb = abs_i16(pb); /* |p-b| */ pc = abs_i16(pc); /* |p-c| */ __m128i smallest = _mm_min_epi16(pc, _mm_min_epi16(pa, pb)); /* Paeth breaks ties favoring a over b over c. */ __m128i nearest = if_then_else(_mm_cmpeq_epi16(smallest, pa), a, if_then_else(_mm_cmpeq_epi16(smallest, pb), b, c)); /* Note `_epi8`: we need addition to wrap modulo 255. */ d = _mm_add_epi8(d, nearest); store3(row, _mm_packus_epi16(d,d)); prev += 3; row += 3; rb -= 3; } if (rb > 0) { /* It's easiest to do this math (particularly, deal with pc) with 16-bit * intermediates. */ c = b; b = _mm_unpacklo_epi8(load3(prev), zero); a = d; d = _mm_unpacklo_epi8(load3(row ), zero); /* (p-a) == (a+b-c - a) == (b-c) */ __m128i pa = _mm_sub_epi16(b,c); /* (p-b) == (a+b-c - b) == (a-c) */ __m128i pb = _mm_sub_epi16(a,c); /* (p-c) == (a+b-c - c) == (a+b-c-c) == (b-c)+(a-c) */ __m128i pc = _mm_add_epi16(pa,pb); pa = abs_i16(pa); /* |p-a| */ pb = abs_i16(pb); /* |p-b| */ pc = abs_i16(pc); /* |p-c| */ __m128i smallest = _mm_min_epi16(pc, _mm_min_epi16(pa, pb)); /* Paeth breaks ties favoring a over b over c. */ __m128i nearest = if_then_else(_mm_cmpeq_epi16(smallest, pa), a, if_then_else(_mm_cmpeq_epi16(smallest, pb), b, c)); /* Note `_epi8`: we need addition to wrap modulo 255. */ d = _mm_add_epi8(d, nearest); store3(row, _mm_packus_epi16(d,d)); prev += 3; row += 3; rb -= 3; } } void png_read_filter_row_paeth4_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* Paeth tries to predict pixel d using the pixel to the left of it, a, * and two pixels from the previous row, b and c: * prev: c b * row: a d * The Paeth function predicts d to be whichever of a, b, or c is nearest to * p=a+b-c. * * The first pixel has no left context, and so uses an Up filter, p = b. * This works naturally with our main loop's p = a+b-c if we force a and c * to zero. * Here we zero b and d, which become c and a respectively at the start of * the loop. */ png_debug(1, "in png_read_filter_row_paeth4_sse2"); const __m128i zero = _mm_setzero_si128(); __m128i c, b = zero, a, d = zero; int rb = row_info->rowbytes; while (rb > 0) { /* It's easiest to do this math (particularly, deal with pc) with 16-bit * intermediates. */ c = b; b = _mm_unpacklo_epi8(load4(prev), zero); a = d; d = _mm_unpacklo_epi8(load4(row ), zero); /* (p-a) == (a+b-c - a) == (b-c) */ __m128i pa = _mm_sub_epi16(b,c); /* (p-b) == (a+b-c - b) == (a-c) */ __m128i pb = _mm_sub_epi16(a,c); /* (p-c) == (a+b-c - c) == (a+b-c-c) == (b-c)+(a-c) */ __m128i pc = _mm_add_epi16(pa,pb); pa = abs_i16(pa); /* |p-a| */ pb = abs_i16(pb); /* |p-b| */ pc = abs_i16(pc); /* |p-c| */ __m128i smallest = _mm_min_epi16(pc, _mm_min_epi16(pa, pb)); /* Paeth breaks ties favoring a over b over c. */ __m128i nearest = if_then_else(_mm_cmpeq_epi16(smallest, pa), a, if_then_else(_mm_cmpeq_epi16(smallest, pb), b, c)); /* Note `_epi8`: we need addition to wrap modulo 255. */ d = _mm_add_epi8(d, nearest); store4(row, _mm_packus_epi16(d,d)); prev += 4; row += 4; rb -= 4; } } #endif /* PNG_INTEL_SSE_IMPLEMENTATION > 0 */ #endif /* READ */ ================================================ FILE: tess-two/jni/libpng/contrib/intel/intel_init.c ================================================ /* intel_init.c - SSE2 optimized filter functions * * Copyright (c) 2016 Google, Inc. * Written by Mike Klein and Matt Sarett * Derived from arm/arm_init.c, which was * Copyright (c) 2014,2016 Glenn Randers-Pehrson * * Last changed in libpng 1.6.22 [May 26, 2016] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h */ #include "../../pngpriv.h" #ifdef PNG_READ_SUPPORTED #if PNG_INTEL_SSE_IMPLEMENTATION > 0 void png_init_filter_functions_sse2(png_structp pp, unsigned int bpp) { /* The techniques used to implement each of these filters in SSE operate on * one pixel at a time. * So they generally speed up 3bpp images about 3x, 4bpp images about 4x. * They can scale up to 6 and 8 bpp images and down to 2 bpp images, * but they'd not likely have any benefit for 1bpp images. * Most of these can be implemented using only MMX and 64-bit registers, * but they end up a bit slower than using the equally-ubiquitous SSE2. */ png_debug(1, "in png_init_filter_functions_sse2"); if (bpp == 3) { pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub3_sse2; pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg3_sse2; pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth3_sse2; } else if (bpp == 4) { pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub4_sse2; pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg4_sse2; pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth4_sse2; } /* No need optimize PNG_FILTER_VALUE_UP. The compiler should * autovectorize. */ } #endif /* PNG_INTEL_SSE_IMPLEMENTATION > 0 */ #endif /* PNG_READ_SUPPORTED */ ================================================ FILE: tess-two/jni/libpng/contrib/intel/intel_sse.patch ================================================ diff --git a/configure.ac b/configure.ac --- a/configure.ac 2016-08-29 11:46:27.000000000 -0400 +++ b/configure.ac 2016-08-29 16:57:03.866355018 -0400 @@ -386,16 +386,51 @@ AC_ARG_ENABLE([mips-msa], # future host CPU does not match 'mips*') AM_CONDITIONAL([PNG_MIPS_MSA], [test "$enable_mips_msa" != 'no' && case "$host_cpu" in mipsel*|mips64el*) :;; esac]) +# INTEL +# ===== +# +# INTEL SSE (SIMD) support. + +AC_ARG_ENABLE([intel-sse], + AS_HELP_STRING([[[--enable-intel-sse]]], + [Enable Intel SSE optimizations: =no/off, yes/on:] + [no/off: disable the optimizations;] + [yes/on: enable the optimizations.] + [If not specified: determined by the compiler.]), + [case "$enableval" in + no|off) + # disable the default enabling: + AC_DEFINE([PNG_INTEL_SSE_OPT], [0], + [Disable Intel SSE optimizations]) + # Prevent inclusion of the assembler files below: + enable_intel_sse=no;; + yes|on) + AC_DEFINE([PNG_INTEL_SSE_OPT], [1], + [Enable Intel SSE optimizations]);; + *) + AC_MSG_ERROR([--enable-intel-sse=${enable_intel_sse}: invalid value]) + esac]) + +# Add Intel specific files to all builds where the host_cpu is Intel ('x86*') +# or where Intel optimizations were explicitly requested (this allows a +# fallback if a future host CPU does not match 'x86*') +AM_CONDITIONAL([PNG_INTEL_SSE], + [test "$enable_intel_sse" != 'no' && + case "$host_cpu" in + i?86|x86_64) :;; + *) test "$enable_intel_sse" != '';; + esac]) + AC_MSG_NOTICE([[Extra options for compiler: $PNG_COPTS]]) # Config files, substituting as above AC_CONFIG_FILES([Makefile libpng.pc:libpng.pc.in]) AC_CONFIG_FILES([libpng-config:libpng-config.in], [chmod +x libpng-config]) AC_OUTPUT diff --git a/Makefile.am b/Makefile.am --- a/Makefile.am 2016-08-29 11:46:27.000000000 -0400 +++ b/Makefile.am 2016-08-29 16:57:45.955528215 -0400 @@ -97,16 +97,21 @@ libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SO arm/filter_neon.S arm/filter_neon_intrinsics.c endif if PNG_MIPS_MSA libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES += mips/mips_init.c\ mips/filter_msa_intrinsics.c endif +if PNG_INTEL_SSE +libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES += contrib/intel/intel_init.c\ + contrib/intel/filter_sse2_intrinsics.c +endif + nodist_libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_SOURCES = pnglibconf.h libpng@PNGLIB_MAJOR@@PNGLIB_MINOR@_la_LDFLAGS = -no-undefined -export-dynamic \ -version-number @PNGLIB_MAJOR@@PNGLIB_MINOR@:@PNGLIB_RELEASE@:0 if HAVE_LD_VERSION_SCRIPT # Versioned symbols and restricted exports if HAVE_SOLARIS_LD diff --git a/pngpriv.h b/pngpriv.h --- debug16/pngpriv.h 2016-08-30 10:46:36.000000000 -0400 +++ libpng16/pngpriv.h 2016-08-30 11:57:25.672280202 -0400 @@ -185,16 +185,52 @@ #ifndef PNG_MIPS_MSA_OPT # if defined(__mips_msa) && (__mips_isa_rev >= 5) && defined(PNG_ALIGNED_MEMORY_SUPPORTED) # define PNG_MIPS_MSA_OPT 2 # else # define PNG_MIPS_MSA_OPT 0 # endif #endif +#ifndef PNG_INTEL_SSE_OPT +# ifdef PNG_INTEL_SSE + /* Only check for SSE if the build configuration has been modified to + * enable SSE optimizations. This means that these optimizations will + * be off by default. See contrib/intel for more details. + */ +# if defined(__SSE4_1__) || defined(__AVX__) || defined(__SSSE3__) || \ + defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) || \ + (defined(_M_IX86_FP) && _M_IX86_FP >= 2) +# define PNG_INTEL_SSE_OPT 1 +# endif +# endif +#endif + +#if PNG_INTEL_SSE_OPT > 0 +# ifndef PNG_INTEL_SSE_IMPLEMENTATION +# if defined(__SSE4_1__) || defined(__AVX__) + /* We are not actually using AVX, but checking for AVX is the best + way we can detect SSE4.1 and SSSE3 on MSVC. + */ +# define PNG_INTEL_SSE_IMPLEMENTATION 3 +# elif defined(__SSSE3__) +# define PNG_INTEL_SSE_IMPLEMENTATION 2 +# elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) || \ + (defined(_M_IX86_FP) && _M_IX86_FP >= 2) +# define PNG_INTEL_SSE_IMPLEMENTATION 1 +# else +# define PNG_INTEL_SSE_IMPLEMENTATION 0 +# endif +# endif + +# if PNG_INTEL_SSE_IMPLEMENTATION > 0 +# define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_sse2 +# endif +#endif + #if PNG_MIPS_MSA_OPT > 0 # define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_msa # ifndef PNG_MIPS_MSA_IMPLEMENTATION # if defined(__mips_msa) # if defined(__clang__) # elif defined(__GNUC__) # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7) # define PNG_MIPS_MSA_IMPLEMENTATION 2 @@ -1232,16 +1268,31 @@ PNG_INTERNAL_FUNCTION(void,png_read_filt PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg4_msa,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth3_msa,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_msa,(png_row_infop row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); #endif +#if PNG_INTEL_SSE_IMPLEMENTATION > 0 +PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub3_sse2,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); +PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub4_sse2,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); +PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg3_sse2,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); +PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg4_sse2,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); +PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth3_sse2,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); +PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_sse2,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); +#endif + /* Choose the best filter to use and filter the row data */ PNG_INTERNAL_FUNCTION(void,png_write_find_filter,(png_structrp png_ptr, png_row_infop row_info),PNG_EMPTY); #ifdef PNG_SEQUENTIAL_READ_SUPPORTED PNG_INTERNAL_FUNCTION(void,png_read_IDAT_data,(png_structrp png_ptr, png_bytep output, png_alloc_size_t avail_out),PNG_EMPTY); /* Read 'avail_out' bytes of data from the IDAT stream. If the output buffer @@ -1967,16 +2018,21 @@ PNG_INTERNAL_FUNCTION(void, PNG_FILTER_O PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_neon, (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); #endif #if PNG_MIPS_MSA_OPT > 0 PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_msa, (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); #endif + +# if PNG_INTEL_SSE_IMPLEMENTATION > 0 +PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_sse2, + (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); +# endif #endif PNG_INTERNAL_FUNCTION(png_uint_32, png_check_keyword, (png_structrp png_ptr, png_const_charp key, png_bytep new_key), PNG_EMPTY); /* Maintainer: Put new private prototypes here ^ */ #include "pngdebug.h" ================================================ FILE: tess-two/jni/libpng/contrib/libtests/fakepng.c ================================================ /* Fake a PNG - just write it out directly. * * COPYRIGHT: Written by John Cunningham Bowler, 2014. * To the extent possible under law, the author has waived all copyright and * related or neighboring rights to this work. This work is published from: * United States. * */ #include #include /* for crc32 */ void put_uLong(uLong val) { putchar(val >> 24); putchar(val >> 16); putchar(val >> 8); putchar(val >> 0); } void put_chunk(const unsigned char *chunk, uInt length) { uLong crc; put_uLong(length-4); /* Exclude the tag */ fwrite(chunk, length, 1, stdout); crc = crc32(0, Z_NULL, 0); put_uLong(crc32(crc, chunk, length)); } const unsigned char signature[] = { 137, 80, 78, 71, 13, 10, 26, 10 }; const unsigned char IHDR[] = { 73, 72, 68, 82, /* IHDR */ 0, 0, 0, 1, /* width */ 0, 0, 0, 1, /* height */ 1, /* bit depth */ 0, /* color type: greyscale */ 0, /* compression method */ 0, /* filter method */ 0 /* interlace method: none */ }; const unsigned char unknown[] = { 'u', 'n', 'K', 'n' /* "unKn" - private safe to copy */ }; int main(void) { fwrite(signature, sizeof signature, 1, stdout); put_chunk(IHDR, sizeof IHDR); for (;;) put_chunk(unknown, sizeof unknown); } ================================================ FILE: tess-two/jni/libpng/contrib/libtests/gentests.sh ================================================ #!/bin/sh # # Copyright (c) 2013 John Cunningham Bowler # # Last changed in libpng 1.6.0 [February 14, 2013] # # This code is released under the libpng license. # For conditions of distribution and use, see the disclaimer # and license in png.h # # Generate a set of PNG test images. The images are generated in a # sub-directory called 'tests' by default, however a command line argument will # change that name. The generation requires a built version of makepng in the # current directory. # usage(){ exec >&2 echo "$0 []" echo ' Generate a set of PNG test files in "directory" ("tests" by default)' exit 1 } mp="$PWD/makepng" test -x "$mp" || { exec >&2 echo "$0: the 'makepng' program must exist" echo " in the directory within which this program:" echo " $mp" echo " is executed" usage } # Just one argument: the directory testdir="tests" test $# -gt 1 && { testdir="$1" shift } test $# -eq 0 || usage # Take care not to clobber something if test -e "$testdir" then test -d "$testdir" || usage else # mkdir -p isn't portable, so do the following mkdir "$testdir" 2>/dev/null || mkdir -p "$testdir" || usage fi # This fails in a very satisfactory way if it's not accessible cd "$testdir" :>"test$$.png" || { exec >&2 echo "$testdir: directory not writable" usage } rm "test$$.png" || { exec >&2 echo "$testdir: you have create but not write privileges here." echo " This is unexpected. You have a spurion; "'"'"test$$.png"'"'"." echo " You need to remove this yourself. Try a different directory." exit 1 } # Now call makepng ($mp) to create every file we can think of with a # reasonable name doit(){ for gamma in "" --sRGB --linear --1.8 do case "$gamma" in "") gname=;; --sRGB) gname="-srgb";; --linear) gname="-lin";; --1.8) gname="-18";; *) gname="-$gamma";; esac "$mp" $gamma "$1" "$2" "test-$1-$2$gname.png" done } # for ct in gray palette do for bd in 1 2 4 8 do doit "$ct" "$bd" done done # doit "gray" "16" # for ct in gray-alpha rgb rgb-alpha do for bd in 8 16 do doit "$ct" "$bd" done done ================================================ FILE: tess-two/jni/libpng/contrib/libtests/makepng.c ================================================ /* makepng.c */ #define _ISOC99_SOURCE /* Copyright: */ #define COPYRIGHT "\251 2013,2015 John Cunningham Bowler" /* * Last changed in libpng 1.6.20 [November 24, 2015] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * Make a test PNG image. The arguments are as follows: * * makepng [--sRGB|--linear|--1.8] [--tRNS] [--nofilters] \ * color-type bit-depth [file-name] * * The color-type may be numeric (and must match the numbers used by the PNG * specification) or one of the format names listed below. The bit-depth is the * component bit depth, or the pixel bit-depth for a color-mapped image. * * Without any options no color-space information is written, with the options * an sRGB or the appropriate gAMA chunk is written. "1.8" refers to the * display system used on older Apple computers to correct for high ambient * light levels in the viewing environment; it applies a transform of * approximately value^(1/1.45) to the color values and so a gAMA chunk of 65909 * is written (1.45/2.2). * * The image data is generated internally. Unless --color is given the images * used are as follows: * * 1 channel: a square image with a diamond, the least luminous colors are on * the edge of the image, the most luminous in the center. * * 2 channels: the color channel increases in luminosity from top to bottom, the * alpha channel increases in opacity from left to right. * * 3 channels: linear combinations of, from the top-left corner clockwise, * black, green, white, red. * * 4 channels: linear combinations of, from the top-left corner clockwise, * transparent, red, green, blue. * * For color-mapped images a four channel color-map is used and if --tRNS is * given the PNG file has a tRNS chunk, as follows: * * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white * 2-bit: entry 0: transparent-green * entry 1: 40%-red * entry 2: 80%-blue * entry 3: opaque-white * 4-bit: the 16 combinations of the 2-bit case * 8-bit: the 256 combinations of the 4-bit case * * The palette always has 2^bit-depth entries and the tRNS chunk one fewer. The * image is the 1-channel diamond, but using palette index, not luminosity. * * For formats other than color-mapped ones if --tRNS is specified a tRNS chunk * is generated with all channels equal to the low bits of 0x0101. * * Image size is determined by the final pixel depth in bits, i.e. channels x * bit-depth, as follows: * * 8 bits or less: 64x64 * 16 bits: 256x256 * More than 16 bits: 1024x1024 * * Row filtering is the libpng default but may be turned off (the 'none' filter * is used on every row) with the --nofilters option. * * The images are not interlaced. * * If file-name is given then the PNG is written to that file, else it is * written to stdout. Notice that stdout is not supported on systems where, by * default, it assumes text output; this program makes no attempt to change the * text mode of stdout! * * makepng --color= ... * * If --color is given then the whole image has that color, color-mapped images * will have exactly one palette entry and all image files with be 16x16 in * size. The color value is 1 to 4 decimal numbers as appropriate for the color * type. * * makepng --small ... * * If --small is given the images are no larger than required to include every * possible pixel value for the format. * * For formats with pixels 8 bits or fewer in size the images consist of a * single row with 2^pixel-depth pixels, one of every possible value. * * For formats with 16-bit pixels a 256x256 image is generated containing every * possible pixel value. * * For larger pixel sizes a 256x256 image is generated where the first row * consists of each pixel that has identical byte values throughout the pixel * followed by rows where the byte values differ within the pixel. * * In all cases the pixel values are arranged in such a way that the SUB and UP * filters give byte sequences for maximal zlib compression. By default (if * --nofilters is not given) the SUB filter is used on the first row and the UP * filter on all following rows. * * The --small option is meant to provide good test-case coverage, however the * images are not easy to examine visually. Without the --small option the * images contain identical color values; the pixel values are adjusted * according to the gamma encoding with no gamma encoding being interpreted as * sRGB. * * LICENSING * ========= * * This code is copyright of the authors, see the COPYRIGHT define above. The * code is licensed as above, using the libpng license. The code generates * images which are solely the product of the code; the options choose which of * the many possibilities to generate. The images that result (but not the code * which generates them) are licensed as defined here: * * IMPORTANT: the COPYRIGHT #define must contain ISO-Latin-1 characters, the * IMAGE_LICENSING #define must contain UTF-8 characters. The 'copyright' * symbol 0xA9U (\251) in ISO-Latin-1 encoding and 0xC20xA9 (\302\251) in UTF-8. */ #define IMAGE_LICENSING "Dedicated to the public domain per Creative Commons "\ "license \"CC0 1.0\"; https://creativecommons.org/publicdomain/zero/1.0/" #include /* for offsetof */ #include #include #include #include #include #include #include #include #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H) # include #endif /* Define the following to use this test against your installed libpng, rather * than the one being built here: */ #ifdef PNG_FREESTANDING_TESTS # include #else # include "../../png.h" #endif #include /* Work round for GCC complaints about casting a (double) function result to * an unsigned: */ static unsigned int flooru(double d) { d = floor(d); return (unsigned int)d; } static png_byte floorb(double d) { d = floor(d); return (png_byte)d; } /* This structure is used for inserting extra chunks (the --insert argument, not * documented above.) */ typedef struct chunk_insert { struct chunk_insert *next; void (*insert)(png_structp, png_infop, int, png_charpp); int nparams; png_charp parameters[1]; } chunk_insert; static unsigned int channels_of_type(int color_type) { if (color_type & PNG_COLOR_MASK_PALETTE) return 1; else { int channels = 1; if (color_type & PNG_COLOR_MASK_COLOR) channels = 3; if (color_type & PNG_COLOR_MASK_ALPHA) return channels + 1; else return channels; } } static unsigned int pixel_depth_of_type(int color_type, int bit_depth) { return channels_of_type(color_type) * bit_depth; } static unsigned int image_size_of_type(int color_type, int bit_depth, unsigned int *colors, int small) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (small) { if (pixel_depth <= 8) /* there will be one row */ return 1 << pixel_depth; else return 256; } else if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } } static void set_color(png_colorp color, png_bytep trans, unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha, png_const_bytep gamma_table) { color->red = gamma_table[red]; color->green = gamma_table[green]; color->blue = gamma_table[blue]; *trans = (png_byte)alpha; } static int generate_palette(png_colorp palette, png_bytep trans, int bit_depth, png_const_bytep gamma_table, unsigned int *colors) { /* * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white * 2-bit: entry 0: transparent-green * entry 1: 40%-red * entry 2: 80%-blue * entry 3: opaque-white * 4-bit: the 16 combinations of the 2-bit case * 8-bit: the 256 combinations of the 4-bit case */ switch (colors[0]) { default: fprintf(stderr, "makepng: --colors=...: invalid count %u\n", colors[0]); exit(1); case 1: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255, gamma_table); return 1; case 2: set_color(palette+0, trans+0, colors[1], colors[1], colors[1], colors[2], gamma_table); return 1; case 3: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255, gamma_table); return 1; case 4: set_color(palette+0, trans+0, colors[1], colors[2], colors[3], colors[4], gamma_table); return 1; case 0: if (bit_depth == 1) { set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table); set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table); return 2; } else { unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */ unsigned int x, y; volatile unsigned int ip = 0; for (x=0; x> 3; if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes)) { row += offset; switch (bit_depth) { case 1: case 2: case 4: /* Don't gamma correct - values get smashed */ { unsigned int shift = (8 - bit_depth) - (x & 0x7U); mask <<= shift; value = (value << shift) & mask; *row = (png_byte)((*row & ~mask) | value); } return; default: fprintf(stderr, "makepng: bad bit depth (internal error)\n"); exit(1); case 16: value = flooru(65535*pow(value/65535.,conv)+.5); *row++ = (png_byte)(value >> 8); *row = (png_byte)value; return; case 8: *row = gamma_table[value]; return; } } else { fprintf(stderr, "makepng: row buffer overflow (internal error)\n"); exit(1); } } else { fprintf(stderr, "makepng: component overflow (internal error)\n"); exit(1); } } static int /* filter mask for row */ generate_row(png_bytep row, size_t rowbytes, unsigned int y, int color_type, int bit_depth, png_const_bytep gamma_table, double conv, unsigned int *colors, int small) { int filters = 0; /* file *MASK*, 0 means the default, not NONE */ png_uint_32 size_max = image_size_of_type(color_type, bit_depth, colors, small)-1; png_uint_32 depth_max = (1U << bit_depth)-1; /* up to 65536 */ if (colors[0] == 0) if (small) { unsigned int pixel_depth = pixel_depth_of_type(color_type, bit_depth); /* For pixel depths less than 16 generate a single row containing all the * possible pixel values. For 16 generate all 65536 byte pair * combinations in a 256x256 pixel array. */ switch (pixel_depth) { case 1: assert(y == 0 && rowbytes == 1 && size_max == 1); row[0] = 0x6CU; /* binary: 01101100, only top 2 bits used */ filters = PNG_FILTER_NONE; break; case 2: assert(y == 0 && rowbytes == 1 && size_max == 3); row[0] = 0x1BU; /* binary 00011011, all bits used */ filters = PNG_FILTER_NONE; break; case 4: assert(y == 0 && rowbytes == 8 && size_max == 15); row[0] = 0x01U; row[1] = 0x23U; /* SUB gives 0x22U for all following bytes */ row[2] = 0x45U; row[3] = 0x67U; row[4] = 0x89U; row[5] = 0xABU; row[6] = 0xCDU; row[7] = 0xEFU; filters = PNG_FILTER_SUB; break; case 8: /* The row will have all the pixel values in order starting with * '1', the SUB filter will change every byte into '1' (including * the last, which generates pixel value '0'). Since the SUB filter * has value 1 this should result in maximum compression. */ assert(y == 0 && rowbytes == 256 && size_max == 255); for (;;) { row[size_max] = 0xFFU & (size_max+1); if (size_max == 0) break; --size_max; } filters = PNG_FILTER_SUB; break; case 16: /* Rows are generated such that each row has a constant difference * between the first and second byte of each pixel and so that the * difference increases by 1 at each row. The rows start with the * first byte value of 0 and the value increases to 255 across the * row. * * The difference starts at 1, so the first row is: * * 0 1 1 2 2 3 3 4 ... 254 255 255 0 * * This means that running the SUB filter on the first row produces: * * [SUB==1] 0 1 0 1 0 1... * * Then the difference is 2 on the next row, giving: * * 0 2 1 3 2 4 3 5 ... 254 0 255 1 * * When the UP filter is run on this libpng produces: * * [UP ==2] 0 1 0 1 0 1... * * And so on for all the remain rows to the final two * rows: * * row 254: 0 255 1 0 2 1 3 2 4 3 ... 254 253 255 254 * row 255: 0 0 1 1 2 2 3 3 4 4 ... 254 254 255 255 */ assert(rowbytes == 512 && size_max == 255); for (;;) { row[2*size_max ] = 0xFFU & size_max; row[2*size_max+1] = 0xFFU & (size_max+y+1); if (size_max == 0) break; --size_max; } /* The first row must include PNG_FILTER_UP so that libpng knows we * need to keep it for the following row: */ filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP); break; case 24: case 32: case 48: case 64: /* The rows are filled by an alogorithm similar to the above, in the * first row pixel bytes are all equal, increasing from 0 by 1 for * each pixel. In the second row the bytes within a pixel are * incremented 1,3,5,7,... from the previous row byte. Using an odd * number ensures all the possible byte values are used. */ assert(size_max == 255 && rowbytes == 256*(pixel_depth>>3)); pixel_depth >>= 3; /* now in bytes */ while (rowbytes > 0) { const size_t pixel_index = --rowbytes/pixel_depth; if (y == 0) row[rowbytes] = 0xFFU & pixel_index; else { const size_t byte_offset = rowbytes - pixel_index * pixel_depth; row[rowbytes] = 0xFFU & (pixel_index + (byte_offset * 2*y) + 1); } } filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP); break; default: assert(0/*NOT REACHED*/); } } else switch (channels_of_type(color_type)) { /* 1 channel: a square image with a diamond, the least luminous colors are on * the edge of the image, the most luminous in the center. */ case 1: { png_uint_32 x; png_uint_32 base = 2*size_max - abs(2*y-size_max); for (x=0; x<=size_max; ++x) { png_uint_32 luma = base - abs(2*x-size_max); /* 'luma' is now in the range 0..2*size_max, we need * 0..depth_max */ luma = (luma*depth_max + size_max) / (2*size_max); set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv); } } break; /* 2 channels: the color channel increases in luminosity from top to bottom, * the alpha channel increases in opacity from left to right. */ case 2: { png_uint_32 alpha = (depth_max * y * 2 + size_max) / (2 * size_max); png_uint_32 x; for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 2*x, bit_depth, (depth_max * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table, conv); } } break; /* 3 channels: linear combinations of, from the top-left corner clockwise, * black, green, white, red. */ case 3: { /* x0: the black->red scale (the value of the red component) at the * start of the row (blue and green are 0). * x1: the green->white scale (the value of the red and blue * components at the end of the row; green is depth_max). */ png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max); png_uint_32 x; /* Interpolate x/depth_max from start to end: * * start end difference * red: Y Y 0 * green: 0 depth_max depth_max * blue: 0 Y Y */ for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 3*x+0, bit_depth, /* red */ Y, gamma_table, conv); set_value(row, rowbytes, 3*x+1, bit_depth, /* green */ (depth_max * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 3*x+2, bit_depth, /* blue */ (Y * x * 2 + size_max) / (2 * size_max), gamma_table, conv); } } break; /* 4 channels: linear combinations of, from the top-left corner clockwise, * transparent, red, green, blue. */ case 4: { /* x0: the transparent->blue scale (the value of the blue and alpha * components) at the start of the row (red and green are 0). * x1: the red->green scale (the value of the red and green * components at the end of the row; blue is 0 and alpha is * depth_max). */ png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max); png_uint_32 x; /* Interpolate x/depth_max from start to end: * * start end difference * red: 0 depth_max-Y depth_max-Y * green: 0 Y Y * blue: Y 0 -Y * alpha: Y depth_max depth_max-Y */ for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 4*x+0, bit_depth, /* red */ ((depth_max-Y) * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 4*x+1, bit_depth, /* green */ (Y * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 4*x+2, bit_depth, /* blue */ Y - (Y * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 4*x+3, bit_depth, /* alpha */ Y + ((depth_max-Y) * x * 2 + size_max) / (2 * size_max), gamma_table, conv); } } break; default: fprintf(stderr, "makepng: internal bad channel count\n"); exit(2); } else if (color_type & PNG_COLOR_MASK_PALETTE) { /* Palette with fixed color: the image rows are all 0 and the image width * is 16. */ memset(row, 0, rowbytes); } else if (colors[0] == channels_of_type(color_type)) switch (channels_of_type(color_type)) { case 1: { const png_uint_32 luma = colors[1]; png_uint_32 x; for (x=0; x<=size_max; ++x) set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv); } break; case 2: { const png_uint_32 luma = colors[1]; const png_uint_32 alpha = colors[2]; png_uint_32 x; for (x=0; x 0 && gamma < 1000) gamma = PNG_FP_1; if (gamma > 0) real_gamma = gamma; { unsigned int i; if (real_gamma == 45455) for (i=0; i<256; ++i) { gamma_table[i] = (png_byte)i; conv = 1.; } else { /* Convert 'i' from sRGB (45455) to real_gamma, this makes * the images look the same regardless of the gAMA chunk. */ conv = real_gamma; conv /= 45455; gamma_table[0] = 0; for (i=1; i<255; ++i) gamma_table[i] = floorb(pow(i/255.,conv) * 255 + .5); gamma_table[255] = 255; } } png_set_IHDR(png_ptr, info_ptr, size, ysize, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); if (color_type & PNG_COLOR_MASK_PALETTE) { int npalette; png_color palette[256]; png_byte trans[256]; npalette = generate_palette(palette, trans, bit_depth, gamma_table, colors); png_set_PLTE(png_ptr, info_ptr, palette, npalette); if (tRNS) png_set_tRNS(png_ptr, info_ptr, trans, npalette-1, NULL/*transparent color*/); /* Reset gamma_table to prevent the image rows being changed */ for (npalette=0; npalette<256; ++npalette) gamma_table[npalette] = (png_byte)npalette; } else if (tRNS) { png_color_16 col; col.red = col.green = col.blue = col.gray = 0x0101U & ((1U< 0) /* Else don't set color space information */ { png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma); /* Just use the sRGB values here. */ png_set_cHRM_fixed(png_ptr, info_ptr, /* color x y */ /* white */ 31270, 32900, /* red */ 64000, 33000, /* green */ 30000, 60000, /* blue */ 15000, 6000 ); } /* Insert extra information. */ while (insert != NULL) { insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters); insert = insert->next; } /* Write the file header. */ png_write_info(png_ptr, info_ptr); /* Restrict the filters */ png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters); { # ifdef PNG_WRITE_INTERLACING_SUPPORTED int passes = png_set_interlace_handling(png_ptr); # else /* !WRITE_INTERLACING */ int passes = 1; # endif /* !WRITE_INTERLACING */ int pass; png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = malloc(rowbytes); if (row == NULL) png_error(png_ptr, "OOM allocating row buffer"); for (pass = 0; pass < passes; ++pass) { unsigned int y; for (y=0; y 0) { /* Round up to a multiple of 4 here to allow an iCCP profile * to be padded to a 4x boundary. */ png_bytep data = malloc((total+3)&~3); if (data != NULL) { size_t new_size = 0; for (;;) { ch = getc(fp); if (ch == EOF) break; data[new_size++] = (png_byte)ch; } if (ferror(fp) || new_size != total) { perror("temporary file"); fprintf(stderr, "temporary file read error\n"); free(data); } else { (void)fclose(fp); *result = data; return total; } } else fprintf(stderr, "%s: out of memory loading file\n", name); } else fprintf(stderr, "%s: empty file\n", name); } } } else { perror(name); fprintf(stderr, "%s: open failed\n", name); } fclose(fp); } else fprintf(stderr, "makepng: %s: could not open temporary file\n", name); exit(1); return 0; } static png_size_t load_fake(png_charp param, png_bytepp profile) { char *endptr = NULL; uint64_t size = strtoull(param, &endptr, 0/*base*/); /* The 'fake' format is *[string] */ if (endptr != NULL && *endptr == '*') { size_t len = strlen(++endptr); size_t result = (size_t)size; if (len == 0) len = 1; /* capture the terminating '\0' */ /* Now repeat that string to fill 'size' bytes. */ if (result == size && (*profile = malloc(result)) != NULL) { png_bytep out = *profile; if (len == 1) memset(out, *endptr, result); else { while (size >= len) { memcpy(out, endptr, len); out += len; size -= len; } memcpy(out, endptr, size); } return result; } else { fprintf(stderr, "%s: size exceeds system limits\n", param); exit(1); } } return 0; } static void check_param_count(int nparams, int expect) { if (nparams != expect) { fprintf(stderr, "bad parameter count (internal error)\n"); exit(1); } } static void insert_iCCP(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { png_bytep profile = NULL; png_uint_32 proflen = 0; int result; check_param_count(nparams, 2); switch (params[1][0]) { case '<': { png_size_t filelen = load_file(params[1]+1, &profile); if (filelen > 0xfffffffc) /* Maximum profile length */ { fprintf(stderr, "%s: file too long (%lu) for an ICC profile\n", params[1]+1, (unsigned long)filelen); exit(1); } proflen = (png_uint_32)filelen; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { png_size_t fake_len = load_fake(params[1], &profile); if (fake_len > 0) /* else a simple parameter */ { if (fake_len > 0xffffffff) /* Maximum profile length */ { fprintf(stderr, "%s: fake data too long (%lu) for an ICC profile\n", params[1], (unsigned long)fake_len); exit(1); } proflen = (png_uint_32)(fake_len & ~3U); /* Always fix up the profile length. */ png_save_uint_32(profile, proflen); break; } } default: fprintf(stderr, "--insert iCCP \"%s\": unrecognized\n", params[1]); fprintf(stderr, " use '<' to read a file: \" 3) { png_uint_32 prof_header = png_get_uint_32(profile); if (prof_header != proflen) { fprintf(stderr, "--insert iCCP %s: profile length field wrong:\n", params[1]); fprintf(stderr, " actual %lu, recorded value %lu (corrected)\n", (unsigned long)proflen, (unsigned long)prof_header); png_save_uint_32(profile, proflen); } } if (result && profile != NULL && proflen >=4) png_set_iCCP(png_ptr, info_ptr, params[0], PNG_COMPRESSION_TYPE_BASE, profile, proflen); if (profile) free(profile); if (!result) exit(1); } static void clear_text(png_text *text, png_charp keyword) { text->compression = -1; /* none */ text->key = keyword; text->text = NULL; text->text_length = 0; /* libpng calculates this */ text->itxt_length = 0; /* libpng calculates this */ text->lang = NULL; text->lang_key = NULL; } static void set_text(png_structp png_ptr, png_infop info_ptr, png_textp text, png_charp param) { switch (param[0]) { case '<': { png_bytep file = NULL; text->text_length = load_file(param+1, &file); text->text = (png_charp)file; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { png_bytep data = NULL; png_size_t fake_len = load_fake(param, &data); if (fake_len > 0) /* else a simple parameter */ { text->text_length = fake_len; text->text = (png_charp)data; break; } } default: text->text = param; break; } png_set_text(png_ptr, info_ptr, text, 1); if (text->text != param) free(text->text); } static void insert_tEXt(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { png_text text; check_param_count(nparams, 2); clear_text(&text, params[0]); set_text(png_ptr, info_ptr, &text, params[1]); } static void insert_zTXt(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { png_text text; check_param_count(nparams, 2); clear_text(&text, params[0]); text.compression = 0; /* deflate */ set_text(png_ptr, info_ptr, &text, params[1]); } static void insert_iTXt(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { png_text text; check_param_count(nparams, 4); clear_text(&text, params[0]); text.compression = 2; /* iTXt + deflate */ text.lang = params[1];/* language tag */ text.lang_key = params[2]; /* translated keyword */ set_text(png_ptr, info_ptr, &text, params[3]); } static void insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { int i; png_uint_16 freq[256]; /* libpng takes the count from the PLTE count; we don't check it here but we * do set the array to 0 for unspecified entries. */ memset(freq, 0, sizeof freq); for (i=0; inext = NULL; cip->insert = insert; cip->nparams = nparams; for (i=0; iparameters[i] = list[i]; return cip; } static chunk_insert * find_insert(png_const_charp what, png_charp param) { png_uint_32 chunk = 0; png_charp parameter_list[1024]; int i, nparams; /* Assemble the chunk name */ for (i=0; i<4; ++i) { char ch = what[i]; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) chunk = (chunk << 8) + what[i]; else break; } if (i < 4 || what[4] != 0) { fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what); exit(1); } /* Assemble the parameter list. */ nparams = find_parameters(what, param, parameter_list, 1024); # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) switch (chunk) { case CHUNK(105,67,67,80): /* iCCP */ if (nparams == 2) return make_insert(what, insert_iCCP, nparams, parameter_list); break; case CHUNK(116,69,88,116): /* tEXt */ if (nparams == 2) return make_insert(what, insert_tEXt, nparams, parameter_list); break; case CHUNK(122,84,88,116): /* zTXt */ if (nparams == 2) return make_insert(what, insert_zTXt, nparams, parameter_list); break; case CHUNK(105,84,88,116): /* iTXt */ if (nparams == 4) return make_insert(what, insert_iTXt, nparams, parameter_list); break; case CHUNK(104,73,83,84): /* hIST */ if (nparams <= 256) return make_insert(what, insert_hIST, nparams, parameter_list); break; case CHUNK(115,66,73,84): /* sBIT */ if (nparams <= 4) return make_insert(what, insert_sBIT, nparams, parameter_list); break; #if 0 case CHUNK(115,80,76,84): /* sPLT */ return make_insert(what, insert_sPLT, nparams, parameter_list); #endif default: fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n", what); exit(1); } bad_parameter_count(what, nparams); return NULL; } /* This is necessary because libpng expects writeable strings for things like * text chunks (maybe this should be fixed...) */ static png_charp strstash(png_const_charp foo) { /* The program indicates a memory allocation error by crashing, this is by * design. */ if (foo != NULL) { png_charp bar = malloc(strlen(foo)+1); return strcpy(bar, foo); } return NULL; } static png_charp strstash_list(const png_const_charp *text) { size_t foo = 0; png_charp result, bar; const png_const_charp *line = text; while (*line != NULL) foo += strlen(*line++); result = bar = malloc(foo+1); line = text; while (*line != NULL) { foo = strlen(*line); memcpy(bar, *line++, foo); bar += foo; } *bar = 0; return result; } /* These are used to insert Copyright and Licence fields, they allow the text to * have \n unlike the --insert option. */ static chunk_insert * add_tEXt(const char *key, const png_const_charp *text) { static char what[5] = { 116, 69, 88, 116, 0 }; png_charp parameter_list[3]; parameter_list[0] = strstash(key); parameter_list[1] = strstash_list(text); parameter_list[2] = NULL; return make_insert(what, insert_tEXt, 2, parameter_list); } static chunk_insert * add_iTXt(const char *key, const char *language, const char *language_key, const png_const_charp *text) { static char what[5] = { 105, 84, 88, 116, 0 }; png_charp parameter_list[5]; parameter_list[0] = strstash(key); parameter_list[1] = strstash(language); parameter_list[2] = strstash(language_key); parameter_list[3] = strstash_list(text); parameter_list[4] = NULL; return make_insert(what, insert_iTXt, 4, parameter_list); } /* This is a not-very-good parser for a sequence of numbers (including 0). It * doesn't accept some apparently valid things, but it accepts all the sensible * combinations. */ static void parse_color(char *arg, unsigned int *colors) { unsigned int ncolors = 0; while (*arg && ncolors < 4) { char *ep = arg; unsigned long ul = strtoul(arg, &ep, 0); if (ul > 65535) { fprintf(stderr, "makepng --color=...'%s': too big\n", arg); exit(1); } if (ep == arg) { fprintf(stderr, "makepng --color=...'%s': not a valid color\n", arg); exit(1); } if (*ep) ++ep; /* skip a separator */ arg = ep; colors[++ncolors] = (unsigned int)ul; /* checked above */ } if (*arg) { fprintf(stderr, "makepng --color=...'%s': too many values\n", arg); exit(1); } *colors = ncolors; } int main(int argc, char **argv) { FILE *fp = stdout; const char *file_name = NULL; int color_type = 8; /* invalid */ int bit_depth = 32; /* invalid */ int small = 0; /* make full size images */ int tRNS = 0; /* don't output a tRNS chunk */ unsigned int colors[5]; unsigned int filters = PNG_ALL_FILTERS; png_fixed_point gamma = 0; /* not set */ chunk_insert *head_insert = NULL; chunk_insert **insert_ptr = &head_insert; memset(colors, 0, sizeof colors); while (--argc > 0) { char *arg = *++argv; if (strcmp(arg, "--small") == 0) { small = 1; continue; } if (strcmp(arg, "--tRNS") == 0) { tRNS = 1; continue; } if (strcmp(arg, "--sRGB") == 0) { gamma = PNG_DEFAULT_sRGB; continue; } if (strcmp(arg, "--linear") == 0) { gamma = PNG_FP_1; continue; } if (strcmp(arg, "--1.8") == 0) { gamma = PNG_GAMMA_MAC_18; continue; } if (strcmp(arg, "--nofilters") == 0) { filters = PNG_FILTER_NONE; continue; } if (strncmp(arg, "--color=", 8) == 0) { parse_color(arg+8, colors); continue; } if (argc >= 3 && strcmp(arg, "--insert") == 0) { png_const_charp what = *++argv; png_charp param = *++argv; chunk_insert *new_insert; argc -= 2; new_insert = find_insert(what, param); if (new_insert != NULL) { *insert_ptr = new_insert; insert_ptr = &new_insert->next; } continue; } if (arg[0] == '-') { fprintf(stderr, "makepng: %s: invalid option\n", arg); exit(1); } if (strcmp(arg, "palette") == 0) { color_type = PNG_COLOR_TYPE_PALETTE; continue; } if (strncmp(arg, "gray", 4) == 0) { if (arg[4] == 0) { color_type = PNG_COLOR_TYPE_GRAY; continue; } else if (strcmp(arg+4, "a") == 0 || strcmp(arg+4, "alpha") == 0 || strcmp(arg+4, "-alpha") == 0) { color_type = PNG_COLOR_TYPE_GRAY_ALPHA; continue; } } if (strncmp(arg, "rgb", 3) == 0) { if (arg[3] == 0) { color_type = PNG_COLOR_TYPE_RGB; continue; } else if (strcmp(arg+3, "a") == 0 || strcmp(arg+3, "alpha") == 0 || strcmp(arg+3, "-alpha") == 0) { color_type = PNG_COLOR_TYPE_RGB_ALPHA; continue; } } if (color_type == 8 && isdigit(arg[0])) { color_type = atoi(arg); if (color_type < 0 || color_type > 6 || color_type == 1 || color_type == 5) { fprintf(stderr, "makepng: %s: not a valid color type\n", arg); exit(1); } continue; } if (bit_depth == 32 && isdigit(arg[0])) { bit_depth = atoi(arg); if (bit_depth <= 0 || bit_depth > 16 || (bit_depth & -bit_depth) != bit_depth) { fprintf(stderr, "makepng: %s: not a valid bit depth\n", arg); exit(1); } continue; } if (argc == 1) /* It's the file name */ { fp = fopen(arg, "wb"); if (fp == NULL) { fprintf(stderr, "%s: %s: could not open\n", arg, strerror(errno)); exit(1); } file_name = arg; continue; } fprintf(stderr, "makepng: %s: unknown argument\n", arg); exit(1); } /* argument while loop */ if (color_type == 8 || bit_depth == 32) { fprintf(stderr, "usage: makepng [--small] [--sRGB|--linear|--1.8] " "[--color=...] color-type bit-depth [file-name]\n" " Make a test PNG file, by default writes to stdout.\n" " Other options are available, UTSL.\n"); exit(1); } /* Check the colors */ { const unsigned int lim = (color_type == PNG_COLOR_TYPE_PALETTE ? 255U : (1U< lim) { fprintf(stderr, "makepng: --color=...: %u out of range [0..%u]\n", colors[i], lim); exit(1); } } /* small and colors are incomparible (will probably crash if both are used at * the same time!) */ if (small && colors[0] != 0) { fprintf(stderr, "makepng: --color --small: only one at a time!\n"); exit(1); } /* Restrict the filters for more speed to those we know are used for the * generated images. */ if (filters == PNG_ALL_FILTERS && !small/*small provides defaults*/) { if ((color_type & PNG_COLOR_MASK_PALETTE) != 0 || bit_depth < 8) filters = PNG_FILTER_NONE; else if (color_type & PNG_COLOR_MASK_COLOR) /* rgb */ { if (bit_depth == 8) filters &= ~(PNG_FILTER_NONE | PNG_FILTER_AVG); else filters = PNG_FILTER_SUB | PNG_FILTER_PAETH; } else /* gray 8 or 16-bit */ filters &= ~PNG_FILTER_NONE; } /* Insert standard copyright and licence text. */ { static png_const_charp copyright[] = { COPYRIGHT, /* ISO-Latin-1 */ NULL }; static png_const_charp licensing[] = { IMAGE_LICENSING, /* UTF-8 */ NULL }; chunk_insert *new_insert; new_insert = add_tEXt("Copyright", copyright); if (new_insert != NULL) { *insert_ptr = new_insert; insert_ptr = &new_insert->next; } new_insert = add_iTXt("Licensing", "en", NULL, licensing); if (new_insert != NULL) { *insert_ptr = new_insert; insert_ptr = &new_insert->next; } } { int ret = write_png(&file_name, fp, color_type, bit_depth, gamma, head_insert, filters, colors, small, tRNS); if (ret != 0 && file_name != NULL) remove(file_name); return ret; } } ================================================ FILE: tess-two/jni/libpng/contrib/libtests/pngimage.c ================================================ /* pngimage.c * * Copyright (c) 2015,2016 John Cunningham Bowler * * Last changed in libpng 1.6.24 [August 4, 2016] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * Test the png_read_png and png_write_png interfaces. Given a PNG file load it * using png_read_png and then write with png_write_png. Test all possible * transforms. */ #include #include #include #include #include #include #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H) # include #endif /* Define the following to use this test against your installed libpng, rather * than the one being built here: */ #ifdef PNG_FREESTANDING_TESTS # include #else # include "../../png.h" #endif #ifndef PNG_SETJMP_SUPPORTED # include /* because png.h did *not* include this */ #endif /* 1.6.1 added support for the configure test harness, which uses 77 to indicate * a skipped test, in earlier versions we need to succeed on a skipped test, so: */ #if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H) # define SKIP 77 #else # define SKIP 0 #endif #if PNG_LIBPNG_VER < 10700 /* READ_PNG and WRITE_PNG were not defined, so: */ # ifdef PNG_INFO_IMAGE_SUPPORTED # ifdef PNG_SEQUENTIAL_READ_SUPPORTED # define PNG_READ_PNG_SUPPORTED # endif /* SEQUENTIAL_READ */ # ifdef PNG_WRITE_SUPPORTED # define PNG_WRITE_PNG_SUPPORTED # endif /* WRITE */ # endif /* INFO_IMAGE */ #endif /* pre 1.7.0 */ #ifdef PNG_READ_PNG_SUPPORTED /* If a transform is valid on both read and write this implies that if the * transform is applied to read it must also be applied on write to produce * meaningful data. This is because these transforms when performed on read * produce data with a memory format that does not correspond to a PNG format. * * Most of these transforms are invertible; after applying the transform on * write the result is the original PNG data that would have would have been * read if no transform were applied. * * The exception is _SHIFT, which destroys the low order bits marked as not * significant in a PNG with the sBIT chunk. * * The following table lists, for each transform, the conditions under which it * is expected to do anything. Conditions are defined as follows: * * 1) Color mask bits required - simply a mask to AND with color_type; one of * these must be present for the transform to fire, except that 0 means * 'always'. * 2) Color mask bits which must be absent - another mask - none of these must * be present. * 3) Bit depths - a mask of component bit depths for the transform to fire. * 4) 'read' - the transform works in png_read_png. * 5) 'write' - the transform works in png_write_png. * 6) PNG_INFO_chunk; a mask of the chunks that must be present for the * transform to fire. All must be present - the requirement is that * png_get_valid() & mask == mask, so if mask is 0 there is no requirement. * * The condition refers to the original image state - if multiple transforms are * used together it is possible to cause a transform that wouldn't fire on the * original image to fire. */ static struct transform_info { const char *name; int transform; png_uint_32 valid_chunks; # define CHUNK_NONE 0 # define CHUNK_sBIT PNG_INFO_sBIT # define CHUNK_tRNS PNG_INFO_tRNS png_byte color_mask_required; png_byte color_mask_absent; # define COLOR_MASK_X 0 # define COLOR_MASK_P PNG_COLOR_MASK_PALETTE # define COLOR_MASK_C PNG_COLOR_MASK_COLOR # define COLOR_MASK_A PNG_COLOR_MASK_ALPHA # define COLOR_MASK_ALL (PALETTE+COLOR+ALPHA) /* absent = gray, no alpha */ png_byte bit_depths; # define BD_ALL (1 + 2 + 4 + 8 + 16) # define BD_PAL (1 + 2 + 4 + 8) # define BD_LOW (1 + 2 + 4) # define BD_16 16 # define BD_TRUE (8+16) /* i.e. true-color depths */ png_byte when; # define TRANSFORM_R 1 # define TRANSFORM_W 2 # define TRANSFORM_RW 3 png_byte tested; /* the transform was tested somewhere */ } transform_info[] = { /* List ALL the PNG_TRANSFORM_ macros here. Check for support using the READ * macros; even if the transform is supported on write it cannot be tested * without the read support. */ # define T(name,chunk,cm_required,cm_absent,bd,when)\ { #name, PNG_TRANSFORM_ ## name, CHUNK_ ## chunk,\ COLOR_MASK_ ## cm_required, COLOR_MASK_ ## cm_absent, BD_ ## bd,\ TRANSFORM_ ## when, 0/*!tested*/ } #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED T(STRIP_16, NONE, X, X, 16, R), /* drops the bottom 8 bits when bit depth is 16 */ #endif #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED T(STRIP_ALPHA, NONE, A, X, ALL, R), /* removes the alpha channel if present */ #endif #ifdef PNG_WRITE_PACK_SUPPORTED # define TRANSFORM_RW_PACK TRANSFORM_RW #else # define TRANSFORM_RW_PACK TRANSFORM_R #endif #ifdef PNG_READ_PACK_SUPPORTED T(PACKING, NONE, X, X, LOW, RW_PACK), /* unpacks low-bit-depth components into 1 byte per component on read, * reverses this on write. */ #endif #ifdef PNG_WRITE_PACKSWAP_SUPPORTED # define TRANSFORM_RW_PACKSWAP TRANSFORM_RW #else # define TRANSFORM_RW_PACKSWAP TRANSFORM_R #endif #ifdef PNG_READ_PACKSWAP_SUPPORTED T(PACKSWAP, NONE, X, X, LOW, RW_PACKSWAP), /* reverses the order of low-bit-depth components packed into a byte */ #endif #ifdef PNG_READ_EXPAND_SUPPORTED T(EXPAND, NONE, P, X, ALL, R), /* expands PLTE PNG files to RGB (no tRNS) or RGBA (tRNS) * * Note that the 'EXPAND' transform does lots of different things: */ T(EXPAND, NONE, X, C, ALL, R), /* expands grayscale PNG files to RGB, or RGBA */ T(EXPAND, tRNS, X, A, ALL, R), /* expands the tRNS chunk in files without alpha */ #endif #ifdef PNG_WRITE_INVERT_SUPPORTED # define TRANSFORM_RW_INVERT TRANSFORM_RW #else # define TRANSFORM_RW_INVERT TRANSFORM_R #endif #ifdef PNG_READ_INVERT_SUPPORTED T(INVERT_MONO, NONE, X, C, ALL, RW_INVERT), /* converts gray-scale components to 1..0 from 0..1 */ #endif #ifdef PNG_WRITE_SHIFT_SUPPORTED # define TRANSFORM_RW_SHIFT TRANSFORM_RW #else # define TRANSFORM_RW_SHIFT TRANSFORM_R #endif #ifdef PNG_READ_SHIFT_SUPPORTED T(SHIFT, sBIT, X, X, ALL, RW_SHIFT), /* reduces component values to the original range based on the sBIT chunk, * this is only partially reversible - the low bits are lost and cannot be * recovered on write. In fact write code replicates the bits to generate * new low-order bits. */ #endif #ifdef PNG_WRITE_BGR_SUPPORTED # define TRANSFORM_RW_BGR TRANSFORM_RW #else # define TRANSFORM_RW_BGR TRANSFORM_R #endif #ifdef PNG_READ_BGR_SUPPORTED T(BGR, NONE, C, P, TRUE, RW_BGR), /* reverses the rgb component values of true-color pixels */ #endif #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED # define TRANSFORM_RW_SWAP_ALPHA TRANSFORM_RW #else # define TRANSFORM_RW_SWAP_ALPHA TRANSFORM_R #endif #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED T(SWAP_ALPHA, NONE, A, X, TRUE, RW_SWAP_ALPHA), /* swaps the alpha channel of RGBA or GA pixels to the front - ARGB or * AG, on write reverses the process. */ #endif #ifdef PNG_WRITE_SWAP_SUPPORTED # define TRANSFORM_RW_SWAP TRANSFORM_RW #else # define TRANSFORM_RW_SWAP TRANSFORM_R #endif #ifdef PNG_READ_SWAP_SUPPORTED T(SWAP_ENDIAN, NONE, X, P, 16, RW_SWAP), /* byte-swaps 16-bit component values */ #endif #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED # define TRANSFORM_RW_INVERT_ALPHA TRANSFORM_RW #else # define TRANSFORM_RW_INVERT_ALPHA TRANSFORM_R #endif #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED T(INVERT_ALPHA, NONE, A, X, TRUE, RW_INVERT_ALPHA), /* converts an alpha channel from 0..1 to 1..0 */ #endif #ifdef PNG_WRITE_FILLER_SUPPORTED T(STRIP_FILLER_BEFORE, NONE, A, P, TRUE, W), /* 'A' for a filler! */ /* on write skips a leading filler channel; testing requires data with a * filler channel so this is produced from RGBA or GA images by removing * the 'alpha' flag from the color type in place. */ T(STRIP_FILLER_AFTER, NONE, A, P, TRUE, W), /* on write strips a trailing filler channel */ #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED T(GRAY_TO_RGB, NONE, X, C, ALL, R), /* expands grayscale images to RGB, also causes the palette part of * 'EXPAND' to happen. Low bit depth grayscale images are expanded to * 8-bits per component and no attempt is made to convert the image to a * palette image. While this transform is partially reversible * png_write_png does not currently support this. */ T(GRAY_TO_RGB, NONE, P, X, ALL, R), /* The 'palette' side effect mentioned above; a bit bogus but this is the * way the libpng code works. */ #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED T(EXPAND_16, NONE, X, X, PAL, R), /* expands images to 16-bits per component, as a side effect expands * palette images to RGB and expands the tRNS chunk if present, so it can * modify 16-bit per component images as well: */ T(EXPAND_16, tRNS, X, A, 16, R), /* side effect of EXPAND_16 - expands the tRNS chunk in an RGB or G 16-bit * image. */ #endif #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED T(SCALE_16, NONE, X, X, 16, R), /* scales 16-bit components to 8-bits. */ #endif { NULL /*name*/, 0, 0, 0, 0, 0, 0, 0/*!tested*/ } #undef T }; #define ARRAY_SIZE(a) ((sizeof a)/(sizeof a[0])) #define TTABLE_SIZE ARRAY_SIZE(transform_info) /* Some combinations of options that should be reversible are not; these cases * are bugs. */ static int known_bad_combos[][2] = { /* problem, antidote */ { PNG_TRANSFORM_SHIFT | PNG_TRANSFORM_INVERT_ALPHA, 0/*antidote*/ } }; static int is_combo(int transforms) { return transforms & (transforms-1); /* non-zero if more than one set bit */ } static int first_transform(int transforms) { return transforms & -transforms; /* lowest set bit */ } static int is_bad_combo(int transforms) { unsigned int i; for (i=0; ifirst.next = NULL; buffer->last = NULL; buffer->current = NULL; } static void buffer_destroy_list(struct buffer_list *list) { if (list != NULL) { struct buffer_list *next = list->next; DELETE(list); buffer_destroy_list(next); } } static void buffer_destroy(struct buffer *buffer) { struct buffer_list *list = buffer->first.next; buffer_init(buffer); buffer_destroy_list(list); } #ifdef PNG_WRITE_PNG_SUPPORTED static void buffer_start_write(struct buffer *buffer) { buffer->last = &buffer->first; buffer->end_count = 0; buffer->current = NULL; } #endif static void buffer_start_read(struct buffer *buffer) { buffer->current = &buffer->first; buffer->read_count = 0; } #ifdef ENOMEM /* required by POSIX 1003.1 */ # define MEMORY ENOMEM #else # define MEMORY ERANGE /* required by ANSI-C */ #endif static struct buffer * get_buffer(png_structp pp) /* Used from libpng callbacks to get the current buffer */ { return (struct buffer*)png_get_io_ptr(pp); } static struct buffer_list * buffer_extend(struct buffer_list *current) { struct buffer_list *add; assert(current->next == NULL); add = NEW(struct buffer_list); if (add == NULL) return NULL; add->next = NULL; current->next = add; return add; } /* Load a buffer from a file; does the equivalent of buffer_start_write. On a * read error returns an errno value, else returns 0. */ static int buffer_from_file(struct buffer *buffer, FILE *fp) { struct buffer_list *last = &buffer->first; size_t count = 0; for (;;) { size_t r = fread(last->buffer+count, 1/*size*/, (sizeof last->buffer)-count, fp); if (r > 0) { count += r; if (count >= sizeof last->buffer) { assert(count == sizeof last->buffer); count = 0; if (last->next == NULL) { last = buffer_extend(last); if (last == NULL) return MEMORY; } else last = last->next; } } else /* fread failed - probably end of file */ { if (feof(fp)) { buffer->last = last; buffer->end_count = count; return 0; /* no error */ } /* Some kind of funky error; errno should be non-zero */ return errno == 0 ? ERANGE : errno; } } } /* This structure is used to control the test of a single file. */ typedef enum { VERBOSE, /* switches on all messages */ INFORMATION, WARNINGS, /* switches on warnings */ LIBPNG_WARNING, APP_WARNING, ERRORS, /* just errors */ APP_FAIL, /* continuable error - no need to longjmp */ LIBPNG_ERROR, /* this and higher cause a longjmp */ LIBPNG_BUG, /* erroneous behavior in libpng */ APP_ERROR, /* such as out-of-memory in a callback */ QUIET, /* no normal messages */ USER_ERROR, /* such as file-not-found */ INTERNAL_ERROR } error_level; #define LEVEL_MASK 0xf /* where the level is in 'options' */ #define EXHAUSTIVE 0x010 /* Test all combinations of active options */ #define STRICT 0x020 /* Fail on warnings as well as errors */ #define LOG 0x040 /* Log pass/fail to stdout */ #define CONTINUE 0x080 /* Continue on APP_FAIL errors */ #define SKIP_BUGS 0x100 /* Skip over known bugs */ #define LOG_SKIPPED 0x200 /* Log skipped bugs */ #define FIND_BAD_COMBOS 0x400 /* Attempt to deduce bad combos */ #define LIST_COMBOS 0x800 /* List combos by name */ /* Result masks apply to the result bits in the 'results' field below; these * bits are simple 1U<options = WARNINGS; /* default to !verbose, !quiet */ dp->filename = NULL; dp->operation = NULL; dp->original_pp = NULL; dp->original_ip = NULL; dp->original_rows = NULL; dp->read_pp = NULL; dp->read_ip = NULL; buffer_init(&dp->original_file); # ifdef PNG_WRITE_PNG_SUPPORTED dp->write_pp = NULL; buffer_init(&dp->written_file); # endif } static void display_clean_read(struct display *dp) { if (dp->read_pp != NULL) png_destroy_read_struct(&dp->read_pp, &dp->read_ip, NULL); } #ifdef PNG_WRITE_PNG_SUPPORTED static void display_clean_write(struct display *dp) { if (dp->write_pp != NULL) png_destroy_write_struct(&dp->write_pp, NULL); } #endif static void display_clean(struct display *dp) { # ifdef PNG_WRITE_PNG_SUPPORTED display_clean_write(dp); # endif display_clean_read(dp); dp->original_rowbytes = 0; dp->original_rows = NULL; dp->chunks = 0; png_destroy_read_struct(&dp->original_pp, &dp->original_ip, NULL); /* leave the filename for error detection */ dp->results = 0; /* reset for next time */ } static void display_destroy(struct display *dp) { /* Release any memory held in the display. */ # ifdef PNG_WRITE_PNG_SUPPORTED buffer_destroy(&dp->written_file); # endif buffer_destroy(&dp->original_file); } static struct display * get_dp(png_structp pp) /* The display pointer is always stored in the png_struct error pointer */ { struct display *dp = (struct display*)png_get_error_ptr(pp); if (dp == NULL) { fprintf(stderr, "pngimage: internal error (no display)\n"); exit(99); /* prevents a crash */ } return dp; } /* error handling */ #ifdef __GNUC__ # define VGATTR __attribute__((__format__ (__printf__,3,4))) /* Required to quiet GNUC warnings when the compiler sees a stdarg function * that calls one of the stdio v APIs. */ #else # define VGATTR #endif static void VGATTR display_log(struct display *dp, error_level level, const char *fmt, ...) /* 'level' is as above, fmt is a stdio style format string. This routine * does not return if level is above LIBPNG_WARNING */ { dp->results |= 1U << level; if (level > (error_level)(dp->options & LEVEL_MASK)) { const char *lp; va_list ap; switch (level) { case INFORMATION: lp = "information"; break; case LIBPNG_WARNING: lp = "warning(libpng)"; break; case APP_WARNING: lp = "warning(pngimage)"; break; case APP_FAIL: lp = "error(continuable)"; break; case LIBPNG_ERROR: lp = "error(libpng)"; break; case LIBPNG_BUG: lp = "bug(libpng)"; break; case APP_ERROR: lp = "error(pngimage)"; break; case USER_ERROR: lp = "error(user)"; break; case INTERNAL_ERROR: /* anything unexpected is an internal error: */ case VERBOSE: case WARNINGS: case ERRORS: case QUIET: default: lp = "bug(pngimage)"; break; } fprintf(stderr, "%s: %s: %s", dp->filename != NULL ? dp->filename : "", lp, dp->operation); if (dp->transforms != 0) { int tr = dp->transforms; if (is_combo(tr)) { if (dp->options & LIST_COMBOS) { int trx = tr; fprintf(stderr, "("); if (trx) { int start = 0; while (trx) { int trz = trx & -trx; if (start) fprintf(stderr, "+"); fprintf(stderr, "%s", transform_name(trz)); start = 1; trx &= ~trz; } } else fprintf(stderr, "-"); fprintf(stderr, ")"); } else fprintf(stderr, "(0x%x)", tr); } else fprintf(stderr, "(%s)", transform_name(tr)); } fprintf(stderr, ": "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); } /* else do not output any message */ /* Errors cause this routine to exit to the fail code */ if (level > APP_FAIL || (level > ERRORS && !(dp->options & CONTINUE))) longjmp(dp->error_return, level); } /* error handler callbacks for libpng */ static void PNGCBAPI display_warning(png_structp pp, png_const_charp warning) { display_log(get_dp(pp), LIBPNG_WARNING, "%s", warning); } static void PNGCBAPI display_error(png_structp pp, png_const_charp error) { struct display *dp = get_dp(pp); display_log(dp, LIBPNG_ERROR, "%s", error); } static void display_cache_file(struct display *dp, const char *filename) /* Does the initial cache of the file. */ { FILE *fp; int ret; dp->filename = filename; if (filename != NULL) { fp = fopen(filename, "rb"); if (fp == NULL) display_log(dp, USER_ERROR, "open failed: %s", strerror(errno)); } else fp = stdin; ret = buffer_from_file(&dp->original_file, fp); fclose(fp); if (ret != 0) display_log(dp, APP_ERROR, "read failed: %s", strerror(ret)); } static void buffer_read(struct display *dp, struct buffer *bp, png_bytep data, png_size_t size) { struct buffer_list *last = bp->current; size_t read_count = bp->read_count; while (size > 0) { size_t avail; if (last == NULL || (last == bp->last && read_count >= bp->end_count)) { display_log(dp, USER_ERROR, "file truncated (%lu bytes)", (unsigned long)size); /*NOTREACHED*/ break; } else if (read_count >= sizeof last->buffer) { /* Move to the next buffer: */ last = last->next; read_count = 0; bp->current = last; /* Avoid update outside the loop */ /* And do a sanity check (the EOF case is caught above) */ if (last == NULL) { display_log(dp, INTERNAL_ERROR, "damaged buffer list"); /*NOTREACHED*/ break; } } avail = (sizeof last->buffer) - read_count; if (avail > size) avail = size; memcpy(data, last->buffer + read_count, avail); read_count += avail; size -= avail; data += avail; } bp->read_count = read_count; } static void PNGCBAPI read_function(png_structp pp, png_bytep data, png_size_t size) { buffer_read(get_dp(pp), get_buffer(pp), data, size); } static void read_png(struct display *dp, struct buffer *bp, const char *operation, int transforms) { png_structp pp; png_infop ip; /* This cleans out any previous read and sets operation and transforms to * empty. */ display_clean_read(dp); if (operation != NULL) /* else this is a verify and do not overwrite info */ { dp->operation = operation; dp->transforms = transforms; } dp->read_pp = pp = png_create_read_struct(PNG_LIBPNG_VER_STRING, dp, display_error, display_warning); if (pp == NULL) display_log(dp, LIBPNG_ERROR, "failed to create read struct"); /* The png_read_png API requires us to make the info struct, but it does the * call to png_read_info. */ dp->read_ip = ip = png_create_info_struct(pp); if (ip == NULL) display_log(dp, LIBPNG_ERROR, "failed to create info struct"); # ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Remove the user limits, if any */ png_set_user_limits(pp, 0x7fffffff, 0x7fffffff); # endif /* Set the IO handling */ buffer_start_read(bp); png_set_read_fn(pp, bp, read_function); png_read_png(pp, ip, transforms, NULL/*params*/); #if 0 /* crazy debugging */ { png_bytep pr = png_get_rows(pp, ip)[0]; size_t rb = png_get_rowbytes(pp, ip); size_t cb; char c = ' '; fprintf(stderr, "%.4x %2d (%3lu bytes):", transforms, png_get_bit_depth(pp,ip), (unsigned long)rb); for (cb=0; cboriginal_file, "original read", 0/*no transform*/); /* Move the result to the 'original' fields */ dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL; dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL; dp->original_rowbytes = png_get_rowbytes(pp, ip); if (dp->original_rowbytes == 0) display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0"); dp->chunks = png_get_valid(pp, ip, 0xffffffff); if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */ display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag"); dp->original_rows = png_get_rows(pp, ip); if (dp->original_rows == NULL) display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers"); if (!png_get_IHDR(pp, ip, &dp->width, &dp->height, &dp->bit_depth, &dp->color_type, &dp->interlace_method, &dp->compression_method, &dp->filter_method)) display_log(dp, LIBPNG_BUG, "png_get_IHDR failed"); /* 'active' transforms are discovered based on the original image format; * running one active transform can activate others. At present the code * does not attempt to determine the closure. */ { png_uint_32 chunks = dp->chunks; int active = 0, inactive = 0; int ct = dp->color_type; int bd = dp->bit_depth; unsigned int i; for (i=0; iactive_transforms = active; dp->ignored_transforms = inactive; /* excluding write-only transforms */ } } static int compare_read(struct display *dp, int applied_transforms) { /* Compare the png_info from read_ip with original_info */ size_t rowbytes; png_uint_32 width, height; int bit_depth, color_type; int interlace_method, compression_method, filter_method; const char *e = NULL; png_get_IHDR(dp->read_pp, dp->read_ip, &width, &height, &bit_depth, &color_type, &interlace_method, &compression_method, &filter_method); # define C(item) if (item != dp->item) \ display_log(dp, APP_WARNING, "IHDR " #item "(%lu) changed to %lu",\ (unsigned long)dp->item, (unsigned long)item), e = #item /* The IHDR should be identical: */ C(width); C(height); C(bit_depth); C(color_type); C(interlace_method); C(compression_method); C(filter_method); /* 'e' remains set to the name of the last thing changed: */ if (e) display_log(dp, APP_ERROR, "IHDR changed (%s)", e); /* All the chunks from the original PNG should be preserved in the output PNG * because the PNG format has not been changed. */ { unsigned long chunks = png_get_valid(dp->read_pp, dp->read_ip, 0xffffffff); if (chunks != dp->chunks) display_log(dp, APP_FAIL, "PNG chunks changed from 0x%lx to 0x%lx", (unsigned long)dp->chunks, chunks); } /* rowbytes should be the same */ rowbytes = png_get_rowbytes(dp->read_pp, dp->read_ip); /* NOTE: on 64-bit systems this may trash the top bits of rowbytes, * which could lead to weird error messages. */ if (rowbytes != dp->original_rowbytes) display_log(dp, APP_ERROR, "PNG rowbytes changed from %lu to %lu", (unsigned long)dp->original_rowbytes, (unsigned long)rowbytes); /* The rows should be the same too, unless the applied transforms includes * the shift transform, in which case low bits may have been lost. */ { png_bytepp rows = png_get_rows(dp->read_pp, dp->read_ip); unsigned int mask; /* mask (if not zero) for the final byte */ if (bit_depth < 8) { /* Need the stray bits at the end, this depends only on the low bits * of the image width; overflow does not matter. If the width is an * exact multiple of 8 bits this gives a mask of 0, not 0xff. */ mask = 0xff & (0xff00 >> ((bit_depth * width) & 7)); } else mask = 0; if (rows == NULL) display_log(dp, LIBPNG_BUG, "png_get_rows returned NULL"); if ((applied_transforms & PNG_TRANSFORM_SHIFT) == 0 || (dp->active_transforms & PNG_TRANSFORM_SHIFT) == 0 || color_type == PNG_COLOR_TYPE_PALETTE) { unsigned long y; for (y=0; yoriginal_rows[y]; if (memcmp(row, orig, rowbytes-(mask != 0)) != 0 || (mask != 0 && ((row[rowbytes-1] & mask) != (orig[rowbytes-1] & mask)))) { size_t x; /* Find the first error */ for (x=0; x 0x%.2x", (unsigned long)x, (unsigned long)y, orig[x], row[x]); return 0; /* don't keep reporting failed rows on 'continue' */ } } } else # ifdef PNG_sBIT_SUPPORTED { unsigned long y; int bpp; /* bits-per-pixel then bytes-per-pixel */ /* components are up to 8 bytes in size */ png_byte sig_bits[8]; png_color_8p sBIT; if (png_get_sBIT(dp->read_pp, dp->read_ip, &sBIT) != PNG_INFO_sBIT) display_log(dp, INTERNAL_ERROR, "active shift transform but no sBIT in file"); switch (color_type) { case PNG_COLOR_TYPE_GRAY: sig_bits[0] = sBIT->gray; bpp = bit_depth; break; case PNG_COLOR_TYPE_GA: sig_bits[0] = sBIT->gray; sig_bits[1] = sBIT->alpha; bpp = 2 * bit_depth; break; case PNG_COLOR_TYPE_RGB: sig_bits[0] = sBIT->red; sig_bits[1] = sBIT->green; sig_bits[2] = sBIT->blue; bpp = 3 * bit_depth; break; case PNG_COLOR_TYPE_RGBA: sig_bits[0] = sBIT->red; sig_bits[1] = sBIT->green; sig_bits[2] = sBIT->blue; sig_bits[3] = sBIT->alpha; bpp = 4 * bit_depth; break; default: display_log(dp, LIBPNG_ERROR, "invalid colour type %d", color_type); /*NOTREACHED*/ bpp = 0; break; } { int b; for (b=0; 8*b bit_depth/*!palette*/) display_log(dp, LIBPNG_BUG, "invalid sBIT[%u] value %d returned for PNG bit depth %d", b, sig_bits[b], bit_depth); } } if (bpp < 8 && bpp != bit_depth) { /* sanity check; this is a grayscale PNG; something is wrong in the * code above. */ display_log(dp, INTERNAL_ERROR, "invalid bpp %u for bit_depth %u", bpp, bit_depth); } switch (bit_depth) { int b; case 16: /* Two bytes per component, big-endian */ for (b = (bpp >> 4); b > 0; --b) { unsigned int sig = (unsigned int)(0xffff0000 >> sig_bits[b]); sig_bits[2*b+1] = (png_byte)sig; sig_bits[2*b+0] = (png_byte)(sig >> 8); /* big-endian */ } break; case 8: /* One byte per component */ for (b=0; b*8 < bpp; ++b) sig_bits[b] = (png_byte)(0xff00 >> sig_bits[b]); break; case 1: /* allowed, but dumb */ /* Value is 1 */ sig_bits[0] = 0xff; break; case 2: /* Replicate 4 times */ /* Value is 1 or 2 */ b = 0x3 & ((0x3<<2) >> sig_bits[0]); b |= b << 2; b |= b << 4; sig_bits[0] = (png_byte)b; break; case 4: /* Relicate twice */ /* Value is 1, 2, 3 or 4 */ b = 0xf & ((0xf << 4) >> sig_bits[0]); b |= b << 4; sig_bits[0] = (png_byte)b; break; default: display_log(dp, LIBPNG_BUG, "invalid bit depth %d", bit_depth); break; } /* Convert bpp to bytes; this gives '1' for low-bit depth grayscale, * where there are multiple pixels per byte. */ bpp = (bpp+7) >> 3; /* The mask can be combined with sig_bits[0] */ if (mask != 0) { mask &= sig_bits[0]; if (bpp != 1 || mask == 0) display_log(dp, INTERNAL_ERROR, "mask calculation error %u, %u", bpp, mask); } for (y=0; yoriginal_rows[y]; unsigned long x; for (x=0; x<(width-(mask!=0)); ++x) { int b; for (b=0; b%.2x", x, b, y, orig[-1], row[-1]); return 0; } } } if (mask != 0 && (*row & mask) != (*orig & mask)) { display_log(dp, APP_FAIL, "significant bits at (%lu[end],%lu) changed", x, y); return 0; } } /* for y */ } # else /* !sBIT */ display_log(dp, INTERNAL_ERROR, "active shift transform but no sBIT support"); # endif /* !sBIT */ } return 1; /* compare succeeded */ } #ifdef PNG_WRITE_PNG_SUPPORTED static void buffer_write(struct display *dp, struct buffer *buffer, png_bytep data, png_size_t size) /* Generic write function used both from the write callback provided to * libpng and from the generic read code. */ { /* Write the data into the buffer, adding buffers as required */ struct buffer_list *last = buffer->last; size_t end_count = buffer->end_count; while (size > 0) { size_t avail; if (end_count >= sizeof last->buffer) { if (last->next == NULL) { last = buffer_extend(last); if (last == NULL) display_log(dp, APP_ERROR, "out of memory saving file"); } else last = last->next; buffer->last = last; /* avoid the need to rewrite every time */ end_count = 0; } avail = (sizeof last->buffer) - end_count; if (avail > size) avail = size; memcpy(last->buffer + end_count, data, avail); end_count += avail; size -= avail; data += avail; } buffer->end_count = end_count; } static void PNGCBAPI write_function(png_structp pp, png_bytep data, png_size_t size) { buffer_write(get_dp(pp), get_buffer(pp), data, size); } static void write_png(struct display *dp, png_infop ip, int transforms) { display_clean_write(dp); /* safety */ buffer_start_write(&dp->written_file); dp->operation = "write"; dp->transforms = transforms; dp->write_pp = png_create_write_struct(PNG_LIBPNG_VER_STRING, dp, display_error, display_warning); if (dp->write_pp == NULL) display_log(dp, APP_ERROR, "failed to create write png_struct"); png_set_write_fn(dp->write_pp, &dp->written_file, write_function, NULL/*flush*/); # ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Remove the user limits, if any */ png_set_user_limits(dp->write_pp, 0x7fffffff, 0x7fffffff); # endif /* Certain transforms require the png_info to be zapped to allow the * transform to work correctly. */ if (transforms & (PNG_TRANSFORM_PACKING| PNG_TRANSFORM_STRIP_FILLER| PNG_TRANSFORM_STRIP_FILLER_BEFORE)) { int ct = dp->color_type; if (transforms & (PNG_TRANSFORM_STRIP_FILLER| PNG_TRANSFORM_STRIP_FILLER_BEFORE)) ct &= ~PNG_COLOR_MASK_ALPHA; png_set_IHDR(dp->write_pp, ip, dp->width, dp->height, dp->bit_depth, ct, dp->interlace_method, dp->compression_method, dp->filter_method); } png_write_png(dp->write_pp, ip, transforms, NULL/*params*/); /* Clean it on the way out - if control returns to the caller then the * written_file contains the required data. */ display_clean_write(dp); } #endif /* WRITE_PNG */ static int skip_transform(struct display *dp, int tr) /* Helper to test for a bad combo and log it if it is skipped */ { if ((dp->options & SKIP_BUGS) != 0 && is_bad_combo(tr)) { /* Log this to stdout if logging is on, otherwise just do an information * display_log. */ if ((dp->options & LOG_SKIPPED) != 0) { printf("SKIP: %s transforms ", dp->filename); while (tr != 0) { int next = first_transform(tr); tr &= ~next; printf("%s", transform_name(next)); if (tr != 0) putchar('+'); } putchar('\n'); } else display_log(dp, INFORMATION, "%s: skipped known bad combo 0x%x", dp->filename, tr); return 1; /* skip */ } return 0; /* don't skip */ } static void test_one_file(struct display *dp, const char *filename) { /* First cache the file and update the display original file * information for the new file. */ dp->operation = "cache file"; dp->transforms = 0; display_cache_file(dp, filename); update_display(dp); /* First test: if there are options that should be ignored for this file * verify that they really are ignored. */ if (dp->ignored_transforms != 0) { read_png(dp, &dp->original_file, "ignored transforms", dp->ignored_transforms); /* The result should be identical to the original_rows */ if (!compare_read(dp, 0/*transforms applied*/)) return; /* no point testing more */ } #ifdef PNG_WRITE_PNG_SUPPORTED /* Second test: write the original PNG data out to a new file (to test the * write side) then read the result back in and make sure that it hasn't * changed. */ dp->operation = "write"; write_png(dp, dp->original_ip, 0/*transforms*/); read_png(dp, &dp->written_file, NULL, 0/*transforms*/); if (!compare_read(dp, 0/*transforms applied*/)) return; #endif /* Third test: the active options. Test each in turn, or, with the * EXHAUSTIVE option, test all possible combinations. */ { /* Use unsigned int here because the code below to increment through all * the possibilities exhaustively has to use a compare and that must be * unsigned, because some transforms are negative on a 16-bit system. */ unsigned int active = dp->active_transforms; const int exhaustive = (dp->options & EXHAUSTIVE) != 0; unsigned int current = first_transform(active); unsigned int bad_transforms = 0; unsigned int bad_combo = ~0U; /* bitwise AND of failing transforms */ unsigned int bad_combo_list = 0; /* bitwise OR of failures */ for (;;) { read_png(dp, &dp->original_file, "active transforms", current); /* If this involved any irreversible transformations then if we write * it out with just the reversible transformations and read it in again * with the same transforms we should get the same thing. At present * this isn't done - it just seems like a waste of time and it would * require two sets of read png_struct/png_info. * * If there were no irreversible transformations then if we write it * out and read it back in again (without the reversible transforms) * we should get back to the place where we started. */ #ifdef PNG_WRITE_PNG_SUPPORTED if ((current & write_transforms) == current) { /* All transforms reversible: write the PNG with the transformations * reversed, then read it back in with no transformations. The * result should be the same as the original apart from the loss of * low order bits because of the SHIFT/sBIT transform. */ dp->operation = "reversible transforms"; write_png(dp, dp->read_ip, current); /* And if this is read back in, because all the transformations were * reversible, the result should be the same. */ read_png(dp, &dp->written_file, NULL, 0); if (!compare_read(dp, current/*for the SHIFT/sBIT transform*/)) { /* This set of transforms failed. If a single bit is set - if * there is just one transform - don't include this in further * 'exhaustive' tests. Notice that each transform is tested on * its own before testing combos in the exhaustive case. */ if (is_combo(current)) { bad_combo &= current; bad_combo_list |= current; } else bad_transforms |= current; } } #endif /* Now move to the next transform */ if (exhaustive) /* all combinations */ { unsigned int next = current; do { if (next == read_transforms) /* Everything tested */ goto combo; ++next; } /* skip known bad combos if the relevant option is set; skip * combos involving known bad single transforms in all cases. */ while ( (next & read_transforms) <= current || (next & active) == 0 /* skip cases that do nothing */ || (next & bad_transforms) != 0 || skip_transform(dp, next)); assert((next & read_transforms) == next); current = next; } else /* one at a time */ { active &= ~current; if (active == 0) goto combo; current = first_transform(active); } } combo: if (dp->options & FIND_BAD_COMBOS) { /* bad_combos identifies the combos that occur in all failing cases; * bad_combo_list identifies transforms that do not prevent the * failure. */ if (bad_combo != ~0U) printf("%s[0x%x]: PROBLEM: 0x%x[0x%x] ANTIDOTE: 0x%x\n", dp->filename, active, bad_combo, bad_combo_list, rw_transforms & ~bad_combo_list); else printf("%s: no %sbad combos found\n", dp->filename, (dp->options & SKIP_BUGS) ? "additional " : ""); } } } static int do_test(struct display *dp, const char *file) /* Exists solely to isolate the setjmp clobbers */ { int ret = setjmp(dp->error_return); if (ret == 0) { test_one_file(dp, file); return 0; } else if (ret < ERRORS) /* shouldn't longjmp on warnings */ display_log(dp, INTERNAL_ERROR, "unexpected return code %d", ret); return ret; } int main(const int argc, const char * const * const argv) { /* For each file on the command line test it with a range of transforms */ int option_end, ilog = 0; struct display d; validate_T(); display_init(&d); for (option_end=1; option_end QUIET) /* abort on user or internal error */ return 99; } /* Here on any return, including failures, except user/internal issues */ { const int pass = (d.options & STRICT) ? RESULT_STRICT(d.results) : RESULT_RELAXED(d.results); if (!pass) ++errors; if (d.options & LOG) { int j; printf("%s: pngimage ", pass ? "PASS" : "FAIL"); for (j=1; j #include #include #include #include #include #include #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H) # include #endif /* Define the following to use this test against your installed libpng, rather * than the one being built here: */ #ifdef PNG_FREESTANDING_TESTS # include #else # include "../../png.h" #endif /* 1.6.1 added support for the configure test harness, which uses 77 to indicate * a skipped test, in earlier versions we need to succeed on a skipped test, so: */ #if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H) # define SKIP 77 #else # define SKIP 0 #endif #ifdef PNG_SIMPLIFIED_READ_SUPPORTED /* Else nothing can be done */ #include "../tools/sRGB.h" /* KNOWN ISSUES * * These defines switch on alternate algorithms for format conversions to match * the current libpng implementation; they are set to allow pngstest to pass * even though libpng is producing answers that are not as correct as they * should be. */ #define ALLOW_UNUSED_GPC 0 /* If true include unused static GPC functions and declare an external array * of them to hide the fact that they are unused. This is for development * use while testing the correct function to use to take into account libpng * misbehavior, such as using a simple power law to correct sRGB to linear. */ /* The following is to support direct compilation of this file as C++ */ #ifdef __cplusplus # define voidcast(type, value) static_cast(value) # define aligncastconst(type, value) \ static_cast(static_cast(value)) #else # define voidcast(type, value) (value) # define aligncastconst(type, value) ((const void*)(value)) #endif /* __cplusplus */ /* During parallel runs of pngstest each temporary file needs a unique name, * this is used to permit uniqueness using a command line argument which can be * up to 22 characters long. */ static char tmpf[23] = "TMP"; /* Generate random bytes. This uses a boring repeatable algorithm and it * is implemented here so that it gives the same set of numbers on every * architecture. It's a linear congruential generator (Knuth or Sedgewick * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and * Hill, "The Art of Electronics". */ static void make_random_bytes(png_uint_32* seed, void* pv, size_t size) { png_uint_32 u0 = seed[0], u1 = seed[1]; png_bytep bytes = voidcast(png_bytep, pv); /* There are thirty three bits, the next bit in the sequence is bit-33 XOR * bit-20. The top 1 bit is in u1, the bottom 32 are in u0. */ size_t i; for (i=0; i> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff; u1 <<= 8; u1 |= u0 >> 24; u0 <<= 8; u0 |= u; *bytes++ = (png_byte)u; } seed[0] = u0; seed[1] = u1; } static png_uint_32 color_seed[2]; static void reseed(void) { color_seed[0] = 0x12345678U; color_seed[1] = 0x9abcdefU; } static void random_color(png_colorp color) { make_random_bytes(color_seed, color, sizeof *color); } /* Math support - neither Cygwin nor Visual Studio have C99 support and we need * a predictable rounding function, so make one here: */ static double closestinteger(double x) { return floor(x + .5); } /* Cast support: remove GCC whines. */ static png_byte u8d(double d) { d = closestinteger(d); return (png_byte)d; } static png_uint_16 u16d(double d) { d = closestinteger(d); return (png_uint_16)d; } /* sRGB support: use exact calculations rounded to the nearest int, see the * fesetround() call in main(). sRGB_to_d optimizes the 8 to 16-bit conversion. */ static double sRGB_to_d[256]; static double g22_to_d[256]; static void init_sRGB_to_d(void) { int i; sRGB_to_d[0] = 0; for (i=1; i<255; ++i) sRGB_to_d[i] = linear_from_sRGB(i/255.); sRGB_to_d[255] = 1; g22_to_d[0] = 0; for (i=1; i<255; ++i) g22_to_d[i] = pow(i/255., 1/.45455); g22_to_d[255] = 1; } static png_byte sRGB(double linear /*range 0.0 .. 1.0*/) { return u8d(255 * sRGB_from_linear(linear)); } static png_byte isRGB(int fixed_linear) { return sRGB(fixed_linear / 65535.); } #if 0 /* not used */ static png_byte unpremultiply(int component, int alpha) { if (alpha <= component) return 255; /* Arbitrary, but consistent with the libpng code */ else if (alpha >= 65535) return isRGB(component); else return sRGB((double)component / alpha); } #endif static png_uint_16 ilinear(int fixed_srgb) { return u16d(65535 * sRGB_to_d[fixed_srgb]); } static png_uint_16 ilineara(int fixed_srgb, int alpha) { return u16d((257 * alpha) * sRGB_to_d[fixed_srgb]); } static png_uint_16 ilinear_g22(int fixed_srgb) { return u16d(65535 * g22_to_d[fixed_srgb]); } #if ALLOW_UNUSED_GPC static png_uint_16 ilineara_g22(int fixed_srgb, int alpha) { return u16d((257 * alpha) * g22_to_d[fixed_srgb]); } #endif static double YfromRGBint(int ir, int ig, int ib) { double r = ir; double g = ig; double b = ib; return YfromRGB(r, g, b); } #if 0 /* unused */ /* The error that results from using a 2.2 power law in place of the correct * sRGB transform, given an 8-bit value which might be either sRGB or power-law. */ static int power_law_error8(int value) { if (value > 0 && value < 255) { double vd = value / 255.; double e = fabs( pow(sRGB_to_d[value], 1/2.2) - sRGB_from_linear(pow(vd, 2.2))); /* Always allow an extra 1 here for rounding errors */ e = 1+floor(255 * e); return (int)e; } return 0; } static int error_in_sRGB_roundtrip = 56; /* by experiment */ static int power_law_error16(int value) { if (value > 0 && value < 65535) { /* Round trip the value through an 8-bit representation but using * non-matching to/from conversions. */ double vd = value / 65535.; double e = fabs( pow(sRGB_from_linear(vd), 2.2) - linear_from_sRGB(pow(vd, 1/2.2))); /* Always allow an extra 1 here for rounding errors */ e = error_in_sRGB_roundtrip+floor(65535 * e); return (int)e; } return 0; } static int compare_8bit(int v1, int v2, int error_limit, int multiple_algorithms) { int e = abs(v1-v2); int ev1, ev2; if (e <= error_limit) return 1; if (!multiple_algorithms) return 0; ev1 = power_law_error8(v1); if (e <= ev1) return 1; ev2 = power_law_error8(v2); if (e <= ev2) return 1; return 0; } static int compare_16bit(int v1, int v2, int error_limit, int multiple_algorithms) { int e = abs(v1-v2); int ev1, ev2; if (e <= error_limit) return 1; /* "multiple_algorithms" in this case means that a color-map has been * involved somewhere, so we can deduce that the values were forced to 8-bit * (like the via_linear case for 8-bit.) */ if (!multiple_algorithms) return 0; ev1 = power_law_error16(v1); if (e <= ev1) return 1; ev2 = power_law_error16(v2); if (e <= ev2) return 1; return 0; } #endif /* unused */ #define USE_FILE 1 /* else memory */ #define USE_STDIO 2 /* else use file name */ #define STRICT 4 /* fail on warnings too */ #define VERBOSE 8 #define KEEP_TMPFILES 16 /* else delete temporary files */ #define KEEP_GOING 32 #define ACCUMULATE 64 #define FAST_WRITE 128 #define sRGB_16BIT 256 #define NO_RESEED 512 /* do not reseed on each new file */ #define GBG_ERROR 1024 /* do not ignore the gamma+background_rgb_to_gray * libpng warning. */ static void print_opts(png_uint_32 opts) { if (opts & USE_FILE) printf(" --file"); if (opts & USE_STDIO) printf(" --stdio"); if (!(opts & STRICT)) printf(" --nostrict"); if (opts & VERBOSE) printf(" --verbose"); if (opts & KEEP_TMPFILES) printf(" --preserve"); if (opts & KEEP_GOING) printf(" --keep-going"); if (opts & ACCUMULATE) printf(" --accumulate"); if (!(opts & FAST_WRITE)) /* --fast is currently the default */ printf(" --slow"); if (opts & sRGB_16BIT) printf(" --sRGB-16bit"); if (opts & NO_RESEED) printf(" --noreseed"); #if PNG_LIBPNG_VER < 10700 /* else on by default */ if (opts & GBG_ERROR) printf(" --fault-gbg-warning"); #endif } #define FORMAT_NO_CHANGE 0x80000000 /* additional flag */ /* A name table for all the formats - defines the format of the '+' arguments to * pngstest. */ #define FORMAT_COUNT 64 #define FORMAT_MASK 0x3f static PNG_CONST char * PNG_CONST format_names[FORMAT_COUNT] = { "sRGB-gray", "sRGB-gray+alpha", "sRGB-rgb", "sRGB-rgb+alpha", "linear-gray", "linear-gray+alpha", "linear-rgb", "linear-rgb+alpha", "color-mapped-sRGB-gray", "color-mapped-sRGB-gray+alpha", "color-mapped-sRGB-rgb", "color-mapped-sRGB-rgb+alpha", "color-mapped-linear-gray", "color-mapped-linear-gray+alpha", "color-mapped-linear-rgb", "color-mapped-linear-rgb+alpha", "sRGB-gray", "sRGB-gray+alpha", "sRGB-bgr", "sRGB-bgr+alpha", "linear-gray", "linear-gray+alpha", "linear-bgr", "linear-bgr+alpha", "color-mapped-sRGB-gray", "color-mapped-sRGB-gray+alpha", "color-mapped-sRGB-bgr", "color-mapped-sRGB-bgr+alpha", "color-mapped-linear-gray", "color-mapped-linear-gray+alpha", "color-mapped-linear-bgr", "color-mapped-linear-bgr+alpha", "sRGB-gray", "alpha+sRGB-gray", "sRGB-rgb", "alpha+sRGB-rgb", "linear-gray", "alpha+linear-gray", "linear-rgb", "alpha+linear-rgb", "color-mapped-sRGB-gray", "color-mapped-alpha+sRGB-gray", "color-mapped-sRGB-rgb", "color-mapped-alpha+sRGB-rgb", "color-mapped-linear-gray", "color-mapped-alpha+linear-gray", "color-mapped-linear-rgb", "color-mapped-alpha+linear-rgb", "sRGB-gray", "alpha+sRGB-gray", "sRGB-bgr", "alpha+sRGB-bgr", "linear-gray", "alpha+linear-gray", "linear-bgr", "alpha+linear-bgr", "color-mapped-sRGB-gray", "color-mapped-alpha+sRGB-gray", "color-mapped-sRGB-bgr", "color-mapped-alpha+sRGB-bgr", "color-mapped-linear-gray", "color-mapped-alpha+linear-gray", "color-mapped-linear-bgr", "color-mapped-alpha+linear-bgr", }; /* Decode an argument to a format number. */ static png_uint_32 formatof(const char *arg) { char *ep; unsigned long format = strtoul(arg, &ep, 0); if (ep > arg && *ep == 0 && format < FORMAT_COUNT) return (png_uint_32)format; else for (format=0; format < FORMAT_COUNT; ++format) { if (strcmp(format_names[format], arg) == 0) return (png_uint_32)format; } fprintf(stderr, "pngstest: format name '%s' invalid\n", arg); return FORMAT_COUNT; } /* Bitset/test functions for formats */ #define FORMAT_SET_COUNT (FORMAT_COUNT / 32) typedef struct { png_uint_32 bits[FORMAT_SET_COUNT]; } format_list; static void format_init(format_list *pf) { int i; for (i=0; ibits[i] = 0; /* All off */ } #if 0 /* currently unused */ static void format_clear(format_list *pf) { int i; for (i=0; ibits[i] = 0; } #endif static int format_is_initial(format_list *pf) { int i; for (i=0; ibits[i] != 0) return 0; return 1; } static int format_set(format_list *pf, png_uint_32 format) { if (format < FORMAT_COUNT) return pf->bits[format >> 5] |= ((png_uint_32)1) << (format & 31); return 0; } #if 0 /* currently unused */ static int format_unset(format_list *pf, png_uint_32 format) { if (format < FORMAT_COUNT) return pf->bits[format >> 5] &= ~((png_uint_32)1) << (format & 31); return 0; } #endif static int format_isset(format_list *pf, png_uint_32 format) { return format < FORMAT_COUNT && (pf->bits[format >> 5] & (((png_uint_32)1) << (format & 31))) != 0; } static void format_default(format_list *pf, int redundant) { if (redundant) { int i; /* set everything, including flags that are pointless */ for (i=0; ibits[i] = ~(png_uint_32)0; } else { png_uint_32 f; for (f=0; finput_file != NULL) rewind(image->input_file); } /* Free the image buffer; the buffer is re-used on a re-read, this is just for * cleanup. */ static void freebuffer(Image *image) { if (image->buffer) free(image->buffer); image->buffer = NULL; image->bufsize = 0; image->allocsize = 0; } /* Delete function; cleans out all the allocated data and the temporary file in * the image. */ static void freeimage(Image *image) { freebuffer(image); png_image_free(&image->image); if (image->input_file != NULL) { fclose(image->input_file); image->input_file = NULL; } if (image->input_memory != NULL) { free(image->input_memory); image->input_memory = NULL; image->input_memory_size = 0; } if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0) { (void)remove(image->tmpfile_name); image->tmpfile_name[0] = 0; } } /* This is actually a re-initializer; allows an image structure to be re-used by * freeing everything that relates to an old image. */ static void initimage(Image *image, png_uint_32 opts, const char *file_name, int stride_extra) { freeimage(image); memset(&image->image, 0, sizeof image->image); image->opts = opts; image->file_name = file_name; image->stride_extra = stride_extra; } /* Make sure the image buffer is big enough; allows re-use of the buffer if the * image is re-read. */ #define BUFFER_INIT8 73 static void allocbuffer(Image *image) { png_size_t size = PNG_IMAGE_BUFFER_SIZE(image->image, image->stride); if (size+32 > image->bufsize) { freebuffer(image); image->buffer = voidcast(png_bytep, malloc(size+32)); if (image->buffer == NULL) { fflush(stdout); fprintf(stderr, "simpletest: out of memory allocating %lu(+32) byte buffer\n", (unsigned long)size); exit(1); } image->bufsize = size+32; } memset(image->buffer, 95, image->bufsize); memset(image->buffer+16, BUFFER_INIT8, size); image->allocsize = size; } /* Make sure 16 bytes match the given byte. */ static int check16(png_const_bytep bp, int b) { int i = 16; do if (*bp != b) return 1; while (--i); return 0; } /* Check for overwrite in the image buffer. */ static void checkbuffer(Image *image, const char *arg) { if (check16(image->buffer, 95)) { fflush(stdout); fprintf(stderr, "%s: overwrite at start of image buffer\n", arg); exit(1); } if (check16(image->buffer+16+image->allocsize, 95)) { fflush(stdout); fprintf(stderr, "%s: overwrite at end of image buffer\n", arg); exit(1); } } /* ERROR HANDLING */ /* Log a terminal error, also frees the libpng part of the image if necessary. */ static int logerror(Image *image, const char *a1, const char *a2, const char *a3) { fflush(stdout); if (image->image.warning_or_error) fprintf(stderr, "%s%s%s: %s\n", a1, a2, a3, image->image.message); else fprintf(stderr, "%s%s%s\n", a1, a2, a3); if (image->image.opaque != NULL) { fprintf(stderr, "%s: image opaque pointer non-NULL on error\n", image->file_name); png_image_free(&image->image); } return 0; } /* Log an error and close a file (just a utility to do both things in one * function call.) */ static int logclose(Image *image, FILE *f, const char *name, const char *operation) { int e = errno; fclose(f); return logerror(image, name, operation, strerror(e)); } /* Make sure the png_image has been freed - validates that libpng is doing what * the spec says and freeing the image. */ static int checkopaque(Image *image) { if (image->image.opaque != NULL) { png_image_free(&image->image); return logerror(image, image->file_name, ": opaque not NULL", ""); } /* Separate out the gamma+background_rgb_to_gray warning because it may * produce opaque component errors: */ else if (image->image.warning_or_error != 0 && (strcmp(image->image.message, "libpng does not support gamma+background+rgb_to_gray") == 0 ? (image->opts & GBG_ERROR) != 0 : (image->opts & STRICT) != 0)) return logerror(image, image->file_name, (image->opts & GBG_ERROR) != 0 ? " --fault-gbg-warning" : " --strict", ""); else return 1; } /* IMAGE COMPARISON/CHECKING */ /* Compare the pixels of two images, which should be the same but aren't. The * images must have been checked for a size match. */ typedef struct { /* The components, for grayscale images the gray value is in 'g' and if alpha * is not present 'a' is set to 255 or 65535 according to format. */ int r, g, b, a; } Pixel; typedef struct { /* The background as the original sRGB 8-bit value converted to the final * integer format and as a double precision linear value in the range 0..1 * for with partially transparent pixels. */ int ir, ig, ib; double dr, dg, db; /* linear r,g,b scaled to 0..1 */ } Background; /* Basic image formats; control the data but not the layout thereof. */ #define BASE_FORMATS\ (PNG_FORMAT_FLAG_ALPHA|PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_LINEAR) /* Read a Pixel from a buffer. The code below stores the correct routine for * the format in a function pointer, these are the routines: */ static void gp_g8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = p->g = p->b = pp[0]; p->a = 255; } static void gp_ga8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = p->g = p->b = pp[0]; p->a = pp[1]; } #ifdef PNG_FORMAT_AFIRST_SUPPORTED static void gp_ag8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = p->g = p->b = pp[1]; p->a = pp[0]; } #endif static void gp_rgb8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = pp[0]; p->g = pp[1]; p->b = pp[2]; p->a = 255; } #ifdef PNG_FORMAT_BGR_SUPPORTED static void gp_bgr8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = pp[2]; p->g = pp[1]; p->b = pp[0]; p->a = 255; } #endif static void gp_rgba8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = pp[0]; p->g = pp[1]; p->b = pp[2]; p->a = pp[3]; } #ifdef PNG_FORMAT_BGR_SUPPORTED static void gp_bgra8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = pp[2]; p->g = pp[1]; p->b = pp[0]; p->a = pp[3]; } #endif #ifdef PNG_FORMAT_AFIRST_SUPPORTED static void gp_argb8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = pp[1]; p->g = pp[2]; p->b = pp[3]; p->a = pp[0]; } #endif #if defined(PNG_FORMAT_AFIRST_SUPPORTED) && defined(PNG_FORMAT_BGR_SUPPORTED) static void gp_abgr8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = pp[3]; p->g = pp[2]; p->b = pp[1]; p->a = pp[0]; } #endif static void gp_g16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = p->g = p->b = pp[0]; p->a = 65535; } static void gp_ga16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = p->g = p->b = pp[0]; p->a = pp[1]; } #ifdef PNG_FORMAT_AFIRST_SUPPORTED static void gp_ag16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = p->g = p->b = pp[1]; p->a = pp[0]; } #endif static void gp_rgb16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = pp[0]; p->g = pp[1]; p->b = pp[2]; p->a = 65535; } #ifdef PNG_FORMAT_BGR_SUPPORTED static void gp_bgr16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = pp[2]; p->g = pp[1]; p->b = pp[0]; p->a = 65535; } #endif static void gp_rgba16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = pp[0]; p->g = pp[1]; p->b = pp[2]; p->a = pp[3]; } #ifdef PNG_FORMAT_BGR_SUPPORTED static void gp_bgra16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = pp[2]; p->g = pp[1]; p->b = pp[0]; p->a = pp[3]; } #endif #ifdef PNG_FORMAT_AFIRST_SUPPORTED static void gp_argb16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = pp[1]; p->g = pp[2]; p->b = pp[3]; p->a = pp[0]; } #endif #if defined(PNG_FORMAT_AFIRST_SUPPORTED) && defined(PNG_FORMAT_BGR_SUPPORTED) static void gp_abgr16(Pixel *p, png_const_voidp pb) { png_const_uint_16p pp = voidcast(png_const_uint_16p, pb); p->r = pp[3]; p->g = pp[2]; p->b = pp[1]; p->a = pp[0]; } #endif /* Given a format, return the correct one of the above functions. */ static void (* get_pixel(png_uint_32 format))(Pixel *p, png_const_voidp pb) { /* The color-map flag is irrelevant here - the caller of the function * returned must either pass the buffer or, for a color-mapped image, the * correct entry in the color-map. */ if (format & PNG_FORMAT_FLAG_LINEAR) { if (format & PNG_FORMAT_FLAG_COLOR) { # ifdef PNG_FORMAT_BGR_SUPPORTED if (format & PNG_FORMAT_FLAG_BGR) { if (format & PNG_FORMAT_FLAG_ALPHA) { # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) return gp_abgr16; else # endif return gp_bgra16; } else return gp_bgr16; } else # endif { if (format & PNG_FORMAT_FLAG_ALPHA) { # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) return gp_argb16; else # endif return gp_rgba16; } else return gp_rgb16; } } else { if (format & PNG_FORMAT_FLAG_ALPHA) { # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) return gp_ag16; else # endif return gp_ga16; } else return gp_g16; } } else { if (format & PNG_FORMAT_FLAG_COLOR) { # ifdef PNG_FORMAT_BGR_SUPPORTED if (format & PNG_FORMAT_FLAG_BGR) { if (format & PNG_FORMAT_FLAG_ALPHA) { # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) return gp_abgr8; else # endif return gp_bgra8; } else return gp_bgr8; } else # endif { if (format & PNG_FORMAT_FLAG_ALPHA) { # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) return gp_argb8; else # endif return gp_rgba8; } else return gp_rgb8; } } else { if (format & PNG_FORMAT_FLAG_ALPHA) { # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) return gp_ag8; else # endif return gp_ga8; } else return gp_g8; } } } /* Convertion between pixel formats. The code above effectively eliminates the * component ordering changes leaving three basic changes: * * 1) Remove an alpha channel by pre-multiplication or compositing on a * background color. (Adding an alpha channel is a no-op.) * * 2) Remove color by mapping to grayscale. (Grayscale to color is a no-op.) * * 3) Convert between 8-bit and 16-bit components. (Both directtions are * relevant.) * * This gives the following base format conversion matrix: * * OUT: ----- 8-bit ----- ----- 16-bit ----- * IN G GA RGB RGBA G GA RGB RGBA * 8 G . . . . lin lin lin lin * 8 GA bckg . bckc . pre' pre pre' pre * 8 RGB g8 g8 . . glin glin lin lin * 8 RGBA g8b g8 bckc . gpr' gpre pre' pre * 16 G sRGB sRGB sRGB sRGB . . . . * 16 GA b16g unpg b16c unpc A . A . * 16 RGB sG sG sRGB sRGB g16 g16 . . * 16 RGBA gb16 sGp cb16 sCp g16 g16' A . * * 8-bit to 8-bit: * bckg: composite on gray background * bckc: composite on color background * g8: convert sRGB components to sRGB grayscale * g8b: convert sRGB components to grayscale and composite on gray background * * 8-bit to 16-bit: * lin: make sRGB components linear, alpha := 65535 * pre: make sRGB components linear and premultiply by alpha (scale alpha) * pre': as 'pre' but alpha := 65535 * glin: make sRGB components linear, convert to grayscale, alpha := 65535 * gpre: make sRGB components grayscale and linear and premultiply by alpha * gpr': as 'gpre' but alpha := 65535 * * 16-bit to 8-bit: * sRGB: convert linear components to sRGB, alpha := 255 * unpg: unpremultiply gray component and convert to sRGB (scale alpha) * unpc: unpremultiply color components and convert to sRGB (scale alpha) * b16g: composite linear onto gray background and convert the result to sRGB * b16c: composite linear onto color background and convert the result to sRGB * sG: convert linear RGB to sRGB grayscale * sGp: unpremultiply RGB then convert to sRGB grayscale * sCp: unpremultiply RGB then convert to sRGB * gb16: composite linear onto background and convert to sRGB grayscale * (order doesn't matter, the composite and grayscale operations permute) * cb16: composite linear onto background and convert to sRGB * * 16-bit to 16-bit: * A: set alpha to 65535 * g16: convert linear RGB to linear grayscale (alpha := 65535) * g16': as 'g16' but alpha is unchanged */ /* Simple copy: */ static void gpc_noop(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = in->r; out->g = in->g; out->b = in->b; out->a = in->a; } #if ALLOW_UNUSED_GPC static void gpc_nop8(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->a == 0) out->r = out->g = out->b = 255; else { out->r = in->r; out->g = in->g; out->b = in->b; } out->a = in->a; } #endif #if ALLOW_UNUSED_GPC static void gpc_nop6(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->a == 0) out->r = out->g = out->b = 65535; else { out->r = in->r; out->g = in->g; out->b = in->b; } out->a = in->a; } #endif /* 8-bit to 8-bit conversions */ /* bckg: composite on gray background */ static void gpc_bckg(Pixel *out, const Pixel *in, const Background *back) { if (in->a <= 0) out->r = out->g = out->b = back->ig; else if (in->a >= 255) out->r = out->g = out->b = in->g; else { double a = in->a / 255.; out->r = out->g = out->b = sRGB(sRGB_to_d[in->g] * a + back->dg * (1-a)); } out->a = 255; } /* bckc: composite on color background */ static void gpc_bckc(Pixel *out, const Pixel *in, const Background *back) { if (in->a <= 0) { out->r = back->ir; out->g = back->ig; out->b = back->ib; } else if (in->a >= 255) { out->r = in->r; out->g = in->g; out->b = in->b; } else { double a = in->a / 255.; out->r = sRGB(sRGB_to_d[in->r] * a + back->dr * (1-a)); out->g = sRGB(sRGB_to_d[in->g] * a + back->dg * (1-a)); out->b = sRGB(sRGB_to_d[in->b] * a + back->db * (1-a)); } out->a = 255; } /* g8: convert sRGB components to sRGB grayscale */ static void gpc_g8(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = in->g; else out->r = out->g = out->b = sRGB(YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b])); out->a = in->a; } /* g8b: convert sRGB components to grayscale and composite on gray background */ static void gpc_g8b(Pixel *out, const Pixel *in, const Background *back) { if (in->a <= 0) out->r = out->g = out->b = back->ig; else if (in->a >= 255) { if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = in->g; else out->r = out->g = out->b = sRGB(YfromRGB( sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b])); } else { double a = in->a/255.; out->r = out->g = out->b = sRGB(a * YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b]) + back->dg * (1-a)); } out->a = 255; } /* 8-bit to 16-bit conversions */ /* lin: make sRGB components linear, alpha := 65535 */ static void gpc_lin(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilinear(in->r); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilinear(in->b); } else { out->g = ilinear(in->g); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilinear(in->b); } out->a = 65535; } /* pre: make sRGB components linear and premultiply by alpha (scale alpha) */ static void gpc_pre(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilineara(in->r, in->a); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilineara(in->b, in->a); } else { out->g = ilineara(in->g, in->a); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilineara(in->b, in->a); } out->a = in->a * 257; } /* pre': as 'pre' but alpha := 65535 */ static void gpc_preq(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilineara(in->r, in->a); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilineara(in->b, in->a); } else { out->g = ilineara(in->g, in->a); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilineara(in->b, in->a); } out->a = 65535; } /* glin: make sRGB components linear, convert to grayscale, alpha := 65535 */ static void gpc_glin(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = ilinear(in->g); else out->r = out->g = out->b = u16d(65535 * YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b])); out->a = 65535; } /* gpre: make sRGB components grayscale and linear and premultiply by alpha */ static void gpc_gpre(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = ilineara(in->g, in->a); else out->r = out->g = out->b = u16d(in->a * 257 * YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b])); out->a = 257 * in->a; } /* gpr': as 'gpre' but alpha := 65535 */ static void gpc_gprq(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = ilineara(in->g, in->a); else out->r = out->g = out->b = u16d(in->a * 257 * YfromRGB(sRGB_to_d[in->r], sRGB_to_d[in->g], sRGB_to_d[in->b])); out->a = 65535; } /* 8-bit to 16-bit conversions for gAMA 45455 encoded values */ /* Lin: make gAMA 45455 components linear, alpha := 65535 */ static void gpc_Lin(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilinear_g22(in->r); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilinear_g22(in->b); } else { out->g = ilinear_g22(in->g); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilinear_g22(in->b); } out->a = 65535; } #if ALLOW_UNUSED_GPC /* Pre: make gAMA 45455 components linear and premultiply by alpha (scale alpha) */ static void gpc_Pre(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilineara_g22(in->r, in->a); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilineara_g22(in->b, in->a); } else { out->g = ilineara_g22(in->g, in->a); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilineara_g22(in->b, in->a); } out->a = in->a * 257; } #endif #if ALLOW_UNUSED_GPC /* Pre': as 'Pre' but alpha := 65535 */ static void gpc_Preq(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilineara_g22(in->r, in->a); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilineara_g22(in->b, in->a); } else { out->g = ilineara_g22(in->g, in->a); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilineara_g22(in->b, in->a); } out->a = 65535; } #endif #if ALLOW_UNUSED_GPC /* Glin: make gAMA 45455 components linear, convert to grayscale, alpha := 65535 */ static void gpc_Glin(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = ilinear_g22(in->g); else out->r = out->g = out->b = u16d(65535 * YfromRGB(g22_to_d[in->r], g22_to_d[in->g], g22_to_d[in->b])); out->a = 65535; } #endif #if ALLOW_UNUSED_GPC /* Gpre: make gAMA 45455 components grayscale and linear and premultiply by * alpha. */ static void gpc_Gpre(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = ilineara_g22(in->g, in->a); else out->r = out->g = out->b = u16d(in->a * 257 * YfromRGB(g22_to_d[in->r], g22_to_d[in->g], g22_to_d[in->b])); out->a = 257 * in->a; } #endif #if ALLOW_UNUSED_GPC /* Gpr': as 'Gpre' but alpha := 65535 */ static void gpc_Gprq(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->r == in->g && in->g == in->b) out->r = out->g = out->b = ilineara_g22(in->g, in->a); else out->r = out->g = out->b = u16d(in->a * 257 * YfromRGB(g22_to_d[in->r], g22_to_d[in->g], g22_to_d[in->b])); out->a = 65535; } #endif /* 16-bit to 8-bit conversions */ /* sRGB: convert linear components to sRGB, alpha := 255 */ static void gpc_sRGB(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = isRGB(in->r); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = isRGB(in->b); } else { out->g = isRGB(in->g); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = isRGB(in->b); } out->a = 255; } /* unpg: unpremultiply gray component and convert to sRGB (scale alpha) */ static void gpc_unpg(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->a <= 128) { out->r = out->g = out->b = 255; out->a = 0; } else { out->r = out->g = out->b = sRGB((double)in->g / in->a); out->a = u8d(in->a / 257.); } } /* unpc: unpremultiply color components and convert to sRGB (scale alpha) */ static void gpc_unpc(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->a <= 128) { out->r = out->g = out->b = 255; out->a = 0; } else { out->r = sRGB((double)in->r / in->a); out->g = sRGB((double)in->g / in->a); out->b = sRGB((double)in->b / in->a); out->a = u8d(in->a / 257.); } } /* b16g: composite linear onto gray background and convert the result to sRGB */ static void gpc_b16g(Pixel *out, const Pixel *in, const Background *back) { if (in->a <= 0) out->r = out->g = out->b = back->ig; else { double a = in->a/65535.; double a1 = 1-a; a /= 65535; out->r = out->g = out->b = sRGB(in->g * a + back->dg * a1); } out->a = 255; } /* b16c: composite linear onto color background and convert the result to sRGB*/ static void gpc_b16c(Pixel *out, const Pixel *in, const Background *back) { if (in->a <= 0) { out->r = back->ir; out->g = back->ig; out->b = back->ib; } else { double a = in->a/65535.; double a1 = 1-a; a /= 65535; out->r = sRGB(in->r * a + back->dr * a1); out->g = sRGB(in->g * a + back->dg * a1); out->b = sRGB(in->b * a + back->db * a1); } out->a = 255; } /* sG: convert linear RGB to sRGB grayscale */ static void gpc_sG(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = out->g = out->b = sRGB(YfromRGBint(in->r, in->g, in->b)/65535); out->a = 255; } /* sGp: unpremultiply RGB then convert to sRGB grayscale */ static void gpc_sGp(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->a <= 128) { out->r = out->g = out->b = 255; out->a = 0; } else { out->r = out->g = out->b = sRGB(YfromRGBint(in->r, in->g, in->b)/in->a); out->a = u8d(in->a / 257.); } } /* sCp: unpremultiply RGB then convert to sRGB */ static void gpc_sCp(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->a <= 128) { out->r = out->g = out->b = 255; out->a = 0; } else { out->r = sRGB((double)in->r / in->a); out->g = sRGB((double)in->g / in->a); out->b = sRGB((double)in->b / in->a); out->a = u8d(in->a / 257.); } } /* gb16: composite linear onto background and convert to sRGB grayscale */ /* (order doesn't matter, the composite and grayscale operations permute) */ static void gpc_gb16(Pixel *out, const Pixel *in, const Background *back) { if (in->a <= 0) out->r = out->g = out->b = back->ig; else if (in->a >= 65535) out->r = out->g = out->b = isRGB(in->g); else { double a = in->a / 65535.; double a1 = 1-a; a /= 65535; out->r = out->g = out->b = sRGB(in->g * a + back->dg * a1); } out->a = 255; } /* cb16: composite linear onto background and convert to sRGB */ static void gpc_cb16(Pixel *out, const Pixel *in, const Background *back) { if (in->a <= 0) { out->r = back->ir; out->g = back->ig; out->b = back->ib; } else if (in->a >= 65535) { out->r = isRGB(in->r); out->g = isRGB(in->g); out->b = isRGB(in->b); } else { double a = in->a / 65535.; double a1 = 1-a; a /= 65535; out->r = sRGB(in->r * a + back->dr * a1); out->g = sRGB(in->g * a + back->dg * a1); out->b = sRGB(in->b * a + back->db * a1); } out->a = 255; } /* 16-bit to 16-bit conversions */ /* A: set alpha to 65535 */ static void gpc_A(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = in->r; out->g = in->g; out->b = in->b; out->a = 65535; } /* g16: convert linear RGB to linear grayscale (alpha := 65535) */ static void gpc_g16(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = out->g = out->b = u16d(YfromRGBint(in->r, in->g, in->b)); out->a = 65535; } /* g16': as 'g16' but alpha is unchanged */ static void gpc_g16q(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = out->g = out->b = u16d(YfromRGBint(in->r, in->g, in->b)); out->a = in->a; } #if ALLOW_UNUSED_GPC /* Unused functions (to hide them from GCC unused function warnings) */ void (* const gpc_unused[]) (Pixel *out, const Pixel *in, const Background *back) = { gpc_Pre, gpc_Preq, gpc_Glin, gpc_Gpre, gpc_Gprq, gpc_nop8, gpc_nop6 }; #endif /* OUT: ----- 8-bit ----- ----- 16-bit ----- * IN G GA RGB RGBA G GA RGB RGBA * 8 G . . . . lin lin lin lin * 8 GA bckg . bckc . pre' pre pre' pre * 8 RGB g8 g8 . . glin glin lin lin * 8 RGBA g8b g8 bckc . gpr' gpre pre' pre * 16 G sRGB sRGB sRGB sRGB . . . . * 16 GA b16g unpg b16c unpc A . A . * 16 RGB sG sG sRGB sRGB g16 g16 . . * 16 RGBA gb16 sGp cb16 sCp g16 g16' A . * * The matrix is held in an array indexed thus: * * gpc_fn[out_format & BASE_FORMATS][in_format & BASE_FORMATS]; */ /* This will produce a compile time error if the FORMAT_FLAG values don't * match the above matrix! */ #if PNG_FORMAT_FLAG_ALPHA == 1 && PNG_FORMAT_FLAG_COLOR == 2 &&\ PNG_FORMAT_FLAG_LINEAR == 4 static void (* const gpc_fn[8/*in*/][8/*out*/]) (Pixel *out, const Pixel *in, const Background *back) = { /*out: G-8 GA-8 RGB-8 RGBA-8 G-16 GA-16 RGB-16 RGBA-16 */ {gpc_noop,gpc_noop,gpc_noop,gpc_noop, gpc_Lin, gpc_Lin, gpc_Lin, gpc_Lin }, {gpc_bckg,gpc_noop,gpc_bckc,gpc_noop, gpc_preq,gpc_pre, gpc_preq,gpc_pre }, {gpc_g8, gpc_g8, gpc_noop,gpc_noop, gpc_glin,gpc_glin,gpc_lin, gpc_lin }, {gpc_g8b, gpc_g8, gpc_bckc,gpc_noop, gpc_gprq,gpc_gpre,gpc_preq,gpc_pre }, {gpc_sRGB,gpc_sRGB,gpc_sRGB,gpc_sRGB, gpc_noop,gpc_noop,gpc_noop,gpc_noop}, {gpc_b16g,gpc_unpg,gpc_b16c,gpc_unpc, gpc_A, gpc_noop,gpc_A, gpc_noop}, {gpc_sG, gpc_sG, gpc_sRGB,gpc_sRGB, gpc_g16, gpc_g16, gpc_noop,gpc_noop}, {gpc_gb16,gpc_sGp, gpc_cb16,gpc_sCp, gpc_g16, gpc_g16q,gpc_A, gpc_noop} }; /* The array is repeated for the cases where both the input and output are color * mapped because then different algorithms are used. */ static void (* const gpc_fn_colormapped[8/*in*/][8/*out*/]) (Pixel *out, const Pixel *in, const Background *back) = { /*out: G-8 GA-8 RGB-8 RGBA-8 G-16 GA-16 RGB-16 RGBA-16 */ {gpc_noop,gpc_noop,gpc_noop,gpc_noop, gpc_lin, gpc_lin, gpc_lin, gpc_lin }, {gpc_bckg,gpc_noop,gpc_bckc,gpc_noop, gpc_preq,gpc_pre, gpc_preq,gpc_pre }, {gpc_g8, gpc_g8, gpc_noop,gpc_noop, gpc_glin,gpc_glin,gpc_lin, gpc_lin }, {gpc_g8b, gpc_g8, gpc_bckc,gpc_noop, gpc_gprq,gpc_gpre,gpc_preq,gpc_pre }, {gpc_sRGB,gpc_sRGB,gpc_sRGB,gpc_sRGB, gpc_noop,gpc_noop,gpc_noop,gpc_noop}, {gpc_b16g,gpc_unpg,gpc_b16c,gpc_unpc, gpc_A, gpc_noop,gpc_A, gpc_noop}, {gpc_sG, gpc_sG, gpc_sRGB,gpc_sRGB, gpc_g16, gpc_g16, gpc_noop,gpc_noop}, {gpc_gb16,gpc_sGp, gpc_cb16,gpc_sCp, gpc_g16, gpc_g16q,gpc_A, gpc_noop} }; /* The error arrays record the error in the same matrix; 64 entries, however * the different algorithms used in libpng for colormap and direct conversions * mean that four separate matrices are used (for each combination of * colormapped and direct.) * * In some cases the conversion between sRGB formats goes via a linear * intermediate; an sRGB to linear conversion (as above) is followed by a simple * linear to sRGB step with no other conversions. This is done by a separate * error array from an arbitrary 'in' format to one of the four basic outputs * (since final output is always sRGB not colormapped). * * These arrays may be modified if the --accumulate flag is set during the run; * then instead of logging errors they are simply added in. * * The three entries are currently for transparent, partially transparent and * opaque input pixel values. Notice that alpha should be exact in each case. * * Errors in alpha should only occur when converting from a direct format * to a colormapped format, when alpha is effectively smashed (so large * errors can occur.) There should be no error in the '0' and 'opaque' * values. The fourth entry in the array is used for the alpha error (and it * should always be zero for the 'via linear' case since this is never color * mapped.) * * Mapping to a colormap smashes the colors, it is necessary to have separate * values for these cases because they are much larger; it is very much * impossible to obtain a reasonable result, these are held in * gpc_error_to_colormap. */ #if PNG_FORMAT_FLAG_COLORMAP == 8 /* extra check also required */ # include "pngstest-errors.h" /* machine generated */ #endif /* COLORMAP flag check */ #endif /* flag checks */ typedef struct { /* Basic pixel information: */ Image* in_image; /* Input image */ const Image* out_image; /* Output image */ /* 'background' is the value passed to the gpc_ routines, it may be NULL if * it should not be used (*this* program has an error if it crashes as a * result!) */ Background background_color; const Background* background; /* Precalculated values: */ int in_opaque; /* Value of input alpha that is opaque */ int is_palette; /* Sample values come from the palette */ int accumulate; /* Accumlate component errors (don't log) */ int output_8bit; /* Output is 8-bit (else 16-bit) */ void (*in_gp)(Pixel*, png_const_voidp); void (*out_gp)(Pixel*, png_const_voidp); void (*transform)(Pixel *out, const Pixel *in, const Background *back); /* A function to perform the required transform */ void (*from_linear)(Pixel *out, const Pixel *in, const Background *back); /* For 'via_linear' transforms the final, from linear, step, else NULL */ png_uint_16 error[4]; /* Three error values for transparent, partially transparent and opaque * input pixels (in turn). */ png_uint_16 *error_ptr; /* Where these are stored in the static array (for 'accumulate') */ } Transform; /* Return a 'transform' as above for the given format conversion. */ static void transform_from_formats(Transform *result, Image *in_image, const Image *out_image, png_const_colorp background, int via_linear) { png_uint_32 in_format, out_format; png_uint_32 in_base, out_base; memset(result, 0, sizeof *result); /* Store the original images for error messages */ result->in_image = in_image; result->out_image = out_image; in_format = in_image->image.format; out_format = out_image->image.format; if (in_format & PNG_FORMAT_FLAG_LINEAR) result->in_opaque = 65535; else result->in_opaque = 255; result->output_8bit = (out_format & PNG_FORMAT_FLAG_LINEAR) == 0; result->is_palette = 0; /* set by caller if required */ result->accumulate = (in_image->opts & ACCUMULATE) != 0; /* The loaders (which need the ordering information) */ result->in_gp = get_pixel(in_format); result->out_gp = get_pixel(out_format); /* Remove the ordering information: */ in_format &= BASE_FORMATS | PNG_FORMAT_FLAG_COLORMAP; in_base = in_format & BASE_FORMATS; out_format &= BASE_FORMATS | PNG_FORMAT_FLAG_COLORMAP; out_base = out_format & BASE_FORMATS; if (via_linear) { /* Check for an error in this program: */ if (out_format & (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLORMAP)) { fprintf(stderr, "internal transform via linear error 0x%x->0x%x\n", in_format, out_format); exit(1); } result->transform = gpc_fn[in_base][out_base | PNG_FORMAT_FLAG_LINEAR]; result->from_linear = gpc_fn[out_base | PNG_FORMAT_FLAG_LINEAR][out_base]; result->error_ptr = gpc_error_via_linear[in_format][out_format]; } else if (~in_format & out_format & PNG_FORMAT_FLAG_COLORMAP) { /* The input is not colormapped but the output is, the errors will * typically be large (only the grayscale-no-alpha case permits preserving * even 8-bit values.) */ result->transform = gpc_fn[in_base][out_base]; result->from_linear = NULL; result->error_ptr = gpc_error_to_colormap[in_base][out_base]; } else { /* The caller handles the colormap->pixel value conversion, so the * transform function just gets a pixel value, however because libpng * currently contains a different implementation for mapping a colormap if * both input and output are colormapped we need different conversion * functions to deal with errors in the libpng implementation. */ if (in_format & out_format & PNG_FORMAT_FLAG_COLORMAP) result->transform = gpc_fn_colormapped[in_base][out_base]; else result->transform = gpc_fn[in_base][out_base]; result->from_linear = NULL; result->error_ptr = gpc_error[in_format][out_format]; } /* Follow the libpng simplified API rules to work out what to pass to the gpc * routines as a background value, if one is not required pass NULL so that * this program crashes in the even of a programming error. */ result->background = NULL; /* default: not required */ /* Rule 1: background only need be supplied if alpha is to be removed */ if (in_format & ~out_format & PNG_FORMAT_FLAG_ALPHA) { /* The input value is 'NULL' to use the background and (otherwise) an sRGB * background color (to use a solid color). The code above uses a fixed * byte value, BUFFER_INIT8, for buffer even for 16-bit output. For * linear (16-bit) output the sRGB background color is ignored; the * composition is always on the background (so BUFFER_INIT8 * 257), except * that for the colormap (i.e. linear colormapped output) black is used. */ result->background = &result->background_color; if (out_format & PNG_FORMAT_FLAG_LINEAR || via_linear) { if (out_format & PNG_FORMAT_FLAG_COLORMAP) { result->background_color.ir = result->background_color.ig = result->background_color.ib = 0; result->background_color.dr = result->background_color.dg = result->background_color.db = 0; } else { result->background_color.ir = result->background_color.ig = result->background_color.ib = BUFFER_INIT8 * 257; result->background_color.dr = result->background_color.dg = result->background_color.db = 0; } } else /* sRGB output */ { if (background != NULL) { if (out_format & PNG_FORMAT_FLAG_COLOR) { result->background_color.ir = background->red; result->background_color.ig = background->green; result->background_color.ib = background->blue; /* TODO: sometimes libpng uses the power law conversion here, how * to handle this? */ result->background_color.dr = sRGB_to_d[background->red]; result->background_color.dg = sRGB_to_d[background->green]; result->background_color.db = sRGB_to_d[background->blue]; } else /* grayscale: libpng only looks at 'g' */ { result->background_color.ir = result->background_color.ig = result->background_color.ib = background->green; /* TODO: sometimes libpng uses the power law conversion here, how * to handle this? */ result->background_color.dr = result->background_color.dg = result->background_color.db = sRGB_to_d[background->green]; } } else if ((out_format & PNG_FORMAT_FLAG_COLORMAP) == 0) { result->background_color.ir = result->background_color.ig = result->background_color.ib = BUFFER_INIT8; /* TODO: sometimes libpng uses the power law conversion here, how * to handle this? */ result->background_color.dr = result->background_color.dg = result->background_color.db = sRGB_to_d[BUFFER_INIT8]; } /* Else the output is colormapped and a background color must be * provided; if pngstest crashes then that is a bug in this program * (though libpng should png_error as well.) */ else result->background = NULL; } } if (result->background == NULL) { result->background_color.ir = result->background_color.ig = result->background_color.ib = -1; /* not used */ result->background_color.dr = result->background_color.dg = result->background_color.db = 1E30; /* not used */ } /* Copy the error values into the Transform: */ result->error[0] = result->error_ptr[0]; result->error[1] = result->error_ptr[1]; result->error[2] = result->error_ptr[2]; result->error[3] = result->error_ptr[3]; } /* Compare two pixels. * * OLD error values: static int error_to_linear = 811; * by experiment * static int error_to_linear_grayscale = 424; * by experiment * static int error_to_sRGB = 6; * by experiment * static int error_to_sRGB_grayscale = 17; * libpng error by calculation + 2 by experiment * static int error_in_compose = 2; * by experiment * static int error_in_premultiply = 1; * * The following is *just* the result of a round trip from 8-bit sRGB to linear * then back to 8-bit sRGB when it is done by libpng. There are two problems: * * 1) libpng currently uses a 2.2 power law with no linear segment, this results * in instability in the low values and even with 16-bit precision sRGB(1) ends * up mapping to sRGB(0) as a result of rounding in the 16-bit representation. * This gives an error of 1 in the handling of value 1 only. * * 2) libpng currently uses an intermediate 8-bit linear value in gamma * correction of 8-bit values. This results in many more errors, the worse of * which is mapping sRGB(14) to sRGB(0). * * The general 'error_via_linear' is more complex because of pre-multiplication, * this compounds the 8-bit errors according to the alpha value of the pixel. * As a result 256 values are pre-calculated for error_via_linear. */ #if 0 static int error_in_libpng_gamma; static int error_via_linear[256]; /* Indexed by 8-bit alpha */ static void init_error_via_linear(void) { int alpha; error_via_linear[0] = 255; /* transparent pixel */ for (alpha=1; alpha<=255; ++alpha) { /* 16-bit values less than 128.5 get rounded to 8-bit 0 and so the worst * case error arises with 16-bit 128.5, work out what sRGB * (non-associated) value generates 128.5; any value less than this is * going to map to 0, so the worst error is floor(value). * * Note that errors are considerably higher (more than a factor of 2) * because libpng uses a simple power law for sRGB data at present. * * Add .1 for arithmetic errors inside libpng. */ double v = floor(255*pow(.5/*(128.5 * 255 / 65535)*/ / alpha, 1/2.2)+.1); error_via_linear[alpha] = (int)v; } /* This is actually 14.99, but, despite the closeness to 15, 14 seems to work * ok in this case. */ error_in_libpng_gamma = 14; } #endif static void print_pixel(char string[64], const Pixel *pixel, png_uint_32 format) { switch (format & (PNG_FORMAT_FLAG_ALPHA|PNG_FORMAT_FLAG_COLOR)) { case 0: sprintf(string, "%s(%d)", format_names[format], pixel->g); break; case PNG_FORMAT_FLAG_ALPHA: sprintf(string, "%s(%d,%d)", format_names[format], pixel->g, pixel->a); break; case PNG_FORMAT_FLAG_COLOR: sprintf(string, "%s(%d,%d,%d)", format_names[format], pixel->r, pixel->g, pixel->b); break; case PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA: sprintf(string, "%s(%d,%d,%d,%d)", format_names[format], pixel->r, pixel->g, pixel->b, pixel->a); break; default: sprintf(string, "invalid-format"); break; } } static int logpixel(const Transform *transform, png_uint_32 x, png_uint_32 y, const Pixel *in, const Pixel *calc, const Pixel *out, const char *reason) { const png_uint_32 in_format = transform->in_image->image.format; const png_uint_32 out_format = transform->out_image->image.format; png_uint_32 back_format = out_format & ~PNG_FORMAT_FLAG_ALPHA; const char *via_linear = ""; char pixel_in[64], pixel_calc[64], pixel_out[64], pixel_loc[64]; char background_info[100]; print_pixel(pixel_in, in, in_format); print_pixel(pixel_calc, calc, out_format); print_pixel(pixel_out, out, out_format); if (transform->is_palette) sprintf(pixel_loc, "palette: %lu", (unsigned long)y); else sprintf(pixel_loc, "%lu,%lu", (unsigned long)x, (unsigned long)y); if (transform->from_linear != NULL) { via_linear = " (via linear)"; /* And as a result the *read* format which did any background processing * was itself linear, so the background color information is also * linear. */ back_format |= PNG_FORMAT_FLAG_LINEAR; } if (transform->background != NULL) { Pixel back; char pixel_back[64]; back.r = transform->background->ir; back.g = transform->background->ig; back.b = transform->background->ib; back.a = -1; /* not used */ print_pixel(pixel_back, &back, back_format); sprintf(background_info, " on background %s", pixel_back); } else background_info[0] = 0; if (transform->in_image->file_name != transform->out_image->file_name) { char error_buffer[512]; sprintf(error_buffer, "(%s) %s error%s:\n %s%s ->\n %s\n not: %s.\n" "Use --preserve and examine: ", pixel_loc, reason, via_linear, pixel_in, background_info, pixel_out, pixel_calc); return logerror(transform->in_image, transform->in_image->file_name, error_buffer, transform->out_image->file_name); } else { char error_buffer[512]; sprintf(error_buffer, "(%s) %s error%s:\n %s%s ->\n %s\n not: %s.\n" " The error happened when reading the original file with this format.", pixel_loc, reason, via_linear, pixel_in, background_info, pixel_out, pixel_calc); return logerror(transform->in_image, transform->in_image->file_name, error_buffer, ""); } } static int cmppixel(Transform *transform, png_const_voidp in, png_const_voidp out, png_uint_32 x, png_uint_32 y/*or palette index*/) { int maxerr; png_const_charp errmsg; Pixel pixel_in, pixel_calc, pixel_out; transform->in_gp(&pixel_in, in); if (transform->from_linear == NULL) transform->transform(&pixel_calc, &pixel_in, transform->background); else { transform->transform(&pixel_out, &pixel_in, transform->background); transform->from_linear(&pixel_calc, &pixel_out, NULL); } transform->out_gp(&pixel_out, out); /* Eliminate the case where the input and output values match exactly. */ if (pixel_calc.a == pixel_out.a && pixel_calc.r == pixel_out.r && pixel_calc.g == pixel_out.g && pixel_calc.b == pixel_out.b) return 1; /* Eliminate the case where the output pixel is transparent and the output * is 8-bit - any component values are valid. Don't check the input alpha * here to also skip the 16-bit small alpha cases. */ if (transform->output_8bit && pixel_calc.a == 0 && pixel_out.a == 0) return 1; /* Check for alpha errors first; an alpha error can damage the components too * so avoid spurious checks on components if one is found. */ errmsg = NULL; { int err_a = abs(pixel_calc.a-pixel_out.a); if (err_a > transform->error[3]) { /* If accumulating check the components too */ if (transform->accumulate) transform->error[3] = (png_uint_16)err_a; else errmsg = "alpha"; } } /* Now if *either* of the output alphas are 0 but alpha is within tolerance * eliminate the 8-bit component comparison. */ if (errmsg == NULL && transform->output_8bit && (pixel_calc.a == 0 || pixel_out.a == 0)) return 1; if (errmsg == NULL) /* else just signal an alpha error */ { int err_r = abs(pixel_calc.r - pixel_out.r); int err_g = abs(pixel_calc.g - pixel_out.g); int err_b = abs(pixel_calc.b - pixel_out.b); int limit; if ((err_r | err_g | err_b) == 0) return 1; /* exact match */ /* Mismatch on a component, check the input alpha */ if (pixel_in.a >= transform->in_opaque) { errmsg = "opaque component"; limit = 2; /* opaque */ } else if (pixel_in.a > 0) { errmsg = "alpha component"; limit = 1; /* partially transparent */ } else { errmsg = "transparent component (background)"; limit = 0; /* transparent */ } maxerr = err_r; if (maxerr < err_g) maxerr = err_g; if (maxerr < err_b) maxerr = err_b; if (maxerr <= transform->error[limit]) return 1; /* within the error limits */ /* Handle a component mis-match; log it, just return an error code, or * accumulate it. */ if (transform->accumulate) { transform->error[limit] = (png_uint_16)maxerr; return 1; /* to cause the caller to keep going */ } } /* Failure to match and not accumulating, so the error must be logged. */ return logpixel(transform, x, y, &pixel_in, &pixel_calc, &pixel_out, errmsg); } static png_byte component_loc(png_byte loc[4], png_uint_32 format) { /* Given a format return the number of channels and the location of * each channel. * * The mask 'loc' contains the component offset of the channels in the * following order. Note that if 'format' is grayscale the entries 1-3 must * all contain the location of the gray channel. * * 0: alpha * 1: red or gray * 2: green or gray * 3: blue or gray */ png_byte channels; if (format & PNG_FORMAT_FLAG_COLOR) { channels = 3; loc[2] = 1; # ifdef PNG_FORMAT_BGR_SUPPORTED if (format & PNG_FORMAT_FLAG_BGR) { loc[1] = 2; loc[3] = 0; } else # endif { loc[1] = 0; loc[3] = 2; } } else { channels = 1; loc[1] = loc[2] = loc[3] = 0; } if (format & PNG_FORMAT_FLAG_ALPHA) { # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) { loc[0] = 0; ++loc[1]; ++loc[2]; ++loc[3]; } else # endif loc[0] = channels; ++channels; } else loc[0] = 4; /* not present */ return channels; } /* Compare two images, the original 'a', which was written out then read back in * to * give image 'b'. The formats may have been changed. */ static int compare_two_images(Image *a, Image *b, int via_linear, png_const_colorp background) { ptrdiff_t stridea = a->stride; ptrdiff_t strideb = b->stride; png_const_bytep rowa = a->buffer+16; png_const_bytep rowb = b->buffer+16; const png_uint_32 width = a->image.width; const png_uint_32 height = a->image.height; const png_uint_32 formata = a->image.format; const png_uint_32 formatb = b->image.format; const unsigned int a_sample = PNG_IMAGE_SAMPLE_SIZE(formata); const unsigned int b_sample = PNG_IMAGE_SAMPLE_SIZE(formatb); int alpha_added, alpha_removed; int bchannels; int btoa[4]; png_uint_32 y; Transform tr; /* This should never happen: */ if (width != b->image.width || height != b->image.height) return logerror(a, a->file_name, ": width x height changed: ", b->file_name); /* Set up the background and the transform */ transform_from_formats(&tr, a, b, background, via_linear); /* Find the first row and inter-row space. */ if (!(formata & PNG_FORMAT_FLAG_COLORMAP) && (formata & PNG_FORMAT_FLAG_LINEAR)) stridea *= 2; if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) && (formatb & PNG_FORMAT_FLAG_LINEAR)) strideb *= 2; if (stridea < 0) rowa += (height-1) * (-stridea); if (strideb < 0) rowb += (height-1) * (-strideb); /* First shortcut the two colormap case by comparing the image data; if it * matches then we expect the colormaps to match, although this is not * absolutely necessary for an image match. If the colormaps fail to match * then there is a problem in libpng. */ if (formata & formatb & PNG_FORMAT_FLAG_COLORMAP) { /* Only check colormap entries that actually exist; */ png_const_bytep ppa, ppb; int match; png_byte in_use[256], amax = 0, bmax = 0; memset(in_use, 0, sizeof in_use); ppa = rowa; ppb = rowb; /* Do this the slow way to accumulate the 'in_use' flags, don't break out * of the loop until the end; this validates the color-mapped data to * ensure all pixels are valid color-map indexes. */ for (y=0, match=1; y bmax) bmax = bval; if (bval != aval) match = 0; in_use[aval] = 1; if (aval > amax) amax = aval; } } /* If the buffers match then the colormaps must too. */ if (match) { /* Do the color-maps match, entry by entry? Only check the 'in_use' * entries. An error here should be logged as a color-map error. */ png_const_bytep a_cmap = (png_const_bytep)a->colormap; png_const_bytep b_cmap = (png_const_bytep)b->colormap; int result = 1; /* match by default */ /* This is used in logpixel to get the error message correct. */ tr.is_palette = 1; for (y=0; y<256; ++y, a_cmap += a_sample, b_cmap += b_sample) if (in_use[y]) { /* The colormap entries should be valid, but because libpng doesn't * do any checking at present the original image may contain invalid * pixel values. These cause an error here (at present) unless * accumulating errors in which case the program just ignores them. */ if (y >= a->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)a->image.colormap_entries); logerror(a, a->file_name, ": bad pixel index: ", pindex); } result = 0; } else if (y >= b->image.colormap_entries) { if ((b->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)b->image.colormap_entries); logerror(b, b->file_name, ": bad pixel index: ", pindex); } result = 0; } /* All the mismatches are logged here; there can only be 256! */ else if (!cmppixel(&tr, a_cmap, b_cmap, 0, y)) result = 0; } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; result = 1; /* force a continue */ } return result; } /* else the image buffers don't match pixel-wise so compare sample values * instead, but first validate that the pixel indexes are in range (but * only if not accumulating, when the error is ignored.) */ else if ((a->opts & ACCUMULATE) == 0) { /* Check the original image first, * TODO: deal with input images with bad pixel values? */ if (amax >= a->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", amax, (unsigned long)a->image.colormap_entries); return logerror(a, a->file_name, ": bad pixel index: ", pindex); } else if (bmax >= b->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", bmax, (unsigned long)b->image.colormap_entries); return logerror(b, b->file_name, ": bad pixel index: ", pindex); } } } /* We can directly compare pixel values without the need to use the read * or transform support (i.e. a memory compare) if: * * 1) The bit depth has not changed. * 2) RGB to grayscale has not been done (the reverse is ok; we just compare * the three RGB values to the original grayscale.) * 3) An alpha channel has not been removed from an 8-bit format, or the * 8-bit alpha value of the pixel was 255 (opaque). * * If an alpha channel has been *added* then it must have the relevant opaque * value (255 or 65535). * * The fist two the tests (in the order given above) (using the boolean * equivalence !a && !b == !(a || b)) */ if (!(((formata ^ formatb) & PNG_FORMAT_FLAG_LINEAR) | (formata & (formatb ^ PNG_FORMAT_FLAG_COLOR) & PNG_FORMAT_FLAG_COLOR))) { /* Was an alpha channel changed? */ const png_uint_32 alpha_changed = (formata ^ formatb) & PNG_FORMAT_FLAG_ALPHA; /* Was an alpha channel removed? (The third test.) If so the direct * comparison is only possible if the input alpha is opaque. */ alpha_removed = (formata & alpha_changed) != 0; /* Was an alpha channel added? */ alpha_added = (formatb & alpha_changed) != 0; /* The channels may have been moved between input and output, this finds * out how, recording the result in the btoa array, which says where in * 'a' to find each channel of 'b'. If alpha was added then btoa[alpha] * ends up as 4 (and is not used.) */ { int i; png_byte aloc[4]; png_byte bloc[4]; /* The following are used only if the formats match, except that * 'bchannels' is a flag for matching formats. btoa[x] says, for each * channel in b, where to find the corresponding value in a, for the * bchannels. achannels may be different for a gray to rgb transform * (a will be 1 or 2, b will be 3 or 4 channels.) */ (void)component_loc(aloc, formata); bchannels = component_loc(bloc, formatb); /* Hence the btoa array. */ for (i=0; i<4; ++i) if (bloc[i] < 4) btoa[bloc[i]] = aloc[i]; /* may be '4' for alpha */ if (alpha_added) alpha_added = bloc[0]; /* location of alpha channel in image b */ else alpha_added = 4; /* Won't match an image b channel */ if (alpha_removed) alpha_removed = aloc[0]; /* location of alpha channel in image a */ else alpha_removed = 4; } } else { /* Direct compare is not possible, cancel out all the corresponding local * variables. */ bchannels = 0; alpha_removed = alpha_added = 4; btoa[3] = btoa[2] = btoa[1] = btoa[0] = 4; /* 4 == not present */ } for (y=0; ycolormap + a_sample * *ppa++; else psa = ppa, ppa += a_sample; if (formatb & PNG_FORMAT_FLAG_COLORMAP) psb = (png_const_bytep)b->colormap + b_sample * *ppb++; else psb = ppb, ppb += b_sample; /* Do the fast test if possible. */ if (bchannels) { /* Check each 'b' channel against either the corresponding 'a' * channel or the opaque alpha value, as appropriate. If * alpha_removed value is set (not 4) then also do this only if the * 'a' alpha channel (alpha_removed) is opaque; only relevant for * the 8-bit case. */ if (formatb & PNG_FORMAT_FLAG_LINEAR) /* 16-bit checks */ { png_const_uint_16p pua = aligncastconst(png_const_uint_16p, psa); png_const_uint_16p pub = aligncastconst(png_const_uint_16p, psb); switch (bchannels) { case 4: if (pua[btoa[3]] != pub[3]) break; case 3: if (pua[btoa[2]] != pub[2]) break; case 2: if (pua[btoa[1]] != pub[1]) break; case 1: if (pua[btoa[0]] != pub[0]) break; if (alpha_added != 4 && pub[alpha_added] != 65535) break; continue; /* x loop */ default: break; /* impossible */ } } else if (alpha_removed == 4 || psa[alpha_removed] == 255) { switch (bchannels) { case 4: if (psa[btoa[3]] != psb[3]) break; case 3: if (psa[btoa[2]] != psb[2]) break; case 2: if (psa[btoa[1]] != psb[1]) break; case 1: if (psa[btoa[0]] != psb[0]) break; if (alpha_added != 4 && psb[alpha_added] != 255) break; continue; /* x loop */ default: break; /* impossible */ } } } /* If we get to here the fast match failed; do the slow match for this * pixel. */ if (!cmppixel(&tr, psa, psb, x, y) && (a->opts & KEEP_GOING) == 0) return 0; /* error case */ } } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; } return 1; } /* Read the file; how the read gets done depends on which of input_file and * input_memory have been set. */ static int read_file(Image *image, png_uint_32 format, png_const_colorp background) { memset(&image->image, 0, sizeof image->image); image->image.version = PNG_IMAGE_VERSION; if (image->input_memory != NULL) { if (!png_image_begin_read_from_memory(&image->image, image->input_memory, image->input_memory_size)) return logerror(image, "memory init: ", image->file_name, ""); } # ifdef PNG_STDIO_SUPPORTED else if (image->input_file != NULL) { if (!png_image_begin_read_from_stdio(&image->image, image->input_file)) return logerror(image, "stdio init: ", image->file_name, ""); } else { if (!png_image_begin_read_from_file(&image->image, image->file_name)) return logerror(image, "file init: ", image->file_name, ""); } # else else { return logerror(image, "unsupported file/stdio init: ", image->file_name, ""); } # endif /* This must be set after the begin_read call: */ if (image->opts & sRGB_16BIT) image->image.flags |= PNG_IMAGE_FLAG_16BIT_sRGB; /* Have an initialized image with all the data we need plus, maybe, an * allocated file (myfile) or buffer (mybuffer) that need to be freed. */ { int result; png_uint_32 image_format; /* Print both original and output formats. */ image_format = image->image.format; if (image->opts & VERBOSE) { printf("%s %lu x %lu %s -> %s", image->file_name, (unsigned long)image->image.width, (unsigned long)image->image.height, format_names[image_format & FORMAT_MASK], (format & FORMAT_NO_CHANGE) != 0 || image->image.format == format ? "no change" : format_names[format & FORMAT_MASK]); if (background != NULL) printf(" background(%d,%d,%d)\n", background->red, background->green, background->blue); else printf("\n"); fflush(stdout); } /* 'NO_CHANGE' combined with the color-map flag forces the base format * flags to be set on read to ensure that the original representation is * not lost in the pass through a colormap format. */ if ((format & FORMAT_NO_CHANGE) != 0) { if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0 && (image_format & PNG_FORMAT_FLAG_COLORMAP) != 0) format = (image_format & ~BASE_FORMATS) | (format & BASE_FORMATS); else format = image_format; } image->image.format = format; image->stride = PNG_IMAGE_ROW_STRIDE(image->image) + image->stride_extra; allocbuffer(image); result = png_image_finish_read(&image->image, background, image->buffer+16, (png_int_32)image->stride, image->colormap); checkbuffer(image, image->file_name); if (result) return checkopaque(image); else return logerror(image, image->file_name, ": image read failed", ""); } } /* Reads from a filename, which must be in image->file_name, but uses * image->opts to choose the method. The file is always read in its native * format (the one the simplified API suggests). */ static int read_one_file(Image *image) { if (!(image->opts & USE_FILE) || (image->opts & USE_STDIO)) { /* memory or stdio. */ FILE *f = fopen(image->file_name, "rb"); if (f != NULL) { if (image->opts & USE_FILE) image->input_file = f; else /* memory */ { if (fseek(f, 0, SEEK_END) == 0) { long int cb = ftell(f); if (cb > 0) { #ifndef __COVERITY__ if ((unsigned long int)cb <= (size_t)~(size_t)0) #endif { png_bytep b = voidcast(png_bytep, malloc((size_t)cb)); if (b != NULL) { rewind(f); if (fread(b, (size_t)cb, 1, f) == 1) { fclose(f); image->input_memory_size = cb; image->input_memory = b; } else { free(b); return logclose(image, f, image->file_name, ": read failed: "); } } else return logclose(image, f, image->file_name, ": out of memory: "); } else return logclose(image, f, image->file_name, ": file too big for this architecture: "); /* cb is the length of the file as a (long) and * this is greater than the maximum amount of * memory that can be requested from malloc. */ } else if (cb == 0) return logclose(image, f, image->file_name, ": zero length: "); else return logclose(image, f, image->file_name, ": tell failed: "); } else return logclose(image, f, image->file_name, ": seek failed: "); } } else return logerror(image, image->file_name, ": open failed: ", strerror(errno)); } return read_file(image, FORMAT_NO_CHANGE, NULL); } #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED static int write_one_file(Image *output, Image *image, int convert_to_8bit) { if (image->opts & FAST_WRITE) image->image.flags |= PNG_IMAGE_FLAG_FAST; if (image->opts & USE_STDIO) { #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED #ifndef __COVERITY__ FILE *f = tmpfile(); #else /* Experimental. Coverity says tmpfile() is insecure because it * generates predictable names. * * It is possible to satisfy Coverity by using mkstemp(); however, * any platform supporting mkstemp() undoubtedly has a secure tmpfile() * implementation as well, and doesn't need the fix. Note that * the fix won't work on platforms that don't support mkstemp(). * * https://www.securecoding.cert.org/confluence/display/c/ * FIO21-C.+Do+not+create+temporary+files+in+shared+directories * says that most historic implementations of tmpfile() provide * only a limited number of possible temporary file names * (usually 26) before file names are recycled. That article also * provides a secure solution that unfortunately depends upon mkstemp(). */ char tmpfile[] = "pngstest-XXXXXX"; int filedes; FILE *f; umask(0177); filedes = mkstemp(tmpfile); if (filedes < 0) f = NULL; else { f = fdopen(filedes,"w+"); /* Hide the filename immediately and ensure that the file does * not exist after the program ends */ (void) unlink(tmpfile); } #endif if (f != NULL) { if (png_image_write_to_stdio(&image->image, f, convert_to_8bit, image->buffer+16, (png_int_32)image->stride, image->colormap)) { if (fflush(f) == 0) { rewind(f); initimage(output, image->opts, "tmpfile", image->stride_extra); output->input_file = f; if (!checkopaque(image)) return 0; } else return logclose(image, f, "tmpfile", ": flush: "); } else { fclose(f); return logerror(image, "tmpfile", ": write failed", ""); } } else return logerror(image, "tmpfile", ": open: ", strerror(errno)); #else /* SIMPLIFIED_WRITE_STDIO */ return logerror(image, "tmpfile", ": open: unsupported", ""); #endif /* SIMPLIFIED_WRITE_STDIO */ } else if (image->opts & USE_FILE) { #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED static int counter = 0; char name[32]; sprintf(name, "%s%d.png", tmpf, ++counter); if (png_image_write_to_file(&image->image, name, convert_to_8bit, image->buffer+16, (png_int_32)image->stride, image->colormap)) { initimage(output, image->opts, output->tmpfile_name, image->stride_extra); /* Afterwards, or freeimage will delete it! */ strcpy(output->tmpfile_name, name); if (!checkopaque(image)) return 0; } else return logerror(image, name, ": write failed", ""); #else /* SIMPLIFIED_WRITE_STDIO */ return logerror(image, "stdio", ": open: unsupported", ""); #endif /* SIMPLIFIED_WRITE_STDIO */ } else /* use memory */ { png_alloc_size_t size; if (png_image_write_get_memory_size(image->image, size, convert_to_8bit, image->buffer+16, (png_int_32)image->stride, image->colormap)) { /* This is non-fatal but ignoring it was causing serious problems in * the macro to be ignored: */ if (size > PNG_IMAGE_PNG_SIZE_MAX(image->image)) return logerror(image, "memory", ": PNG_IMAGE_SIZE_MAX wrong", ""); initimage(output, image->opts, "memory", image->stride_extra); output->input_memory = malloc(size); if (output->input_memory != NULL) { output->input_memory_size = size; if (png_image_write_to_memory(&image->image, output->input_memory, &output->input_memory_size, convert_to_8bit, image->buffer+16, (png_int_32)image->stride, image->colormap)) { /* This is also non-fatal but it safes safer to error out anyway: */ if (size != output->input_memory_size) return logerror(image, "memory", ": memory size wrong", ""); } else return logerror(image, "memory", ": write failed", ""); } else return logerror(image, "memory", ": out of memory", ""); } else return logerror(image, "memory", ": get size:", ""); } /* 'output' has an initialized temporary image, read this back in and compare * this against the original: there should be no change since the original * format was written unmodified unless 'convert_to_8bit' was specified. * However, if the original image was color-mapped, a simple read will zap * the linear, color and maybe alpha flags, this will cause spurious failures * under some circumstances. */ if (read_file(output, image->image.format | FORMAT_NO_CHANGE, NULL)) { png_uint_32 original_format = image->image.format; if (convert_to_8bit) original_format &= ~PNG_FORMAT_FLAG_LINEAR; if ((output->image.format & BASE_FORMATS) != (original_format & BASE_FORMATS)) return logerror(image, image->file_name, ": format changed on read: ", output->file_name); return compare_two_images(image, output, 0/*via linear*/, NULL); } else return logerror(output, output->tmpfile_name, ": read of new file failed", ""); } #endif static int testimage(Image *image, png_uint_32 opts, format_list *pf) { int result; Image copy; /* Copy the original data, stealing it from 'image' */ checkopaque(image); copy = *image; copy.opts = opts; copy.buffer = NULL; copy.bufsize = 0; copy.allocsize = 0; image->input_file = NULL; image->input_memory = NULL; image->input_memory_size = 0; image->tmpfile_name[0] = 0; { png_uint_32 counter; Image output; newimage(&output); result = 1; /* Use the low bit of 'counter' to indicate whether or not to do alpha * removal with a background color or by composting onto the image; this * step gets skipped if it isn't relevant */ for (counter=0; counter<2*FORMAT_COUNT; ++counter) if (format_isset(pf, counter >> 1)) { png_uint_32 format = counter >> 1; png_color background_color; png_colorp background = NULL; /* If there is a format change that removes the alpha channel then * the background is relevant. If the output is 8-bit color-mapped * then a background color *must* be provided, otherwise there are * two tests to do - one with a color, the other with NULL. The * NULL test happens second. */ if ((counter & 1) == 0) { if ((format & PNG_FORMAT_FLAG_ALPHA) == 0 && (image->image.format & PNG_FORMAT_FLAG_ALPHA) != 0) { /* Alpha/transparency will be removed, the background is * relevant: make it a color the first time */ random_color(&background_color); background = &background_color; /* BUT if the output is to a color-mapped 8-bit format then * the background must always be a color, so increment 'counter' * to skip the NULL test. */ if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0 && (format & PNG_FORMAT_FLAG_LINEAR) == 0) ++counter; } /* Otherwise an alpha channel is not being eliminated, just leave * background NULL and skip the (counter & 1) NULL test. */ else ++counter; } /* else just use NULL for background */ resetimage(©); copy.opts = opts; /* in case read_file needs to change it */ result = read_file(©, format, background); if (!result) break; /* Make sure the file just read matches the original file. */ result = compare_two_images(image, ©, 0/*via linear*/, background); if (!result) break; # ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED /* Write the *copy* just made to a new file to make sure the write * side works ok. Check the conversion to sRGB if the copy is * linear. */ output.opts = opts; result = write_one_file(&output, ©, 0/*convert to 8bit*/); if (!result) break; /* Validate against the original too; the background is needed here * as well so that compare_two_images knows what color was used. */ result = compare_two_images(image, &output, 0, background); if (!result) break; if ((format & PNG_FORMAT_FLAG_LINEAR) != 0 && (format & PNG_FORMAT_FLAG_COLORMAP) == 0) { /* 'output' is linear, convert to the corresponding sRGB format. */ output.opts = opts; result = write_one_file(&output, ©, 1/*convert to 8bit*/); if (!result) break; /* This may involve a conversion via linear; in the ideal world * this would round-trip correctly, but libpng 1.5.7 is not the * ideal world so allow a drift (error_via_linear). * * 'image' has an alpha channel but 'output' does not then there * will a strip-alpha-channel operation (because 'output' is * linear), handle this by composing on black when doing the * comparison. */ result = compare_two_images(image, &output, 1/*via_linear*/, background); if (!result) break; } # endif /* PNG_SIMPLIFIED_WRITE_SUPPORTED */ } freeimage(&output); } freeimage(©); return result; } static int test_one_file(const char *file_name, format_list *formats, png_uint_32 opts, int stride_extra, int log_pass) { int result; Image image; if (!(opts & NO_RESEED)) reseed(); /* ensure that the random numbers don't depend on file order */ newimage(&image); initimage(&image, opts, file_name, stride_extra); result = read_one_file(&image); if (result) result = testimage(&image, opts, formats); freeimage(&image); /* Ensure that stderr is flushed into any log file */ fflush(stderr); if (log_pass) { if (result) printf("PASS:"); else printf("FAIL:"); # ifndef PNG_SIMPLIFIED_WRITE_SUPPORTED printf(" (no write)"); # endif print_opts(opts); printf(" %s\n", file_name); /* stdout may not be line-buffered if it is piped to a file, so: */ fflush(stdout); } else if (!result) exit(1); return result; } int main(int argc, char **argv) { png_uint_32 opts = FAST_WRITE | STRICT; format_list formats; const char *touch = NULL; int log_pass = 0; int redundant = 0; int stride_extra = 0; int retval = 0; int c; #if PNG_LIBPNG_VER >= 10700 /* This error should not exist in 1.7 or later: */ opts |= GBG_ERROR; #endif init_sRGB_to_d(); #if 0 init_error_via_linear(); #endif format_init(&formats); reseed(); /* initialize random number seeds */ for (c=1; c= sizeof tmpf) { fflush(stdout); fprintf(stderr, "%s: %s is too long for a temp file prefix\n", argv[0], argv[c]); exit(99); } /* Safe: checked above */ strncpy(tmpf, argv[c], sizeof (tmpf)-1); } else { fflush(stdout); fprintf(stderr, "%s: %s requires a temporary file prefix\n", argv[0], arg); exit(99); } } else if (strcmp(arg, "--touch") == 0) { if (c+1 < argc) touch = argv[++c]; else { fflush(stdout); fprintf(stderr, "%s: %s requires a file name argument\n", argv[0], arg); exit(99); } } else if (arg[0] == '+') { png_uint_32 format = formatof(arg+1); if (format > FORMAT_COUNT) exit(99); format_set(&formats, format); } else if (arg[0] == '-' && arg[1] != 0 && (arg[1] != '0' || arg[2] != 0)) { fflush(stdout); fprintf(stderr, "%s: unknown option: %s\n", argv[0], arg); exit(99); } else { if (format_is_initial(&formats)) format_default(&formats, redundant); if (arg[0] == '-') { const int term = (arg[1] == '0' ? 0 : '\n'); unsigned int ich = 0; /* Loop reading files, use a static buffer to simplify this and just * stop if the name gets to long. */ static char buffer[4096]; do { int ch = getchar(); /* Don't allow '\0' in file names, and terminate with '\n' or, * for -0, just '\0' (use -print0 to find to make this work!) */ if (ch == EOF || ch == term || ch == 0) { buffer[ich] = 0; if (ich > 0 && !test_one_file(buffer, &formats, opts, stride_extra, log_pass)) retval = 1; if (ch == EOF) break; ich = 0; --ich; /* so that the increment below sets it to 0 again */ } else buffer[ich] = (char)ch; } while (++ich < sizeof buffer); if (ich) { buffer[32] = 0; buffer[4095] = 0; fprintf(stderr, "%s...%s: file name too long\n", buffer, buffer+(4096-32)); exit(99); } } else if (!test_one_file(arg, &formats, opts, stride_extra, log_pass)) retval = 1; } } if (opts & ACCUMULATE) { unsigned int in; printf("/* contrib/libtests/pngstest-errors.h\n"); printf(" *\n"); printf(" * BUILT USING:" PNG_HEADER_VERSION_STRING); printf(" *\n"); printf(" * This code is released under the libpng license.\n"); printf(" * For conditions of distribution and use, see the disclaimer\n"); printf(" * and license in png.h\n"); printf(" *\n"); printf(" * THIS IS A MACHINE GENERATED FILE: do not edit it directly!\n"); printf(" * Instead run:\n"); printf(" *\n"); printf(" * pngstest --accumulate\n"); printf(" *\n"); printf(" * on as many PNG files as possible; at least PNGSuite and\n"); printf(" * contrib/libtests/testpngs.\n"); printf(" */\n"); printf("static png_uint_16 gpc_error[16/*in*/][16/*out*/][4/*a*/] =\n"); printf("{\n"); for (in=0; in<16; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<16; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 15) { putchar(','); if (out % 4 == 3) printf("\n "); } } printf("\n }"); if (in < 15) putchar(','); else putchar('\n'); } printf("};\n"); printf("static png_uint_16 gpc_error_via_linear[16][4/*out*/][4] =\n"); printf("{\n"); for (in=0; in<16; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<4; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error_via_linear[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 3) putchar(','); } printf("\n }"); if (in < 15) putchar(','); else putchar('\n'); } printf("};\n"); printf("static png_uint_16 gpc_error_to_colormap[8/*i*/][8/*o*/][4] =\n"); printf("{\n"); for (in=0; in<8; ++in) { unsigned int out; printf(" { /* input: %s */\n ", format_names[in]); for (out=0; out<8; ++out) { unsigned int alpha; printf(" {"); for (alpha=0; alpha<4; ++alpha) { printf(" %d", gpc_error_to_colormap[in][out][alpha]); if (alpha < 3) putchar(','); } printf(" }"); if (out < 7) { putchar(','); if (out % 4 == 3) printf("\n "); } } printf("\n }"); if (in < 7) putchar(','); else putchar('\n'); } printf("};\n"); printf("/* END MACHINE GENERATED */\n"); } if (retval == 0 && touch != NULL) { FILE *fsuccess = fopen(touch, "wt"); if (fsuccess != NULL) { int error = 0; fprintf(fsuccess, "PNG simple API tests succeeded\n"); fflush(fsuccess); error = ferror(fsuccess); if (fclose(fsuccess) || error) { fflush(stdout); fprintf(stderr, "%s: write failed\n", touch); exit(99); } } else { fflush(stdout); fprintf(stderr, "%s: open failed\n", touch); exit(99); } } return retval; } #else /* !PNG_SIMPLIFIED_READ_SUPPORTED */ int main(void) { fprintf(stderr, "pngstest: no read support in libpng, test skipped\n"); /* So the test is skipped: */ return SKIP; } #endif /* PNG_SIMPLIFIED_READ_SUPPORTED */ ================================================ FILE: tess-two/jni/libpng/contrib/libtests/pngunknown.c ================================================ /* pngunknown.c - test the read side unknown chunk handling * * Last changed in libpng 1.6.22 [May 26, 2016] * Copyright (c) 2015,2016 Glenn Randers-Pehrson * Written by John Cunningham Bowler * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * NOTES: * This is a C program that is intended to be linked against libpng. It * allows the libpng unknown handling code to be tested by interpreting * arguments to save or discard combinations of chunks. The program is * currently just a minimal validation for the built-in libpng facilities. */ #include #include #include #include /* Define the following to use this test against your installed libpng, rather * than the one being built here: */ #ifdef PNG_FREESTANDING_TESTS # include #else # include "../../png.h" #endif /* 1.6.1 added support for the configure test harness, which uses 77 to indicate * a skipped test, in earlier versions we need to succeed on a skipped test, so: */ #if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H) # define SKIP 77 #else # define SKIP 0 #endif /* Since this program tests the ability to change the unknown chunk handling * these must be defined: */ #if defined(PNG_SET_UNKNOWN_CHUNKS_SUPPORTED) &&\ defined(PNG_STDIO_SUPPORTED) &&\ defined(PNG_READ_SUPPORTED) /* One of these must be defined to allow us to find out what happened. It is * still useful to set unknown chunk handling without either of these in order * to cause *known* chunks to be discarded. This can be a significant * efficiency gain, but it can't really be tested here. */ #if defined(PNG_READ_USER_CHUNKS_SUPPORTED) ||\ defined(PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED) #if PNG_LIBPNG_VER < 10500 /* This deliberately lacks the PNG_CONST. */ typedef png_byte *png_const_bytep; /* This is copied from 1.5.1 png.h: */ #define PNG_INTERLACE_ADAM7_PASSES 7 #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7) #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7) #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3) #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3) #define PNG_PASS_ROWS(height, pass) (((height)+(((1<>PNG_PASS_ROW_SHIFT(pass)) #define PNG_PASS_COLS(width, pass) (((width)+(((1<>PNG_PASS_COL_SHIFT(pass)) #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \ (((yIn)<>(((7-(off))-(pass))<<2)) & 0xFU) | \ ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U)) #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \ ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1) #define PNG_COL_IN_INTERLACE_PASS(x, pass) \ ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1) /* These are needed too for the default build: */ #define PNG_WRITE_16BIT_SUPPORTED #define PNG_READ_16BIT_SUPPORTED /* This comes from pnglibconf.h afer 1.5: */ #define PNG_FP_1 100000 #define PNG_GAMMA_THRESHOLD_FIXED\ ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1)) #endif #if PNG_LIBPNG_VER < 10600 /* 1.6.0 constifies many APIs. The following exists to allow pngvalid to be * compiled against earlier versions. */ # define png_const_structp png_structp #endif #if PNG_LIBPNG_VER < 10700 /* Copied from libpng 1.7.0 png.h */ #define PNG_u2(b1, b2) (((unsigned int)(b1) << 8) + (b2)) #define PNG_U16(b1, b2) ((png_uint_16)PNG_u2(b1, b2)) #define PNG_U32(b1, b2, b3, b4)\ (((png_uint_32)PNG_u2(b1, b2) << 16) + PNG_u2(b3, b4)) /* Constants for known chunk types. */ #define png_IDAT PNG_U32( 73, 68, 65, 84) #define png_IEND PNG_U32( 73, 69, 78, 68) #define png_IHDR PNG_U32( 73, 72, 68, 82) #define png_PLTE PNG_U32( 80, 76, 84, 69) #define png_bKGD PNG_U32( 98, 75, 71, 68) #define png_cHRM PNG_U32( 99, 72, 82, 77) #define png_fRAc PNG_U32(102, 82, 65, 99) /* registered, not defined */ #define png_gAMA PNG_U32(103, 65, 77, 65) #define png_gIFg PNG_U32(103, 73, 70, 103) #define png_gIFt PNG_U32(103, 73, 70, 116) /* deprecated */ #define png_gIFx PNG_U32(103, 73, 70, 120) #define png_hIST PNG_U32(104, 73, 83, 84) #define png_iCCP PNG_U32(105, 67, 67, 80) #define png_iTXt PNG_U32(105, 84, 88, 116) #define png_oFFs PNG_U32(111, 70, 70, 115) #define png_pCAL PNG_U32(112, 67, 65, 76) #define png_pHYs PNG_U32(112, 72, 89, 115) #define png_sBIT PNG_U32(115, 66, 73, 84) #define png_sCAL PNG_U32(115, 67, 65, 76) #define png_sPLT PNG_U32(115, 80, 76, 84) #define png_sRGB PNG_U32(115, 82, 71, 66) #define png_sTER PNG_U32(115, 84, 69, 82) #define png_tEXt PNG_U32(116, 69, 88, 116) #define png_tIME PNG_U32(116, 73, 77, 69) #define png_tRNS PNG_U32(116, 82, 78, 83) #define png_zTXt PNG_U32(122, 84, 88, 116) /* Test on flag values as defined in the spec (section 5.4): */ #define PNG_CHUNK_ANCILLARY(c) (1 & ((c) >> 29)) #define PNG_CHUNK_CRITICAL(c) (!PNG_CHUNK_ANCILLARY(c)) #define PNG_CHUNK_PRIVATE(c) (1 & ((c) >> 21)) #define PNG_CHUNK_RESERVED(c) (1 & ((c) >> 13)) #define PNG_CHUNK_SAFE_TO_COPY(c) (1 & ((c) >> 5)) #endif /* PNG_LIBPNG_VER < 10700 */ #ifdef __cplusplus # define this not_the_cpp_this # define new not_the_cpp_new # define voidcast(type, value) static_cast(value) #else # define voidcast(type, value) (value) #endif /* __cplusplus */ /* Unused formal parameter errors are removed using the following macro which is * expected to have no bad effects on performance. */ #ifndef UNUSED # if defined(__GNUC__) || defined(_MSC_VER) # define UNUSED(param) (void)param; # else # define UNUSED(param) # endif #endif /* Types of chunks not known to libpng */ #define png_vpAg PNG_U32(118, 112, 65, 103) /* Chunk information */ #define PNG_INFO_tEXt 0x10000000U #define PNG_INFO_iTXt 0x20000000U #define PNG_INFO_zTXt 0x40000000U #define PNG_INFO_sTER 0x01000000U #define PNG_INFO_vpAg 0x02000000U #define ABSENT 0 #define START 1 #define END 2 static struct { char name[5]; png_uint_32 flag; png_uint_32 tag; int unknown; /* Chunk not known to libpng */ int all; /* Chunk set by the '-1' option */ int position; /* position in pngtest.png */ int keep; /* unknown handling setting */ } chunk_info[] = { /* Critical chunks */ { "IDAT", PNG_INFO_IDAT, png_IDAT, 0, 0, START, 0 }, /* must be [0] */ { "PLTE", PNG_INFO_PLTE, png_PLTE, 0, 0, ABSENT, 0 }, /* Non-critical chunks that libpng handles */ /* This is a mess but it seems to be the only way to do it - there is no way * to check for a definition outside a #if. */ { "bKGD", PNG_INFO_bKGD, png_bKGD, # ifdef PNG_READ_bKGD_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "cHRM", PNG_INFO_cHRM, png_cHRM, # ifdef PNG_READ_cHRM_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "gAMA", PNG_INFO_gAMA, png_gAMA, # ifdef PNG_READ_gAMA_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "hIST", PNG_INFO_hIST, png_hIST, # ifdef PNG_READ_hIST_SUPPORTED 0, # else 1, # endif 1, ABSENT, 0 }, { "iCCP", PNG_INFO_iCCP, png_iCCP, # ifdef PNG_READ_iCCP_SUPPORTED 0, # else 1, # endif 1, ABSENT, 0 }, { "iTXt", PNG_INFO_iTXt, png_iTXt, # ifdef PNG_READ_iTXt_SUPPORTED 0, # else 1, # endif 1, ABSENT, 0 }, { "oFFs", PNG_INFO_oFFs, png_oFFs, # ifdef PNG_READ_oFFs_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "pCAL", PNG_INFO_pCAL, png_pCAL, # ifdef PNG_READ_pCAL_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "pHYs", PNG_INFO_pHYs, png_pHYs, # ifdef PNG_READ_pHYs_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "sBIT", PNG_INFO_sBIT, png_sBIT, # ifdef PNG_READ_sBIT_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "sCAL", PNG_INFO_sCAL, png_sCAL, # ifdef PNG_READ_sCAL_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "sPLT", PNG_INFO_sPLT, png_sPLT, # ifdef PNG_READ_sPLT_SUPPORTED 0, # else 1, # endif 1, ABSENT, 0 }, { "sRGB", PNG_INFO_sRGB, png_sRGB, # ifdef PNG_READ_sRGB_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "tEXt", PNG_INFO_tEXt, png_tEXt, # ifdef PNG_READ_tEXt_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "tIME", PNG_INFO_tIME, png_tIME, # ifdef PNG_READ_tIME_SUPPORTED 0, # else 1, # endif 1, START, 0 }, { "tRNS", PNG_INFO_tRNS, png_tRNS, # ifdef PNG_READ_tRNS_SUPPORTED 0, # else 1, # endif 0, ABSENT, 0 }, { "zTXt", PNG_INFO_zTXt, png_zTXt, # ifdef PNG_READ_zTXt_SUPPORTED 0, # else 1, # endif 1, END, 0 }, /* No libpng handling */ { "sTER", PNG_INFO_sTER, png_sTER, 1, 1, START, 0 }, { "vpAg", PNG_INFO_vpAg, png_vpAg, 1, 0, START, 0 }, }; #define NINFO ((int)((sizeof chunk_info)/(sizeof chunk_info[0]))) static void clear_keep(void) { int i = NINFO; while (--i >= 0) chunk_info[i].keep = 0; } static int find(const char *name) { int i = NINFO; while (--i >= 0) { if (memcmp(chunk_info[i].name, name, 4) == 0) break; } return i; } static int findb(const png_byte *name) { int i = NINFO; while (--i >= 0) { if (memcmp(chunk_info[i].name, name, 4) == 0) break; } return i; } static int find_by_flag(png_uint_32 flag) { int i = NINFO; while (--i >= 0) if (chunk_info[i].flag == flag) return i; fprintf(stderr, "pngunknown: internal error\n"); exit(4); } static int ancillary(const char *name) { return PNG_CHUNK_ANCILLARY(PNG_U32(name[0], name[1], name[2], name[3])); } #ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED static int ancillaryb(const png_byte *name) { return PNG_CHUNK_ANCILLARY(PNG_U32(name[0], name[1], name[2], name[3])); } #endif /* Type of an error_ptr */ typedef struct { jmp_buf error_return; png_structp png_ptr; png_infop info_ptr, end_ptr; png_uint_32 before_IDAT; png_uint_32 after_IDAT; int error_count; int warning_count; int keep; /* the default value */ const char *program; const char *file; const char *test; } display; static const char init[] = "initialization"; static const char cmd[] = "command line"; static void init_display(display *d, const char *program) { memset(d, 0, sizeof *d); d->png_ptr = NULL; d->info_ptr = d->end_ptr = NULL; d->error_count = d->warning_count = 0; d->program = program; d->file = program; d->test = init; } static void clean_display(display *d) { png_destroy_read_struct(&d->png_ptr, &d->info_ptr, &d->end_ptr); /* This must not happen - it might cause an app crash */ if (d->png_ptr != NULL || d->info_ptr != NULL || d->end_ptr != NULL) { fprintf(stderr, "%s(%s): png_destroy_read_struct error\n", d->file, d->test); exit(1); } } PNG_FUNCTION(void, display_exit, (display *d), static PNG_NORETURN) { ++(d->error_count); if (d->png_ptr != NULL) clean_display(d); /* During initialization and if this is a single command line argument set * exit now - there is only one test, otherwise longjmp to do the next test. */ if (d->test == init || d->test == cmd) exit(1); longjmp(d->error_return, 1); } static int display_rc(const display *d, int strict) { return d->error_count + (strict ? d->warning_count : 0); } /* libpng error and warning callbacks */ PNG_FUNCTION(void, (PNGCBAPI error), (png_structp png_ptr, const char *message), static PNG_NORETURN) { display *d = (display*)png_get_error_ptr(png_ptr); fprintf(stderr, "%s(%s): libpng error: %s\n", d->file, d->test, message); display_exit(d); } static void PNGCBAPI warning(png_structp png_ptr, const char *message) { display *d = (display*)png_get_error_ptr(png_ptr); fprintf(stderr, "%s(%s): libpng warning: %s\n", d->file, d->test, message); ++(d->warning_count); } static png_uint_32 get_valid(display *d, png_infop info_ptr) { png_uint_32 flags = png_get_valid(d->png_ptr, info_ptr, (png_uint_32)~0); /* Map the text chunks back into the flags */ { png_textp text; png_uint_32 ntext = png_get_text(d->png_ptr, info_ptr, &text, NULL); while (ntext-- > 0) switch (text[ntext].compression) { case -1: flags |= PNG_INFO_tEXt; break; case 0: flags |= PNG_INFO_zTXt; break; case 1: case 2: flags |= PNG_INFO_iTXt; break; default: fprintf(stderr, "%s(%s): unknown text compression %d\n", d->file, d->test, text[ntext].compression); display_exit(d); } } return flags; } #ifdef PNG_READ_USER_CHUNKS_SUPPORTED static int PNGCBAPI read_callback(png_structp pp, png_unknown_chunkp pc) { /* This function mimics the behavior of png_set_keep_unknown_chunks by * returning '0' to keep the chunk and '1' to discard it. */ display *d = voidcast(display*, png_get_user_chunk_ptr(pp)); int chunk = findb(pc->name); int keep, discard; if (chunk < 0) /* not one in our list, so not a known chunk */ keep = d->keep; else { keep = chunk_info[chunk].keep; if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT) { /* See the comments in png.h - use the default for unknown chunks, * do not keep known chunks. */ if (chunk_info[chunk].unknown) keep = d->keep; else keep = PNG_HANDLE_CHUNK_NEVER; } } switch (keep) { default: fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file, d->test, chunk_info[chunk].keep); display_exit(d); case PNG_HANDLE_CHUNK_AS_DEFAULT: case PNG_HANDLE_CHUNK_NEVER: discard = 1/*handled; discard*/; break; case PNG_HANDLE_CHUNK_IF_SAFE: case PNG_HANDLE_CHUNK_ALWAYS: discard = 0/*not handled; keep*/; break; } /* Also store information about this chunk in the display, the relevant flag * is set if the chunk is to be kept ('not handled'.) */ if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */ { png_uint_32 flag = chunk_info[chunk].flag; if (pc->location & PNG_AFTER_IDAT) d->after_IDAT |= flag; else d->before_IDAT |= flag; } /* However if there is no support to store unknown chunks don't ask libpng to * do it; there will be an png_error. */ # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED return discard; # else return 1; /*handled; discard*/ # endif } #endif /* READ_USER_CHUNKS_SUPPORTED */ #ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED static png_uint_32 get_unknown(display *d, png_infop info_ptr, int after_IDAT) { /* Create corresponding 'unknown' flags */ png_uint_32 flags = 0; UNUSED(after_IDAT) { png_unknown_chunkp unknown; int num_unknown = png_get_unknown_chunks(d->png_ptr, info_ptr, &unknown); while (--num_unknown >= 0) { int chunk = findb(unknown[num_unknown].name); /* Chunks not known to pngunknown must be validated here; since they * must also be unknown to libpng the 'display->keep' behavior should * have been used. */ if (chunk < 0) switch (d->keep) { default: /* impossible */ case PNG_HANDLE_CHUNK_AS_DEFAULT: case PNG_HANDLE_CHUNK_NEVER: fprintf(stderr, "%s(%s): %s: %s: unknown chunk saved\n", d->file, d->test, d->keep ? "discard" : "default", unknown[num_unknown].name); ++(d->error_count); break; case PNG_HANDLE_CHUNK_IF_SAFE: if (!ancillaryb(unknown[num_unknown].name)) { fprintf(stderr, "%s(%s): if-safe: %s: unknown critical chunk saved\n", d->file, d->test, unknown[num_unknown].name); ++(d->error_count); break; } /* FALL THROUGH (safe) */ case PNG_HANDLE_CHUNK_ALWAYS: break; } else flags |= chunk_info[chunk].flag; } } return flags; } #else /* SAVE_UNKNOWN_CHUNKS */ static png_uint_32 get_unknown(display *d, png_infop info_ptr, int after_IDAT) /* Otherwise this will return the cached values set by any user callback */ { UNUSED(info_ptr); if (after_IDAT) return d->after_IDAT; else return d->before_IDAT; } # ifndef PNG_READ_USER_CHUNKS_SUPPORTED /* The #defines above should mean this is never reached, it's just here as * a check to ensure the logic is correct. */ # error No store support and no user chunk support, this will not work # endif /* READ_USER_CHUNKS */ #endif /* SAVE_UNKNOWN_CHUNKS */ static int check(FILE *fp, int argc, const char **argv, png_uint_32p flags/*out*/, display *d, int set_callback) { int i, npasses, ipass; png_uint_32 height; d->keep = PNG_HANDLE_CHUNK_AS_DEFAULT; d->before_IDAT = 0; d->after_IDAT = 0; /* Some of these errors are permanently fatal and cause an exit here, others * are per-test and cause an error return. */ d->png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, d, error, warning); if (d->png_ptr == NULL) { fprintf(stderr, "%s(%s): could not allocate png struct\n", d->file, d->test); /* Terminate here, this error is not test specific. */ exit(1); } d->info_ptr = png_create_info_struct(d->png_ptr); d->end_ptr = png_create_info_struct(d->png_ptr); if (d->info_ptr == NULL || d->end_ptr == NULL) { fprintf(stderr, "%s(%s): could not allocate png info\n", d->file, d->test); clean_display(d); exit(1); } png_init_io(d->png_ptr, fp); # ifdef PNG_READ_USER_CHUNKS_SUPPORTED /* This is only done if requested by the caller; it interferes with the * standard store/save mechanism. */ if (set_callback) png_set_read_user_chunk_fn(d->png_ptr, d, read_callback); # else UNUSED(set_callback) # endif /* Handle each argument in turn; multiple settings are possible for the same * chunk and multiple calls will occur (the last one should override all * preceding ones). */ for (i=0; i= 10700 &&\ !defined(PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED) if (option < PNG_HANDLE_CHUNK_IF_SAFE) # endif /* 1.7+ SAVE_UNKNOWN_CHUNKS */ { png_byte name[5]; memcpy(name, chunk_info[chunk].name, 5); png_set_keep_unknown_chunks(d->png_ptr, option, name, 1); chunk_info[chunk].keep = option; } continue; } break; case 7: /* default */ if (memcmp(argv[i], "default", 7) == 0) { # if PNG_LIBPNG_VER >= 10700 &&\ !defined(PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED) if (option < PNG_HANDLE_CHUNK_IF_SAFE) # endif /* 1.7+ SAVE_UNKNOWN_CHUNKS */ png_set_keep_unknown_chunks(d->png_ptr, option, NULL, 0); d->keep = option; continue; } break; case 3: /* all */ if (memcmp(argv[i], "all", 3) == 0) { # if PNG_LIBPNG_VER >= 10700 &&\ !defined(PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED) if (option < PNG_HANDLE_CHUNK_IF_SAFE) # endif /* 1.7+ SAVE_UNKNOWN_CHUNKS */ png_set_keep_unknown_chunks(d->png_ptr, option, NULL, -1); d->keep = option; for (chunk = 0; chunk < NINFO; ++chunk) if (chunk_info[chunk].all) chunk_info[chunk].keep = option; continue; } break; default: /* some misplaced = */ break; } } fprintf(stderr, "%s(%s): %s: unrecognized chunk argument\n", d->file, d->test, argv[i]); display_exit(d); } png_read_info(d->png_ptr, d->info_ptr); switch (png_get_interlace_type(d->png_ptr, d->info_ptr)) { case PNG_INTERLACE_NONE: npasses = 1; break; case PNG_INTERLACE_ADAM7: npasses = PNG_INTERLACE_ADAM7_PASSES; break; default: /* Hard error because it is not test specific */ fprintf(stderr, "%s(%s): invalid interlace type\n", d->file, d->test); clean_display(d); exit(1); } /* Skip the image data, if IDAT is not being handled then don't do this * because it will cause a CRC error. */ if (chunk_info[0/*IDAT*/].keep == PNG_HANDLE_CHUNK_AS_DEFAULT) { png_start_read_image(d->png_ptr); height = png_get_image_height(d->png_ptr, d->info_ptr); if (npasses > 1) { png_uint_32 width = png_get_image_width(d->png_ptr, d->info_ptr); for (ipass=0; ipass 0) { png_uint_32 y; for (y=0; ypng_ptr, NULL, NULL); } } } /* interlaced */ else /* not interlaced */ { png_uint_32 y; for (y=0; ypng_ptr, NULL, NULL); } } png_read_end(d->png_ptr, d->end_ptr); flags[0] = get_valid(d, d->info_ptr); flags[1] = get_unknown(d, d->info_ptr, 0/*before IDAT*/); /* Only png_read_png sets PNG_INFO_IDAT! */ flags[chunk_info[0/*IDAT*/].keep != PNG_HANDLE_CHUNK_AS_DEFAULT] |= PNG_INFO_IDAT; flags[2] = get_valid(d, d->end_ptr); flags[3] = get_unknown(d, d->end_ptr, 1/*after IDAT*/); clean_display(d); return d->keep; } static void check_error(display *d, png_uint_32 flags, const char *message) { while (flags) { png_uint_32 flag = flags & -(png_int_32)flags; int i = find_by_flag(flag); fprintf(stderr, "%s(%s): chunk %s: %s\n", d->file, d->test, chunk_info[i].name, message); ++(d->error_count); flags &= ~flag; } } static void check_handling(display *d, int def, png_uint_32 chunks, png_uint_32 known, png_uint_32 unknown, const char *position, int set_callback) { while (chunks) { png_uint_32 flag = chunks & -(png_int_32)chunks; int i = find_by_flag(flag); int keep = chunk_info[i].keep; const char *type; const char *errorx = NULL; if (chunk_info[i].unknown) { if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT) { type = "UNKNOWN (default)"; keep = def; } else type = "UNKNOWN (specified)"; if (flag & known) errorx = "chunk processed"; else switch (keep) { case PNG_HANDLE_CHUNK_AS_DEFAULT: if (flag & unknown) errorx = "DEFAULT: unknown chunk saved"; break; case PNG_HANDLE_CHUNK_NEVER: if (flag & unknown) errorx = "DISCARD: unknown chunk saved"; break; case PNG_HANDLE_CHUNK_IF_SAFE: if (ancillary(chunk_info[i].name)) { if (!(flag & unknown)) errorx = "IF-SAFE: unknown ancillary chunk lost"; } else if (flag & unknown) errorx = "IF-SAFE: unknown critical chunk saved"; break; case PNG_HANDLE_CHUNK_ALWAYS: if (!(flag & unknown)) errorx = "SAVE: unknown chunk lost"; break; default: errorx = "internal error: bad keep"; break; } } /* unknown chunk */ else /* known chunk */ { type = "KNOWN"; if (flag & known) { /* chunk was processed, it won't have been saved because that is * caught below when checking for inconsistent processing. */ if (keep != PNG_HANDLE_CHUNK_AS_DEFAULT) errorx = "!DEFAULT: known chunk processed"; } else /* not processed */ switch (keep) { case PNG_HANDLE_CHUNK_AS_DEFAULT: errorx = "DEFAULT: known chunk not processed"; break; case PNG_HANDLE_CHUNK_NEVER: if (flag & unknown) errorx = "DISCARD: known chunk saved"; break; case PNG_HANDLE_CHUNK_IF_SAFE: if (ancillary(chunk_info[i].name)) { if (!(flag & unknown)) errorx = "IF-SAFE: known ancillary chunk lost"; } else if (flag & unknown) errorx = "IF-SAFE: known critical chunk saved"; break; case PNG_HANDLE_CHUNK_ALWAYS: if (!(flag & unknown)) errorx = "SAVE: known chunk lost"; break; default: errorx = "internal error: bad keep (2)"; break; } } if (errorx != NULL) { ++(d->error_count); fprintf(stderr, "%s(%s%s): %s %s %s: %s\n", d->file, d->test, set_callback ? ",callback" : "", type, chunk_info[i].name, position, errorx); } chunks &= ~flag; } } static void perform_one_test(FILE *fp, int argc, const char **argv, png_uint_32 *default_flags, display *d, int set_callback) { int def; png_uint_32 flags[2][4]; rewind(fp); clear_keep(); memcpy(flags[0], default_flags, sizeof flags[0]); def = check(fp, argc, argv, flags[1], d, set_callback); /* If IDAT is being handled as unknown the image read is skipped and all the * IDATs after the first end up in the end info struct, so in this case add * IDAT to the list of unknowns. (Do this after 'check' above sets the * chunk_info 'keep' fields.) * * Note that the flag setting has to be in the 'known' field to avoid * triggering the consistency check below and the flag must only be set if * there are multiple IDATs, so if the check above did find an unknown IDAT * after IDAT. */ if (chunk_info[0/*IDAT*/].keep != PNG_HANDLE_CHUNK_AS_DEFAULT && (flags[1][3] & PNG_INFO_IDAT) != 0) flags[0][2] |= PNG_INFO_IDAT; /* Chunks should either be known or unknown, never both and this should apply * whether the chunk is before or after the IDAT (actually, the app can * probably change this by swapping the handling after the image, but this * test does not do that.) */ check_error(d, (flags[0][0]|flags[0][2]) & (flags[0][1]|flags[0][3]), "chunk handled inconsistently in count tests"); check_error(d, (flags[1][0]|flags[1][2]) & (flags[1][1]|flags[1][3]), "chunk handled inconsistently in option tests"); /* Now find out what happened to each chunk before and after the IDAT and * determine if the behavior was correct. First some basic sanity checks, * any known chunk should be known in the original count, any unknown chunk * should be either known or unknown in the original. */ { png_uint_32 test; test = flags[1][0] & ~flags[0][0]; check_error(d, test, "new known chunk before IDAT"); test = flags[1][1] & ~(flags[0][0] | flags[0][1]); check_error(d, test, "new unknown chunk before IDAT"); test = flags[1][2] & ~flags[0][2]; check_error(d, test, "new known chunk after IDAT"); test = flags[1][3] & ~(flags[0][2] | flags[0][3]); check_error(d, test, "new unknown chunk after IDAT"); } /* Now each chunk in the original list should have been handled according to * the options set for that chunk, regardless of whether libpng knows about * it or not. */ check_handling(d, def, flags[0][0] | flags[0][1], flags[1][0], flags[1][1], "before IDAT", set_callback); check_handling(d, def, flags[0][2] | flags[0][3], flags[1][2], flags[1][3], "after IDAT", set_callback); } static void perform_one_test_safe(FILE *fp, int argc, const char **argv, png_uint_32 *default_flags, display *d, const char *test) { if (setjmp(d->error_return) == 0) { d->test = test; /* allow use of d->error_return */ # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED perform_one_test(fp, argc, argv, default_flags, d, 0); # endif # ifdef PNG_READ_USER_CHUNKS_SUPPORTED perform_one_test(fp, argc, argv, default_flags, d, 1); # endif d->test = init; /* prevent use of d->error_return */ } } static const char *standard_tests[] = { "discard", "default=discard", 0, "save", "default=save", 0, "if-safe", "default=if-safe", 0, "vpAg", "vpAg=if-safe", 0, "sTER", "sTER=if-safe", 0, "IDAT", "default=discard", "IDAT=save", 0, "sAPI", "bKGD=save", "cHRM=save", "gAMA=save", "all=discard", "iCCP=save", "sBIT=save", "sRGB=save", 0, 0/*end*/ }; static PNG_NORETURN void usage(const char *program, const char *reason) { fprintf(stderr, "pngunknown: %s: usage:\n %s [--strict] " "--default|{(CHNK|default|all)=(default|discard|if-safe|save)} " "testfile.png\n", reason, program); exit(99); } int main(int argc, const char **argv) { FILE *fp; png_uint_32 default_flags[4/*valid,unknown{before,after}*/]; int strict = 0, default_tests = 0; const char *count_argv = "default=save"; const char *touch_file = NULL; display d; init_display(&d, argv[0]); while (++argv, --argc > 0) { if (strcmp(*argv, "--strict") == 0) strict = 1; else if (strcmp(*argv, "--default") == 0) default_tests = 1; else if (strcmp(*argv, "--touch") == 0) { if (argc > 1) touch_file = *++argv, --argc; else usage(d.program, "--touch: missing file name"); } else break; } /* A file name is required, but there should be no other arguments if * --default was specified. */ if (argc <= 0) usage(d.program, "missing test file"); /* GCC BUG: if (default_tests && argc != 1) triggers some weird GCC argc * optimization which causes warnings with -Wstrict-overflow! */ else if (default_tests) if (argc != 1) usage(d.program, "extra arguments"); /* The name of the test file is the last argument; remove it. */ d.file = argv[--argc]; fp = fopen(d.file, "rb"); if (fp == NULL) { perror(d.file); exit(99); } /* First find all the chunks, known and unknown, in the test file, a failure * here aborts the whole test. * * If 'save' is supported then the normal saving method should happen, * otherwise if 'read' is supported then the read callback will do the * same thing. If both are supported the 'read' callback won't be * instantiated by default. If 'save' is *not* supported then a user * callback is required even though we can call png_get_unknown_chunks. */ if (check(fp, 1, &count_argv, default_flags, &d, # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED 0 # else 1 # endif ) != PNG_HANDLE_CHUNK_ALWAYS) { fprintf(stderr, "%s: %s: internal error\n", d.program, d.file); exit(99); } /* Now find what the various supplied options cause to change: */ if (!default_tests) { d.test = cmd; /* acts as a flag to say exit, do not longjmp */ # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED perform_one_test(fp, argc, argv, default_flags, &d, 0); # endif # ifdef PNG_READ_USER_CHUNKS_SUPPORTED perform_one_test(fp, argc, argv, default_flags, &d, 1); # endif d.test = init; } else { const char **test = standard_tests; /* Set the exit_test pointer here so we can continue after a libpng error. * NOTE: this leaks memory because the png_struct data from the failing * test is never freed. */ while (*test) { const char *this_test = *test++; const char **next = test; int count = display_rc(&d, strict), new_count; const char *result; int arg_count = 0; while (*next) ++next, ++arg_count; perform_one_test_safe(fp, arg_count, test, default_flags, &d, this_test); new_count = display_rc(&d, strict); if (new_count == count) result = "PASS"; else result = "FAIL"; printf("%s: %s %s\n", result, d.program, this_test); test = next+1; } } fclose(fp); if (display_rc(&d, strict) == 0) { /* Success, touch the success file if appropriate */ if (touch_file != NULL) { FILE *fsuccess = fopen(touch_file, "wt"); if (fsuccess != NULL) { int err = 0; fprintf(fsuccess, "PNG unknown tests succeeded\n"); fflush(fsuccess); err = ferror(fsuccess); if (fclose(fsuccess) || err) { fprintf(stderr, "%s: write failed\n", touch_file); exit(99); } } else { fprintf(stderr, "%s: open failed\n", touch_file); exit(99); } } return 0; } return 1; } #else /* !(READ_USER_CHUNKS || SAVE_UNKNOWN_CHUNKS) */ int main(void) { fprintf(stderr, " test ignored: no support to find out about unknown chunks\n"); /* So the test is skipped: */ return SKIP; } #endif /* READ_USER_CHUNKS || SAVE_UNKNOWN_CHUNKS */ #else /* !(SET_UNKNOWN_CHUNKS && READ) */ int main(void) { fprintf(stderr, " test ignored: no support to modify unknown chunk handling\n"); /* So the test is skipped: */ return SKIP; } #endif /* SET_UNKNOWN_CHUNKS && READ*/ ================================================ FILE: tess-two/jni/libpng/contrib/libtests/pngvalid.c ================================================ /* pngvalid.c - validate libpng by constructing then reading png files. * * Last changed in libpng 1.6.24 [August 4, 2016] * Copyright (c) 2014-2016 Glenn Randers-Pehrson * Written by John Cunningham Bowler * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * NOTES: * This is a C program that is intended to be linked against libpng. It * generates bitmaps internally, stores them as PNG files (using the * sequential write code) then reads them back (using the sequential * read code) and validates that the result has the correct data. * * The program can be modified and extended to test the correctness of * transformations performed by libpng. */ #define _POSIX_SOURCE 1 #define _ISOC99_SOURCE 1 /* For floating point */ #define _GNU_SOURCE 1 /* For the floating point exception extension */ #include #include #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H) # include #endif #ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */ # include #endif #ifndef FE_DIVBYZERO # define FE_DIVBYZERO 0 #endif #ifndef FE_INVALID # define FE_INVALID 0 #endif #ifndef FE_OVERFLOW # define FE_OVERFLOW 0 #endif /* Define the following to use this test against your installed libpng, rather * than the one being built here: */ #ifdef PNG_FREESTANDING_TESTS # include #else # include "../../png.h" #endif #ifdef PNG_ZLIB_HEADER # include PNG_ZLIB_HEADER #else # include /* For crc32 */ #endif /* 1.6.1 added support for the configure test harness, which uses 77 to indicate * a skipped test, in earlier versions we need to succeed on a skipped test, so: */ #if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H) # define SKIP 77 #else # define SKIP 0 #endif /* pngvalid requires write support and one of the fixed or floating point APIs. */ #if defined(PNG_WRITE_SUPPORTED) &&\ (defined(PNG_FIXED_POINT_SUPPORTED) || defined(PNG_FLOATING_POINT_SUPPORTED)) #if PNG_LIBPNG_VER < 10500 /* This deliberately lacks the const. */ typedef png_byte *png_const_bytep; /* This is copied from 1.5.1 png.h: */ #define PNG_INTERLACE_ADAM7_PASSES 7 #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7) #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7) #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3) #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3) #define PNG_PASS_ROWS(height, pass) (((height)+(((1<>PNG_PASS_ROW_SHIFT(pass)) #define PNG_PASS_COLS(width, pass) (((width)+(((1<>PNG_PASS_COL_SHIFT(pass)) #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \ (((yIn)<>(((7-(off))-(pass))<<2)) & 0xFU) | \ ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U)) #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \ ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1) #define PNG_COL_IN_INTERLACE_PASS(x, pass) \ ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1) /* These are needed too for the default build: */ #define PNG_WRITE_16BIT_SUPPORTED #define PNG_READ_16BIT_SUPPORTED /* This comes from pnglibconf.h afer 1.5: */ #define PNG_FP_1 100000 #define PNG_GAMMA_THRESHOLD_FIXED\ ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1)) #endif #if PNG_LIBPNG_VER < 10600 /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be * compiled against earlier versions. */ # define png_const_structp png_structp #endif #ifndef RELEASE_BUILD /* RELEASE_BUILD is true for releases and release candidates: */ # define RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC) #endif #if RELEASE_BUILD # define debugonly(something) #else /* !RELEASE_BUILD */ # define debugonly(something) something #endif /* !RELEASE_BUILD */ #include /* For floating point constants */ #include /* For malloc */ #include /* For memcpy, memset */ #include /* For floor */ /* Convenience macros. */ #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) #define CHUNK_IHDR CHUNK(73,72,68,82) #define CHUNK_PLTE CHUNK(80,76,84,69) #define CHUNK_IDAT CHUNK(73,68,65,84) #define CHUNK_IEND CHUNK(73,69,78,68) #define CHUNK_cHRM CHUNK(99,72,82,77) #define CHUNK_gAMA CHUNK(103,65,77,65) #define CHUNK_sBIT CHUNK(115,66,73,84) #define CHUNK_sRGB CHUNK(115,82,71,66) /* Unused formal parameter errors are removed using the following macro which is * expected to have no bad effects on performance. */ #ifndef UNUSED # if defined(__GNUC__) || defined(_MSC_VER) # define UNUSED(param) (void)param; # else # define UNUSED(param) # endif #endif /***************************** EXCEPTION HANDLING *****************************/ #ifdef PNG_FREESTANDING_TESTS # include #else # include "../visupng/cexcept.h" #endif #ifdef __cplusplus # define this not_the_cpp_this # define new not_the_cpp_new # define voidcast(type, value) static_cast(value) #else # define voidcast(type, value) (value) #endif /* __cplusplus */ struct png_store; define_exception_type(struct png_store*); /* The following are macros to reduce typing everywhere where the well known * name 'the_exception_context' must be defined. */ #define anon_context(ps) struct exception_context *the_exception_context = \ &(ps)->exception_context #define context(ps,fault) anon_context(ps); png_store *fault /* This macro returns the number of elements in an array as an (unsigned int), * it is necessary to avoid the inability of certain versions of GCC to use * the value of a compile-time constant when performing range checks. It must * be passed an array name. */ #define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0]))) /* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires * some broken GCC versions to be fixed up to avoid invalid whining about auto * variables that are *not* changed within the scope of a setjmp being changed. * * Feel free to extend the list of broken versions. */ #define is_gnu(major,minor)\ (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor) #define is_gnu_patch(major,minor,patch)\ is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0 /* For the moment just do it always; all versions of GCC seem to be broken: */ #ifdef __GNUC__ const void * volatile make_volatile_for_gnu; # define gnu_volatile(x) make_volatile_for_gnu = &x; #else /* !GNUC broken versions */ # define gnu_volatile(x) #endif /* !GNUC broken versions */ /******************************* UTILITIES ************************************/ /* Error handling is particularly problematic in production code - error * handlers often themselves have bugs which lead to programs that detect * minor errors crashing. The following functions deal with one very * common class of errors in error handlers - attempting to format error or * warning messages into buffers that are too small. */ static size_t safecat(char *buffer, size_t bufsize, size_t pos, const char *cat) { while (pos < bufsize && cat != NULL && *cat != 0) buffer[pos++] = *cat++; if (pos >= bufsize) pos = bufsize-1; buffer[pos] = 0; return pos; } static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n) { char number[64]; sprintf(number, "%d", n); return safecat(buffer, bufsize, pos, number); } #ifdef PNG_READ_TRANSFORMS_SUPPORTED static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d, int precision) { char number[64]; sprintf(number, "%.*f", precision, d); return safecat(buffer, bufsize, pos, number); } #endif static const char invalid[] = "invalid"; static const char sep[] = ": "; static const char *colour_types[8] = { "grayscale", invalid, "truecolour", "indexed-colour", "grayscale with alpha", invalid, "truecolour with alpha", invalid }; #ifdef PNG_READ_TRANSFORMS_SUPPORTED /* Convert a double precision value to fixed point. */ static png_fixed_point fix(double d) { d = floor(d * PNG_FP_1 + .5); return (png_fixed_point)d; } #endif /* PNG_READ_SUPPORTED */ /* Generate random bytes. This uses a boring repeatable algorithm and it * is implemented here so that it gives the same set of numbers on every * architecture. It's a linear congruential generator (Knuth or Sedgewick * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise * Generation.) */ static void make_random_bytes(png_uint_32* seed, void* pv, size_t size) { png_uint_32 u0 = seed[0], u1 = seed[1]; png_bytep bytes = voidcast(png_bytep, pv); /* There are thirty three bits, the next bit in the sequence is bit-33 XOR * bit-20. The top 1 bit is in u1, the bottom 32 are in u0. */ size_t i; for (i=0; i> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff; u1 <<= 8; u1 |= u0 >> 24; u0 <<= 8; u0 |= u; *bytes++ = (png_byte)u; } seed[0] = u0; seed[1] = u1; } static void make_four_random_bytes(png_uint_32* seed, png_bytep bytes) { make_random_bytes(seed, bytes, 4); } #if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED ||\ defined PNG_WRITE_FILTER_SUPPORTED static void randomize(void *pv, size_t size) { static png_uint_32 random_seed[2] = {0x56789abc, 0xd}; make_random_bytes(random_seed, pv, size); } #define R8(this) randomize(&(this), sizeof (this)) #ifdef PNG_READ_SUPPORTED static png_byte random_byte(void) { unsigned char b1[1]; randomize(b1, sizeof b1); return b1[0]; } #endif /* READ */ static png_uint_16 random_u16(void) { unsigned char b2[2]; randomize(b2, sizeof b2); return png_get_uint_16(b2); } #if defined PNG_READ_RGB_TO_GRAY_SUPPORTED ||\ defined PNG_READ_FILLER_SUPPORTED static png_uint_32 random_u32(void) { unsigned char b4[4]; randomize(b4, sizeof b4); return png_get_uint_32(b4); } #endif /* READ_FILLER || READ_RGB_TO_GRAY */ #endif /* READ || WRITE_tRNS || WRITE_FILTER */ #if defined PNG_READ_TRANSFORMS_SUPPORTED ||\ defined PNG_WRITE_FILTER_SUPPORTED static unsigned int random_mod(unsigned int max) { return random_u16() % max; /* 0 .. max-1 */ } #endif /* READ_TRANSFORMS || WRITE_FILTER */ #if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\ (defined PNG_READ_FILLER_SUPPORTED) static int random_choice(void) { return random_byte() & 1; } #endif /* READ_RGB_TO_GRAY || READ_FILLER */ /* A numeric ID based on PNG file characteristics. The 'do_interlace' field * simply records whether pngvalid did the interlace itself or whether it * was done by libpng. Width and height must be less than 256. 'palette' is an * index of the palette to use for formats with a palette otherwise a boolean * indicating if a tRNS chunk was generated. */ #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \ ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \ (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24))) #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U)) #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU)) #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f) #define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3)) #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1)) #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff) #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff) /* Utility to construct a standard name for a standard image. */ static size_t standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type, int bit_depth, unsigned int npalette, int interlace_type, png_uint_32 w, png_uint_32 h, int do_interlace) { pos = safecat(buffer, bufsize, pos, colour_types[colour_type]); if (colour_type == 3) /* must have a palette */ { pos = safecat(buffer, bufsize, pos, "["); pos = safecatn(buffer, bufsize, pos, npalette); pos = safecat(buffer, bufsize, pos, "]"); } else if (npalette != 0) pos = safecat(buffer, bufsize, pos, "+tRNS"); pos = safecat(buffer, bufsize, pos, " "); pos = safecatn(buffer, bufsize, pos, bit_depth); pos = safecat(buffer, bufsize, pos, " bit"); if (interlace_type != PNG_INTERLACE_NONE) { pos = safecat(buffer, bufsize, pos, " interlaced"); if (do_interlace) pos = safecat(buffer, bufsize, pos, "(pngvalid)"); else pos = safecat(buffer, bufsize, pos, "(libpng)"); } if (w > 0 || h > 0) { pos = safecat(buffer, bufsize, pos, " "); pos = safecatn(buffer, bufsize, pos, w); pos = safecat(buffer, bufsize, pos, "x"); pos = safecatn(buffer, bufsize, pos, h); } return pos; } static size_t standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id) { return standard_name(buffer, bufsize, pos, COL_FROM_ID(id), DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id), WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id)); } /* Convenience API and defines to list valid formats. Note that 16 bit read and * write support is required to do 16 bit read tests (we must be able to make a * 16 bit image to test!) */ #ifdef PNG_WRITE_16BIT_SUPPORTED # define WRITE_BDHI 4 # ifdef PNG_READ_16BIT_SUPPORTED # define READ_BDHI 4 # define DO_16BIT # endif #else # define WRITE_BDHI 3 #endif #ifndef DO_16BIT # define READ_BDHI 3 #endif /* The following defines the number of different palettes to generate for * each log bit depth of a colour type 3 standard image. */ #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U) static int next_format(png_bytep colour_type, png_bytep bit_depth, unsigned int* palette_number, int low_depth_gray, int tRNS) { if (*bit_depth == 0) { *colour_type = 0; if (low_depth_gray) *bit_depth = 1; else *bit_depth = 8; *palette_number = 0; return 1; } if (*colour_type < 4/*no alpha channel*/) { /* Add multiple palettes for colour type 3, one image with tRNS * and one without for other non-alpha formats: */ unsigned int pn = ++*palette_number; png_byte ct = *colour_type; if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) || (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth))) return 1; /* No: next bit depth */ *palette_number = 0; } *bit_depth = (png_byte)(*bit_depth << 1); /* Palette images are restricted to 8 bit depth */ if (*bit_depth <= 8 #ifdef DO_16BIT || (*colour_type != 3 && *bit_depth <= 16) #endif ) return 1; /* Move to the next color type, or return 0 at the end. */ switch (*colour_type) { case 0: *colour_type = 2; *bit_depth = 8; return 1; case 2: *colour_type = 3; *bit_depth = 1; return 1; case 3: *colour_type = 4; *bit_depth = 8; return 1; case 4: *colour_type = 6; *bit_depth = 8; return 1; default: return 0; } } #ifdef PNG_READ_TRANSFORMS_SUPPORTED static unsigned int sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth, png_uint_32 x, unsigned int sample_index, int swap16, int littleendian) { png_uint_32 bit_index, result; /* Find a sample index for the desired sample: */ x *= bit_depth; bit_index = x; if ((colour_type & 1) == 0) /* !palette */ { if (colour_type & 2) bit_index *= 3; if (colour_type & 4) bit_index += x; /* Alpha channel */ /* Multiple channels; select one: */ if (colour_type & (2+4)) bit_index += sample_index * bit_depth; } /* Return the sample from the row as an integer. */ row += bit_index >> 3; result = *row; if (bit_depth == 8) return result; else if (bit_depth > 8) { if (swap16) return (*++row << 8) + result; else return (result << 8) + *++row; } /* Less than 8 bits per sample. By default PNG has the big end of * the egg on the left of the screen, but if littleendian is set * then the big end is on the right. */ bit_index &= 7; if (!littleendian) bit_index = 8-bit_index-bit_depth; return (result >> bit_index) & ((1U<> 3] & ~destMask; unsigned int sourceByte = fromBuffer[fromIndex >> 3]; /* Don't rely on << or >> supporting '0' here, just in case: */ fromIndex &= 7; if (littleendian) { if (fromIndex > 0) sourceByte >>= fromIndex; if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7; } else { if (fromIndex > 0) sourceByte <<= fromIndex; if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7; } toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask)); } else /* One or more bytes */ memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3); } #ifdef PNG_READ_SUPPORTED /* Copy a complete row of pixels, taking into account potential partial * bytes at the end. */ static void row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth, int littleendian) { memcpy(toBuffer, fromBuffer, bitWidth >> 3); if ((bitWidth & 7) != 0) { unsigned int mask; toBuffer += bitWidth >> 3; fromBuffer += bitWidth >> 3; if (littleendian) mask = 0xff << (bitWidth & 7); else mask = 0xff >> (bitWidth & 7); *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); } } /* Compare pixels - they are assumed to start at the first byte in the * given buffers. */ static int pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width) { #if PNG_LIBPNG_VER < 10506 if (memcmp(pa, pb, bit_width>>3) == 0) { png_uint_32 p; if ((bit_width & 7) == 0) return 0; /* Ok, any differences? */ p = pa[bit_width >> 3]; p ^= pb[bit_width >> 3]; if (p == 0) return 0; /* There are, but they may not be significant, remove the bits * after the end (the low order bits in PNG.) */ bit_width &= 7; p >>= 8-bit_width; if (p == 0) return 0; } #else /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing * bits too: */ if (memcmp(pa, pb, (bit_width+7)>>3) == 0) return 0; #endif /* Return the index of the changed byte. */ { png_uint_32 where = 0; while (pa[where] == pb[where]) ++where; return 1+where; } } #endif /* PNG_READ_SUPPORTED */ /*************************** BASIC PNG FILE WRITING ***************************/ /* A png_store takes data from the sequential writer or provides data * to the sequential reader. It can also store the result of a PNG * write for later retrieval. */ #define STORE_BUFFER_SIZE 500 /* arbitrary */ typedef struct png_store_buffer { struct png_store_buffer* prev; /* NOTE: stored in reverse order */ png_byte buffer[STORE_BUFFER_SIZE]; } png_store_buffer; #define FILE_NAME_SIZE 64 typedef struct store_palette_entry /* record of a single palette entry */ { png_byte red; png_byte green; png_byte blue; png_byte alpha; } store_palette_entry, store_palette[256]; typedef struct png_store_file { struct png_store_file* next; /* as many as you like... */ char name[FILE_NAME_SIZE]; unsigned int IDAT_bits; /* Number of bits in IDAT size */ png_uint_32 IDAT_size; /* Total size of IDAT data */ png_uint_32 id; /* must be correct (see FILEID) */ png_size_t datacount; /* In this (the last) buffer */ png_store_buffer data; /* Last buffer in file */ int npalette; /* Number of entries in palette */ store_palette_entry* palette; /* May be NULL */ } png_store_file; /* The following is a pool of memory allocated by a single libpng read or write * operation. */ typedef struct store_pool { struct png_store *store; /* Back pointer */ struct store_memory *list; /* List of allocated memory */ png_byte mark[4]; /* Before and after data */ /* Statistics for this run. */ png_alloc_size_t max; /* Maximum single allocation */ png_alloc_size_t current; /* Current allocation */ png_alloc_size_t limit; /* Highest current allocation */ png_alloc_size_t total; /* Total allocation */ /* Overall statistics (retained across successive runs). */ png_alloc_size_t max_max; png_alloc_size_t max_limit; png_alloc_size_t max_total; } store_pool; typedef struct png_store { /* For cexcept.h exception handling - simply store one of these; * the context is a self pointer but it may point to a different * png_store (in fact it never does in this program.) */ struct exception_context exception_context; unsigned int verbose :1; unsigned int treat_warnings_as_errors :1; unsigned int expect_error :1; unsigned int expect_warning :1; unsigned int saw_warning :1; unsigned int speed :1; unsigned int progressive :1; /* use progressive read */ unsigned int validated :1; /* used as a temporary flag */ int nerrors; int nwarnings; int noptions; /* number of options below: */ struct { unsigned char option; /* option number, 0..30 */ unsigned char setting; /* setting (unset,invalid,on,off) */ } options[16]; char test[128]; /* Name of test */ char error[256]; /* Share fields */ png_uint_32 chunklen; /* Length of chunk+overhead (chunkpos >= 8) */ png_uint_32 chunktype;/* Type of chunk (valid if chunkpos >= 4) */ png_uint_32 chunkpos; /* Position in chunk */ png_uint_32 IDAT_size;/* Accumulated IDAT size in .new */ unsigned int IDAT_bits;/* Cache of the file store value */ /* Read fields */ png_structp pread; /* Used to read a saved file */ png_infop piread; png_store_file* current; /* Set when reading */ png_store_buffer* next; /* Set when reading */ png_size_t readpos; /* Position in *next */ png_byte* image; /* Buffer for reading interlaced images */ png_size_t cb_image; /* Size of this buffer */ png_size_t cb_row; /* Row size of the image(s) */ uLong IDAT_crc; png_uint_32 IDAT_len; /* Used when re-chunking IDAT chunks */ png_uint_32 IDAT_pos; /* Used when re-chunking IDAT chunks */ png_uint_32 image_h; /* Number of rows in a single image */ store_pool read_memory_pool; /* Write fields */ png_store_file* saved; png_structp pwrite; /* Used when writing a new file */ png_infop piwrite; png_size_t writepos; /* Position in .new */ char wname[FILE_NAME_SIZE]; png_store_buffer new; /* The end of the new PNG file being written. */ store_pool write_memory_pool; store_palette_entry* palette; int npalette; } png_store; /* Initialization and cleanup */ static void store_pool_mark(png_bytep mark) { static png_uint_32 store_seed[2] = { 0x12345678, 1}; make_four_random_bytes(store_seed, mark); } #ifdef PNG_READ_TRANSFORMS_SUPPORTED /* Use this for random 32 bit values; this function makes sure the result is * non-zero. */ static png_uint_32 random_32(void) { for (;;) { png_byte mark[4]; png_uint_32 result; store_pool_mark(mark); result = png_get_uint_32(mark); if (result != 0) return result; } } #endif /* PNG_READ_SUPPORTED */ static void store_pool_init(png_store *ps, store_pool *pool) { memset(pool, 0, sizeof *pool); pool->store = ps; pool->list = NULL; pool->max = pool->current = pool->limit = pool->total = 0; pool->max_max = pool->max_limit = pool->max_total = 0; store_pool_mark(pool->mark); } static void store_init(png_store* ps) { memset(ps, 0, sizeof *ps); init_exception_context(&ps->exception_context); store_pool_init(ps, &ps->read_memory_pool); store_pool_init(ps, &ps->write_memory_pool); ps->verbose = 0; ps->treat_warnings_as_errors = 0; ps->expect_error = 0; ps->expect_warning = 0; ps->saw_warning = 0; ps->speed = 0; ps->progressive = 0; ps->validated = 0; ps->nerrors = ps->nwarnings = 0; ps->pread = NULL; ps->piread = NULL; ps->saved = ps->current = NULL; ps->next = NULL; ps->readpos = 0; ps->image = NULL; ps->cb_image = 0; ps->cb_row = 0; ps->image_h = 0; ps->pwrite = NULL; ps->piwrite = NULL; ps->writepos = 0; ps->chunkpos = 8; ps->chunktype = 0; ps->chunklen = 16; ps->IDAT_size = 0; ps->IDAT_bits = 0; ps->new.prev = NULL; ps->palette = NULL; ps->npalette = 0; ps->noptions = 0; } static void store_freebuffer(png_store_buffer* psb) { if (psb->prev) { store_freebuffer(psb->prev); free(psb->prev); psb->prev = NULL; } } static void store_freenew(png_store *ps) { store_freebuffer(&ps->new); ps->writepos = 0; ps->chunkpos = 8; ps->chunktype = 0; ps->chunklen = 16; ps->IDAT_size = 0; ps->IDAT_bits = 0; if (ps->palette != NULL) { free(ps->palette); ps->palette = NULL; ps->npalette = 0; } } static void store_storenew(png_store *ps) { png_store_buffer *pb; pb = voidcast(png_store_buffer*, malloc(sizeof *pb)); if (pb == NULL) png_error(ps->pwrite, "store new: OOM"); *pb = ps->new; ps->new.prev = pb; ps->writepos = 0; } static void store_freefile(png_store_file **ppf) { if (*ppf != NULL) { store_freefile(&(*ppf)->next); store_freebuffer(&(*ppf)->data); (*ppf)->datacount = 0; if ((*ppf)->palette != NULL) { free((*ppf)->palette); (*ppf)->palette = NULL; (*ppf)->npalette = 0; } free(*ppf); *ppf = NULL; } } static unsigned int bits_of(png_uint_32 num) { /* Return the number of bits in 'num' */ unsigned int b = 0; if (num & 0xffff0000U) b += 16U, num >>= 16; if (num & 0xff00U) b += 8U, num >>= 8; if (num & 0xf0U) b += 4U, num >>= 4; if (num & 0xcU) b += 2U, num >>= 2; if (num & 0x2U) ++b, num >>= 1; if (num) ++b; return b; /* 0..32 */ } /* Main interface to file storeage, after writing a new PNG file (see the API * below) call store_storefile to store the result with the given name and id. */ static void store_storefile(png_store *ps, png_uint_32 id) { png_store_file *pf; if (ps->chunkpos != 0U || ps->chunktype != 0U || ps->chunklen != 0U || ps->IDAT_size == 0) png_error(ps->pwrite, "storefile: incomplete write"); pf = voidcast(png_store_file*, malloc(sizeof *pf)); if (pf == NULL) png_error(ps->pwrite, "storefile: OOM"); safecat(pf->name, sizeof pf->name, 0, ps->wname); pf->id = id; pf->data = ps->new; pf->datacount = ps->writepos; pf->IDAT_size = ps->IDAT_size; pf->IDAT_bits = bits_of(ps->IDAT_size); /* Because the IDAT always has zlib header stuff this must be true: */ if (pf->IDAT_bits == 0U) png_error(ps->pwrite, "storefile: 0 sized IDAT"); ps->new.prev = NULL; ps->writepos = 0; ps->chunkpos = 8; ps->chunktype = 0; ps->chunklen = 16; ps->IDAT_size = 0; pf->palette = ps->palette; pf->npalette = ps->npalette; ps->palette = 0; ps->npalette = 0; /* And save it. */ pf->next = ps->saved; ps->saved = pf; } /* Generate an error message (in the given buffer) */ static size_t store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize, size_t pos, const char *msg) { if (pp != NULL && pp == ps->pread) { /* Reading a file */ pos = safecat(buffer, bufsize, pos, "read: "); if (ps->current != NULL) { pos = safecat(buffer, bufsize, pos, ps->current->name); pos = safecat(buffer, bufsize, pos, sep); } } else if (pp != NULL && pp == ps->pwrite) { /* Writing a file */ pos = safecat(buffer, bufsize, pos, "write: "); pos = safecat(buffer, bufsize, pos, ps->wname); pos = safecat(buffer, bufsize, pos, sep); } else { /* Neither reading nor writing (or a memory error in struct delete) */ pos = safecat(buffer, bufsize, pos, "pngvalid: "); } if (ps->test[0] != 0) { pos = safecat(buffer, bufsize, pos, ps->test); pos = safecat(buffer, bufsize, pos, sep); } pos = safecat(buffer, bufsize, pos, msg); return pos; } /* Verbose output to the error stream: */ static void store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix, png_const_charp message) { char buffer[512]; if (prefix) fputs(prefix, stderr); (void)store_message(ps, pp, buffer, sizeof buffer, 0, message); fputs(buffer, stderr); fputc('\n', stderr); } /* Log an error or warning - the relevant count is always incremented. */ static void store_log(png_store* ps, png_const_structp pp, png_const_charp message, int is_error) { /* The warning is copied to the error buffer if there are no errors and it is * the first warning. The error is copied to the error buffer if it is the * first error (overwriting any prior warnings). */ if (is_error ? (ps->nerrors)++ == 0 : (ps->nwarnings)++ == 0 && ps->nerrors == 0) store_message(ps, pp, ps->error, sizeof ps->error, 0, message); if (ps->verbose) store_verbose(ps, pp, is_error ? "error: " : "warning: ", message); } #ifdef PNG_READ_SUPPORTED /* Internal error function, called with a png_store but no libpng stuff. */ static void internal_error(png_store *ps, png_const_charp message) { store_log(ps, NULL, message, 1 /* error */); /* And finally throw an exception. */ { struct exception_context *the_exception_context = &ps->exception_context; Throw ps; } } #endif /* PNG_READ_SUPPORTED */ /* Functions to use as PNG callbacks. */ static void PNGCBAPI store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */ { png_const_structp pp = ppIn; png_store *ps = voidcast(png_store*, png_get_error_ptr(pp)); if (!ps->expect_error) store_log(ps, pp, message, 1 /* error */); /* And finally throw an exception. */ { struct exception_context *the_exception_context = &ps->exception_context; Throw ps; } } static void PNGCBAPI store_warning(png_structp ppIn, png_const_charp message) { png_const_structp pp = ppIn; png_store *ps = voidcast(png_store*, png_get_error_ptr(pp)); if (!ps->expect_warning) store_log(ps, pp, message, 0 /* warning */); else ps->saw_warning = 1; } /* These somewhat odd functions are used when reading an image to ensure that * the buffer is big enough, the png_structp is for errors. */ /* Return a single row from the correct image. */ static png_bytep store_image_row(const png_store* ps, png_const_structp pp, int nImage, png_uint_32 y) { png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2; if (ps->image == NULL) png_error(pp, "no allocated image"); if (coffset + ps->cb_row + 3 > ps->cb_image) png_error(pp, "image too small"); return ps->image + coffset; } static void store_image_free(png_store *ps, png_const_structp pp) { if (ps->image != NULL) { png_bytep image = ps->image; if (image[-1] != 0xed || image[ps->cb_image] != 0xfe) { if (pp != NULL) png_error(pp, "png_store image overwrite (1)"); else store_log(ps, NULL, "png_store image overwrite (2)", 1); } ps->image = NULL; ps->cb_image = 0; --image; free(image); } } static void store_ensure_image(png_store *ps, png_const_structp pp, int nImages, png_size_t cbRow, png_uint_32 cRows) { png_size_t cb = nImages * cRows * (cbRow + 5); if (ps->cb_image < cb) { png_bytep image; store_image_free(ps, pp); /* The buffer is deliberately mis-aligned. */ image = voidcast(png_bytep, malloc(cb+2)); if (image == NULL) { /* Called from the startup - ignore the error for the moment. */ if (pp == NULL) return; png_error(pp, "OOM allocating image buffer"); } /* These magic tags are used to detect overwrites above. */ ++image; image[-1] = 0xed; image[cb] = 0xfe; ps->image = image; ps->cb_image = cb; } /* We have an adequate sized image; lay out the rows. There are 2 bytes at * the start and three at the end of each (this ensures that the row * alignment starts out odd - 2+1 and changes for larger images on each row.) */ ps->cb_row = cbRow; ps->image_h = cRows; /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178). * This deliberately doesn't match the bits in the size test image which are * outside the image; these are set to 0xff (all 1). To make the row * comparison work in the 'size' test case the size rows are pre-initialized * to the same value prior to calling 'standard_row'. */ memset(ps->image, 178, cb); /* Then put in the marks. */ while (--nImages >= 0) { png_uint_32 y; for (y=0; yimage; if (image[-1] != 0xed || image[ps->cb_image] != 0xfe) png_error(pp, "image overwrite"); else { png_size_t cbRow = ps->cb_row; png_uint_32 rows = ps->image_h; image += iImage * (cbRow+5) * ps->image_h; image += 2; /* skip image first row markers */ while (rows-- > 0) { if (image[-2] != 190 || image[-1] != 239) png_error(pp, "row start overwritten"); if (image[cbRow] != 222 || image[cbRow+1] != 173 || image[cbRow+2] != 17) png_error(pp, "row end overwritten"); image += cbRow+5; } } } #endif /* PNG_READ_SUPPORTED */ static int valid_chunktype(png_uint_32 chunktype) { /* Each byte in the chunk type must be in one of the ranges 65..90, 97..122 * (both inclusive), so: */ unsigned int i; for (i=0; i<4; ++i) { unsigned int c = chunktype & 0xffU; if (!((c >= 65U && c <= 90U) || (c >= 97U && c <= 122U))) return 0; chunktype >>= 8; } return 1; /* It's valid */ } static void PNGCBAPI store_write(png_structp ppIn, png_bytep pb, png_size_t st) { png_const_structp pp = ppIn; png_store *ps = voidcast(png_store*, png_get_io_ptr(pp)); size_t writepos = ps->writepos; png_uint_32 chunkpos = ps->chunkpos; png_uint_32 chunktype = ps->chunktype; png_uint_32 chunklen = ps->chunklen; if (ps->pwrite != pp) png_error(pp, "store state damaged"); /* Technically this is legal, but in practice libpng never writes more than * the maximum chunk size at once so if it happens something weird has * changed inside libpng (probably). */ if (st > 0x7fffffffU) png_error(pp, "unexpected write size"); /* Now process the bytes to be written. Do this in units of the space in the * output (write) buffer or, at the start 4 bytes for the chunk type and * length limited in any case by the amount of data. */ while (st > 0) { if (writepos >= STORE_BUFFER_SIZE) store_storenew(ps), writepos = 0; if (chunkpos < 4) { png_byte b = *pb++; --st; chunklen = (chunklen << 8) + b; ps->new.buffer[writepos++] = b; ++chunkpos; } else if (chunkpos < 8) { png_byte b = *pb++; --st; chunktype = (chunktype << 8) + b; ps->new.buffer[writepos++] = b; if (++chunkpos == 8) { chunklen &= 0xffffffffU; if (chunklen > 0x7fffffffU) png_error(pp, "chunk length too great"); chunktype &= 0xffffffffU; if (chunktype == CHUNK_IDAT) { if (chunklen > ~ps->IDAT_size) png_error(pp, "pngvalid internal image too large"); ps->IDAT_size += chunklen; } else if (!valid_chunktype(chunktype)) png_error(pp, "invalid chunk type"); chunklen += 12; /* for header and CRC */ } } else /* chunkpos >= 8 */ { png_size_t cb = st; if (cb > STORE_BUFFER_SIZE - writepos) cb = STORE_BUFFER_SIZE - writepos; if (cb > chunklen - chunkpos/* bytes left in chunk*/) cb = (png_size_t)/*SAFE*/(chunklen - chunkpos); memcpy(ps->new.buffer + writepos, pb, cb); chunkpos += (png_uint_32)/*SAFE*/cb; pb += cb; writepos += cb; st -= cb; if (chunkpos >= chunklen) /* must be equal */ chunkpos = chunktype = chunklen = 0; } } /* while (st > 0) */ ps->writepos = writepos; ps->chunkpos = chunkpos; ps->chunktype = chunktype; ps->chunklen = chunklen; } static void PNGCBAPI store_flush(png_structp ppIn) { UNUSED(ppIn) /*DOES NOTHING*/ } #ifdef PNG_READ_SUPPORTED static size_t store_read_buffer_size(png_store *ps) { /* Return the bytes available for read in the current buffer. */ if (ps->next != &ps->current->data) return STORE_BUFFER_SIZE; return ps->current->datacount; } /* Return total bytes available for read. */ static size_t store_read_buffer_avail(png_store *ps) { if (ps->current != NULL && ps->next != NULL) { png_store_buffer *next = &ps->current->data; size_t cbAvail = ps->current->datacount; while (next != ps->next && next != NULL) { next = next->prev; cbAvail += STORE_BUFFER_SIZE; } if (next != ps->next) png_error(ps->pread, "buffer read error"); if (cbAvail > ps->readpos) return cbAvail - ps->readpos; } return 0; } static int store_read_buffer_next(png_store *ps) { png_store_buffer *pbOld = ps->next; png_store_buffer *pbNew = &ps->current->data; if (pbOld != pbNew) { while (pbNew != NULL && pbNew->prev != pbOld) pbNew = pbNew->prev; if (pbNew != NULL) { ps->next = pbNew; ps->readpos = 0; return 1; } png_error(ps->pread, "buffer lost"); } return 0; /* EOF or error */ } /* Need separate implementation and callback to allow use of the same code * during progressive read, where the io_ptr is set internally by libpng. */ static void store_read_imp(png_store *ps, png_bytep pb, png_size_t st) { if (ps->current == NULL || ps->next == NULL) png_error(ps->pread, "store state damaged"); while (st > 0) { size_t cbAvail = store_read_buffer_size(ps) - ps->readpos; if (cbAvail > 0) { if (cbAvail > st) cbAvail = st; memcpy(pb, ps->next->buffer + ps->readpos, cbAvail); st -= cbAvail; pb += cbAvail; ps->readpos += cbAvail; } else if (!store_read_buffer_next(ps)) png_error(ps->pread, "read beyond end of file"); } } static png_size_t store_read_chunk(png_store *ps, png_bytep pb, const png_size_t max, const png_size_t min) { png_uint_32 chunklen = ps->chunklen; png_uint_32 chunktype = ps->chunktype; png_uint_32 chunkpos = ps->chunkpos; png_size_t st = max; if (st > 0) do { if (chunkpos >= chunklen) /* end of last chunk */ { png_byte buffer[8]; /* Read the header of the next chunk: */ store_read_imp(ps, buffer, 8U); chunklen = png_get_uint_32(buffer) + 12U; chunktype = png_get_uint_32(buffer+4U); chunkpos = 0U; /* Position read so far */ } if (chunktype == CHUNK_IDAT) { png_uint_32 IDAT_pos = ps->IDAT_pos; png_uint_32 IDAT_len = ps->IDAT_len; png_uint_32 IDAT_size = ps->IDAT_size; /* The IDAT headers are constructed here; skip the input header. */ if (chunkpos < 8U) chunkpos = 8U; if (IDAT_pos == IDAT_len) { png_byte random = random_byte(); /* Make a new IDAT chunk, if IDAT_len is 0 this is the first IDAT, * if IDAT_size is 0 this is the end. At present this is set up * using a random number so that there is a 25% chance before * the start of the first IDAT chunk being 0 length. */ if (IDAT_len == 0U) /* First IDAT */ { switch (random & 3U) { case 0U: IDAT_len = 12U; break; /* 0 bytes */ case 1U: IDAT_len = 13U; break; /* 1 byte */ default: IDAT_len = random_u32(); IDAT_len %= IDAT_size; IDAT_len += 13U; /* 1..IDAT_size bytes */ break; } } else if (IDAT_size == 0U) /* all IDAT data read */ { /* The last (IDAT) chunk should be positioned at the CRC now: */ if (chunkpos != chunklen-4U) png_error(ps->pread, "internal: IDAT size mismatch"); /* The only option here is to add a zero length IDAT, this * happens 25% of the time. Because of the check above * chunklen-4U-chunkpos must be zero, we just need to skip the * CRC now. */ if ((random & 3U) == 0U) IDAT_len = 12U; /* Output another 0 length IDAT */ else { /* End of IDATs, skip the CRC to make the code above load the * next chunk header next time round. */ png_byte buffer[4]; store_read_imp(ps, buffer, 4U); chunkpos += 4U; ps->IDAT_pos = IDAT_pos; ps->IDAT_len = IDAT_len; ps->IDAT_size = 0U; continue; /* Read the next chunk */ } } else { /* Middle of IDATs, use 'random' to determine the number of bits * to use in the IDAT length. */ IDAT_len = random_u32(); IDAT_len &= (1U << (1U + random % ps->IDAT_bits)) - 1U; if (IDAT_len > IDAT_size) IDAT_len = IDAT_size; IDAT_len += 12U; /* zero bytes may occur */ } IDAT_pos = 0U; ps->IDAT_crc = 0x35af061e; /* Ie: crc32(0UL, "IDAT", 4) */ } /* IDAT_pos == IDAT_len */ if (IDAT_pos < 8U) /* Return the header */ do { png_uint_32 b; unsigned int shift; if (IDAT_pos < 4U) b = IDAT_len - 12U; else b = CHUNK_IDAT; shift = 3U & IDAT_pos; ++IDAT_pos; if (shift < 3U) b >>= 8U*(3U-shift); *pb++ = 0xffU & b; } while (--st > 0 && IDAT_pos < 8); else if (IDAT_pos < IDAT_len - 4U) /* I.e not the CRC */ { if (chunkpos < chunklen-4U) { uInt avail = (uInt)-1; if (avail > (IDAT_len-4U) - IDAT_pos) avail = (uInt)/*SAFE*/((IDAT_len-4U) - IDAT_pos); if (avail > st) avail = (uInt)/*SAFE*/st; if (avail > (chunklen-4U) - chunkpos) avail = (uInt)/*SAFE*/((chunklen-4U) - chunkpos); store_read_imp(ps, pb, avail); ps->IDAT_crc = crc32(ps->IDAT_crc, pb, avail); pb += (png_size_t)/*SAFE*/avail; st -= (png_size_t)/*SAFE*/avail; chunkpos += (png_uint_32)/*SAFE*/avail; IDAT_size -= (png_uint_32)/*SAFE*/avail; IDAT_pos += (png_uint_32)/*SAFE*/avail; } else /* skip the input CRC */ { png_byte buffer[4]; store_read_imp(ps, buffer, 4U); chunkpos += 4U; } } else /* IDAT crc */ do { uLong b = ps->IDAT_crc; unsigned int shift = (IDAT_len - IDAT_pos); /* 4..1 */ ++IDAT_pos; if (shift > 1U) b >>= 8U*(shift-1U); *pb++ = 0xffU & b; } while (--st > 0 && IDAT_pos < IDAT_len); ps->IDAT_pos = IDAT_pos; ps->IDAT_len = IDAT_len; ps->IDAT_size = IDAT_size; } else /* !IDAT */ { /* If there is still some pending IDAT data after the IDAT chunks have * been processed there is a problem: */ if (ps->IDAT_len > 0 && ps->IDAT_size > 0) png_error(ps->pread, "internal: missing IDAT data"); if (chunktype == CHUNK_IEND && ps->IDAT_len == 0U) png_error(ps->pread, "internal: missing IDAT"); if (chunkpos < 8U) /* Return the header */ do { png_uint_32 b; unsigned int shift; if (chunkpos < 4U) b = chunklen - 12U; else b = chunktype; shift = 3U & chunkpos; ++chunkpos; if (shift < 3U) b >>= 8U*(3U-shift); *pb++ = 0xffU & b; } while (--st > 0 && chunkpos < 8); else /* Return chunk bytes, including the CRC */ { png_size_t avail = st; if (avail > chunklen - chunkpos) avail = (png_size_t)/*SAFE*/(chunklen - chunkpos); store_read_imp(ps, pb, avail); pb += avail; st -= avail; chunkpos += (png_uint_32)/*SAFE*/avail; /* Check for end of chunk and end-of-file; don't try to read a new * chunk header at this point unless instructed to do so by 'min'. */ if (chunkpos >= chunklen && max-st >= min && store_read_buffer_avail(ps) == 0) break; } } /* !IDAT */ } while (st > 0); ps->chunklen = chunklen; ps->chunktype = chunktype; ps->chunkpos = chunkpos; return st; /* space left */ } static void PNGCBAPI store_read(png_structp ppIn, png_bytep pb, png_size_t st) { png_const_structp pp = ppIn; png_store *ps = voidcast(png_store*, png_get_io_ptr(pp)); if (ps == NULL || ps->pread != pp) png_error(pp, "bad store read call"); store_read_chunk(ps, pb, st, st); } static void store_progressive_read(png_store *ps, png_structp pp, png_infop pi) { if (ps->pread != pp || ps->current == NULL || ps->next == NULL) png_error(pp, "store state damaged (progressive)"); /* This is another Horowitz and Hill random noise generator. In this case * the aim is to stress the progressive reader with truly horrible variable * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers * is generated. We could probably just count from 1 to 32767 and get as * good a result. */ while (store_read_buffer_avail(ps) > 0) { static png_uint_32 noise = 2; png_size_t cb; png_byte buffer[512]; /* Generate 15 more bits of stuff: */ noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff); cb = noise & 0x1ff; cb -= store_read_chunk(ps, buffer, cb, 1); png_process_data(pp, pi, buffer, cb); } } #endif /* PNG_READ_SUPPORTED */ /* The caller must fill this in: */ static store_palette_entry * store_write_palette(png_store *ps, int npalette) { if (ps->pwrite == NULL) store_log(ps, NULL, "attempt to write palette without write stream", 1); if (ps->palette != NULL) png_error(ps->pwrite, "multiple store_write_palette calls"); /* This function can only return NULL if called with '0'! */ if (npalette > 0) { ps->palette = voidcast(store_palette_entry*, malloc(npalette * sizeof *ps->palette)); if (ps->palette == NULL) png_error(ps->pwrite, "store new palette: OOM"); ps->npalette = npalette; } return ps->palette; } #ifdef PNG_READ_SUPPORTED static store_palette_entry * store_current_palette(png_store *ps, int *npalette) { /* This is an internal error (the call has been made outside a read * operation.) */ if (ps->current == NULL) { store_log(ps, ps->pread, "no current stream for palette", 1); return NULL; } /* The result may be null if there is no palette. */ *npalette = ps->current->npalette; return ps->current->palette; } #endif /* PNG_READ_SUPPORTED */ /***************************** MEMORY MANAGEMENT*** ***************************/ #ifdef PNG_USER_MEM_SUPPORTED /* A store_memory is simply the header for an allocated block of memory. The * pointer returned to libpng is just after the end of the header block, the * allocated memory is followed by a second copy of the 'mark'. */ typedef struct store_memory { store_pool *pool; /* Originating pool */ struct store_memory *next; /* Singly linked list */ png_alloc_size_t size; /* Size of memory allocated */ png_byte mark[4]; /* ID marker */ } store_memory; /* Handle a fatal error in memory allocation. This calls png_error if the * libpng struct is non-NULL, else it outputs a message and returns. This means * that a memory problem while libpng is running will abort (png_error) the * handling of particular file while one in cleanup (after the destroy of the * struct has returned) will simply keep going and free (or attempt to free) * all the memory. */ static void store_pool_error(png_store *ps, png_const_structp pp, const char *msg) { if (pp != NULL) png_error(pp, msg); /* Else we have to do it ourselves. png_error eventually calls store_log, * above. store_log accepts a NULL png_structp - it just changes what gets * output by store_message. */ store_log(ps, pp, msg, 1 /* error */); } static void store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory) { /* Note that pp may be NULL (see store_pool_delete below), the caller has * found 'memory' in pool->list *and* unlinked this entry, so this is a valid * pointer (for sure), but the contents may have been trashed. */ if (memory->pool != pool) store_pool_error(pool->store, pp, "memory corrupted (pool)"); else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0) store_pool_error(pool->store, pp, "memory corrupted (start)"); /* It should be safe to read the size field now. */ else { png_alloc_size_t cb = memory->size; if (cb > pool->max) store_pool_error(pool->store, pp, "memory corrupted (size)"); else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark) != 0) store_pool_error(pool->store, pp, "memory corrupted (end)"); /* Finally give the library a chance to find problems too: */ else { pool->current -= cb; free(memory); } } } static void store_pool_delete(png_store *ps, store_pool *pool) { if (pool->list != NULL) { fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test, pool == &ps->read_memory_pool ? "read" : "write", pool == &ps->read_memory_pool ? (ps->current != NULL ? ps->current->name : "unknown file") : ps->wname); ++ps->nerrors; do { store_memory *next = pool->list; pool->list = next->next; next->next = NULL; fprintf(stderr, "\t%lu bytes @ %p\n", (unsigned long)next->size, (const void*)(next+1)); /* The NULL means this will always return, even if the memory is * corrupted. */ store_memory_free(NULL, pool, next); } while (pool->list != NULL); } /* And reset the other fields too for the next time. */ if (pool->max > pool->max_max) pool->max_max = pool->max; pool->max = 0; if (pool->current != 0) /* unexpected internal error */ fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n", ps->test, pool == &ps->read_memory_pool ? "read" : "write", pool == &ps->read_memory_pool ? (ps->current != NULL ? ps->current->name : "unknown file") : ps->wname); pool->current = 0; if (pool->limit > pool->max_limit) pool->max_limit = pool->limit; pool->limit = 0; if (pool->total > pool->max_total) pool->max_total = pool->total; pool->total = 0; /* Get a new mark too. */ store_pool_mark(pool->mark); } /* The memory callbacks: */ static png_voidp PNGCBAPI store_malloc(png_structp ppIn, png_alloc_size_t cb) { png_const_structp pp = ppIn; store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp)); store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) + (sizeof pool->mark))); if (new != NULL) { if (cb > pool->max) pool->max = cb; pool->current += cb; if (pool->current > pool->limit) pool->limit = pool->current; pool->total += cb; new->size = cb; memcpy(new->mark, pool->mark, sizeof new->mark); memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark); new->pool = pool; new->next = pool->list; pool->list = new; ++new; } else { /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed * other than to retrieve the allocation pointer! libpng calls the * store_malloc callback in two basic cases: * * 1) From png_malloc; png_malloc will do a png_error itself if NULL is * returned. * 2) From png_struct or png_info structure creation; png_malloc is * to return so cleanup can be performed. * * To handle this store_malloc can log a message, but can't do anything * else. */ store_log(pool->store, pp, "out of memory", 1 /* is_error */); } return new; } static void PNGCBAPI store_free(png_structp ppIn, png_voidp memory) { png_const_structp pp = ppIn; store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp)); store_memory *this = voidcast(store_memory*, memory), **test; /* Because libpng calls store_free with a dummy png_struct when deleting * png_struct or png_info via png_destroy_struct_2 it is necessary to check * the passed in png_structp to ensure it is valid, and not pass it to * png_error if it is not. */ if (pp != pool->store->pread && pp != pool->store->pwrite) pp = NULL; /* First check that this 'memory' really is valid memory - it must be in the * pool list. If it is, use the shared memory_free function to free it. */ --this; for (test = &pool->list; *test != this; test = &(*test)->next) { if (*test == NULL) { store_pool_error(pool->store, pp, "bad pointer to free"); return; } } /* Unlink this entry, *test == this. */ *test = this->next; this->next = NULL; store_memory_free(pp, pool, this); } #endif /* PNG_USER_MEM_SUPPORTED */ /* Setup functions. */ /* Cleanup when aborting a write or after storing the new file. */ static void store_write_reset(png_store *ps) { if (ps->pwrite != NULL) { anon_context(ps); Try png_destroy_write_struct(&ps->pwrite, &ps->piwrite); Catch_anonymous { /* memory corruption: continue. */ } ps->pwrite = NULL; ps->piwrite = NULL; } /* And make sure that all the memory has been freed - this will output * spurious errors in the case of memory corruption above, but this is safe. */ # ifdef PNG_USER_MEM_SUPPORTED store_pool_delete(ps, &ps->write_memory_pool); # endif store_freenew(ps); } /* The following is the main write function, it returns a png_struct and, * optionally, a png_info suitable for writiing a new PNG file. Use * store_storefile above to record this file after it has been written. The * returned libpng structures as destroyed by store_write_reset above. */ static png_structp set_store_for_write(png_store *ps, png_infopp ppi, const char *name) { anon_context(ps); Try { if (ps->pwrite != NULL) png_error(ps->pwrite, "write store already in use"); store_write_reset(ps); safecat(ps->wname, sizeof ps->wname, 0, name); /* Don't do the slow memory checks if doing a speed test, also if user * memory is not supported we can't do it anyway. */ # ifdef PNG_USER_MEM_SUPPORTED if (!ps->speed) ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning, &ps->write_memory_pool, store_malloc, store_free); else # endif ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning); png_set_write_fn(ps->pwrite, ps, store_write, store_flush); # ifdef PNG_SET_OPTION_SUPPORTED { int opt; for (opt=0; optnoptions; ++opt) if (png_set_option(ps->pwrite, ps->options[opt].option, ps->options[opt].setting) == PNG_OPTION_INVALID) png_error(ps->pwrite, "png option invalid"); } # endif if (ppi != NULL) *ppi = ps->piwrite = png_create_info_struct(ps->pwrite); } Catch_anonymous return NULL; return ps->pwrite; } /* Cleanup when finished reading (either due to error or in the success case). * This routine exists even when there is no read support to make the code * tidier (avoid a mass of ifdefs) and so easier to maintain. */ static void store_read_reset(png_store *ps) { # ifdef PNG_READ_SUPPORTED if (ps->pread != NULL) { anon_context(ps); Try png_destroy_read_struct(&ps->pread, &ps->piread, NULL); Catch_anonymous { /* error already output: continue */ } ps->pread = NULL; ps->piread = NULL; } # endif # ifdef PNG_USER_MEM_SUPPORTED /* Always do this to be safe. */ store_pool_delete(ps, &ps->read_memory_pool); # endif ps->current = NULL; ps->next = NULL; ps->readpos = 0; ps->validated = 0; ps->chunkpos = 8; ps->chunktype = 0; ps->chunklen = 16; ps->IDAT_size = 0; } #ifdef PNG_READ_SUPPORTED static void store_read_set(png_store *ps, png_uint_32 id) { png_store_file *pf = ps->saved; while (pf != NULL) { if (pf->id == id) { ps->current = pf; ps->next = NULL; ps->IDAT_size = pf->IDAT_size; ps->IDAT_bits = pf->IDAT_bits; /* just a cache */ ps->IDAT_len = 0; ps->IDAT_pos = 0; ps->IDAT_crc = 0UL; store_read_buffer_next(ps); return; } pf = pf->next; } { size_t pos; char msg[FILE_NAME_SIZE+64]; pos = standard_name_from_id(msg, sizeof msg, 0, id); pos = safecat(msg, sizeof msg, pos, ": file not found"); png_error(ps->pread, msg); } } /* The main interface for reading a saved file - pass the id number of the file * to retrieve. Ids must be unique or the earlier file will be hidden. The API * returns a png_struct and, optionally, a png_info. Both of these will be * destroyed by store_read_reset above. */ static png_structp set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id, const char *name) { /* Set the name for png_error */ safecat(ps->test, sizeof ps->test, 0, name); if (ps->pread != NULL) png_error(ps->pread, "read store already in use"); store_read_reset(ps); /* Both the create APIs can return NULL if used in their default mode * (because there is no other way of handling an error because the jmp_buf * by default is stored in png_struct and that has not been allocated!) * However, given that store_error works correctly in these circumstances * we don't ever expect NULL in this program. */ # ifdef PNG_USER_MEM_SUPPORTED if (!ps->speed) ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning, &ps->read_memory_pool, store_malloc, store_free); else # endif ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning); if (ps->pread == NULL) { struct exception_context *the_exception_context = &ps->exception_context; store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)", 1 /*error*/); Throw ps; } # ifdef PNG_SET_OPTION_SUPPORTED { int opt; for (opt=0; optnoptions; ++opt) if (png_set_option(ps->pread, ps->options[opt].option, ps->options[opt].setting) == PNG_OPTION_INVALID) png_error(ps->pread, "png option invalid"); } # endif store_read_set(ps, id); if (ppi != NULL) *ppi = ps->piread = png_create_info_struct(ps->pread); return ps->pread; } #endif /* PNG_READ_SUPPORTED */ /* The overall cleanup of a store simply calls the above then removes all the * saved files. This does not delete the store itself. */ static void store_delete(png_store *ps) { store_write_reset(ps); store_read_reset(ps); store_freefile(&ps->saved); store_image_free(ps, NULL); } /*********************** PNG FILE MODIFICATION ON READ ************************/ /* Files may be modified on read. The following structure contains a complete * png_store together with extra members to handle modification and a special * read callback for libpng. To use this the 'modifications' field must be set * to a list of png_modification structures that actually perform the * modification, otherwise a png_modifier is functionally equivalent to a * png_store. There is a special read function, set_modifier_for_read, which * replaces set_store_for_read. */ typedef enum modifier_state { modifier_start, /* Initial value */ modifier_signature, /* Have a signature */ modifier_IHDR /* Have an IHDR */ } modifier_state; typedef struct CIE_color { /* A single CIE tristimulus value, representing the unique response of a * standard observer to a variety of light spectra. The observer recognizes * all spectra that produce this response as the same color, therefore this * is effectively a description of a color. */ double X, Y, Z; } CIE_color; typedef struct color_encoding { /* A description of an (R,G,B) encoding of color (as defined above); this * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and * (0,0,1) plus an encoding value that is used to encode the linear * components R, G and B to give the actual values R^gamma, G^gamma and * B^gamma that are stored. */ double gamma; /* Encoding (file) gamma of space */ CIE_color red, green, blue; /* End points */ } color_encoding; #ifdef PNG_READ_SUPPORTED #if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED static double chromaticity_x(CIE_color c) { return c.X / (c.X + c.Y + c.Z); } static double chromaticity_y(CIE_color c) { return c.Y / (c.X + c.Y + c.Z); } static CIE_color white_point(const color_encoding *encoding) { CIE_color white; white.X = encoding->red.X + encoding->green.X + encoding->blue.X; white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y; white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z; return white; } #endif /* READ_TRANSFORMS && READ_cHRM */ #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED static void normalize_color_encoding(color_encoding *encoding) { const double whiteY = encoding->red.Y + encoding->green.Y + encoding->blue.Y; if (whiteY != 1) { encoding->red.X /= whiteY; encoding->red.Y /= whiteY; encoding->red.Z /= whiteY; encoding->green.X /= whiteY; encoding->green.Y /= whiteY; encoding->green.Z /= whiteY; encoding->blue.X /= whiteY; encoding->blue.Y /= whiteY; encoding->blue.Z /= whiteY; } } #endif #ifdef PNG_READ_TRANSFORMS_SUPPORTED static size_t safecat_color_encoding(char *buffer, size_t bufsize, size_t pos, const color_encoding *e, double encoding_gamma) { if (e != 0) { if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, "("); pos = safecat(buffer, bufsize, pos, "R("); pos = safecatd(buffer, bufsize, pos, e->red.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Z, 4); pos = safecat(buffer, bufsize, pos, "),G("); pos = safecatd(buffer, bufsize, pos, e->green.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Z, 4); pos = safecat(buffer, bufsize, pos, "),B("); pos = safecatd(buffer, bufsize, pos, e->blue.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4); pos = safecat(buffer, bufsize, pos, ")"); if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, ")"); } if (encoding_gamma != 0) { pos = safecat(buffer, bufsize, pos, "^"); pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5); } return pos; } #endif /* READ_TRANSFORMS */ #endif /* PNG_READ_SUPPORTED */ typedef struct png_modifier { png_store this; /* I am a png_store */ struct png_modification *modifications; /* Changes to make */ modifier_state state; /* My state */ /* Information from IHDR: */ png_byte bit_depth; /* From IHDR */ png_byte colour_type; /* From IHDR */ /* While handling PLTE, IDAT and IEND these chunks may be pended to allow * other chunks to be inserted. */ png_uint_32 pending_len; png_uint_32 pending_chunk; /* Test values */ double *gammas; unsigned int ngammas; unsigned int ngamma_tests; /* Number of gamma tests to run*/ double current_gamma; /* 0 if not set */ const color_encoding *encodings; unsigned int nencodings; const color_encoding *current_encoding; /* If an encoding has been set */ unsigned int encoding_counter; /* For iteration */ int encoding_ignored; /* Something overwrote it */ /* Control variables used to iterate through possible encodings, the * following must be set to 0 and tested by the function that uses the * png_modifier because the modifier only sets it to 1 (true.) */ unsigned int repeat :1; /* Repeat this transform test. */ unsigned int test_uses_encoding :1; /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */ png_byte sbitlow; /* Error control - these are the limits on errors accepted by the gamma tests * below. */ double maxout8; /* Maximum output value error */ double maxabs8; /* Absolute sample error 0..1 */ double maxcalc8; /* Absolute sample error 0..1 */ double maxpc8; /* Percentage sample error 0..100% */ double maxout16; /* Maximum output value error */ double maxabs16; /* Absolute sample error 0..1 */ double maxcalc16;/* Absolute sample error 0..1 */ double maxcalcG; /* Absolute sample error 0..1 */ double maxpc16; /* Percentage sample error 0..100% */ /* This is set by transforms that need to allow a higher limit, it is an * internal check on pngvalid to ensure that the calculated error limits are * not ridiculous; without this it is too easy to make a mistake in pngvalid * that allows any value through. * * NOTE: this is not checked in release builds. */ double limit; /* limit on error values, normally 4E-3 */ /* Log limits - values above this are logged, but not necessarily * warned. */ double log8; /* Absolute error in 8 bits to log */ double log16; /* Absolute error in 16 bits to log */ /* Logged 8 and 16 bit errors ('output' values): */ double error_gray_2; double error_gray_4; double error_gray_8; double error_gray_16; double error_color_8; double error_color_16; double error_indexed; /* Flags: */ /* Whether to call png_read_update_info, not png_read_start_image, and how * many times to call it. */ int use_update_info; /* Whether or not to interlace. */ int interlace_type :9; /* int, but must store '1' */ /* Run the standard tests? */ unsigned int test_standard :1; /* Run the odd-sized image and interlace read/write tests? */ unsigned int test_size :1; /* Run tests on reading with a combination of transforms, */ unsigned int test_transform :1; unsigned int test_tRNS :1; /* Includes tRNS images */ /* When to use the use_input_precision option, this controls the gamma * validation code checks. If set any value that is within the transformed * range input-.5 to input+.5 will be accepted, otherwise the value must be * within the normal limits. It should not be necessary to set this; the * result should always be exact within the permitted error limits. */ unsigned int use_input_precision :1; unsigned int use_input_precision_sbit :1; unsigned int use_input_precision_16to8 :1; /* If set assume that the calculation bit depth is set by the input * precision, not the output precision. */ unsigned int calculations_use_input_precision :1; /* If set assume that the calculations are done in 16 bits even if the sample * depth is 8 bits. */ unsigned int assume_16_bit_calculations :1; /* Which gamma tests to run: */ unsigned int test_gamma_threshold :1; unsigned int test_gamma_transform :1; /* main tests */ unsigned int test_gamma_sbit :1; unsigned int test_gamma_scale16 :1; unsigned int test_gamma_background :1; unsigned int test_gamma_alpha_mode :1; unsigned int test_gamma_expand16 :1; unsigned int test_exhaustive :1; /* Whether or not to run the low-bit-depth grayscale tests. This fails on * gamma images in some cases because of gross inaccuracies in the grayscale * gamma handling for low bit depth. */ unsigned int test_lbg :1; unsigned int test_lbg_gamma_threshold :1; unsigned int test_lbg_gamma_transform :1; unsigned int test_lbg_gamma_sbit :1; unsigned int test_lbg_gamma_composition :1; unsigned int log :1; /* Log max error */ /* Buffer information, the buffer size limits the size of the chunks that can * be modified - they must fit (including header and CRC) into the buffer! */ size_t flush; /* Count of bytes to flush */ size_t buffer_count; /* Bytes in buffer */ size_t buffer_position; /* Position in buffer */ png_byte buffer[1024]; } png_modifier; /* This returns true if the test should be stopped now because it has already * failed and it is running silently. */ static int fail(png_modifier *pm) { return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 || (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0)); } static void modifier_init(png_modifier *pm) { memset(pm, 0, sizeof *pm); store_init(&pm->this); pm->modifications = NULL; pm->state = modifier_start; pm->sbitlow = 1U; pm->ngammas = 0; pm->ngamma_tests = 0; pm->gammas = 0; pm->current_gamma = 0; pm->encodings = 0; pm->nencodings = 0; pm->current_encoding = 0; pm->encoding_counter = 0; pm->encoding_ignored = 0; pm->repeat = 0; pm->test_uses_encoding = 0; pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0; pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0; pm->maxcalcG = 0; pm->limit = 4E-3; pm->log8 = pm->log16 = 0; /* Means 'off' */ pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0; pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0; pm->error_indexed = 0; pm->use_update_info = 0; pm->interlace_type = PNG_INTERLACE_NONE; pm->test_standard = 0; pm->test_size = 0; pm->test_transform = 0; # ifdef PNG_WRITE_tRNS_SUPPORTED pm->test_tRNS = 1; # else pm->test_tRNS = 0; # endif pm->use_input_precision = 0; pm->use_input_precision_sbit = 0; pm->use_input_precision_16to8 = 0; pm->calculations_use_input_precision = 0; pm->assume_16_bit_calculations = 0; pm->test_gamma_threshold = 0; pm->test_gamma_transform = 0; pm->test_gamma_sbit = 0; pm->test_gamma_scale16 = 0; pm->test_gamma_background = 0; pm->test_gamma_alpha_mode = 0; pm->test_gamma_expand16 = 0; pm->test_lbg = 1; pm->test_lbg_gamma_threshold = 1; pm->test_lbg_gamma_transform = 1; pm->test_lbg_gamma_sbit = 1; pm->test_lbg_gamma_composition = 1; pm->test_exhaustive = 0; pm->log = 0; /* Rely on the memset for all the other fields - there are no pointers */ } #ifdef PNG_READ_TRANSFORMS_SUPPORTED /* This controls use of checks that explicitly know how libpng digitizes the * samples in calculations; setting this circumvents simple error limit checking * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5 * algorithm. */ #define DIGITIZE PNG_LIBPNG_VER < 10700 /* If pm->calculations_use_input_precision is set then operations will happen * with the precision of the input, not the precision of the output depth. * * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16 * bit precision. This only affects those of the following limits that pertain * to a calculation - not a digitization operation - unless the following API is * called directly. */ #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED #if DIGITIZE static double digitize(double value, int depth, int do_round) { /* 'value' is in the range 0 to 1, the result is the same value rounded to a * multiple of the digitization factor - 8 or 16 bits depending on both the * sample depth and the 'assume' setting. Digitization is normally by * rounding and 'do_round' should be 1, if it is 0 the digitized value will * be truncated. */ const unsigned int digitization_factor = (1U << depth) -1; /* Limiting the range is done as a convenience to the caller - it's easier to * do it once here than every time at the call site. */ if (value <= 0) value = 0; else if (value >= 1) value = 1; value *= digitization_factor; if (do_round) value += .5; return floor(value)/digitization_factor; } #endif #endif /* RGB_TO_GRAY */ #ifdef PNG_READ_GAMMA_SUPPORTED static double abserr(const png_modifier *pm, int in_depth, int out_depth) { /* Absolute error permitted in linear values - affected by the bit depth of * the calculations. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxabs16; else return pm->maxabs8; } static double calcerr(const png_modifier *pm, int in_depth, int out_depth) { /* Error in the linear composition arithmetic - only relevant when * composition actually happens (0 < alpha < 1). */ if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxcalc16; else if (pm->assume_16_bit_calculations) return pm->maxcalcG; else return pm->maxcalc8; } static double pcerr(const png_modifier *pm, int in_depth, int out_depth) { /* Percentage error permitted in the linear values. Note that the specified * value is a percentage but this routine returns a simple number. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxpc16 * .01; else return pm->maxpc8 * .01; } /* Output error - the error in the encoded value. This is determined by the * digitization of the output so can be +/-0.5 in the actual output value. In * the expand_16 case with the current code in libpng the expand happens after * all the calculations are done in 8 bit arithmetic, so even though the output * depth is 16 the output error is determined by the 8 bit calculation. * * This limit is not determined by the bit depth of internal calculations. * * The specified parameter does *not* include the base .5 digitization error but * it is added here. */ static double outerr(const png_modifier *pm, int in_depth, int out_depth) { /* There is a serious error in the 2 and 4 bit grayscale transform because * the gamma table value (8 bits) is simply shifted, not rounded, so the * error in 4 bit grayscale gamma is up to the value below. This is a hack * to allow pngvalid to succeed: * * TODO: fix this in libpng */ if (out_depth == 2) return .73182-.5; if (out_depth == 4) return .90644-.5; if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxout16; /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ else if (out_depth == 16) return pm->maxout8 * 257; else return pm->maxout8; } /* This does the same thing as the above however it returns the value to log, * rather than raising a warning. This is useful for debugging to track down * exactly what set of parameters cause high error values. */ static double outlog(const png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; } /* This complements the above by providing the appropriate quantization for the * final value. Normally this would just be quantization to an integral value, * but in the 8 bit calculation case it's actually quantization to a multiple of * 257! */ static int output_quantization_factor(const png_modifier *pm, int in_depth, int out_depth) { if (out_depth == 16 && in_depth != 16 && pm->calculations_use_input_precision) return 257; else return 1; } #endif /* PNG_READ_GAMMA_SUPPORTED */ /* One modification structure must be provided for each chunk to be modified (in * fact more than one can be provided if multiple separate changes are desired * for a single chunk.) Modifications include adding a new chunk when a * suitable chunk does not exist. * * The caller of modify_fn will reset the CRC of the chunk and record 'modified' * or 'added' as appropriate if the modify_fn returns 1 (true). If the * modify_fn is NULL the chunk is simply removed. */ typedef struct png_modification { struct png_modification *next; png_uint_32 chunk; /* If the following is NULL all matching chunks will be removed: */ int (*modify_fn)(struct png_modifier *pm, struct png_modification *me, int add); /* If the following is set to PLTE, IDAT or IEND and the chunk has not been * found and modified (and there is a modify_fn) the modify_fn will be called * to add the chunk before the relevant chunk. */ png_uint_32 add; unsigned int modified :1; /* Chunk was modified */ unsigned int added :1; /* Chunk was added */ unsigned int removed :1; /* Chunk was removed */ } png_modification; static void modification_reset(png_modification *pmm) { if (pmm != NULL) { pmm->modified = 0; pmm->added = 0; pmm->removed = 0; modification_reset(pmm->next); } } static void modification_init(png_modification *pmm) { memset(pmm, 0, sizeof *pmm); pmm->next = NULL; pmm->chunk = 0; pmm->modify_fn = NULL; pmm->add = 0; modification_reset(pmm); } #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED static void modifier_current_encoding(const png_modifier *pm, color_encoding *ce) { if (pm->current_encoding != 0) *ce = *pm->current_encoding; else memset(ce, 0, sizeof *ce); ce->gamma = pm->current_gamma; } #endif #ifdef PNG_READ_TRANSFORMS_SUPPORTED static size_t safecat_current_encoding(char *buffer, size_t bufsize, size_t pos, const png_modifier *pm) { pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding, pm->current_gamma); if (pm->encoding_ignored) pos = safecat(buffer, bufsize, pos, "[overridden]"); return pos; } #endif /* Iterate through the usefully testable color encodings. An encoding is one * of: * * 1) Nothing (no color space, no gamma). * 2) Just a gamma value from the gamma array (including 1.0) * 3) A color space from the encodings array with the corresponding gamma. * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations) * * The iterator selects these in turn, the randomizer selects one at random, * which is used depends on the setting of the 'test_exhaustive' flag. Notice * that this function changes the colour space encoding so it must only be * called on completion of the previous test. This is what 'modifier_reset' * does, below. * * After the function has been called the 'repeat' flag will still be set; the * caller of modifier_reset must reset it at the start of each run of the test! */ static unsigned int modifier_total_encodings(const png_modifier *pm) { return 1 + /* (1) nothing */ pm->ngammas + /* (2) gamma values to test */ pm->nencodings + /* (3) total number of encodings */ /* The following test only works after the first time through the * png_modifier code because 'bit_depth' is set when the IHDR is read. * modifier_reset, below, preserves the setting until after it has called * the iterate function (also below.) * * For this reason do not rely on this function outside a call to * modifier_reset. */ ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ? pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */ } static void modifier_encoding_iterate(png_modifier *pm) { if (!pm->repeat && /* Else something needs the current encoding again. */ pm->test_uses_encoding) /* Some transform is encoding dependent */ { if (pm->test_exhaustive) { if (++pm->encoding_counter >= modifier_total_encodings(pm)) pm->encoding_counter = 0; /* This will stop the repeat */ } else { /* Not exhaustive - choose an encoding at random; generate a number in * the range 1..(max-1), so the result is always non-zero: */ if (pm->encoding_counter == 0) pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1; else pm->encoding_counter = 0; } if (pm->encoding_counter > 0) pm->repeat = 1; } else if (!pm->repeat) pm->encoding_counter = 0; } static void modifier_reset(png_modifier *pm) { store_read_reset(&pm->this); pm->limit = 4E-3; pm->pending_len = pm->pending_chunk = 0; pm->flush = pm->buffer_count = pm->buffer_position = 0; pm->modifications = NULL; pm->state = modifier_start; modifier_encoding_iterate(pm); /* The following must be set in the next run. In particular * test_uses_encodings must be set in the _ini function of each transform * that looks at the encodings. (Not the 'add' function!) */ pm->test_uses_encoding = 0; pm->current_gamma = 0; pm->current_encoding = 0; pm->encoding_ignored = 0; /* These only become value after IHDR is read: */ pm->bit_depth = pm->colour_type = 0; } /* The following must be called before anything else to get the encoding set up * on the modifier. In particular it must be called before the transform init * functions are called. */ static void modifier_set_encoding(png_modifier *pm) { /* Set the encoding to the one specified by the current encoding counter, * first clear out all the settings - this corresponds to an encoding_counter * of 0. */ pm->current_gamma = 0; pm->current_encoding = 0; pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */ /* Now, if required, set the gamma and encoding fields. */ if (pm->encoding_counter > 0) { /* The gammas[] array is an array of screen gammas, not encoding gammas, * so we need the inverse: */ if (pm->encoding_counter <= pm->ngammas) pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1]; else { unsigned int i = pm->encoding_counter - pm->ngammas; if (i >= pm->nencodings) { i %= pm->nencodings; pm->current_gamma = 1; /* Linear, only in the 16 bit case */ } else pm->current_gamma = pm->encodings[i].gamma; pm->current_encoding = pm->encodings + i; } } } /* Enquiry functions to find out what is set. Notice that there is an implicit * assumption below that the first encoding in the list is the one for sRGB. */ static int modifier_color_encoding_is_sRGB(const png_modifier *pm) { return pm->current_encoding != 0 && pm->current_encoding == pm->encodings && pm->current_encoding->gamma == pm->current_gamma; } static int modifier_color_encoding_is_set(const png_modifier *pm) { return pm->current_gamma != 0; } /* The guts of modification are performed during a read. */ static void modifier_crc(png_bytep buffer) { /* Recalculate the chunk CRC - a complete chunk must be in * the buffer, at the start. */ uInt datalen = png_get_uint_32(buffer); uLong crc = crc32(0, buffer+4, datalen+4); /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value. */ png_save_uint_32(buffer+datalen+8, (png_uint_32)crc); } static void modifier_setbuffer(png_modifier *pm) { modifier_crc(pm->buffer); pm->buffer_count = png_get_uint_32(pm->buffer)+12; pm->buffer_position = 0; } /* Separate the callback into the actual implementation (which is passed the * png_modifier explicitly) and the callback, which gets the modifier from the * png_struct. */ static void modifier_read_imp(png_modifier *pm, png_bytep pb, png_size_t st) { while (st > 0) { size_t cb; png_uint_32 len, chunk; png_modification *mod; if (pm->buffer_position >= pm->buffer_count) switch (pm->state) { static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 }; case modifier_start: store_read_chunk(&pm->this, pm->buffer, 8, 8); /* signature. */ pm->buffer_count = 8; pm->buffer_position = 0; if (memcmp(pm->buffer, sign, 8) != 0) png_error(pm->this.pread, "invalid PNG file signature"); pm->state = modifier_signature; break; case modifier_signature: store_read_chunk(&pm->this, pm->buffer, 13+12, 13+12); /* IHDR */ pm->buffer_count = 13+12; pm->buffer_position = 0; if (png_get_uint_32(pm->buffer) != 13 || png_get_uint_32(pm->buffer+4) != CHUNK_IHDR) png_error(pm->this.pread, "invalid IHDR"); /* Check the list of modifiers for modifications to the IHDR. */ mod = pm->modifications; while (mod != NULL) { if (mod->chunk == CHUNK_IHDR && mod->modify_fn && (*mod->modify_fn)(pm, mod, 0)) { mod->modified = 1; modifier_setbuffer(pm); } /* Ignore removal or add if IHDR! */ mod = mod->next; } /* Cache information from the IHDR (the modified one.) */ pm->bit_depth = pm->buffer[8+8]; pm->colour_type = pm->buffer[8+8+1]; pm->state = modifier_IHDR; pm->flush = 0; break; case modifier_IHDR: default: /* Read a new chunk and process it until we see PLTE, IDAT or * IEND. 'flush' indicates that there is still some data to * output from the preceding chunk. */ if ((cb = pm->flush) > 0) { if (cb > st) cb = st; pm->flush -= cb; store_read_chunk(&pm->this, pb, cb, cb); pb += cb; st -= cb; if (st == 0) return; } /* No more bytes to flush, read a header, or handle a pending * chunk. */ if (pm->pending_chunk != 0) { png_save_uint_32(pm->buffer, pm->pending_len); png_save_uint_32(pm->buffer+4, pm->pending_chunk); pm->pending_len = 0; pm->pending_chunk = 0; } else store_read_chunk(&pm->this, pm->buffer, 8, 8); pm->buffer_count = 8; pm->buffer_position = 0; /* Check for something to modify or a terminator chunk. */ len = png_get_uint_32(pm->buffer); chunk = png_get_uint_32(pm->buffer+4); /* Terminators first, they may have to be delayed for added * chunks */ if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT || chunk == CHUNK_IEND) { mod = pm->modifications; while (mod != NULL) { if ((mod->add == chunk || (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) && mod->modify_fn != NULL && !mod->modified && !mod->added) { /* Regardless of what the modify function does do not run * this again. */ mod->added = 1; if ((*mod->modify_fn)(pm, mod, 1 /*add*/)) { /* Reset the CRC on a new chunk */ if (pm->buffer_count > 0) modifier_setbuffer(pm); else { pm->buffer_position = 0; mod->removed = 1; } /* The buffer has been filled with something (we assume) * so output this. Pend the current chunk. */ pm->pending_len = len; pm->pending_chunk = chunk; break; /* out of while */ } } mod = mod->next; } /* Don't do any further processing if the buffer was modified - * otherwise the code will end up modifying a chunk that was * just added. */ if (mod != NULL) break; /* out of switch */ } /* If we get to here then this chunk may need to be modified. To * do this it must be less than 1024 bytes in total size, otherwise * it just gets flushed. */ if (len+12 <= sizeof pm->buffer) { png_size_t s = len+12-pm->buffer_count; store_read_chunk(&pm->this, pm->buffer+pm->buffer_count, s, s); pm->buffer_count = len+12; /* Check for a modification, else leave it be. */ mod = pm->modifications; while (mod != NULL) { if (mod->chunk == chunk) { if (mod->modify_fn == NULL) { /* Remove this chunk */ pm->buffer_count = pm->buffer_position = 0; mod->removed = 1; break; /* Terminate the while loop */ } else if ((*mod->modify_fn)(pm, mod, 0)) { mod->modified = 1; /* The chunk may have been removed: */ if (pm->buffer_count == 0) { pm->buffer_position = 0; break; } modifier_setbuffer(pm); } } mod = mod->next; } } else pm->flush = len+12 - pm->buffer_count; /* data + crc */ /* Take the data from the buffer (if there is any). */ break; } /* Here to read from the modifier buffer (not directly from * the store, as in the flush case above.) */ cb = pm->buffer_count - pm->buffer_position; if (cb > st) cb = st; memcpy(pb, pm->buffer + pm->buffer_position, cb); st -= cb; pb += cb; pm->buffer_position += cb; } } /* The callback: */ static void PNGCBAPI modifier_read(png_structp ppIn, png_bytep pb, png_size_t st) { png_const_structp pp = ppIn; png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp)); if (pm == NULL || pm->this.pread != pp) png_error(pp, "bad modifier_read call"); modifier_read_imp(pm, pb, st); } /* Like store_progressive_read but the data is getting changed as we go so we * need a local buffer. */ static void modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi) { if (pm->this.pread != pp || pm->this.current == NULL || pm->this.next == NULL) png_error(pp, "store state damaged (progressive)"); /* This is another Horowitz and Hill random noise generator. In this case * the aim is to stress the progressive reader with truly horrible variable * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers * is generated. We could probably just count from 1 to 32767 and get as * good a result. */ for (;;) { static png_uint_32 noise = 1; png_size_t cb, cbAvail; png_byte buffer[512]; /* Generate 15 more bits of stuff: */ noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff); cb = noise & 0x1ff; /* Check that this number of bytes are available (in the current buffer.) * (This doesn't quite work - the modifier might delete a chunk; unlikely * but possible, it doesn't happen at present because the modifier only * adds chunks to standard images.) */ cbAvail = store_read_buffer_avail(&pm->this); if (pm->buffer_count > pm->buffer_position) cbAvail += pm->buffer_count - pm->buffer_position; if (cb > cbAvail) { /* Check for EOF: */ if (cbAvail == 0) break; cb = cbAvail; } modifier_read_imp(pm, buffer, cb); png_process_data(pp, pi, buffer, cb); } /* Check the invariants at the end (if this fails it's a problem in this * file!) */ if (pm->buffer_count > pm->buffer_position || pm->this.next != &pm->this.current->data || pm->this.readpos < pm->this.current->datacount) png_error(pp, "progressive read implementation error"); } /* Set up a modifier. */ static png_structp set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id, const char *name) { /* Do this first so that the modifier fields are cleared even if an error * happens allocating the png_struct. No allocation is done here so no * cleanup is required. */ pm->state = modifier_start; pm->bit_depth = 0; pm->colour_type = 255; pm->pending_len = 0; pm->pending_chunk = 0; pm->flush = 0; pm->buffer_count = 0; pm->buffer_position = 0; return set_store_for_read(&pm->this, ppi, id, name); } /******************************** MODIFICATIONS *******************************/ /* Standard modifications to add chunks. These do not require the _SUPPORTED * macros because the chunks can be there regardless of whether this specific * libpng supports them. */ typedef struct gama_modification { png_modification this; png_fixed_point gamma; } gama_modification; static int gama_modify(png_modifier *pm, png_modification *me, int add) { UNUSED(add) /* This simply dumps the given gamma value into the buffer. */ png_save_uint_32(pm->buffer, 4); png_save_uint_32(pm->buffer+4, CHUNK_gAMA); png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma); return 1; } static void gama_modification_init(gama_modification *me, png_modifier *pm, double gammad) { double g; modification_init(&me->this); me->this.chunk = CHUNK_gAMA; me->this.modify_fn = gama_modify; me->this.add = CHUNK_PLTE; g = fix(gammad); me->gamma = (png_fixed_point)g; me->this.next = pm->modifications; pm->modifications = &me->this; } typedef struct chrm_modification { png_modification this; const color_encoding *encoding; png_fixed_point wx, wy, rx, ry, gx, gy, bx, by; } chrm_modification; static int chrm_modify(png_modifier *pm, png_modification *me, int add) { UNUSED(add) /* As with gAMA this just adds the required cHRM chunk to the buffer. */ png_save_uint_32(pm->buffer , 32); png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM); png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx); png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy); png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx); png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry); png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx); png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy); png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx); png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by); return 1; } static void chrm_modification_init(chrm_modification *me, png_modifier *pm, const color_encoding *encoding) { CIE_color white = white_point(encoding); /* Original end points: */ me->encoding = encoding; /* Chromaticities (in fixed point): */ me->wx = fix(chromaticity_x(white)); me->wy = fix(chromaticity_y(white)); me->rx = fix(chromaticity_x(encoding->red)); me->ry = fix(chromaticity_y(encoding->red)); me->gx = fix(chromaticity_x(encoding->green)); me->gy = fix(chromaticity_y(encoding->green)); me->bx = fix(chromaticity_x(encoding->blue)); me->by = fix(chromaticity_y(encoding->blue)); modification_init(&me->this); me->this.chunk = CHUNK_cHRM; me->this.modify_fn = chrm_modify; me->this.add = CHUNK_PLTE; me->this.next = pm->modifications; pm->modifications = &me->this; } typedef struct srgb_modification { png_modification this; png_byte intent; } srgb_modification; static int srgb_modify(png_modifier *pm, png_modification *me, int add) { UNUSED(add) /* As above, ignore add and just make a new chunk */ png_save_uint_32(pm->buffer, 1); png_save_uint_32(pm->buffer+4, CHUNK_sRGB); pm->buffer[8] = ((srgb_modification*)me)->intent; return 1; } static void srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent) { modification_init(&me->this); me->this.chunk = CHUNK_sBIT; if (intent <= 3) /* if valid, else *delete* sRGB chunks */ { me->this.modify_fn = srgb_modify; me->this.add = CHUNK_PLTE; me->intent = intent; } else { me->this.modify_fn = 0; me->this.add = 0; me->intent = 0; } me->this.next = pm->modifications; pm->modifications = &me->this; } #ifdef PNG_READ_GAMMA_SUPPORTED typedef struct sbit_modification { png_modification this; png_byte sbit; } sbit_modification; static int sbit_modify(png_modifier *pm, png_modification *me, int add) { png_byte sbit = ((sbit_modification*)me)->sbit; if (pm->bit_depth > sbit) { int cb = 0; switch (pm->colour_type) { case 0: cb = 1; break; case 2: case 3: cb = 3; break; case 4: cb = 2; break; case 6: cb = 4; break; default: png_error(pm->this.pread, "unexpected colour type in sBIT modification"); } png_save_uint_32(pm->buffer, cb); png_save_uint_32(pm->buffer+4, CHUNK_sBIT); while (cb > 0) (pm->buffer+8)[--cb] = sbit; return 1; } else if (!add) { /* Remove the sBIT chunk */ pm->buffer_count = pm->buffer_position = 0; return 1; } else return 0; /* do nothing */ } static void sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit) { modification_init(&me->this); me->this.chunk = CHUNK_sBIT; me->this.modify_fn = sbit_modify; me->this.add = CHUNK_PLTE; me->sbit = sbit; me->this.next = pm->modifications; pm->modifications = &me->this; } #endif /* PNG_READ_GAMMA_SUPPORTED */ #endif /* PNG_READ_TRANSFORMS_SUPPORTED */ /***************************** STANDARD PNG FILES *****************************/ /* Standard files - write and save standard files. */ /* There are two basic forms of standard images. Those which attempt to have * all the possible pixel values (not possible for 16bpp images, but a range of * values are produced) and those which have a range of image sizes. The former * are used for testing transforms, in particular gamma correction and bit * reduction and increase. The latter are reserved for testing the behavior of * libpng with respect to 'odd' image sizes - particularly small images where * rows become 1 byte and interlace passes disappear. * * The first, most useful, set are the 'transform' images, the second set of * small images are the 'size' images. * * The transform files are constructed with rows which fit into a 1024 byte row * buffer. This makes allocation easier below. Further regardless of the file * format every row has 128 pixels (giving 1024 bytes for 64bpp formats). * * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed * and with an ID derived from the colour type, bit depth and interlace type * as above (FILEID). The width (128) and height (variable) are not stored in * the FILEID - instead the fields are set to 0, indicating a transform file. * * The size files ar constructed with rows a maximum of 128 bytes wide, allowing * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum * height of 16 rows. The width and height are stored in the FILEID and, being * non-zero, indicate a size file. * * Because the PNG filter code is typically the largest CPU consumer within * libpng itself there is a tendency to attempt to optimize it. This results in * special case code which needs to be validated. To cause this to happen the * 'size' images are made to use each possible filter, in so far as this is * possible for smaller images. * * For palette image (colour type 3) multiple transform images are stored with * the same bit depth to allow testing of more colour combinations - * particularly important for testing the gamma code because libpng uses a * different code path for palette images. For size images a single palette is * used. */ /* Make a 'standard' palette. Because there are only 256 entries in a palette * (maximum) this actually makes a random palette in the hope that enough tests * will catch enough errors. (Note that the same palette isn't produced every * time for the same test - it depends on what previous tests have been run - * but a given set of arguments to pngvalid will always produce the same palette * at the same test! This is why pseudo-random number generators are useful for * testing.) * * The store must be open for write when this is called, otherwise an internal * error will occur. This routine contains its own magic number seed, so the * palettes generated don't change if there are intervening errors (changing the * calls to the store_mark seed.) */ static store_palette_entry * make_standard_palette(png_store* ps, int npalette, int do_tRNS) { static png_uint_32 palette_seed[2] = { 0x87654321, 9 }; int i = 0; png_byte values[256][4]; /* Always put in black and white plus the six primary and secondary colors. */ for (; i<8; ++i) { values[i][1] = (png_byte)((i&1) ? 255U : 0U); values[i][2] = (png_byte)((i&2) ? 255U : 0U); values[i][3] = (png_byte)((i&4) ? 255U : 0U); } /* Then add 62 grays (one quarter of the remaining 256 slots). */ { int j = 0; png_byte random_bytes[4]; png_byte need[256]; need[0] = 0; /*got black*/ memset(need+1, 1, (sizeof need)-2); /*need these*/ need[255] = 0; /*but not white*/ while (i<70) { png_byte b; if (j==0) { make_four_random_bytes(palette_seed, random_bytes); j = 4; } b = random_bytes[--j]; if (need[b]) { values[i][1] = b; values[i][2] = b; values[i++][3] = b; } } } /* Finally add 192 colors at random - don't worry about matches to things we * already have, chance is less than 1/65536. Don't worry about grays, * chance is the same, so we get a duplicate or extra gray less than 1 time * in 170. */ for (; i<256; ++i) make_four_random_bytes(palette_seed, values[i]); /* Fill in the alpha values in the first byte. Just use all possible values * (0..255) in an apparently random order: */ { store_palette_entry *palette; png_byte selector[4]; make_four_random_bytes(palette_seed, selector); if (do_tRNS) for (i=0; i<256; ++i) values[i][0] = (png_byte)(i ^ selector[0]); else for (i=0; i<256; ++i) values[i][0] = 255; /* no transparency/tRNS chunk */ /* 'values' contains 256 ARGB values, but we only need 'npalette'. * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low * bit depth cases select colors at random, else it is difficult to have * a set of low bit depth palette test with any chance of a reasonable * range of colors. Do this by randomly permuting values into the low * 'npalette' entries using an XOR mask generated here. This also * permutes the npalette == 256 case in a potentially useful way (there is * no relationship between palette index and the color value therein!) */ palette = store_write_palette(ps, npalette); for (i=0; i 0) png_set_tRNS(pp, pi, tRNS, j, 0/*color*/); #endif } } #ifdef PNG_WRITE_tRNS_SUPPORTED static void set_random_tRNS(png_structp pp, png_infop pi, const png_byte colour_type, const int bit_depth) { /* To make this useful the tRNS color needs to match at least one pixel. * Random values are fine for gray, including the 16-bit case where we know * that the test image contains all the gray values. For RGB we need more * method as only 65536 different RGB values are generated. */ png_color_16 tRNS; const png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1); R8(tRNS); /* makes unset fields random */ if (colour_type & 2/*RGB*/) { if (bit_depth == 8) { tRNS.red = random_u16(); tRNS.green = random_u16(); tRNS.blue = tRNS.red ^ tRNS.green; tRNS.red &= mask; tRNS.green &= mask; tRNS.blue &= mask; } else /* bit_depth == 16 */ { tRNS.red = random_u16(); tRNS.green = (png_uint_16)(tRNS.red * 257); tRNS.blue = (png_uint_16)(tRNS.green * 17); } } else { tRNS.gray = random_u16(); tRNS.gray &= mask; } png_set_tRNS(pp, pi, NULL, 0, &tRNS); } #endif /* The number of passes is related to the interlace type. There was no libpng * API to determine this prior to 1.5, so we need an inquiry function: */ static int npasses_from_interlace_type(png_const_structp pp, int interlace_type) { switch (interlace_type) { default: png_error(pp, "invalid interlace type"); case PNG_INTERLACE_NONE: return 1; case PNG_INTERLACE_ADAM7: return PNG_INTERLACE_ADAM7_PASSES; } } static unsigned int bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth) { switch (colour_type) { default: png_error(pp, "invalid color type"); case 0: return bit_depth; case 2: return 3*bit_depth; case 3: return bit_depth; case 4: return 2*bit_depth; case 6: return 4*bit_depth; } } #define TRANSFORM_WIDTH 128U #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U) #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */ #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */ #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */ static size_t transform_rowsize(png_const_structp pp, png_byte colour_type, png_byte bit_depth) { return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8; } /* transform_width(pp, colour_type, bit_depth) current returns the same number * every time, so just use a macro: */ #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH static png_uint_32 transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth) { switch (bit_size(pp, colour_type, bit_depth)) { case 1: case 2: case 4: return 1; /* Total of 128 pixels */ case 8: return 2; /* Total of 256 pixels/bytes */ case 16: return 512; /* Total of 65536 pixels */ case 24: case 32: return 512; /* 65536 pixels */ case 48: case 64: return 2048;/* 4 x 65536 pixels. */ # define TRANSFORM_HEIGHTMAX 2048 default: return 0; /* Error, will be caught later */ } } #ifdef PNG_READ_SUPPORTED /* The following can only be defined here, now we have the definitions * of the transform image sizes. */ static png_uint_32 standard_width(png_const_structp pp, png_uint_32 id) { png_uint_32 width = WIDTH_FROM_ID(id); UNUSED(pp) if (width == 0) width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id)); return width; } static png_uint_32 standard_height(png_const_structp pp, png_uint_32 id) { png_uint_32 height = HEIGHT_FROM_ID(id); if (height == 0) height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id)); return height; } static png_uint_32 standard_rowsize(png_const_structp pp, png_uint_32 id) { png_uint_32 width = standard_width(pp, id); /* This won't overflow: */ width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id)); return (width + 7) / 8; } #endif /* PNG_READ_SUPPORTED */ static void transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX], png_byte colour_type, png_byte bit_depth, png_uint_32 y) { png_uint_32 v = y << 7; png_uint_32 i = 0; switch (bit_size(pp, colour_type, bit_depth)) { case 1: while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i; return; case 2: while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i; return; case 4: while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i; return; case 8: /* 256 bytes total, 128 bytes in each row set as follows: */ while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i; return; case 16: /* Generate all 65536 pixel values in order, which includes the 8 bit * GA case as well as the 16 bit G case. */ while (i<128) { buffer[2*i] = (png_byte)((v>>8) & 0xff); buffer[2*i+1] = (png_byte)(v & 0xff); ++v; ++i; } return; case 24: /* 65535 pixels, but rotate the values. */ while (i<128) { /* Three bytes per pixel, r, g, b, make b by r^g */ buffer[3*i+0] = (png_byte)((v >> 8) & 0xff); buffer[3*i+1] = (png_byte)(v & 0xff); buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff); ++v; ++i; } return; case 32: /* 65535 pixels, r, g, b, a; just replicate */ while (i<128) { buffer[4*i+0] = (png_byte)((v >> 8) & 0xff); buffer[4*i+1] = (png_byte)(v & 0xff); buffer[4*i+2] = (png_byte)((v >> 8) & 0xff); buffer[4*i+3] = (png_byte)(v & 0xff); ++v; ++i; } return; case 48: /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at * each pixel, g increase by 257 (0x101) and 'b' by 0x1111: */ while (i<128) { png_uint_32 t = v++; buffer[6*i+0] = (png_byte)((t >> 8) & 0xff); buffer[6*i+1] = (png_byte)(t & 0xff); t *= 257; buffer[6*i+2] = (png_byte)((t >> 8) & 0xff); buffer[6*i+3] = (png_byte)(t & 0xff); t *= 17; buffer[6*i+4] = (png_byte)((t >> 8) & 0xff); buffer[6*i+5] = (png_byte)(t & 0xff); ++i; } return; case 64: /* As above in the 32 bit case. */ while (i<128) { png_uint_32 t = v++; buffer[8*i+0] = (png_byte)((t >> 8) & 0xff); buffer[8*i+1] = (png_byte)(t & 0xff); buffer[8*i+4] = (png_byte)((t >> 8) & 0xff); buffer[8*i+5] = (png_byte)(t & 0xff); t *= 257; buffer[8*i+2] = (png_byte)((t >> 8) & 0xff); buffer[8*i+3] = (png_byte)(t & 0xff); buffer[8*i+6] = (png_byte)((t >> 8) & 0xff); buffer[8*i+7] = (png_byte)(t & 0xff); ++i; } return; default: break; } png_error(pp, "internal error"); } /* This is just to do the right cast - could be changed to a function to check * 'bd' but there isn't much point. */ #define DEPTH(bd) ((png_byte)(1U << (bd))) /* This is just a helper for compiling on minimal systems with no write * interlacing support. If there is no write interlacing we can't generate test * cases with interlace: */ #ifdef PNG_WRITE_INTERLACING_SUPPORTED # define INTERLACE_LAST PNG_INTERLACE_LAST # define check_interlace_type(type) ((void)(type)) # define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp) # define do_own_interlace 0 #elif PNG_LIBPNG_VER < 10700 # define set_write_interlace_handling(pp,type) (1) static void check_interlace_type(int const interlace_type) { /* Prior to 1.7.0 libpng does not support the write of an interlaced image * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the * code here does the pixel interlace itself, so: */ if (interlace_type != PNG_INTERLACE_NONE) { /* This is an internal error - --interlace tests should be skipped, not * attempted. */ fprintf(stderr, "pngvalid: no interlace support\n"); exit(99); } } # define INTERLACE_LAST (PNG_INTERLACE_NONE+1) # define do_own_interlace 0 #else /* libpng 1.7+ */ # define set_write_interlace_handling(pp,type)\ npasses_from_interlace_type(pp,type) # define check_interlace_type(type) ((void)(type)) # define INTERLACE_LAST PNG_INTERLACE_LAST # define do_own_interlace 1 #endif /* WRITE_INTERLACING tests */ #define CAN_WRITE_INTERLACE\ PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED /* Do the same thing for read interlacing; this controls whether read tests do * their own de-interlace or use libpng. */ #ifdef PNG_READ_INTERLACING_SUPPORTED # define do_read_interlace 0 #else /* no libpng read interlace support */ # define do_read_interlace 1 #endif /* The following two routines use the PNG interlace support macros from * png.h to interlace or deinterlace rows. */ static void interlace_row(png_bytep buffer, png_const_bytep imageRow, unsigned int pixel_size, png_uint_32 w, int pass, int littleendian) { png_uint_32 xin, xout, xstep; /* Note that this can, trivially, be optimized to a memcpy on pass 7, the * code is presented this way to make it easier to understand. In practice * consult the code in the libpng source to see other ways of doing this. * * It is OK for buffer and imageRow to be identical, because 'xin' moves * faster than 'xout' and we copy up. */ xin = PNG_PASS_START_COL(pass); xstep = 1U<wname); text.text = copy; text.text_length = pos; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/); # ifdef PNG_WRITE_tRNS_SUPPORTED else if (palette_number) set_random_tRNS(pp, pi, colour_type, bit_depth); # endif png_write_info(pp, pi); if (png_get_rowbytes(pp, pi) != transform_rowsize(pp, colour_type, bit_depth)) png_error(pp, "transform row size incorrect"); else { /* Somewhat confusingly this must be called *after* png_write_info * because if it is called before, the information in *pp has not been * updated to reflect the interlaced image. */ int npasses = set_write_interlace_handling(pp, interlace_type); int pass; if (npasses != npasses_from_interlace_type(pp, interlace_type)) png_error(pp, "write: png_set_interlace_handling failed"); for (pass=0; pass 0) interlace_row(buffer, buffer, bit_size(pp, colour_type, bit_depth), w, pass, 0/*data always bigendian*/); else continue; } # endif /* do_own_interlace */ choose_random_filter(pp, pass == 0 && y == 0); png_write_row(pp, buffer); } } } #ifdef PNG_TEXT_SUPPORTED { static char key[] = "end marker"; static char comment[] = "end"; png_text text; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; text.text = comment; text.text_length = (sizeof comment)-1; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif png_write_end(pp, pi); /* And store this under the appropriate id, then clean up. */ store_storefile(ps, FILEID(colour_type, bit_depth, palette_number, interlace_type, 0, 0, 0)); store_write_reset(ps); } Catch(fault) { /* Use the png_store returned by the exception. This may help the compiler * because 'ps' is not used in this branch of the setjmp. Note that fault * and ps will always be the same value. */ store_write_reset(fault); } } static void make_transform_images(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* This is in case of errors. */ safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images"); /* Use next_format to enumerate all the combinations we test, including * generating multiple low bit depth palette images. Non-A images (palette * and direct) are created with and without tRNS chunks. */ while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1)) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { char name[FILE_NAME_SIZE]; standard_name(name, sizeof name, 0, colour_type, bit_depth, palette_number, interlace_type, 0, 0, do_own_interlace); make_transform_image(&pm->this, colour_type, bit_depth, palette_number, interlace_type, name); } } } /* Build a single row for the 'size' test images; this fills in only the * first bit_width bits of the sample row. */ static void size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y) { /* height is in the range 1 to 16, so: */ y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4); /* the following ensures bits are set in small images: */ y ^= 0xA5; while (bit_width >= 8) *buffer++ = (png_byte)y++, bit_width -= 8; /* There may be up to 7 remaining bits, these go in the most significant * bits of the byte. */ if (bit_width > 0) { png_uint_32 mask = (1U<<(8-bit_width))-1; *buffer = (png_byte)((*buffer & mask) | (y & ~mask)); } } static void make_size_image(png_store* const ps, png_byte const colour_type, png_byte const bit_depth, int const interlace_type, png_uint_32 const w, png_uint_32 const h, int const do_interlace) { context(ps, fault); check_interlace_type(interlace_type); Try { png_infop pi; png_structp pp; unsigned int pixel_size; /* Make a name and get an appropriate id for the store: */ char name[FILE_NAME_SIZE]; const png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/, interlace_type, w, h, do_interlace); standard_name_from_id(name, sizeof name, 0, id); pp = set_store_for_write(ps, &pi, name); /* In the event of a problem return control to the Catch statement below * to do the clean up - it is not possible to 'return' directly from a Try * block. */ if (pp == NULL) Throw ps; png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); #ifdef PNG_TEXT_SUPPORTED { static char key[] = "image name"; /* must be writeable */ size_t pos; png_text text; char copy[FILE_NAME_SIZE]; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; /* Yuck: the text must be writable! */ pos = safecat(copy, sizeof copy, 0, ps->wname); text.text = copy; text.text_length = pos; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/); png_write_info(pp, pi); /* Calculate the bit size, divide by 8 to get the byte size - this won't * overflow because we know the w values are all small enough even for * a system where 'unsigned int' is only 16 bits. */ pixel_size = bit_size(pp, colour_type, bit_depth); if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8) png_error(pp, "size row size incorrect"); else { int npasses = npasses_from_interlace_type(pp, interlace_type); png_uint_32 y; int pass; png_byte image[16][SIZE_ROWMAX]; /* To help consistent error detection make the parts of this buffer * that aren't set below all '1': */ memset(image, 0xff, sizeof image); if (!do_interlace && npasses != set_write_interlace_handling(pp, interlace_type)) png_error(pp, "write: png_set_interlace_handling failed"); /* Prepare the whole image first to avoid making it 7 times: */ for (y=0; y 0) { /* Set to all 1's for error detection (libpng tends to * set unset things to 0). */ memset(tempRow, 0xff, sizeof tempRow); interlace_row(tempRow, row, pixel_size, w, pass, 0/*data always bigendian*/); row = tempRow; } else continue; } # ifdef PNG_WRITE_FILTER_SUPPORTED /* Only get to here if the row has some pixels in it, set the * filters to 'all' for the very first row and thereafter to a * single filter. It isn't well documented, but png_set_filter * does accept a filter number (per the spec) as well as a bit * mask. * * The code now uses filters at random, except that on the first * row of an image it ensures that a previous row filter is in * the set so that libpng allocates the row buffer. */ { int filters = 8 << random_mod(PNG_FILTER_VALUE_LAST); if (pass == 0 && y == 0 && (filters < PNG_FILTER_UP || w == 1U)) filters |= PNG_FILTER_UP; png_set_filter(pp, 0/*method*/, filters); } # endif png_write_row(pp, row); } } } #ifdef PNG_TEXT_SUPPORTED { static char key[] = "end marker"; static char comment[] = "end"; png_text text; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; text.text = comment; text.text_length = (sizeof comment)-1; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif png_write_end(pp, pi); /* And store this under the appropriate id, then clean up. */ store_storefile(ps, id); store_write_reset(ps); } Catch(fault) { /* Use the png_store returned by the exception. This may help the compiler * because 'ps' is not used in this branch of the setjmp. Note that fault * and ps will always be the same value. */ store_write_reset(fault); } } static void make_size(png_store* const ps, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { png_uint_32 width; for (width = 1; width <= 16; ++width) { png_uint_32 height; for (height = 1; height <= 16; ++height) { /* The four combinations of DIY interlace and interlace or not - * no interlace + DIY should be identical to no interlace with * libpng doing it. */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 0); make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 1); # ifdef PNG_WRITE_INTERLACING_SUPPORTED make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 0); # endif # if CAN_WRITE_INTERLACE /* 1.7.0 removes the hack that prevented app write of an interlaced * image if WRITE_INTERLACE was not supported */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 1); # endif } } } } static void make_size_images(png_store *ps) { /* This is in case of errors. */ safecat(ps->test, sizeof ps->test, 0, "make size images"); /* Arguments are colour_type, low bit depth, high bit depth */ make_size(ps, 0, 0, WRITE_BDHI); make_size(ps, 2, 3, WRITE_BDHI); make_size(ps, 3, 0, 3 /*palette: max 8 bits*/); make_size(ps, 4, 3, WRITE_BDHI); make_size(ps, 6, 3, WRITE_BDHI); } #ifdef PNG_READ_SUPPORTED /* Return a row based on image id and 'y' for checking: */ static void standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX], png_uint_32 id, png_uint_32 y) { if (WIDTH_FROM_ID(id) == 0) transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y); else size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id)), y); } #endif /* PNG_READ_SUPPORTED */ /* Tests - individual test cases */ /* Like 'make_standard' but errors are deliberately introduced into the calls * to ensure that they get detected - it should not be possible to write an * invalid image with libpng! */ /* TODO: the 'set' functions can probably all be made to take a * png_const_structp rather than a modifiable one. */ #ifdef PNG_WARNINGS_SUPPORTED static void sBIT0_error_fn(png_structp pp, png_infop pi) { /* 0 is invalid... */ png_color_8 bad; bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0; png_set_sBIT(pp, pi, &bad); } static void sBIT_error_fn(png_structp pp, png_infop pi) { png_byte bit_depth; png_color_8 bad; if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE) bit_depth = 8; else bit_depth = png_get_bit_depth(pp, pi); /* Now we know the bit depth we can easily generate an invalid sBIT entry */ bad.red = bad.green = bad.blue = bad.gray = bad.alpha = (png_byte)(bit_depth+1); png_set_sBIT(pp, pi, &bad); } static const struct { void (*fn)(png_structp, png_infop); const char *msg; unsigned int warning :1; /* the error is a warning... */ } error_test[] = { /* no warnings makes these errors undetectable prior to 1.7.0 */ { sBIT0_error_fn, "sBIT(0): failed to detect error", PNG_LIBPNG_VER < 10700 }, { sBIT_error_fn, "sBIT(too big): failed to detect error", PNG_LIBPNG_VER < 10700 }, }; static void make_error(png_store* const ps, png_byte const colour_type, png_byte bit_depth, int interlace_type, int test, png_const_charp name) { context(ps, fault); check_interlace_type(interlace_type); Try { png_infop pi; const png_structp pp = set_store_for_write(ps, &pi, name); png_uint_32 w, h; gnu_volatile(pp) if (pp == NULL) Throw ps; w = transform_width(pp, colour_type, bit_depth); gnu_volatile(w) h = transform_height(pp, colour_type, bit_depth); gnu_volatile(h) png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/); /* Time for a few errors; these are in various optional chunks, the * standard tests test the standard chunks pretty well. */ # define exception__prev exception_prev_1 # define exception__env exception_env_1 Try { gnu_volatile(exception__prev) /* Expect this to throw: */ ps->expect_error = !error_test[test].warning; ps->expect_warning = error_test[test].warning; ps->saw_warning = 0; error_test[test].fn(pp, pi); /* Normally the error is only detected here: */ png_write_info(pp, pi); /* And handle the case where it was only a warning: */ if (ps->expect_warning && ps->saw_warning) Throw ps; /* If we get here there is a problem, we have success - no error or * no warning - when we shouldn't have success. Log an error. */ store_log(ps, pp, error_test[test].msg, 1 /*error*/); } Catch (fault) { /* expected exit */ } #undef exception__prev #undef exception__env /* And clear these flags */ ps->expect_warning = 0; if (ps->expect_error) ps->expect_error = 0; else { /* Now write the whole image, just to make sure that the detected, or * undetected, errro has not created problems inside libpng. This * doesn't work if there was a png_error in png_write_info because that * can abort before PLTE was written. */ if (png_get_rowbytes(pp, pi) != transform_rowsize(pp, colour_type, bit_depth)) png_error(pp, "row size incorrect"); else { int npasses = set_write_interlace_handling(pp, interlace_type); int pass; if (npasses != npasses_from_interlace_type(pp, interlace_type)) png_error(pp, "write: png_set_interlace_handling failed"); for (pass=0; pass 0) interlace_row(buffer, buffer, bit_size(pp, colour_type, bit_depth), w, pass, 0/*data always bigendian*/); else continue; } # endif /* do_own_interlace */ png_write_row(pp, buffer); } } } /* image writing */ png_write_end(pp, pi); } /* The following deletes the file that was just written. */ store_write_reset(ps); } Catch(fault) { store_write_reset(fault); } } static int make_errors(png_modifier* const pm, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { unsigned int test; char name[FILE_NAME_SIZE]; standard_name(name, sizeof name, 0, colour_type, 1<this, colour_type, DEPTH(bdlo), interlace_type, test, name); if (fail(pm)) return 0; } } } return 1; /* keep going */ } #endif /* PNG_WARNINGS_SUPPORTED */ static void perform_error_test(png_modifier *pm) { #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */ /* Need to do this here because we just write in this test. */ safecat(pm->this.test, sizeof pm->this.test, 0, "error test"); if (!make_errors(pm, 0, 0, WRITE_BDHI)) return; if (!make_errors(pm, 2, 3, WRITE_BDHI)) return; if (!make_errors(pm, 3, 0, 3)) return; if (!make_errors(pm, 4, 3, WRITE_BDHI)) return; if (!make_errors(pm, 6, 3, WRITE_BDHI)) return; #else UNUSED(pm) #endif } /* This is just to validate the internal PNG formatting code - if this fails * then the warning messages the library outputs will probably be garbage. */ static void perform_formatting_test(png_store *ps) { #ifdef PNG_TIME_RFC1123_SUPPORTED /* The handle into the formatting code is the RFC1123 support; this test does * nothing if that is compiled out. */ context(ps, fault); Try { png_const_charp correct = "29 Aug 2079 13:53:60 +0000"; png_const_charp result; # if PNG_LIBPNG_VER >= 10600 char timestring[29]; # endif png_structp pp; png_time pt; pp = set_store_for_write(ps, NULL, "libpng formatting test"); if (pp == NULL) Throw ps; /* Arbitrary settings: */ pt.year = 2079; pt.month = 8; pt.day = 29; pt.hour = 13; pt.minute = 53; pt.second = 60; /* a leap second */ # if PNG_LIBPNG_VER < 10600 result = png_convert_to_rfc1123(pp, &pt); # else if (png_convert_to_rfc1123_buffer(timestring, &pt)) result = timestring; else result = NULL; # endif if (result == NULL) png_error(pp, "png_convert_to_rfc1123 failed"); if (strcmp(result, correct) != 0) { size_t pos = 0; char msg[128]; pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123("); pos = safecat(msg, sizeof msg, pos, correct); pos = safecat(msg, sizeof msg, pos, ") returned: '"); pos = safecat(msg, sizeof msg, pos, result); pos = safecat(msg, sizeof msg, pos, "'"); png_error(pp, msg); } store_write_reset(ps); } Catch(fault) { store_write_reset(fault); } #else UNUSED(ps) #endif } #ifdef PNG_READ_SUPPORTED /* Because we want to use the same code in both the progressive reader and the * sequential reader it is necessary to deal with the fact that the progressive * reader callbacks only have one parameter (png_get_progressive_ptr()), so this * must contain all the test parameters and all the local variables directly * accessible to the sequential reader implementation. * * The technique adopted is to reinvent part of what Dijkstra termed a * 'display'; an array of pointers to the stack frames of enclosing functions so * that a nested function definition can access the local (C auto) variables of * the functions that contain its definition. In fact C provides the first * pointer (the local variables - the stack frame pointer) and the last (the * global variables - the BCPL global vector typically implemented as global * addresses), this code requires one more pointer to make the display - the * local variables (and function call parameters) of the function that actually * invokes either the progressive or sequential reader. * * Perhaps confusingly this technique is confounded with classes - the * 'standard_display' defined here is sub-classed as the 'gamma_display' below. * A gamma_display is a standard_display, taking advantage of the ANSI-C * requirement that the pointer to the first member of a structure must be the * same as the pointer to the structure. This allows us to reuse standard_ * functions in the gamma test code; something that could not be done with * nested functions! */ typedef struct standard_display { png_store* ps; /* Test parameters (passed to the function) */ png_byte colour_type; png_byte bit_depth; png_byte red_sBIT; /* Input data sBIT values. */ png_byte green_sBIT; png_byte blue_sBIT; png_byte alpha_sBIT; png_byte interlace_type; png_byte filler; /* Output has a filler */ png_uint_32 id; /* Calculated file ID */ png_uint_32 w; /* Width of image */ png_uint_32 h; /* Height of image */ int npasses; /* Number of interlaced passes */ png_uint_32 pixel_size; /* Width of one pixel in bits */ png_uint_32 bit_width; /* Width of output row in bits */ size_t cbRow; /* Bytes in a row of the output image */ int do_interlace; /* Do interlacing internally */ int littleendian; /* App (row) data is little endian */ int is_transparent; /* Transparency information was present. */ int has_tRNS; /* color type GRAY or RGB with a tRNS chunk. */ int speed; /* Doing a speed test */ int use_update_info;/* Call update_info, not start_image */ struct { png_uint_16 red; png_uint_16 green; png_uint_16 blue; } transparent; /* The transparent color, if set. */ int npalette; /* Number of entries in the palette. */ store_palette palette; } standard_display; static void standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id, int do_interlace, int use_update_info) { memset(dp, 0, sizeof *dp); dp->ps = ps; dp->colour_type = COL_FROM_ID(id); dp->bit_depth = DEPTH_FROM_ID(id); if (dp->bit_depth < 1 || dp->bit_depth > 16) internal_error(ps, "internal: bad bit depth"); if (dp->colour_type == 3) dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8; else dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = dp->bit_depth; dp->interlace_type = INTERLACE_FROM_ID(id); check_interlace_type(dp->interlace_type); dp->id = id; /* All the rest are filled in after the read_info: */ dp->w = 0; dp->h = 0; dp->npasses = 0; dp->pixel_size = 0; dp->bit_width = 0; dp->cbRow = 0; dp->do_interlace = do_interlace; dp->littleendian = 0; dp->is_transparent = 0; dp->speed = ps->speed; dp->use_update_info = use_update_info; dp->npalette = 0; /* Preset the transparent color to black: */ memset(&dp->transparent, 0, sizeof dp->transparent); /* Preset the palette to full intensity/opaque througout: */ memset(dp->palette, 0xff, sizeof dp->palette); } /* Initialize the palette fields - this must be done later because the palette * comes from the particular png_store_file that is selected. */ static void standard_palette_init(standard_display *dp) { store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette); /* The remaining entries remain white/opaque. */ if (dp->npalette > 0) { int i = dp->npalette; memcpy(dp->palette, palette, i * sizeof *palette); /* Check for a non-opaque palette entry: */ while (--i >= 0) if (palette[i].alpha < 255) break; # ifdef __GNUC__ /* GCC can't handle the more obviously optimizable version. */ if (i >= 0) dp->is_transparent = 1; else dp->is_transparent = 0; # else dp->is_transparent = (i >= 0); # endif } } /* Utility to read the palette from the PNG file and convert it into * store_palette format. This returns 1 if there is any transparency in the * palette (it does not check for a transparent colour in the non-palette case.) */ static int read_palette(store_palette palette, int *npalette, png_const_structp pp, png_infop pi) { png_colorp pal; png_bytep trans_alpha; int num; pal = 0; *npalette = -1; if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE) { int i = *npalette; if (i <= 0 || i > 256) png_error(pp, "validate: invalid PLTE count"); while (--i >= 0) { palette[i].red = pal[i].red; palette[i].green = pal[i].green; palette[i].blue = pal[i].blue; } /* Mark the remainder of the entries with a flag value (other than * white/opaque which is the flag value stored above.) */ memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette); } else /* !png_get_PLTE */ { if (*npalette != (-1)) png_error(pp, "validate: invalid PLTE result"); /* But there is no palette, so record this: */ *npalette = 0; memset(palette, 113, sizeof (store_palette)); } trans_alpha = 0; num = 2; /* force error below */ if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 && (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) && /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans, * so in the above call we get a success, we get a pointer (who knows what * to) and we get num_trans == 0: */ !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */ { int i; /* Any of these are crash-worthy - given the implementation of * png_get_tRNS up to 1.5 an app won't crash if it just checks the * result above and fails to check that the variables it passed have * actually been filled in! Note that if the app were to pass the * last, png_color_16p, variable too it couldn't rely on this. */ if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette) png_error(pp, "validate: unexpected png_get_tRNS (palette) result"); for (i=0; iis_transparent) png_error(pp, "validate: palette transparency changed"); if (npalette != dp->npalette) { size_t pos = 0; char msg[64]; pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: "); pos = safecatn(msg, sizeof msg, pos, dp->npalette); pos = safecat(msg, sizeof msg, pos, " -> "); pos = safecatn(msg, sizeof msg, pos, npalette); png_error(pp, msg); } { int i = npalette; /* npalette is aliased */ while (--i >= 0) if (palette[i].red != dp->palette[i].red || palette[i].green != dp->palette[i].green || palette[i].blue != dp->palette[i].blue || palette[i].alpha != dp->palette[i].alpha) png_error(pp, "validate: PLTE or tRNS chunk changed"); } } /* By passing a 'standard_display' the progressive callbacks can be used * directly by the sequential code, the functions suffixed "_imp" are the * implementations, the functions without the suffix are the callbacks. * * The code for the info callback is split into two because this callback calls * png_read_update_info or png_start_read_image and what gets called depends on * whether the info needs updating (we want to test both calls in pngvalid.) */ static void standard_info_part1(standard_display *dp, png_structp pp, png_infop pi) { if (png_get_bit_depth(pp, pi) != dp->bit_depth) png_error(pp, "validate: bit depth changed"); if (png_get_color_type(pp, pi) != dp->colour_type) png_error(pp, "validate: color type changed"); if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE) png_error(pp, "validate: filter type changed"); if (png_get_interlace_type(pp, pi) != dp->interlace_type) png_error(pp, "validate: interlacing changed"); if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE) png_error(pp, "validate: compression type changed"); dp->w = png_get_image_width(pp, pi); if (dp->w != standard_width(pp, dp->id)) png_error(pp, "validate: image width changed"); dp->h = png_get_image_height(pp, pi); if (dp->h != standard_height(pp, dp->id)) png_error(pp, "validate: image height changed"); /* Record (but don't check at present) the input sBIT according to the colour * type information. */ { png_color_8p sBIT = 0; if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT) { int sBIT_invalid = 0; if (sBIT == 0) png_error(pp, "validate: unexpected png_get_sBIT result"); if (dp->colour_type & PNG_COLOR_MASK_COLOR) { if (sBIT->red == 0 || sBIT->red > dp->bit_depth) sBIT_invalid = 1; else dp->red_sBIT = sBIT->red; if (sBIT->green == 0 || sBIT->green > dp->bit_depth) sBIT_invalid = 1; else dp->green_sBIT = sBIT->green; if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth) sBIT_invalid = 1; else dp->blue_sBIT = sBIT->blue; } else /* !COLOR */ { if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth) sBIT_invalid = 1; else dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray; } /* All 8 bits in tRNS for a palette image are significant - see the * spec. */ if (dp->colour_type & PNG_COLOR_MASK_ALPHA) { if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth) sBIT_invalid = 1; else dp->alpha_sBIT = sBIT->alpha; } if (sBIT_invalid) png_error(pp, "validate: sBIT value out of range"); } } /* Important: this is validating the value *before* any transforms have been * put in place. It doesn't matter for the standard tests, where there are * no transforms, but it does for other tests where rowbytes may change after * png_read_update_info. */ if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id)) png_error(pp, "validate: row size changed"); /* Validate the colour type 3 palette (this can be present on other color * types.) */ standard_palette_validate(dp, pp, pi); /* In any case always check for a tranparent color (notice that the * colour type 3 case must not give a successful return on the get_tRNS call * with these arguments!) */ { png_color_16p trans_color = 0; if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS) { if (trans_color == 0) png_error(pp, "validate: unexpected png_get_tRNS (color) result"); switch (dp->colour_type) { case 0: dp->transparent.red = dp->transparent.green = dp->transparent.blue = trans_color->gray; dp->has_tRNS = 1; break; case 2: dp->transparent.red = trans_color->red; dp->transparent.green = trans_color->green; dp->transparent.blue = trans_color->blue; dp->has_tRNS = 1; break; case 3: /* Not expected because it should result in the array case * above. */ png_error(pp, "validate: unexpected png_get_tRNS result"); break; default: png_error(pp, "validate: invalid tRNS chunk with alpha image"); } } } /* Read the number of passes - expected to match the value used when * creating the image (interlaced or not). This has the side effect of * turning on interlace handling (if do_interlace is not set.) */ dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type); if (!dp->do_interlace) { # ifdef PNG_READ_INTERLACING_SUPPORTED if (dp->npasses != png_set_interlace_handling(pp)) png_error(pp, "validate: file changed interlace type"); # else /* !READ_INTERLACING */ /* This should never happen: the relevant tests (!do_interlace) should * not be run. */ if (dp->npasses > 1) png_error(pp, "validate: no libpng interlace support"); # endif /* !READ_INTERLACING */ } /* Caller calls png_read_update_info or png_start_read_image now, then calls * part2. */ } /* This must be called *after* the png_read_update_info call to get the correct * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed * image. */ static void standard_info_part2(standard_display *dp, png_const_structp pp, png_const_infop pi, int nImages) { /* Record cbRow now that it can be found. */ { png_byte ct = png_get_color_type(pp, pi); png_byte bd = png_get_bit_depth(pp, pi); if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) && dp->filler) ct |= 4; /* handle filler as faked alpha channel */ dp->pixel_size = bit_size(pp, ct, bd); } dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size; dp->cbRow = png_get_rowbytes(pp, pi); /* Validate the rowbytes here again. */ if (dp->cbRow != (dp->bit_width+7)/8) png_error(pp, "bad png_get_rowbytes calculation"); /* Then ensure there is enough space for the output image(s). */ store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h); } static void standard_info_imp(standard_display *dp, png_structp pp, png_infop pi, int nImages) { /* Note that the validation routine has the side effect of turning on * interlace handling in the subsequent code. */ standard_info_part1(dp, pp, pi); /* And the info callback has to call this (or png_read_update_info - see * below in the png_modifier code for that variant. */ if (dp->use_update_info) { /* For debugging the effect of multiple calls: */ int i = dp->use_update_info; while (i-- > 0) png_read_update_info(pp, pi); } else png_start_read_image(pp); /* Validate the height, width and rowbytes plus ensure that sufficient buffer * exists for decoding the image. */ standard_info_part2(dp, pp, pi, nImages); } static void PNGCBAPI standard_info(png_structp pp, png_infop pi) { standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); /* Call with nImages==1 because the progressive reader can only produce one * image. */ standard_info_imp(dp, pp, pi, 1 /*only one image*/); } static void PNGCBAPI progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass) { png_const_structp pp = ppIn; const standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); /* When handling interlacing some rows will be absent in each pass, the * callback still gets called, but with a NULL pointer. This is checked * in the 'else' clause below. We need our own 'cbRow', but we can't call * png_get_rowbytes because we got no info structure. */ if (new_row != NULL) { png_bytep row; /* In the case where the reader doesn't do the interlace it gives * us the y in the sub-image: */ if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7) { #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED /* Use this opportunity to validate the png 'current' APIs: */ if (y != png_get_current_row_number(pp)) png_error(pp, "png_get_current_row_number is broken"); if (pass != png_get_current_pass_number(pp)) png_error(pp, "png_get_current_pass_number is broken"); #endif /* USER_TRANSFORM_INFO */ y = PNG_ROW_FROM_PASS_ROW(y, pass); } /* Validate this just in case. */ if (y >= dp->h) png_error(pp, "invalid y to progressive row callback"); row = store_image_row(dp->ps, pp, 0, y); /* Combine the new row into the old: */ #ifdef PNG_READ_INTERLACING_SUPPORTED if (dp->do_interlace) #endif /* READ_INTERLACING */ { if (dp->interlace_type == PNG_INTERLACE_ADAM7) deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass, dp->littleendian); else row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian); } #ifdef PNG_READ_INTERLACING_SUPPORTED else png_progressive_combine_row(pp, row, new_row); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } else if (dp->interlace_type == PNG_INTERLACE_ADAM7 && PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(dp->w, pass) > 0) png_error(pp, "missing row in progressive de-interlacing"); } static void sequential_row(standard_display *dp, png_structp pp, png_infop pi, const int iImage, const int iDisplay) { const int npasses = dp->npasses; const int do_interlace = dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7; const png_uint_32 height = standard_height(pp, dp->id); const png_uint_32 width = standard_width(pp, dp->id); const png_store* ps = dp->ps; int pass; for (pass=0; pass 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass)) { /* Read the row into a pair of temporary buffers, then do the * merge here into the output rows. */ png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX]; /* The following aids (to some extent) error detection - we can * see where png_read_row wrote. Use opposite values in row and * display to make this easier. Don't use 0xff (which is used in * the image write code to fill unused bits) or 0 (which is a * likely value to overwrite unused bits with). */ memset(row, 0xc5, sizeof row); memset(display, 0x5c, sizeof display); png_read_row(pp, row, display); if (iImage >= 0) deinterlace_row(store_image_row(ps, pp, iImage, y), row, dp->pixel_size, dp->w, pass, dp->littleendian); if (iDisplay >= 0) deinterlace_row(store_image_row(ps, pp, iDisplay, y), display, dp->pixel_size, dp->w, pass, dp->littleendian); } } else png_read_row(pp, iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL, iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL); } } /* And finish the read operation (only really necessary if the caller wants * to find additional data in png_info from chunks after the last IDAT.) */ png_read_end(pp, pi); } #ifdef PNG_TEXT_SUPPORTED static void standard_check_text(png_const_structp pp, png_const_textp tp, png_const_charp keyword, png_const_charp text) { char msg[1024]; size_t pos = safecat(msg, sizeof msg, 0, "text: "); size_t ok; pos = safecat(msg, sizeof msg, pos, keyword); pos = safecat(msg, sizeof msg, pos, ": "); ok = pos; if (tp->compression != TEXT_COMPRESSION) { char buf[64]; sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION, tp->compression); pos = safecat(msg, sizeof msg, pos, buf); } if (tp->key == NULL || strcmp(tp->key, keyword) != 0) { pos = safecat(msg, sizeof msg, pos, "keyword \""); if (tp->key != NULL) { pos = safecat(msg, sizeof msg, pos, tp->key); pos = safecat(msg, sizeof msg, pos, "\", "); } else pos = safecat(msg, sizeof msg, pos, "null, "); } if (tp->text == NULL) pos = safecat(msg, sizeof msg, pos, "text lost, "); else { if (tp->text_length != strlen(text)) { char buf[64]; sprintf(buf, "text length changed[%lu->%lu], ", (unsigned long)strlen(text), (unsigned long)tp->text_length); pos = safecat(msg, sizeof msg, pos, buf); } if (strcmp(tp->text, text) != 0) { pos = safecat(msg, sizeof msg, pos, "text becomes \""); pos = safecat(msg, sizeof msg, pos, tp->text); pos = safecat(msg, sizeof msg, pos, "\" (was \""); pos = safecat(msg, sizeof msg, pos, text); pos = safecat(msg, sizeof msg, pos, "\"), "); } } if (tp->itxt_length != 0) pos = safecat(msg, sizeof msg, pos, "iTXt length set, "); if (tp->lang != NULL) { pos = safecat(msg, sizeof msg, pos, "iTXt language \""); pos = safecat(msg, sizeof msg, pos, tp->lang); pos = safecat(msg, sizeof msg, pos, "\", "); } if (tp->lang_key != NULL) { pos = safecat(msg, sizeof msg, pos, "iTXt keyword \""); pos = safecat(msg, sizeof msg, pos, tp->lang_key); pos = safecat(msg, sizeof msg, pos, "\", "); } if (pos > ok) { msg[pos-2] = '\0'; /* Remove the ", " at the end */ png_error(pp, msg); } } static void standard_text_validate(standard_display *dp, png_const_structp pp, png_infop pi, int check_end) { png_textp tp = NULL; png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL); if (num_text == 2 && tp != NULL) { standard_check_text(pp, tp, "image name", dp->ps->current->name); /* This exists because prior to 1.5.18 the progressive reader left the * png_struct z_stream unreset at the end of the image, so subsequent * attempts to use it simply returns Z_STREAM_END. */ if (check_end) standard_check_text(pp, tp+1, "end marker", "end"); } else { char msg[64]; sprintf(msg, "expected two text items, got %lu", (unsigned long)num_text); png_error(pp, msg); } } #else # define standard_text_validate(dp,pp,pi,check_end) ((void)0) #endif static void standard_row_validate(standard_display *dp, png_const_structp pp, int iImage, int iDisplay, png_uint_32 y) { int where; png_byte std[STANDARD_ROWMAX]; /* The row must be pre-initialized to the magic number here for the size * tests to pass: */ memset(std, 178, sizeof std); standard_row(pp, std, dp->id, y); /* At the end both the 'row' and 'display' arrays should end up identical. * In earlier passes 'row' will be partially filled in, with only the pixels * that have been read so far, but 'display' will have those pixels * replicated to fill the unread pixels while reading an interlaced image. */ if (iImage >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iImage, y)[where-1]); png_error(pp, msg); } if (iDisplay >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iDisplay, y)[where-1]); png_error(pp, msg); } } static void standard_image_validate(standard_display *dp, png_const_structp pp, int iImage, int iDisplay) { png_uint_32 y; if (iImage >= 0) store_image_check(dp->ps, pp, iImage); if (iDisplay >= 0) store_image_check(dp->ps, pp, iDisplay); for (y=0; yh; ++y) standard_row_validate(dp, pp, iImage, iDisplay, y); /* This avoids false positives if the validation code is never called! */ dp->ps->validated = 1; } static void PNGCBAPI standard_end(png_structp ppIn, png_infop pi) { png_const_structp pp = ppIn; standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); UNUSED(pi) /* Validate the image - progressive reading only produces one variant for * interlaced images. */ standard_text_validate(dp, pp, pi, PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/); standard_image_validate(dp, pp, 0, -1); } /* A single test run checking the standard image to ensure it is not damaged. */ static void standard_test(png_store* const psIn, png_uint_32 const id, int do_interlace, int use_update_info) { standard_display d; context(psIn, fault); /* Set up the display (stack frame) variables from the arguments to the * function and initialize the locals that are filled in later. */ standard_display_init(&d, psIn, id, do_interlace, use_update_info); /* Everything is protected by a Try/Catch. The functions called also * typically have local Try/Catch blocks. */ Try { png_structp pp; png_infop pi; /* Get a png_struct for reading the image. This will throw an error if it * fails, so we don't need to check the result. */ pp = set_store_for_read(d.ps, &pi, d.id, d.do_interlace ? (d.ps->progressive ? "pngvalid progressive deinterlacer" : "pngvalid sequential deinterlacer") : (d.ps->progressive ? "progressive reader" : "sequential reader")); /* Initialize the palette correctly from the png_store_file. */ standard_palette_init(&d); /* Introduce the correct read function. */ if (d.ps->progressive) { png_set_progressive_read_fn(pp, &d, standard_info, progressive_row, standard_end); /* Now feed data into the reader until we reach the end: */ store_progressive_read(d.ps, pp, pi); } else { /* Note that this takes the store, not the display. */ png_set_read_fn(pp, d.ps, store_read); /* Check the header values: */ png_read_info(pp, pi); /* The code tests both versions of the images that the sequential * reader can produce. */ standard_info_imp(&d, pp, pi, 2 /*images*/); /* Need the total bytes in the image below; we can't get to this point * unless the PNG file values have been checked against the expected * values. */ { sequential_row(&d, pp, pi, 0, 1); /* After the last pass loop over the rows again to check that the * image is correct. */ if (!d.speed) { standard_text_validate(&d, pp, pi, 1/*check_end*/); standard_image_validate(&d, pp, 0, 1); } else d.ps->validated = 1; } } /* Check for validation. */ if (!d.ps->validated) png_error(pp, "image read failed silently"); /* Successful completion. */ } Catch(fault) d.ps = fault; /* make sure this hasn't been clobbered. */ /* In either case clean up the store. */ store_read_reset(d.ps); } static int test_standard(png_modifier* const pm, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info); if (fail(pm)) return 0; } } return 1; /* keep going */ } static void perform_standard_test(png_modifier *pm) { /* Test each colour type over the valid range of bit depths (expressed as * log2(bit_depth) in turn, stop as soon as any error is detected. */ if (!test_standard(pm, 0, 0, READ_BDHI)) return; if (!test_standard(pm, 2, 3, READ_BDHI)) return; if (!test_standard(pm, 3, 0, 3)) return; if (!test_standard(pm, 4, 3, READ_BDHI)) return; if (!test_standard(pm, 6, 3, READ_BDHI)) return; } /********************************** SIZE TESTS ********************************/ static int test_size(png_modifier* const pm, png_byte const colour_type, int bdlo, int const bdhi) { /* Run the tests on each combination. * * NOTE: on my 32 bit x86 each of the following blocks takes * a total of 3.5 seconds if done across every combo of bit depth * width and height. This is a waste of time in practice, hence the * hinc and winc stuff: */ static const png_byte hinc[] = {1, 3, 11, 1, 5}; static const png_byte winc[] = {1, 9, 5, 7, 1}; const int save_bdlo = bdlo; for (; bdlo <= bdhi; ++bdlo) { png_uint_32 h, w; for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo]) { /* First test all the 'size' images against the sequential * reader using libpng to deinterlace (where required.) This * validates the write side of libpng. There are four possibilities * to validate. */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; /* Now validate the interlaced read side - do_interlace true, * in the progressive case this does actually make a difference * to the code used in the non-interlaced case too. */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # if CAN_WRITE_INTERLACE /* Validate the pngvalid code itself: */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif } } /* Now do the tests of libpng interlace handling, after we have made sure * that the pngvalid version works: */ for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo) { png_uint_32 h, w; for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo]) { # ifdef PNG_READ_INTERLACING_SUPPORTED /* Test with pngvalid generated interlaced images first; we have * already verify these are ok (unless pngvalid has self-consistent * read/write errors, which is unlikely), so this detects errors in the * read side first: */ # if CAN_WRITE_INTERLACE standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif # endif /* READ_INTERLACING */ # ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Test the libpng write side against the pngvalid read side: */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif # ifdef PNG_READ_INTERLACING_SUPPORTED # ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Test both together: */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif # endif /* READ_INTERLACING */ } } return 1; /* keep going */ } static void perform_size_test(png_modifier *pm) { /* Test each colour type over the valid range of bit depths (expressed as * log2(bit_depth) in turn, stop as soon as any error is detected. */ if (!test_size(pm, 0, 0, READ_BDHI)) return; if (!test_size(pm, 2, 3, READ_BDHI)) return; /* For the moment don't do the palette test - it's a waste of time when * compared to the grayscale test. */ #if 0 if (!test_size(pm, 3, 0, 3)) return; #endif if (!test_size(pm, 4, 3, READ_BDHI)) return; if (!test_size(pm, 6, 3, READ_BDHI)) return; } /******************************* TRANSFORM TESTS ******************************/ #ifdef PNG_READ_TRANSFORMS_SUPPORTED /* A set of tests to validate libpng image transforms. The possibilities here * are legion because the transforms can be combined in a combinatorial * fashion. To deal with this some measure of restraint is required, otherwise * the tests would take forever. */ typedef struct image_pixel { /* A local (pngvalid) representation of a PNG pixel, in all its * various forms. */ unsigned int red, green, blue, alpha; /* For non-palette images. */ unsigned int palette_index; /* For a palette image. */ png_byte colour_type; /* As in the spec. */ png_byte bit_depth; /* Defines bit size in row */ png_byte sample_depth; /* Scale of samples */ unsigned int have_tRNS :1; /* tRNS chunk may need processing */ unsigned int swap_rgb :1; /* RGB swapped to BGR */ unsigned int alpha_first :1; /* Alpha at start, not end */ unsigned int alpha_inverted :1; /* Alpha channel inverted */ unsigned int mono_inverted :1; /* Gray channel inverted */ unsigned int swap16 :1; /* Byte swap 16-bit components */ unsigned int littleendian :1; /* High bits on right */ unsigned int sig_bits :1; /* Pixel shifted (sig bits only) */ /* For checking the code calculates double precision floating point values * along with an error value, accumulated from the transforms. Because an * sBIT setting allows larger error bounds (indeed, by the spec, apparently * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each * channel is stored. This sBIT value is folded in to the stored error value * at the end of the application of the transforms to the pixel. * * If sig_bits is set above the red, green, blue and alpha values have been * scaled so they only contain the significant bits of the component values. */ double redf, greenf, bluef, alphaf; double rede, greene, bluee, alphae; png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT; } image_pixel; /* Shared utility function, see below. */ static void image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax, unsigned int bMax, unsigned int aMax) { this->redf = this->red / (double)rMax; this->greenf = this->green / (double)gMax; this->bluef = this->blue / (double)bMax; this->alphaf = this->alpha / (double)aMax; if (this->red < rMax) this->rede = this->redf * DBL_EPSILON; else this->rede = 0; if (this->green < gMax) this->greene = this->greenf * DBL_EPSILON; else this->greene = 0; if (this->blue < bMax) this->bluee = this->bluef * DBL_EPSILON; else this->bluee = 0; if (this->alpha < aMax) this->alphae = this->alphaf * DBL_EPSILON; else this->alphae = 0; } /* Initialize the structure for the next pixel - call this before doing any * transforms and call it for each pixel since all the fields may need to be * reset. */ static void image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type, png_byte bit_depth, png_uint_32 x, store_palette palette, const image_pixel *format /*from pngvalid transform of input*/) { const png_byte sample_depth = (png_byte)(colour_type == PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth); const unsigned int max = (1U<swap16); const int littleendian = (format != 0 && format->littleendian); const int sig_bits = (format != 0 && format->sig_bits); /* Initially just set everything to the same number and the alpha to opaque. * Note that this currently assumes a simple palette where entry x has colour * rgb(x,x,x)! */ this->palette_index = this->red = this->green = this->blue = sample(row, colour_type, bit_depth, x, 0, swap16, littleendian); this->alpha = max; this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT = sample_depth; /* Then override as appropriate: */ if (colour_type == 3) /* palette */ { /* This permits the caller to default to the sample value. */ if (palette != 0) { const unsigned int i = this->palette_index; this->red = palette[i].red; this->green = palette[i].green; this->blue = palette[i].blue; this->alpha = palette[i].alpha; } } else /* not palette */ { unsigned int i = 0; if ((colour_type & 4) != 0 && format != 0 && format->alpha_first) { this->alpha = this->red; /* This handles the gray case for 'AG' pixels */ this->palette_index = this->red = this->green = this->blue = sample(row, colour_type, bit_depth, x, 1, swap16, littleendian); i = 1; } if (colour_type & 2) { /* Green is second for both BGR and RGB: */ this->green = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); if (format != 0 && format->swap_rgb) /* BGR */ this->red = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); else this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); } else /* grayscale */ if (format != 0 && format->mono_inverted) this->red = this->green = this->blue = this->red ^ max; if ((colour_type & 4) != 0) /* alpha */ { if (format == 0 || !format->alpha_first) this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); if (format != 0 && format->alpha_inverted) this->alpha ^= max; } } /* Calculate the scaled values, these are simply the values divided by * 'max' and the error is initialized to the double precision epsilon value * from the header file. */ image_pixel_setf(this, sig_bits ? (1U << format->red_sBIT)-1 : max, sig_bits ? (1U << format->green_sBIT)-1 : max, sig_bits ? (1U << format->blue_sBIT)-1 : max, sig_bits ? (1U << format->alpha_sBIT)-1 : max); /* Store the input information for use in the transforms - these will * modify the information. */ this->colour_type = colour_type; this->bit_depth = bit_depth; this->sample_depth = sample_depth; this->have_tRNS = 0; this->swap_rgb = 0; this->alpha_first = 0; this->alpha_inverted = 0; this->mono_inverted = 0; this->swap16 = 0; this->littleendian = 0; this->sig_bits = 0; } #if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\ || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\ || defined PNG_READ_BACKGROUND_SUPPORTED /* Convert a palette image to an rgb image. This necessarily converts the tRNS * chunk at the same time, because the tRNS will be in palette form. The way * palette validation works means that the original palette is never updated, * instead the image_pixel value from the row contains the RGB of the * corresponding palette entry and *this* is updated. Consequently this routine * only needs to change the colour type information. */ static void image_pixel_convert_PLTE(image_pixel *this) { if (this->colour_type == PNG_COLOR_TYPE_PALETTE) { if (this->have_tRNS) { this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; this->have_tRNS = 0; } else this->colour_type = PNG_COLOR_TYPE_RGB; /* The bit depth of the row changes at this point too (notice that this is * the row format, not the sample depth, which is separate.) */ this->bit_depth = 8; } } /* Add an alpha channel; this will import the tRNS information because tRNS is * not valid in an alpha image. The bit depth will invariably be set to at * least 8 prior to 1.7.0. Palette images will be converted to alpha (using * the above API). With png_set_background the alpha channel is never expanded * but this routine is used by pngvalid to simplify code; 'for_background' * records this. */ static void image_pixel_add_alpha(image_pixel *this, const standard_display *display, int for_background) { if (this->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(this); if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0) { if (this->colour_type == PNG_COLOR_TYPE_GRAY) { # if PNG_LIBPNG_VER < 10700 if (!for_background && this->bit_depth < 8) this->bit_depth = this->sample_depth = 8; # endif if (this->have_tRNS) { /* After 1.7 the expansion of bit depth only happens if there is a * tRNS chunk to expand at this point. */ # if PNG_LIBPNG_VER >= 10700 if (!for_background && this->bit_depth < 8) this->bit_depth = this->sample_depth = 8; # endif this->have_tRNS = 0; /* Check the input, original, channel value here against the * original tRNS gray chunk valie. */ if (this->red == display->transparent.red) this->alphaf = 0; else this->alphaf = 1; } else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } else if (this->colour_type == PNG_COLOR_TYPE_RGB) { if (this->have_tRNS) { this->have_tRNS = 0; /* Again, check the exact input values, not the current transformed * value! */ if (this->red == display->transparent.red && this->green == display->transparent.green && this->blue == display->transparent.blue) this->alphaf = 0; else this->alphaf = 1; } else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; } /* The error in the alpha is zero and the sBIT value comes from the * original sBIT data (actually it will always be the original bit depth). */ this->alphae = 0; this->alpha_sBIT = display->alpha_sBIT; } } #endif /* transforms that need image_pixel_add_alpha */ struct transform_display; typedef struct image_transform { /* The name of this transform: a string. */ const char *name; /* Each transform can be disabled from the command line: */ int enable; /* The global list of transforms; read only. */ struct image_transform *const list; /* The global count of the number of times this transform has been set on an * image. */ unsigned int global_use; /* The local count of the number of times this transform has been set. */ unsigned int local_use; /* The next transform in the list, each transform must call its own next * transform after it has processed the pixel successfully. */ const struct image_transform *next; /* A single transform for the image, expressed as a series of function * callbacks and some space for values. * * First a callback to add any required modifications to the png_modifier; * this gets called just before the modifier is set up for read. */ void (*ini)(const struct image_transform *this, struct transform_display *that); /* And a callback to set the transform on the current png_read_struct: */ void (*set)(const struct image_transform *this, struct transform_display *that, png_structp pp, png_infop pi); /* Then a transform that takes an input pixel in one PNG format or another * and modifies it by a pngvalid implementation of the transform (thus * duplicating the libpng intent without, we hope, duplicating the bugs * in the libpng implementation!) The png_structp is solely to allow error * reporting via png_error and png_warning. */ void (*mod)(const struct image_transform *this, image_pixel *that, png_const_structp pp, const struct transform_display *display); /* Add this transform to the list and return true if the transform is * meaningful for this colour type and bit depth - if false then the * transform should have no effect on the image so there's not a lot of * point running it. */ int (*add)(struct image_transform *this, const struct image_transform **that, png_byte colour_type, png_byte bit_depth); } image_transform; typedef struct transform_display { standard_display this; /* Parameters */ png_modifier* pm; const image_transform* transform_list; unsigned int max_gamma_8; /* Local variables */ png_byte output_colour_type; png_byte output_bit_depth; png_byte unpacked; /* Modifications (not necessarily used.) */ gama_modification gama_mod; chrm_modification chrm_mod; srgb_modification srgb_mod; } transform_display; /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */ static void transform_set_encoding(transform_display *this) { /* Set up the png_modifier '_current' fields then use these to determine how * to add appropriate chunks. */ png_modifier *pm = this->pm; modifier_set_encoding(pm); if (modifier_color_encoding_is_set(pm)) { if (modifier_color_encoding_is_sRGB(pm)) srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE); else { /* Set gAMA and cHRM separately. */ gama_modification_init(&this->gama_mod, pm, pm->current_gamma); if (pm->current_encoding != 0) chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding); } } } /* Three functions to end the list: */ static void image_transform_ini_end(const image_transform *this, transform_display *that) { UNUSED(this) UNUSED(that) } static void image_transform_set_end(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { UNUSED(this) UNUSED(that) UNUSED(pp) UNUSED(pi) } /* At the end of the list recalculate the output image pixel value from the * double precision values set up by the preceding 'mod' calls: */ static unsigned int sample_scale(double sample_value, unsigned int scale) { sample_value = floor(sample_value * scale + .5); /* Return NaN as 0: */ if (!(sample_value > 0)) sample_value = 0; else if (sample_value > scale) sample_value = scale; return (unsigned int)sample_value; } static void image_transform_mod_end(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { const unsigned int scale = (1U<sample_depth)-1; const int sig_bits = that->sig_bits; UNUSED(this) UNUSED(pp) UNUSED(display) /* At the end recalculate the digitized red green and blue values according * to the current sample_depth of the pixel. * * The sample value is simply scaled to the maximum, checking for over * and underflow (which can both happen for some image transforms, * including simple size scaling, though libpng doesn't do that at present. */ that->red = sample_scale(that->redf, scale); /* This is a bit bogus; really the above calculation should use the red_sBIT * value, not sample_depth, but because libpng does png_set_shift by just * shifting the bits we get errors if we don't do it the same way. */ if (sig_bits && that->red_sBIT < that->sample_depth) that->red >>= that->sample_depth - that->red_sBIT; /* The error value is increased, at the end, according to the lowest sBIT * value seen. Common sense tells us that the intermediate integer * representations are no more accurate than +/- 0.5 in the integral values, * the sBIT allows the implementation to be worse than this. In addition the * PNG specification actually permits any error within the range (-1..+1), * but that is ignored here. Instead the final digitized value is compared, * below to the digitized value of the error limits - this has the net effect * of allowing (almost) +/-1 in the output value. It's difficult to see how * any algorithm that digitizes intermediate results can be more accurate. */ that->rede += 1./(2*((1U<red_sBIT)-1)); if (that->colour_type & PNG_COLOR_MASK_COLOR) { that->green = sample_scale(that->greenf, scale); if (sig_bits && that->green_sBIT < that->sample_depth) that->green >>= that->sample_depth - that->green_sBIT; that->blue = sample_scale(that->bluef, scale); if (sig_bits && that->blue_sBIT < that->sample_depth) that->blue >>= that->sample_depth - that->blue_sBIT; that->greene += 1./(2*((1U<green_sBIT)-1)); that->bluee += 1./(2*((1U<blue_sBIT)-1)); } else { that->blue = that->green = that->red; that->bluef = that->greenf = that->redf; that->bluee = that->greene = that->rede; } if ((that->colour_type & PNG_COLOR_MASK_ALPHA) || that->colour_type == PNG_COLOR_TYPE_PALETTE) { that->alpha = sample_scale(that->alphaf, scale); that->alphae += 1./(2*((1U<alpha_sBIT)-1)); } else { that->alpha = scale; /* opaque */ that->alphaf = 1; /* Override this. */ that->alphae = 0; /* It's exact ;-) */ } if (sig_bits && that->alpha_sBIT < that->sample_depth) that->alpha >>= that->sample_depth - that->alpha_sBIT; } /* Static 'end' structure: */ static image_transform image_transform_end = { "(end)", /* name */ 1, /* enable */ 0, /* list */ 0, /* global_use */ 0, /* local_use */ 0, /* next */ image_transform_ini_end, image_transform_set_end, image_transform_mod_end, 0 /* never called, I want it to crash if it is! */ }; /* Reader callbacks and implementations, where they differ from the standard * ones. */ static void transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id, const image_transform *transform_list) { memset(dp, 0, sizeof *dp); /* Standard fields */ standard_display_init(&dp->this, &pm->this, id, do_read_interlace, pm->use_update_info); /* Parameter fields */ dp->pm = pm; dp->transform_list = transform_list; dp->max_gamma_8 = 16; /* Local variable fields */ dp->output_colour_type = 255; /* invalid */ dp->output_bit_depth = 255; /* invalid */ dp->unpacked = 0; /* not unpacked */ } static void transform_info_imp(transform_display *dp, png_structp pp, png_infop pi) { /* Reuse the standard stuff as appropriate. */ standard_info_part1(&dp->this, pp, pi); /* Now set the list of transforms. */ dp->transform_list->set(dp->transform_list, dp, pp, pi); /* Update the info structure for these transforms: */ { int i = dp->this.use_update_info; /* Always do one call, even if use_update_info is 0. */ do png_read_update_info(pp, pi); while (--i > 0); } /* And get the output information into the standard_display */ standard_info_part2(&dp->this, pp, pi, 1/*images*/); /* Plus the extra stuff we need for the transform tests: */ dp->output_colour_type = png_get_color_type(pp, pi); dp->output_bit_depth = png_get_bit_depth(pp, pi); /* If png_set_filler is in action then fake the output color type to include * an alpha channel where appropriate. */ if (dp->output_bit_depth >= 8 && (dp->output_colour_type == PNG_COLOR_TYPE_RGB || dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler) dp->output_colour_type |= 4; /* Validate the combination of colour type and bit depth that we are getting * out of libpng; the semantics of something not in the PNG spec are, at * best, unclear. */ switch (dp->output_colour_type) { case PNG_COLOR_TYPE_PALETTE: if (dp->output_bit_depth > 8) goto error; /*FALL THROUGH*/ case PNG_COLOR_TYPE_GRAY: if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 || dp->output_bit_depth == 4) break; /*FALL THROUGH*/ default: if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16) break; /*FALL THROUGH*/ error: { char message[128]; size_t pos; pos = safecat(message, sizeof message, 0, "invalid final bit depth: colour type("); pos = safecatn(message, sizeof message, pos, dp->output_colour_type); pos = safecat(message, sizeof message, pos, ") with bit depth: "); pos = safecatn(message, sizeof message, pos, dp->output_bit_depth); png_error(pp, message); } } /* Use a test pixel to check that the output agrees with what we expect - * this avoids running the whole test if the output is unexpected. This also * checks for internal errors. */ { image_pixel test_pixel; memset(&test_pixel, 0, sizeof test_pixel); test_pixel.colour_type = dp->this.colour_type; /* input */ test_pixel.bit_depth = dp->this.bit_depth; if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE) test_pixel.sample_depth = 8; else test_pixel.sample_depth = test_pixel.bit_depth; /* Don't need sBIT here, but it must be set to non-zero to avoid * arithmetic overflows. */ test_pixel.have_tRNS = dp->this.is_transparent != 0; test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT = test_pixel.alpha_sBIT = test_pixel.sample_depth; dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp); if (test_pixel.colour_type != dp->output_colour_type) { char message[128]; size_t pos = safecat(message, sizeof message, 0, "colour type "); pos = safecatn(message, sizeof message, pos, dp->output_colour_type); pos = safecat(message, sizeof message, pos, " expected "); pos = safecatn(message, sizeof message, pos, test_pixel.colour_type); png_error(pp, message); } if (test_pixel.bit_depth != dp->output_bit_depth) { char message[128]; size_t pos = safecat(message, sizeof message, 0, "bit depth "); pos = safecatn(message, sizeof message, pos, dp->output_bit_depth); pos = safecat(message, sizeof message, pos, " expected "); pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth); png_error(pp, message); } /* If both bit depth and colour type are correct check the sample depth. */ if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE && test_pixel.sample_depth != 8) /* oops - internal error! */ png_error(pp, "pngvalid: internal: palette sample depth not 8"); else if (dp->unpacked && test_pixel.bit_depth != 8) png_error(pp, "pngvalid: internal: bad unpacked pixel depth"); else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE && test_pixel.bit_depth != test_pixel.sample_depth) { char message[128]; size_t pos = safecat(message, sizeof message, 0, "internal: sample depth "); /* Because unless something has set 'unpacked' or the image is palette * mapped we expect the transform to keep sample depth and bit depth * the same. */ pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth); pos = safecat(message, sizeof message, pos, " expected "); pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth); png_error(pp, message); } else if (test_pixel.bit_depth != dp->output_bit_depth) { /* This could be a libpng error too; libpng has not produced what we * expect for the output bit depth. */ char message[128]; size_t pos = safecat(message, sizeof message, 0, "internal: bit depth "); pos = safecatn(message, sizeof message, pos, dp->output_bit_depth); pos = safecat(message, sizeof message, pos, " expected "); pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth); png_error(pp, message); } } } static void PNGCBAPI transform_info(png_structp pp, png_infop pi) { transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)), pp, pi); } static void transform_range_check(png_const_structp pp, unsigned int r, unsigned int g, unsigned int b, unsigned int a, unsigned int in_digitized, double in, unsigned int out, png_byte sample_depth, double err, double limit, const char *name, double digitization_error) { /* Compare the scaled, digitzed, values of our local calculation (in+-err) * with the digitized values libpng produced; 'sample_depth' is the actual * digitization depth of the libpng output colors (the bit depth except for * palette images where it is always 8.) The check on 'err' is to detect * internal errors in pngvalid itself. */ unsigned int max = (1U< limit ||) !(out >= in_min && out <= in_max)) { char message[256]; size_t pos; pos = safecat(message, sizeof message, 0, name); pos = safecat(message, sizeof message, pos, " output value error: rgba("); pos = safecatn(message, sizeof message, pos, r); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, g); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, b); pos = safecat(message, sizeof message, pos, ","); pos = safecatn(message, sizeof message, pos, a); pos = safecat(message, sizeof message, pos, "): "); pos = safecatn(message, sizeof message, pos, out); pos = safecat(message, sizeof message, pos, " expected: "); pos = safecatn(message, sizeof message, pos, in_digitized); pos = safecat(message, sizeof message, pos, " ("); pos = safecatd(message, sizeof message, pos, (in-err)*max, 3); pos = safecat(message, sizeof message, pos, ".."); pos = safecatd(message, sizeof message, pos, (in+err)*max, 3); pos = safecat(message, sizeof message, pos, ")"); png_error(pp, message); } UNUSED(limit) } static void transform_image_validate(transform_display *dp, png_const_structp pp, png_infop pi) { /* Constants for the loop below: */ const png_store* const ps = dp->this.ps; const png_byte in_ct = dp->this.colour_type; const png_byte in_bd = dp->this.bit_depth; const png_uint_32 w = dp->this.w; const png_uint_32 h = dp->this.h; const png_byte out_ct = dp->output_colour_type; const png_byte out_bd = dp->output_bit_depth; const png_byte sample_depth = (png_byte)(out_ct == PNG_COLOR_TYPE_PALETTE ? 8 : out_bd); const png_byte red_sBIT = dp->this.red_sBIT; const png_byte green_sBIT = dp->this.green_sBIT; const png_byte blue_sBIT = dp->this.blue_sBIT; const png_byte alpha_sBIT = dp->this.alpha_sBIT; const int have_tRNS = dp->this.is_transparent; double digitization_error; store_palette out_palette; png_uint_32 y; UNUSED(pi) /* Check for row overwrite errors */ store_image_check(dp->this.ps, pp, 0); /* Read the palette corresponding to the output if the output colour type * indicates a palette, othewise set out_palette to garbage. */ if (out_ct == PNG_COLOR_TYPE_PALETTE) { /* Validate that the palette count itself has not changed - this is not * expected. */ int npalette = (-1); (void)read_palette(out_palette, &npalette, pp, pi); if (npalette != dp->this.npalette) png_error(pp, "unexpected change in palette size"); digitization_error = .5; } else { png_byte in_sample_depth; memset(out_palette, 0x5e, sizeof out_palette); /* use-input-precision means assume that if the input has 8 bit (or less) * samples and the output has 16 bit samples the calculations will be done * with 8 bit precision, not 16. */ if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16) in_sample_depth = 8; else in_sample_depth = in_bd; if (sample_depth != 16 || in_sample_depth > 8 || !dp->pm->calculations_use_input_precision) digitization_error = .5; /* Else calculations are at 8 bit precision, and the output actually * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits: */ else digitization_error = .5 * 257; } for (y=0; ythis.palette, NULL); in_pixel.red_sBIT = red_sBIT; in_pixel.green_sBIT = green_sBIT; in_pixel.blue_sBIT = blue_sBIT; in_pixel.alpha_sBIT = alpha_sBIT; in_pixel.have_tRNS = have_tRNS != 0; /* For error detection, below. */ r = in_pixel.red; g = in_pixel.green; b = in_pixel.blue; a = in_pixel.alpha; /* This applies the transforms to the input data, including output * format operations which must be used when reading the output * pixel that libpng produces. */ dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp); /* Read the output pixel and compare it to what we got, we don't * use the error field here, so no need to update sBIT. in_pixel * says whether we expect libpng to change the output format. */ image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette, &in_pixel); /* We don't expect changes to the index here even if the bit depth is * changed. */ if (in_ct == PNG_COLOR_TYPE_PALETTE && out_ct == PNG_COLOR_TYPE_PALETTE) { if (in_pixel.palette_index != out_pixel.palette_index) png_error(pp, "unexpected transformed palette index"); } /* Check the colours for palette images too - in fact the palette could * be separately verified itself in most cases. */ if (in_pixel.red != out_pixel.red) transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf, out_pixel.red, sample_depth, in_pixel.rede, dp->pm->limit + 1./(2*((1U<pm->limit + 1./(2*((1U<pm->limit + 1./(2*((1U<pm->limit + 1./(2*((1U<this.ps->validated = 1; } static void PNGCBAPI transform_end(png_structp ppIn, png_infop pi) { png_const_structp pp = ppIn; transform_display *dp = voidcast(transform_display*, png_get_progressive_ptr(pp)); if (!dp->this.speed) transform_image_validate(dp, pp, pi); else dp->this.ps->validated = 1; } /* A single test run. */ static void transform_test(png_modifier *pmIn, const png_uint_32 idIn, const image_transform* transform_listIn, const char * const name) { transform_display d; context(&pmIn->this, fault); transform_display_init(&d, pmIn, idIn, transform_listIn); Try { size_t pos = 0; png_structp pp; png_infop pi; char full_name[256]; /* Make sure the encoding fields are correct and enter the required * modifications. */ transform_set_encoding(&d); /* Add any modifications required by the transform list. */ d.transform_list->ini(d.transform_list, &d); /* Add the color space information, if any, to the name. */ pos = safecat(full_name, sizeof full_name, pos, name); pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm); /* Get a png_struct for reading the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name); standard_palette_init(&d.this); # if 0 /* Logging (debugging only) */ { char buffer[256]; (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0, "running test"); fprintf(stderr, "%s\n", buffer); } # endif /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, transform_info, progressive_row, transform_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ transform_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) transform_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); } Catch(fault) { modifier_reset(voidcast(png_modifier*,(void*)fault)); } } /* The transforms: */ #define ITSTRUCT(name) image_transform_##name #define ITDATA(name) image_transform_data_##name #define image_transform_ini image_transform_default_ini #define IT(name)\ static image_transform ITSTRUCT(name) =\ {\ #name,\ 1, /*enable*/\ &PT, /*list*/\ 0, /*global_use*/\ 0, /*local_use*/\ 0, /*next*/\ image_transform_ini,\ image_transform_png_set_##name##_set,\ image_transform_png_set_##name##_mod,\ image_transform_png_set_##name##_add\ } #define PT ITSTRUCT(end) /* stores the previous transform */ /* To save code: */ extern void image_transform_default_ini(const image_transform *this, transform_display *that); /* silence GCC warnings */ void /* private, but almost always needed */ image_transform_default_ini(const image_transform *this, transform_display *that) { this->next->ini(this->next, that); } #ifdef PNG_READ_BACKGROUND_SUPPORTED static int image_transform_default_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) UNUSED(bit_depth) this->next = *that; *that = this; return 1; } #endif #ifdef PNG_READ_EXPAND_SUPPORTED /* png_set_palette_to_rgb */ static void image_transform_png_set_palette_to_rgb_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_palette_to_rgb(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_palette_to_rgb_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_palette_to_rgb_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_PALETTE; } IT(palette_to_rgb); #undef PT #define PT ITSTRUCT(palette_to_rgb) #endif /* PNG_READ_EXPAND_SUPPORTED */ #ifdef PNG_READ_EXPAND_SUPPORTED /* png_set_tRNS_to_alpha */ static void image_transform_png_set_tRNS_to_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_tRNS_to_alpha(pp); /* If there was a tRNS chunk that would get expanded and add an alpha * channel is_transparent must be updated: */ if (that->this.has_tRNS) that->this.is_transparent = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { #if PNG_LIBPNG_VER < 10700 /* LIBPNG BUG: this always forces palette images to RGB. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); #endif /* This effectively does an 'expand' only if there is some transparency to * convert to an alpha channel. */ if (that->have_tRNS) # if PNG_LIBPNG_VER >= 10700 if (that->colour_type != PNG_COLOR_TYPE_PALETTE && (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0) # endif image_pixel_add_alpha(that, &display->this, 0/*!for background*/); #if PNG_LIBPNG_VER < 10700 /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */ else { if (that->bit_depth < 8) that->bit_depth =8; if (that->sample_depth < 8) that->sample_depth = 8; } #endif this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_tRNS_to_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. In addition, after the bug fix in 1.7.0, there is no longer * any action on a palette image. */ return # if PNG_LIBPNG_VER >= 10700 colour_type != PNG_COLOR_TYPE_PALETTE && # endif (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } IT(tRNS_to_alpha); #undef PT #define PT ITSTRUCT(tRNS_to_alpha) #endif /* PNG_READ_EXPAND_SUPPORTED */ #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED /* png_set_gray_to_rgb */ static void image_transform_png_set_gray_to_rgb_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_gray_to_rgb(pp); /* NOTE: this doesn't result in tRNS expansion. */ this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_gray_to_rgb_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* NOTE: we can actually pend the tRNS processing at this point because we * can correctly recognize the original pixel value even though we have * mapped the one gray channel to the three RGB ones, but in fact libpng * doesn't do this, so we don't either. */ if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); /* Simply expand the bit depth and alter the colour type as required. */ if (that->colour_type == PNG_COLOR_TYPE_GRAY) { /* RGB images have a bit depth at least equal to '8' */ if (that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; /* And just changing the colour type works here because the green and blue * channels are being maintained in lock-step with the red/gray: */ that->colour_type = PNG_COLOR_TYPE_RGB; } else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_gray_to_rgb_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) == 0; } IT(gray_to_rgb); #undef PT #define PT ITSTRUCT(gray_to_rgb) #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */ #ifdef PNG_READ_EXPAND_SUPPORTED /* png_set_expand */ static void image_transform_png_set_expand_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand(pp); if (that->this.has_tRNS) that->this.is_transparent = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_expand_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* The general expand case depends on what the colour type is: */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); else if (that->bit_depth < 8) /* grayscale */ that->sample_depth = that->bit_depth = 8; if (that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_expand_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit * depth is at least 8 already. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } IT(expand); #undef PT #define PT ITSTRUCT(expand) #endif /* PNG_READ_EXPAND_SUPPORTED */ #ifdef PNG_READ_EXPAND_SUPPORTED /* png_set_expand_gray_1_2_4_to_8 * Pre 1.7.0 LIBPNG BUG: this just does an 'expand' */ static void image_transform_png_set_expand_gray_1_2_4_to_8_set( const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(pp); /* NOTE: don't expect this to expand tRNS */ this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_expand_gray_1_2_4_to_8_mod( const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { #if PNG_LIBPNG_VER < 10700 image_transform_png_set_expand_mod(this, that, pp, display); #else /* Only expand grayscale of bit depth less than 8: */ if (that->colour_type == PNG_COLOR_TYPE_GRAY && that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; this->next->mod(this->next, that, pp, display); #endif /* 1.7 or later */ } static int image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { #if PNG_LIBPNG_VER < 10700 return image_transform_png_set_expand_add(this, that, colour_type, bit_depth); #else UNUSED(bit_depth) this->next = *that; *that = this; /* This should do nothing unless the color type is gray and the bit depth is * less than 8: */ return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8; #endif /* 1.7 or later */ } IT(expand_gray_1_2_4_to_8); #undef PT #define PT ITSTRUCT(expand_gray_1_2_4_to_8) #endif /* PNG_READ_EXPAND_SUPPORTED */ #ifdef PNG_READ_EXPAND_16_SUPPORTED /* png_set_expand_16 */ static void image_transform_png_set_expand_16_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_16(pp); /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */ # if PNG_LIBPNG_VER < 10700 if (that->this.has_tRNS) that->this.is_transparent = 1; # endif this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_expand_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_expand_16_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; /* expand_16 does something unless the bit depth is already 16. */ return bit_depth < 16; } IT(expand_16); #undef PT #define PT ITSTRUCT(expand_16) #endif /* PNG_READ_EXPAND_16_SUPPORTED */ #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */ /* png_set_scale_16 */ static void image_transform_png_set_scale_16_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_scale_16(pp); # if PNG_LIBPNG_VER < 10700 /* libpng will limit the gamma table size: */ that->max_gamma_8 = PNG_MAX_GAMMA_8; # endif this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_scale_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth == 16) { that->sample_depth = that->bit_depth = 8; if (that->red_sBIT > 8) that->red_sBIT = 8; if (that->green_sBIT > 8) that->green_sBIT = 8; if (that->blue_sBIT > 8) that->blue_sBIT = 8; if (that->alpha_sBIT > 8) that->alpha_sBIT = 8; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_scale_16_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; } IT(scale_16); #undef PT #define PT ITSTRUCT(scale_16) #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */ #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */ /* png_set_strip_16 */ static void image_transform_png_set_strip_16_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_strip_16(pp); # if PNG_LIBPNG_VER < 10700 /* libpng will limit the gamma table size: */ that->max_gamma_8 = PNG_MAX_GAMMA_8; # endif this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_strip_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth == 16) { that->sample_depth = that->bit_depth = 8; if (that->red_sBIT > 8) that->red_sBIT = 8; if (that->green_sBIT > 8) that->green_sBIT = 8; if (that->blue_sBIT > 8) that->blue_sBIT = 8; if (that->alpha_sBIT > 8) that->alpha_sBIT = 8; /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this * configuration option is set. From 1.5.4 the flag is never set and the * 'scale' API (above) must be used. */ # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER >= 10504 # error PNG_READ_ACCURATE_SCALE should not be set # endif /* The strip 16 algorithm drops the low 8 bits rather than calculating * 1/257, so we need to adjust the permitted errors appropriately: * Notice that this is only relevant prior to the addition of the * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!) */ { const double d = (255-128.5)/65535; that->rede += d; that->greene += d; that->bluee += d; that->alphae += d; } # endif } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_strip_16_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; } IT(strip_16); #undef PT #define PT ITSTRUCT(strip_16) #endif /* PNG_READ_16_TO_8_SUPPORTED */ #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED /* png_set_strip_alpha */ static void image_transform_png_set_strip_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_strip_alpha(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_strip_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; that->have_tRNS = 0; that->alphaf = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_strip_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_ALPHA) != 0; } IT(strip_alpha); #undef PT #define PT ITSTRUCT(strip_alpha) #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */ #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green) * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red, * png_fixed_point green) * png_get_rgb_to_gray_status * * The 'default' test here uses values known to be used inside libpng prior to * 1.7.0: * * red: 6968 * green: 23434 * blue: 2366 * * These values are being retained for compatibility, along with the somewhat * broken truncation calculation in the fast-and-inaccurate code path. Older * versions of libpng will fail the accuracy tests below because they use the * truncation algorithm everywhere. */ #define data ITDATA(rgb_to_gray) static struct { double gamma; /* File gamma to use in processing */ /* The following are the parameters for png_set_rgb_to_gray: */ # ifdef PNG_FLOATING_POINT_SUPPORTED double red_to_set; double green_to_set; # else png_fixed_point red_to_set; png_fixed_point green_to_set; # endif /* The actual coefficients: */ double red_coefficient; double green_coefficient; double blue_coefficient; /* Set if the coeefficients have been overridden. */ int coefficients_overridden; } data; #undef image_transform_ini #define image_transform_ini image_transform_png_set_rgb_to_gray_ini static void image_transform_png_set_rgb_to_gray_ini(const image_transform *this, transform_display *that) { png_modifier *pm = that->pm; const color_encoding *e = pm->current_encoding; UNUSED(this) /* Since we check the encoding this flag must be set: */ pm->test_uses_encoding = 1; /* If 'e' is not NULL chromaticity information is present and either a cHRM * or an sRGB chunk will be inserted. */ if (e != 0) { /* Coefficients come from the encoding, but may need to be normalized to a * white point Y of 1.0 */ const double whiteY = e->red.Y + e->green.Y + e->blue.Y; data.red_coefficient = e->red.Y; data.green_coefficient = e->green.Y; data.blue_coefficient = e->blue.Y; if (whiteY != 1) { data.red_coefficient /= whiteY; data.green_coefficient /= whiteY; data.blue_coefficient /= whiteY; } } else { /* The default (built in) coeffcients, as above: */ # if PNG_LIBPNG_VER < 10700 data.red_coefficient = 6968 / 32768.; data.green_coefficient = 23434 / 32768.; data.blue_coefficient = 2366 / 32768.; # else data.red_coefficient = .2126; data.green_coefficient = .7152; data.blue_coefficient = .0722; # endif } data.gamma = pm->current_gamma; /* If not set then the calculations assume linear encoding (implicitly): */ if (data.gamma == 0) data.gamma = 1; /* The arguments to png_set_rgb_to_gray can override the coefficients implied * by the color space encoding. If doing exhaustive checks do the override * in each case, otherwise do it randomly. */ if (pm->test_exhaustive) { /* First time in coefficients_overridden is 0, the following sets it to 1, * so repeat if it is set. If a test fails this may mean we subsequently * skip a non-override test, ignore that. */ data.coefficients_overridden = !data.coefficients_overridden; pm->repeat = data.coefficients_overridden != 0; } else data.coefficients_overridden = random_choice(); if (data.coefficients_overridden) { /* These values override the color encoding defaults, simply use random * numbers. */ png_uint_32 ru; double total; ru = random_u32(); data.green_coefficient = total = (ru & 0xffff) / 65535.; ru >>= 16; data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.; total += data.red_coefficient; data.blue_coefficient = 1 - total; # ifdef PNG_FLOATING_POINT_SUPPORTED data.red_to_set = data.red_coefficient; data.green_to_set = data.green_coefficient; # else data.red_to_set = fix(data.red_coefficient); data.green_to_set = fix(data.green_coefficient); # endif /* The following just changes the error messages: */ pm->encoding_ignored = 1; } else { data.red_to_set = -1; data.green_to_set = -1; } /* Adjust the error limit in the png_modifier because of the larger errors * produced in the digitization during the gamma handling. */ if (data.gamma != 1) /* Use gamma tables */ { if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations) { /* The computations have the form: * * r * rc + g * gc + b * bc * * Each component of which is +/-1/65535 from the gamma_to_1 table * lookup, resulting in a base error of +/-6. The gamma_from_1 * conversion adds another +/-2 in the 16-bit case and * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case. */ # if PNG_LIBPNG_VER < 10700 if (that->this.bit_depth < 16) that->max_gamma_8 = PNG_MAX_GAMMA_8; # endif that->pm->limit += pow( (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ? 8. : 6. + (1<<(15-that->max_gamma_8)) )/65535, data.gamma); } else { /* Rounding to 8 bits in the linear space causes massive errors which * will trigger the error check in transform_range_check. Fix that * here by taking the gamma encoding into account. * * When DIGITIZE is set because a pre-1.7 version of libpng is being * tested allow a bigger slack. * * NOTE: this number only affects the internal limit check in pngvalid, * it has no effect on the limits applied to the libpng values. */ that->pm->limit += pow( # if DIGITIZE 2.0 # else 1.0 # endif /255, data.gamma); } } else { /* With no gamma correction a large error comes from the truncation of the * calculation in the 8 bit case, allow for that here. */ if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations) that->pm->limit += 4E-3; } } static void image_transform_png_set_rgb_to_gray_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { const int error_action = 1; /* no error, no defines in png.h */ # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set); # else png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set, data.green_to_set); # endif # ifdef PNG_READ_cHRM_SUPPORTED if (that->pm->current_encoding != 0) { /* We have an encoding so a cHRM chunk may have been set; if so then * check that the libpng APIs give the correct (X,Y,Z) values within * some margin of error for the round trip through the chromaticity * form. */ # ifdef PNG_FLOATING_POINT_SUPPORTED # define API_function png_get_cHRM_XYZ # define API_form "FP" # define API_type double # define API_cvt(x) (x) # else # define API_function png_get_cHRM_XYZ_fixed # define API_form "fixed" # define API_type png_fixed_point # define API_cvt(x) ((double)(x)/PNG_FP_1) # endif API_type rX, gX, bX; API_type rY, gY, bY; API_type rZ, gZ, bZ; if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ) & PNG_INFO_cHRM) != 0) { double maxe; const char *el; color_encoding e, o; /* Expect libpng to return a normalized result, but the original * color space encoding may not be normalized. */ modifier_current_encoding(that->pm, &o); normalize_color_encoding(&o); /* Sanity check the pngvalid code - the coefficients should match * the normalized Y values of the encoding unless they were * overridden. */ if (data.red_to_set == -1 && data.green_to_set == -1 && (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON || fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON || fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON)) png_error(pp, "internal pngvalid cHRM coefficient error"); /* Generate a colour space encoding. */ e.gamma = o.gamma; /* not used */ e.red.X = API_cvt(rX); e.red.Y = API_cvt(rY); e.red.Z = API_cvt(rZ); e.green.X = API_cvt(gX); e.green.Y = API_cvt(gY); e.green.Z = API_cvt(gZ); e.blue.X = API_cvt(bX); e.blue.Y = API_cvt(bY); e.blue.Z = API_cvt(bZ); /* This should match the original one from the png_modifier, within * the range permitted by the libpng fixed point representation. */ maxe = 0; el = "-"; /* Set to element name with error */ # define CHECK(col,x)\ {\ double err = fabs(o.col.x - e.col.x);\ if (err > maxe)\ {\ maxe = err;\ el = #col "(" #x ")";\ }\ } CHECK(red,X) CHECK(red,Y) CHECK(red,Z) CHECK(green,X) CHECK(green,Y) CHECK(green,Z) CHECK(blue,X) CHECK(blue,Y) CHECK(blue,Z) /* Here in both fixed and floating cases to check the values read * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so * we can't expect better than +/-.5E-5 on the result, allow 1E-5. */ if (maxe >= 1E-5) { size_t pos = 0; char buffer[256]; pos = safecat(buffer, sizeof buffer, pos, API_form); pos = safecat(buffer, sizeof buffer, pos, " cHRM "); pos = safecat(buffer, sizeof buffer, pos, el); pos = safecat(buffer, sizeof buffer, pos, " error: "); pos = safecatd(buffer, sizeof buffer, pos, maxe, 7); pos = safecat(buffer, sizeof buffer, pos, " "); /* Print the color space without the gamma value: */ pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0); pos = safecat(buffer, sizeof buffer, pos, " -> "); pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0); png_error(pp, buffer); } } } # endif /* READ_cHRM */ this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_rgb_to_gray_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0) { double gray, err; # if PNG_LIBPNG_VER < 10700 if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); # endif /* Image now has RGB channels... */ # if DIGITIZE { png_modifier *pm = display->pm; const unsigned int sample_depth = that->sample_depth; const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 : sample_depth); const unsigned int gamma_depth = (sample_depth == 16 ? display->max_gamma_8 : (pm->assume_16_bit_calculations ? display->max_gamma_8 : sample_depth)); int isgray; double r, g, b; double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi; /* Do this using interval arithmetic, otherwise it is too difficult to * handle the errors correctly. * * To handle the gamma correction work out the upper and lower bounds * of the digitized value. Assume rounding here - normally the values * will be identical after this operation if there is only one * transform, feel free to delete the png_error checks on this below in * the future (this is just me trying to ensure it works!) * * Interval arithmetic is exact, but to implement it it must be * possible to control the floating point implementation rounding mode. * This cannot be done in ANSI-C, so instead I reduce the 'lo' values * by DBL_EPSILON and increase the 'hi' values by the same. */ # define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON)) # define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON)) r = rlo = rhi = that->redf; rlo -= that->rede; rlo = DD(rlo, calc_depth, 1/*round*/); rhi += that->rede; rhi = DU(rhi, calc_depth, 1/*round*/); g = glo = ghi = that->greenf; glo -= that->greene; glo = DD(glo, calc_depth, 1/*round*/); ghi += that->greene; ghi = DU(ghi, calc_depth, 1/*round*/); b = blo = bhi = that->bluef; blo -= that->bluee; blo = DD(blo, calc_depth, 1/*round*/); bhi += that->bluee; bhi = DU(bhi, calc_depth, 1/*round*/); isgray = r==g && g==b; if (data.gamma != 1) { const double power = 1/data.gamma; const double abse = .5/(sample_depth == 16 ? 65535 : 255); /* If a gamma calculation is done it is done using lookup tables of * precision gamma_depth, so the already digitized value above may * need to be further digitized here. */ if (gamma_depth != calc_depth) { rlo = DD(rlo, gamma_depth, 0/*truncate*/); rhi = DU(rhi, gamma_depth, 0/*truncate*/); glo = DD(glo, gamma_depth, 0/*truncate*/); ghi = DU(ghi, gamma_depth, 0/*truncate*/); blo = DD(blo, gamma_depth, 0/*truncate*/); bhi = DU(bhi, gamma_depth, 0/*truncate*/); } /* 'abse' is the error in the gamma table calculation itself. */ r = pow(r, power); rlo = DD(pow(rlo, power)-abse, calc_depth, 1); rhi = DU(pow(rhi, power)+abse, calc_depth, 1); g = pow(g, power); glo = DD(pow(glo, power)-abse, calc_depth, 1); ghi = DU(pow(ghi, power)+abse, calc_depth, 1); b = pow(b, power); blo = DD(pow(blo, power)-abse, calc_depth, 1); bhi = DU(pow(bhi, power)+abse, calc_depth, 1); } /* Now calculate the actual gray values. Although the error in the * coefficients depends on whether they were specified on the command * line (in which case truncation to 15 bits happened) or not (rounding * was used) the maxium error in an individual coefficient is always * 2/32768, because even in the rounding case the requirement that * coefficients add up to 32768 can cause a larger rounding error. * * The only time when rounding doesn't occur in 1.5.5 and later is when * the non-gamma code path is used for less than 16 bit data. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; { const int do_round = data.gamma != 1 || calc_depth == 16; const double ce = 2. / 32768; graylo = DD(rlo * (data.red_coefficient-ce) + glo * (data.green_coefficient-ce) + blo * (data.blue_coefficient-ce), calc_depth, do_round); if (graylo > gray) /* always accept the right answer */ graylo = gray; grayhi = DU(rhi * (data.red_coefficient+ce) + ghi * (data.green_coefficient+ce) + bhi * (data.blue_coefficient+ce), calc_depth, do_round); if (grayhi < gray) grayhi = gray; } /* And invert the gamma. */ if (data.gamma != 1) { const double power = data.gamma; /* And this happens yet again, shifting the values once more. */ if (gamma_depth != sample_depth) { rlo = DD(rlo, gamma_depth, 0/*truncate*/); rhi = DU(rhi, gamma_depth, 0/*truncate*/); glo = DD(glo, gamma_depth, 0/*truncate*/); ghi = DU(ghi, gamma_depth, 0/*truncate*/); blo = DD(blo, gamma_depth, 0/*truncate*/); bhi = DU(bhi, gamma_depth, 0/*truncate*/); } gray = pow(gray, power); graylo = DD(pow(graylo, power), sample_depth, 1); grayhi = DU(pow(grayhi, power), sample_depth, 1); } # undef DD # undef DU /* Now the error can be calculated. * * If r==g==b because there is no overall gamma correction libpng * currently preserves the original value. */ if (isgray) err = (that->rede + that->greene + that->bluee)/3; else { err = fabs(grayhi-gray); if (fabs(gray - graylo) > err) err = fabs(graylo-gray); #if !RELEASE_BUILD /* Check that this worked: */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_warning(pp, buffer); pm->limit = err; } #endif /* !RELEASE_BUILD */ } } # else /* !DIGITIZE */ { double r = that->redf; double re = that->rede; double g = that->greenf; double ge = that->greene; double b = that->bluef; double be = that->bluee; # if PNG_LIBPNG_VER < 10700 /* The true gray case involves no math in earlier versions (not * true, there was some if gamma correction was happening too.) */ if (r == g && r == b) { gray = r; err = re; if (err < ge) err = ge; if (err < be) err = be; } else # endif /* before 1.7 */ if (data.gamma == 1) { /* There is no need to do the conversions to and from linear space, * so the calculation should be a lot more accurate. There is a * built in error in the coefficients because they only have 15 bits * and are adjusted to make sure they add up to 32768. This * involves a integer calculation with truncation of the form: * * ((int)(coefficient * 100000) * 32768)/100000 * * This is done to the red and green coefficients (the ones * provided to the API) then blue is calculated from them so the * result adds up to 32768. In the worst case this can result in * a -1 error in red and green and a +2 error in blue. Consequently * the worst case in the calculation below is 2/32768 error. * * TODO: consider fixing this in libpng by rounding the calculation * limiting the error to 1/32768. * * Handling this by adding 2/32768 here avoids needing to increase * the global error limits to take this into account.) */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; err = re * data.red_coefficient + ge * data.green_coefficient + be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON; } else { /* The calculation happens in linear space, and this produces much * wider errors in the encoded space. These are handled here by * factoring the errors in to the calculation. There are two table * lookups in the calculation and each introduces a quantization * error defined by the table size. */ png_modifier *pm = display->pm; double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255); double out_qe = (that->sample_depth > 8 ? .5/65535 : (pm->assume_16_bit_calculations ? .5/(1<max_gamma_8) : .5/255)); double rhi, ghi, bhi, grayhi; double g1 = 1/data.gamma; rhi = r + re + in_qe; if (rhi > 1) rhi = 1; r -= re + in_qe; if (r < 0) r = 0; ghi = g + ge + in_qe; if (ghi > 1) ghi = 1; g -= ge + in_qe; if (g < 0) g = 0; bhi = b + be + in_qe; if (bhi > 1) bhi = 1; b -= be + in_qe; if (b < 0) b = 0; r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON); g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON); b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON); /* Work out the lower and upper bounds for the gray value in the * encoded space, then work out an average and error. Remove the * previously added input quantization error at this point. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient - 2./32768 - out_qe; if (gray <= 0) gray = 0; else { gray *= (1 - 6 * DBL_EPSILON); gray = pow(gray, data.gamma) * (1-DBL_EPSILON); } grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient + bhi * data.blue_coefficient + 2./32768 + out_qe; grayhi *= (1 + 6 * DBL_EPSILON); if (grayhi >= 1) grayhi = 1; else grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON); err = (grayhi - gray) / 2; gray = (grayhi + gray) / 2; if (err <= in_qe) err = gray * DBL_EPSILON; else err -= in_qe; #if !RELEASE_BUILD /* Validate that the error is within limits (this has caused * problems before, it's much easier to detect them here.) */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_warning(pp, buffer); pm->limit = err; } #endif /* !RELEASE_BUILD */ } } # endif /* !DIGITIZE */ that->bluef = that->greenf = that->redf = gray; that->bluee = that->greene = that->rede = err; /* The sBIT is the minium of the three colour channel sBITs. */ if (that->red_sBIT > that->green_sBIT) that->red_sBIT = that->green_sBIT; if (that->red_sBIT > that->blue_sBIT) that->red_sBIT = that->blue_sBIT; that->blue_sBIT = that->green_sBIT = that->red_sBIT; /* And remove the colour bit in the type: */ if (that->colour_type == PNG_COLOR_TYPE_RGB) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_rgb_to_gray_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) != 0; } #undef data IT(rgb_to_gray); #undef PT #define PT ITSTRUCT(rgb_to_gray) #undef image_transform_ini #define image_transform_ini image_transform_default_ini #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */ #ifdef PNG_READ_BACKGROUND_SUPPORTED /* png_set_background(png_structp, png_const_color_16p background_color, * int background_gamma_code, int need_expand, double background_gamma) * png_set_background_fixed(png_structp, png_const_color_16p background_color, * int background_gamma_code, int need_expand, * png_fixed_point background_gamma) * * This ignores the gamma (at present.) */ #define data ITDATA(background) static image_pixel data; static void image_transform_png_set_background_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_byte colour_type, bit_depth; png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */ int expand; png_color_16 back; /* We need a background colour, because we don't know exactly what transforms * have been set we have to supply the colour in the original file format and * so we need to know what that is! The background colour is stored in the * transform_display. */ R8(random_bytes); /* Read the random value, for colour type 3 the background colour is actually * expressed as a 24bit rgb, not an index. */ colour_type = that->this.colour_type; if (colour_type == 3) { colour_type = PNG_COLOR_TYPE_RGB; bit_depth = 8; expand = 0; /* passing in an RGB not a pixel index */ } else { if (that->this.has_tRNS) that->this.is_transparent = 1; bit_depth = that->this.bit_depth; expand = 1; } image_pixel_init(&data, random_bytes, colour_type, bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/); /* Extract the background colour from this image_pixel, but make sure the * unused fields of 'back' are garbage. */ R8(back); if (colour_type & PNG_COLOR_MASK_COLOR) { back.red = (png_uint_16)data.red; back.green = (png_uint_16)data.green; back.blue = (png_uint_16)data.blue; } else back.gray = (png_uint_16)data.red; #ifdef PNG_FLOATING_POINT_SUPPORTED png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); #else png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0); #endif this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_background_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Check for tRNS first: */ if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE) image_pixel_add_alpha(that, &display->this, 1/*for background*/); /* This is only necessary if the alpha value is less than 1. */ if (that->alphaf < 1) { /* Now we do the background calculation without any gamma correction. */ if (that->alphaf <= 0) { that->redf = data.redf; that->greenf = data.greenf; that->bluef = data.bluef; that->rede = data.rede; that->greene = data.greene; that->bluee = data.bluee; that->red_sBIT= data.red_sBIT; that->green_sBIT= data.green_sBIT; that->blue_sBIT= data.blue_sBIT; } else /* 0 < alpha < 1 */ { double alf = 1 - that->alphaf; that->redf = that->redf * that->alphaf + data.redf * alf; that->rede = that->rede * that->alphaf + data.rede * alf + DBL_EPSILON; that->greenf = that->greenf * that->alphaf + data.greenf * alf; that->greene = that->greene * that->alphaf + data.greene * alf + DBL_EPSILON; that->bluef = that->bluef * that->alphaf + data.bluef * alf; that->bluee = that->bluee * that->alphaf + data.bluee * alf + DBL_EPSILON; } /* Remove the alpha type and set the alpha (not in that order.) */ that->alphaf = 1; that->alphae = 0; } if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; /* PNG_COLOR_TYPE_PALETTE is not changed */ this->next->mod(this->next, that, pp, display); } #define image_transform_png_set_background_add image_transform_default_add #undef data IT(background); #undef PT #define PT ITSTRUCT(background) #endif /* PNG_READ_BACKGROUND_SUPPORTED */ /* png_set_quantize(png_structp, png_colorp palette, int num_palette, * int maximum_colors, png_const_uint_16p histogram, int full_quantize) * * Very difficult to validate this! */ /*NOTE: TBD NYI */ /* The data layout transforms are handled by swapping our own channel data, * necessarily these need to happen at the end of the transform list because the * semantic of the channels changes after these are executed. Some of these, * like set_shift and set_packing, can't be done at present because they change * the layout of the data at the sub-sample level so sample() won't get the * right answer. */ /* png_set_invert_alpha */ #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED /* Invert the alpha channel * * png_set_invert_alpha(png_structrp png_ptr) */ static void image_transform_png_set_invert_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_invert_alpha(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_invert_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type & 4) that->alpha_inverted = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_invert_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* Only has an effect on pixels with alpha: */ return (colour_type & 4) != 0; } IT(invert_alpha); #undef PT #define PT ITSTRUCT(invert_alpha) #endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */ /* png_set_bgr */ #ifdef PNG_READ_BGR_SUPPORTED /* Swap R,G,B channels to order B,G,R. * * png_set_bgr(png_structrp png_ptr) * * This only has an effect on RGB and RGBA pixels. */ static void image_transform_png_set_bgr_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_bgr(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_bgr_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_RGB || that->colour_type == PNG_COLOR_TYPE_RGBA) that->swap_rgb = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_bgr_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_RGB || colour_type == PNG_COLOR_TYPE_RGBA; } IT(bgr); #undef PT #define PT ITSTRUCT(bgr) #endif /* PNG_READ_BGR_SUPPORTED */ /* png_set_swap_alpha */ #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED /* Put the alpha channel first. * * png_set_swap_alpha(png_structrp png_ptr) * * This only has an effect on GA and RGBA pixels. */ static void image_transform_png_set_swap_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_swap_alpha(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_swap_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_GA || that->colour_type == PNG_COLOR_TYPE_RGBA) that->alpha_first = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_swap_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_GA || colour_type == PNG_COLOR_TYPE_RGBA; } IT(swap_alpha); #undef PT #define PT ITSTRUCT(swap_alpha) #endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */ /* png_set_swap */ #ifdef PNG_READ_SWAP_SUPPORTED /* Byte swap 16-bit components. * * png_set_swap(png_structrp png_ptr) */ static void image_transform_png_set_swap_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_swap(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_swap_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth == 16) that->swap16 = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_swap_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth == 16; } IT(swap); #undef PT #define PT ITSTRUCT(swap) #endif /* PNG_READ_SWAP_SUPPORTED */ #ifdef PNG_READ_FILLER_SUPPORTED /* Add a filler byte to 8-bit Gray or 24-bit RGB images. * * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags)); * * Flags: * * PNG_FILLER_BEFORE * PNG_FILLER_AFTER */ #define data ITDATA(filler) static struct { png_uint_32 filler; int flags; } data; static void image_transform_png_set_filler_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { /* Need a random choice for 'before' and 'after' as well as for the * filler. The 'filler' value has all 32 bits set, but only bit_depth * will be used. At this point we don't know bit_depth. */ data.filler = random_u32(); data.flags = random_choice(); png_set_filler(pp, data.filler, data.flags); /* The standard display handling stuff also needs to know that * there is a filler, so set that here. */ that->this.filler = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_filler_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth >= 8 && (that->colour_type == PNG_COLOR_TYPE_RGB || that->colour_type == PNG_COLOR_TYPE_GRAY)) { const unsigned int max = (1U << that->bit_depth)-1; that->alpha = data.filler & max; that->alphaf = ((double)that->alpha) / max; that->alphae = 0; /* The filler has been stored in the alpha channel, we must record * that this has been done for the checking later on, the color * type is faked to have an alpha channel, but libpng won't report * this; the app has to know the extra channel is there and this * was recording in standard_display::filler above. */ that->colour_type |= 4; /* alpha added */ that->alpha_first = data.flags == PNG_FILLER_BEFORE; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_filler_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB || colour_type == PNG_COLOR_TYPE_GRAY); } #undef data IT(filler); #undef PT #define PT ITSTRUCT(filler) /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */ /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */ #define data ITDATA(add_alpha) static struct { png_uint_32 filler; int flags; } data; static void image_transform_png_set_add_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { /* Need a random choice for 'before' and 'after' as well as for the * filler. The 'filler' value has all 32 bits set, but only bit_depth * will be used. At this point we don't know bit_depth. */ data.filler = random_u32(); data.flags = random_choice(); png_set_add_alpha(pp, data.filler, data.flags); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_add_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth >= 8 && (that->colour_type == PNG_COLOR_TYPE_RGB || that->colour_type == PNG_COLOR_TYPE_GRAY)) { const unsigned int max = (1U << that->bit_depth)-1; that->alpha = data.filler & max; that->alphaf = ((double)that->alpha) / max; that->alphae = 0; that->colour_type |= 4; /* alpha added */ that->alpha_first = data.flags == PNG_FILLER_BEFORE; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_add_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB || colour_type == PNG_COLOR_TYPE_GRAY); } #undef data IT(add_alpha); #undef PT #define PT ITSTRUCT(add_alpha) #endif /* PNG_READ_FILLER_SUPPORTED */ /* png_set_packing */ #ifdef PNG_READ_PACK_SUPPORTED /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. * * png_set_packing(png_structrp png_ptr) * * This should only affect grayscale and palette images with less than 8 bits * per pixel. */ static void image_transform_png_set_packing_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_packing(pp); that->unpacked = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_packing_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* The general expand case depends on what the colour type is, * low bit-depth pixel values are unpacked into bytes without * scaling, so sample_depth is not changed. */ if (that->bit_depth < 8) /* grayscale or palette */ that->bit_depth = 8; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_packing_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; /* Nothing should happen unless the bit depth is less than 8: */ return bit_depth < 8; } IT(packing); #undef PT #define PT ITSTRUCT(packing) #endif /* PNG_READ_PACK_SUPPORTED */ /* png_set_packswap */ #ifdef PNG_READ_PACKSWAP_SUPPORTED /* Swap pixels packed into bytes; reverses the order on screen so that * the high order bits correspond to the rightmost pixels. * * png_set_packswap(png_structrp png_ptr) */ static void image_transform_png_set_packswap_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_packswap(pp); that->this.littleendian = 1; this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_packswap_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth < 8) that->littleendian = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_packswap_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth < 8; } IT(packswap); #undef PT #define PT ITSTRUCT(packswap) #endif /* PNG_READ_PACKSWAP_SUPPORTED */ /* png_set_invert_mono */ #ifdef PNG_READ_INVERT_MONO_SUPPORTED /* Invert the gray channel * * png_set_invert_mono(png_structrp png_ptr) */ static void image_transform_png_set_invert_mono_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_invert_mono(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_invert_mono_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type & 4) that->mono_inverted = 1; this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_invert_mono_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* Only has an effect on pixels with no colour: */ return (colour_type & 2) == 0; } IT(invert_mono); #undef PT #define PT ITSTRUCT(invert_mono) #endif /* PNG_READ_INVERT_MONO_SUPPORTED */ #ifdef PNG_READ_SHIFT_SUPPORTED /* png_set_shift(png_structp, png_const_color_8p true_bits) * * The output pixels will be shifted by the given true_bits * values. */ #define data ITDATA(shift) static png_color_8 data; static void image_transform_png_set_shift_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { /* Get a random set of shifts. The shifts need to do something * to test the transform, so they are limited to the bit depth * of the input image. Notice that in the following the 'gray' * field is randomized independently. This acts as a check that * libpng does use the correct field. */ const unsigned int depth = that->this.bit_depth; data.red = (png_byte)/*SAFE*/(random_mod(depth)+1); data.green = (png_byte)/*SAFE*/(random_mod(depth)+1); data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1); data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1); data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1); png_set_shift(pp, &data); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_shift_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Copy the correct values into the sBIT fields, libpng does not do * anything to palette data: */ if (that->colour_type != PNG_COLOR_TYPE_PALETTE) { that->sig_bits = 1; /* The sBIT fields are reset to the values previously sent to * png_set_shift according to the colour type. * does. */ if (that->colour_type & 2) /* RGB channels */ { that->red_sBIT = data.red; that->green_sBIT = data.green; that->blue_sBIT = data.blue; } else /* One grey channel */ that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray; that->alpha_sBIT = data.alpha; } this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_shift_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type != PNG_COLOR_TYPE_PALETTE; } IT(shift); #undef PT #define PT ITSTRUCT(shift) #endif /* PNG_READ_SHIFT_SUPPORTED */ #ifdef THIS_IS_THE_PROFORMA static void image_transform_png_set_@_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_@(pp); this->next->set(this->next, that, pp, pi); } static void image_transform_png_set_@_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { this->next->mod(this->next, that, pp, display); } static int image_transform_png_set_@_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; return 1; } IT(@); #endif /* This may just be 'end' if all the transforms are disabled! */ static image_transform *const image_transform_first = &PT; static void transform_enable(const char *name) { /* Everything starts out enabled, so if we see an 'enable' disabled * everything else the first time round. */ static int all_disabled = 0; int found_it = 0; image_transform *list = image_transform_first; while (list != &image_transform_end) { if (strcmp(list->name, name) == 0) { list->enable = 1; found_it = 1; } else if (!all_disabled) list->enable = 0; list = list->list; } all_disabled = 1; if (!found_it) { fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n", name); exit(99); } } static void transform_disable(const char *name) { image_transform *list = image_transform_first; while (list != &image_transform_end) { if (strcmp(list->name, name) == 0) { list->enable = 0; return; } list = list->list; } fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n", name); exit(99); } static void image_transform_reset_count(void) { image_transform *next = image_transform_first; int count = 0; while (next != &image_transform_end) { next->local_use = 0; next->next = 0; next = next->list; ++count; } /* This can only happen if we every have more than 32 transforms (excluding * the end) in the list. */ if (count > 32) abort(); } static int image_transform_test_counter(png_uint_32 counter, unsigned int max) { /* Test the list to see if there is any point contining, given a current * counter and a 'max' value. */ image_transform *next = image_transform_first; while (next != &image_transform_end) { /* For max 0 or 1 continue until the counter overflows: */ counter >>= 1; /* Continue if any entry hasn't reacked the max. */ if (max > 1 && next->local_use < max) return 1; next = next->list; } return max <= 1 && counter == 0; } static png_uint_32 image_transform_add(const image_transform **this, unsigned int max, png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { for (;;) /* until we manage to add something */ { png_uint_32 mask; image_transform *list; /* Find the next counter value, if the counter is zero this is the start * of the list. This routine always returns the current counter (not the * next) so it returns 0 at the end and expects 0 at the beginning. */ if (counter == 0) /* first time */ { image_transform_reset_count(); if (max <= 1) counter = 1; else counter = random_32(); } else /* advance the counter */ { switch (max) { case 0: ++counter; break; case 1: counter <<= 1; break; default: counter = random_32(); break; } } /* Now add all these items, if possible */ *this = &image_transform_end; list = image_transform_first; mask = 1; /* Go through the whole list adding anything that the counter selects: */ while (list != &image_transform_end) { if ((counter & mask) != 0 && list->enable && (max == 0 || list->local_use < max)) { /* Candidate to add: */ if (list->add(list, this, colour_type, bit_depth) || max == 0) { /* Added, so add to the name too. */ *pos = safecat(name, sizeof_name, *pos, " +"); *pos = safecat(name, sizeof_name, *pos, list->name); } else { /* Not useful and max>0, so remove it from *this: */ *this = list->next; list->next = 0; /* And, since we know it isn't useful, stop it being added again * in this run: */ list->local_use = max; } } mask <<= 1; list = list->list; } /* Now if anything was added we have something to do. */ if (*this != &image_transform_end) return counter; /* Nothing added, but was there anything in there to add? */ if (!image_transform_test_counter(counter, max)) return 0; } } static void perform_transform_test(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg, pm->test_tRNS)) { png_uint_32 counter = 0; size_t base_pos; char name[64]; base_pos = safecat(name, sizeof name, 0, "transform:"); for (;;) { size_t pos = base_pos; const image_transform *list = 0; /* 'max' is currently hardwired to '1'; this should be settable on the * command line. */ counter = image_transform_add(&list, 1/*max*/, counter, name, sizeof name, &pos, colour_type, bit_depth); if (counter == 0) break; /* The command line can change this to checking interlaced images. */ do { pm->repeat = 0; transform_test(pm, FILEID(colour_type, bit_depth, palette_number, pm->interlace_type, 0, 0, 0), list, name); if (fail(pm)) return; } while (pm->repeat); } } } #endif /* PNG_READ_TRANSFORMS_SUPPORTED */ /********************************* GAMMA TESTS ********************************/ #ifdef PNG_READ_GAMMA_SUPPORTED /* Reader callbacks and implementations, where they differ from the standard * ones. */ typedef struct gamma_display { standard_display this; /* Parameters */ png_modifier* pm; double file_gamma; double screen_gamma; double background_gamma; png_byte sbit; int threshold_test; int use_input_precision; int scale16; int expand16; int do_background; png_color_16 background_color; /* Local variables */ double maxerrout; double maxerrpc; double maxerrabs; } gamma_display; #define ALPHA_MODE_OFFSET 4 static void gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id, double file_gamma, double screen_gamma, png_byte sbit, int threshold_test, int use_input_precision, int scale16, int expand16, int do_background, const png_color_16 *pointer_to_the_background_color, double background_gamma) { /* Standard fields */ standard_display_init(&dp->this, &pm->this, id, do_read_interlace, pm->use_update_info); /* Parameter fields */ dp->pm = pm; dp->file_gamma = file_gamma; dp->screen_gamma = screen_gamma; dp->background_gamma = background_gamma; dp->sbit = sbit; dp->threshold_test = threshold_test; dp->use_input_precision = use_input_precision; dp->scale16 = scale16; dp->expand16 = expand16; dp->do_background = do_background; if (do_background && pointer_to_the_background_color != 0) dp->background_color = *pointer_to_the_background_color; else memset(&dp->background_color, 0, sizeof dp->background_color); /* Local variable fields */ dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0; } static void gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi) { /* Reuse the standard stuff as appropriate. */ standard_info_part1(&dp->this, pp, pi); /* If requested strip 16 to 8 bits - this is handled automagically below * because the output bit depth is read from the library. Note that there * are interactions with sBIT but, internally, libpng makes sbit at most * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following. */ if (dp->scale16) # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_set_scale_16(pp); # else /* The following works both in 1.5.4 and earlier versions: */ # ifdef PNG_READ_16_TO_8_SUPPORTED png_set_strip_16(pp); # else png_error(pp, "scale16 (16 to 8 bit conversion) not supported"); # endif # endif if (dp->expand16) # ifdef PNG_READ_EXPAND_16_SUPPORTED png_set_expand_16(pp); # else png_error(pp, "expand16 (8 to 16 bit conversion) not supported"); # endif if (dp->do_background >= ALPHA_MODE_OFFSET) { # ifdef PNG_READ_ALPHA_MODE_SUPPORTED { /* This tests the alpha mode handling, if supported. */ int mode = dp->do_background - ALPHA_MODE_OFFSET; /* The gamma value is the output gamma, and is in the standard, * non-inverted, represenation. It provides a default for the PNG file * gamma, but since the file has a gAMA chunk this does not matter. */ const double sg = dp->screen_gamma; # ifndef PNG_FLOATING_POINT_SUPPORTED const png_fixed_point g = fix(sg); # endif # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_alpha_mode(pp, mode, sg); # else png_set_alpha_mode_fixed(pp, mode, g); # endif /* However, for the standard Porter-Duff algorithm the output defaults * to be linear, so if the test requires non-linear output it must be * corrected here. */ if (mode == PNG_ALPHA_STANDARD && sg != 1) { # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_gamma(pp, sg, dp->file_gamma); # else png_fixed_point f = fix(dp->file_gamma); png_set_gamma_fixed(pp, g, f); # endif } } # else png_error(pp, "alpha mode handling not supported"); # endif } else { /* Set up gamma processing. */ # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_gamma(pp, dp->screen_gamma, dp->file_gamma); # else { png_fixed_point s = fix(dp->screen_gamma); png_fixed_point f = fix(dp->file_gamma); png_set_gamma_fixed(pp, s, f); } # endif if (dp->do_background) { # ifdef PNG_READ_BACKGROUND_SUPPORTED /* NOTE: this assumes the caller provided the correct background gamma! */ const double bg = dp->background_gamma; # ifndef PNG_FLOATING_POINT_SUPPORTED const png_fixed_point g = fix(bg); # endif # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_background(pp, &dp->background_color, dp->do_background, 0/*need_expand*/, bg); # else png_set_background_fixed(pp, &dp->background_color, dp->do_background, 0/*need_expand*/, g); # endif # else png_error(pp, "png_set_background not supported"); # endif } } { int i = dp->this.use_update_info; /* Always do one call, even if use_update_info is 0. */ do png_read_update_info(pp, pi); while (--i > 0); } /* Now we may get a different cbRow: */ standard_info_part2(&dp->this, pp, pi, 1 /*images*/); } static void PNGCBAPI gamma_info(png_structp pp, png_infop pi) { gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp, pi); } /* Validate a single component value - the routine gets the input and output * sample values as unscaled PNG component values along with a cache of all the * information required to validate the values. */ typedef struct validate_info { png_const_structp pp; gamma_display *dp; png_byte sbit; int use_input_precision; int do_background; int scale16; unsigned int sbit_max; unsigned int isbit_shift; unsigned int outmax; double gamma_correction; /* Overall correction required. */ double file_inverse; /* Inverse of file gamma. */ double screen_gamma; double screen_inverse; /* Inverse of screen gamma. */ double background_red; /* Linear background value, red or gray. */ double background_green; double background_blue; double maxabs; double maxpc; double maxcalc; double maxout; double maxout_total; /* Total including quantization error */ double outlog; int outquant; } validate_info; static void init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp, int in_depth, int out_depth) { const unsigned int outmax = (1U<pp = pp; vi->dp = dp; if (dp->sbit > 0 && dp->sbit < in_depth) { vi->sbit = dp->sbit; vi->isbit_shift = in_depth - dp->sbit; } else { vi->sbit = (png_byte)in_depth; vi->isbit_shift = 0; } vi->sbit_max = (1U << vi->sbit)-1; /* This mimics the libpng threshold test, '0' is used to prevent gamma * correction in the validation test. */ vi->screen_gamma = dp->screen_gamma; if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD) vi->screen_gamma = vi->screen_inverse = 0; else vi->screen_inverse = 1/vi->screen_gamma; vi->use_input_precision = dp->use_input_precision; vi->outmax = outmax; vi->maxabs = abserr(dp->pm, in_depth, out_depth); vi->maxpc = pcerr(dp->pm, in_depth, out_depth); vi->maxcalc = calcerr(dp->pm, in_depth, out_depth); vi->maxout = outerr(dp->pm, in_depth, out_depth); vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth); vi->maxout_total = vi->maxout + vi->outquant * .5; vi->outlog = outlog(dp->pm, in_depth, out_depth); if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 || (dp->this.colour_type == 3 && dp->this.is_transparent) || ((dp->this.colour_type == 0 || dp->this.colour_type == 2) && dp->this.has_tRNS)) { vi->do_background = dp->do_background; if (vi->do_background != 0) { const double bg_inverse = 1/dp->background_gamma; double r, g, b; /* Caller must at least put the gray value into the red channel */ r = dp->background_color.red; r /= outmax; g = dp->background_color.green; g /= outmax; b = dp->background_color.blue; b /= outmax; # if 0 /* libpng doesn't do this optimization, if we do pngvalid will fail. */ if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD) # endif { r = pow(r, bg_inverse); g = pow(g, bg_inverse); b = pow(b, bg_inverse); } vi->background_red = r; vi->background_green = g; vi->background_blue = b; } } else /* Do not expect any background processing */ vi->do_background = 0; if (vi->do_background == 0) vi->background_red = vi->background_green = vi->background_blue = 0; vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma); if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD) vi->gamma_correction = 0; vi->file_inverse = 1/dp->file_gamma; if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD) vi->file_inverse = 0; vi->scale16 = dp->scale16; } /* This function handles composition of a single non-alpha component. The * argument is the input sample value, in the range 0..1, and the alpha value. * The result is the composed, linear, input sample. If alpha is less than zero * this is the alpha component and the function should not be called! */ static double gamma_component_compose(int do_background, double input_sample, double alpha, double background, int *compose) { switch (do_background) { #ifdef PNG_READ_BACKGROUND_SUPPORTED case PNG_BACKGROUND_GAMMA_SCREEN: case PNG_BACKGROUND_GAMMA_FILE: case PNG_BACKGROUND_GAMMA_UNIQUE: /* Standard PNG background processing. */ if (alpha < 1) { if (alpha > 0) { input_sample = input_sample * alpha + background * (1-alpha); if (compose != NULL) *compose = 1; } else input_sample = background; } break; #endif #ifdef PNG_READ_ALPHA_MODE_SUPPORTED case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD: case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN: /* The components are premultiplied in either case and the output is * gamma encoded (to get standard Porter-Duff we expect the output * gamma to be set to 1.0!) */ case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED: /* The optimization is that the partial-alpha entries are linear * while the opaque pixels are gamma encoded, but this only affects the * output encoding. */ if (alpha < 1) { if (alpha > 0) { input_sample *= alpha; if (compose != NULL) *compose = 1; } else input_sample = 0; } break; #endif default: /* Standard cases where no compositing is done (so the component * value is already correct.) */ UNUSED(alpha) UNUSED(background) UNUSED(compose) break; } return input_sample; } /* This API returns the encoded *input* component, in the range 0..1 */ static double gamma_component_validate(const char *name, const validate_info *vi, const unsigned int id, const unsigned int od, const double alpha /* <0 for the alpha channel itself */, const double background /* component background value */) { const unsigned int isbit = id >> vi->isbit_shift; const unsigned int sbit_max = vi->sbit_max; const unsigned int outmax = vi->outmax; const int do_background = vi->do_background; double i; /* First check on the 'perfect' result obtained from the digitized input * value, id, and compare this against the actual digitized result, 'od'. * 'i' is the input result in the range 0..1: */ i = isbit; i /= sbit_max; /* Check for the fast route: if we don't do any background composition or if * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then * just use the gamma_correction field to correct to the final output gamma. */ if (alpha == 1 /* opaque pixel component */ || !do_background #ifdef PNG_READ_ALPHA_MODE_SUPPORTED || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG #endif || (alpha < 0 /* alpha channel */ #ifdef PNG_READ_ALPHA_MODE_SUPPORTED && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN #endif )) { /* Then get the gamma corrected version of 'i' and compare to 'od', any * error less than .5 is insignificant - just quantization of the output * value to the nearest digital value (nevertheless the error is still * recorded - it's interesting ;-) */ double encoded_sample = i; double encoded_error; /* alpha less than 0 indicates the alpha channel, which is always linear */ if (alpha >= 0 && vi->gamma_correction > 0) encoded_sample = pow(encoded_sample, vi->gamma_correction); encoded_sample *= outmax; encoded_error = fabs(od-encoded_sample); if (encoded_error > vi->dp->maxerrout) vi->dp->maxerrout = encoded_error; if (encoded_error < vi->maxout_total && encoded_error < vi->outlog) return i; } /* The slow route - attempt to do linear calculations. */ /* There may be an error, or background processing is required, so calculate * the actual sample values - unencoded light intensity values. Note that in * practice these are not completely unencoded because they include a * 'viewing correction' to decrease or (normally) increase the perceptual * contrast of the image. There's nothing we can do about this - we don't * know what it is - so assume the unencoded value is perceptually linear. */ { double input_sample = i; /* In range 0..1 */ double output, error, encoded_sample, encoded_error; double es_lo, es_hi; int compose = 0; /* Set to one if composition done */ int output_is_encoded; /* Set if encoded to screen gamma */ int log_max_error = 1; /* Check maximum error values */ png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */ /* Convert to linear light (with the above caveat.) The alpha channel is * already linear. */ if (alpha >= 0) { int tcompose; if (vi->file_inverse > 0) input_sample = pow(input_sample, vi->file_inverse); /* Handle the compose processing: */ tcompose = 0; input_sample = gamma_component_compose(do_background, input_sample, alpha, background, &tcompose); if (tcompose) compose = 1; } /* And similarly for the output value, but we need to check the background * handling to linearize it correctly. */ output = od; output /= outmax; output_is_encoded = vi->screen_gamma > 0; if (alpha < 0) /* The alpha channel */ { #ifdef PNG_READ_ALPHA_MODE_SUPPORTED if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN) #endif { /* In all other cases the output alpha channel is linear already, * don't log errors here, they are much larger in linear data. */ output_is_encoded = 0; log_max_error = 0; } } #ifdef PNG_READ_ALPHA_MODE_SUPPORTED else /* A component */ { if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED && alpha < 1) /* the optimized case - linear output */ { if (alpha > 0) log_max_error = 0; output_is_encoded = 0; } } #endif if (output_is_encoded) output = pow(output, vi->screen_gamma); /* Calculate (or recalculate) the encoded_sample value and repeat the * check above (unnecessary if we took the fast route, but harmless.) */ encoded_sample = input_sample; if (output_is_encoded) encoded_sample = pow(encoded_sample, vi->screen_inverse); encoded_sample *= outmax; encoded_error = fabs(od-encoded_sample); /* Don't log errors in the alpha channel, or the 'optimized' case, * neither are significant to the overall perception. */ if (log_max_error && encoded_error > vi->dp->maxerrout) vi->dp->maxerrout = encoded_error; if (encoded_error < vi->maxout_total) { if (encoded_error < vi->outlog) return i; /* Test passed but error is bigger than the log limit, record why the * test passed: */ pass = "less than maxout:\n"; } /* i: the original input value in the range 0..1 * * pngvalid calculations: * input_sample: linear result; i linearized and composed, range 0..1 * encoded_sample: encoded result; input_sample scaled to ouput bit depth * * libpng calculations: * output: linear result; od scaled to 0..1 and linearized * od: encoded result from libpng */ /* Now we have the numbers for real errors, both absolute values as as a * percentage of the correct value (output): */ error = fabs(input_sample-output); if (log_max_error && error > vi->dp->maxerrabs) vi->dp->maxerrabs = error; /* The following is an attempt to ignore the tendency of quantization to * dominate the percentage errors for lower result values: */ if (log_max_error && input_sample > .5) { double percentage_error = error/input_sample; if (percentage_error > vi->dp->maxerrpc) vi->dp->maxerrpc = percentage_error; } /* Now calculate the digitization limits for 'encoded_sample' using the * 'max' values. Note that maxout is in the encoded space but maxpc and * maxabs are in linear light space. * * First find the maximum error in linear light space, range 0..1: */ { double tmp = input_sample * vi->maxpc; if (tmp < vi->maxabs) tmp = vi->maxabs; /* If 'compose' is true the composition was done in linear space using * integer arithmetic. This introduces an extra error of +/- 0.5 (at * least) in the integer space used. 'maxcalc' records this, taking * into account the possibility that even for 16 bit output 8 bit space * may have been used. */ if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc; /* The 'maxout' value refers to the encoded result, to compare with * this encode input_sample adjusted by the maximum error (tmp) above. */ es_lo = encoded_sample - vi->maxout; if (es_lo > 0 && input_sample-tmp > 0) { double low_value = input_sample-tmp; if (output_is_encoded) low_value = pow(low_value, vi->screen_inverse); low_value *= outmax; if (low_value < es_lo) es_lo = low_value; /* Quantize this appropriately: */ es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant; } else es_lo = 0; es_hi = encoded_sample + vi->maxout; if (es_hi < outmax && input_sample+tmp < 1) { double high_value = input_sample+tmp; if (output_is_encoded) high_value = pow(high_value, vi->screen_inverse); high_value *= outmax; if (high_value > es_hi) es_hi = high_value; es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant; } else es_hi = outmax; } /* The primary test is that the final encoded value returned by the * library should be between the two limits (inclusive) that were * calculated above. */ if (od >= es_lo && od <= es_hi) { /* The value passes, but we may need to log the information anyway. */ if (encoded_error < vi->outlog) return i; if (pass == 0) pass = "within digitization limits:\n"; } { /* There has been an error in processing, or we need to log this * value. */ double is_lo, is_hi; /* pass is set at this point if either of the tests above would have * passed. Don't do these additional tests here - just log the * original [es_lo..es_hi] values. */ if (pass == 0 && vi->use_input_precision && vi->dp->sbit) { /* Ok, something is wrong - this actually happens in current libpng * 16-to-8 processing. Assume that the input value (id, adjusted * for sbit) can be anywhere between value-.5 and value+.5 - quite a * large range if sbit is low. * * NOTE: at present because the libpng gamma table stuff has been * changed to use a rounding algorithm to correct errors in 8-bit * calculations the precise sbit calculation (a shift) has been * lost. This can result in up to a +/-1 error in the presence of * an sbit less than the bit depth. */ # if PNG_LIBPNG_VER < 10700 # define SBIT_ERROR .5 # else # define SBIT_ERROR 1. # endif double tmp = (isbit - SBIT_ERROR)/sbit_max; if (tmp <= 0) tmp = 0; else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1) tmp = pow(tmp, vi->file_inverse); tmp = gamma_component_compose(do_background, tmp, alpha, background, NULL); if (output_is_encoded && tmp > 0 && tmp < 1) tmp = pow(tmp, vi->screen_inverse); is_lo = ceil(outmax * tmp - vi->maxout_total); if (is_lo < 0) is_lo = 0; tmp = (isbit + SBIT_ERROR)/sbit_max; if (tmp >= 1) tmp = 1; else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1) tmp = pow(tmp, vi->file_inverse); tmp = gamma_component_compose(do_background, tmp, alpha, background, NULL); if (output_is_encoded && tmp > 0 && tmp < 1) tmp = pow(tmp, vi->screen_inverse); is_hi = floor(outmax * tmp + vi->maxout_total); if (is_hi > outmax) is_hi = outmax; if (!(od < is_lo || od > is_hi)) { if (encoded_error < vi->outlog) return i; pass = "within input precision limits:\n"; } /* One last chance. If this is an alpha channel and the 16to8 * option has been used and 'inaccurate' scaling is used then the * bit reduction is obtained by simply using the top 8 bits of the * value. * * This is only done for older libpng versions when the 'inaccurate' * (chop) method of scaling was used. */ # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER < 10504 /* This may be required for other components in the future, * but at present the presence of gamma correction effectively * prevents the errors in the component scaling (I don't quite * understand why, but since it's better this way I care not * to ask, JB 20110419.) */ if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 && vi->sbit + vi->isbit_shift == 16) { tmp = ((id >> 8) - .5)/255; if (tmp > 0) { is_lo = ceil(outmax * tmp - vi->maxout_total); if (is_lo < 0) is_lo = 0; } else is_lo = 0; tmp = ((id >> 8) + .5)/255; if (tmp < 1) { is_hi = floor(outmax * tmp + vi->maxout_total); if (is_hi > outmax) is_hi = outmax; } else is_hi = outmax; if (!(od < is_lo || od > is_hi)) { if (encoded_error < vi->outlog) return i; pass = "within 8 bit limits:\n"; } } # endif # endif } else /* !use_input_precision */ is_lo = es_lo, is_hi = es_hi; /* Attempt to output a meaningful error/warning message: the message * output depends on the background/composite operation being performed * because this changes what parameters were actually used above. */ { size_t pos = 0; /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal * places. Just use outmax to work out which. */ int precision = (outmax >= 1000 ? 6 : 3); int use_input=1, use_background=0, do_compose=0; char msg[256]; if (pass != 0) pos = safecat(msg, sizeof msg, pos, "\n\t"); /* Set up the various flags, the output_is_encoded flag above * is also used below. do_compose is just a double check. */ switch (do_background) { # ifdef PNG_READ_BACKGROUND_SUPPORTED case PNG_BACKGROUND_GAMMA_SCREEN: case PNG_BACKGROUND_GAMMA_FILE: case PNG_BACKGROUND_GAMMA_UNIQUE: use_background = (alpha >= 0 && alpha < 1); /*FALL THROUGH*/ # endif # ifdef PNG_READ_ALPHA_MODE_SUPPORTED case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD: case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN: case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED: # endif /* ALPHA_MODE_SUPPORTED */ do_compose = (alpha > 0 && alpha < 1); use_input = (alpha != 0); break; default: break; } /* Check the 'compose' flag */ if (compose != do_compose) png_error(vi->pp, "internal error (compose)"); /* 'name' is the component name */ pos = safecat(msg, sizeof msg, pos, name); pos = safecat(msg, sizeof msg, pos, "("); pos = safecatn(msg, sizeof msg, pos, id); if (use_input || pass != 0/*logging*/) { if (isbit != id) { /* sBIT has reduced the precision of the input: */ pos = safecat(msg, sizeof msg, pos, ", sbit("); pos = safecatn(msg, sizeof msg, pos, vi->sbit); pos = safecat(msg, sizeof msg, pos, "): "); pos = safecatn(msg, sizeof msg, pos, isbit); } pos = safecat(msg, sizeof msg, pos, "/"); /* The output is either "id/max" or "id sbit(sbit): isbit/max" */ pos = safecatn(msg, sizeof msg, pos, vi->sbit_max); } pos = safecat(msg, sizeof msg, pos, ")"); /* A component may have been multiplied (in linear space) by the * alpha value, 'compose' says whether this is relevant. */ if (compose || pass != 0) { /* If any form of composition is being done report our * calculated linear value here (the code above doesn't record * the input value before composition is performed, so what * gets reported is the value after composition.) */ if (use_input || pass != 0) { if (vi->file_inverse > 0) { pos = safecat(msg, sizeof msg, pos, "^"); pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2); } else pos = safecat(msg, sizeof msg, pos, "[linear]"); pos = safecat(msg, sizeof msg, pos, "*(alpha)"); pos = safecatd(msg, sizeof msg, pos, alpha, precision); } /* Now record the *linear* background value if it was used * (this function is not passed the original, non-linear, * value but it is contained in the test name.) */ if (use_background) { pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " "); pos = safecat(msg, sizeof msg, pos, "(background)"); pos = safecatd(msg, sizeof msg, pos, background, precision); pos = safecat(msg, sizeof msg, pos, "*"); pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision); } } /* Report the calculated value (input_sample) and the linearized * libpng value (output) unless this is just a component gamma * correction. */ if (compose || alpha < 0 || pass != 0) { pos = safecat(msg, sizeof msg, pos, pass != 0 ? " =\n\t" : " = "); pos = safecatd(msg, sizeof msg, pos, input_sample, precision); pos = safecat(msg, sizeof msg, pos, " (libpng: "); pos = safecatd(msg, sizeof msg, pos, output, precision); pos = safecat(msg, sizeof msg, pos, ")"); /* Finally report the output gamma encoding, if any. */ if (output_is_encoded) { pos = safecat(msg, sizeof msg, pos, " ^"); pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2); pos = safecat(msg, sizeof msg, pos, "(to screen) ="); } else pos = safecat(msg, sizeof msg, pos, " [screen is linear] ="); } if ((!compose && alpha >= 0) || pass != 0) { if (pass != 0) /* logging */ pos = safecat(msg, sizeof msg, pos, "\n\t[overall:"); /* This is the non-composition case, the internal linear * values are irrelevant (though the log below will reveal * them.) Output a much shorter warning/error message and report * the overall gamma correction. */ if (vi->gamma_correction > 0) { pos = safecat(msg, sizeof msg, pos, " ^"); pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2); pos = safecat(msg, sizeof msg, pos, "(gamma correction) ="); } else pos = safecat(msg, sizeof msg, pos, " [no gamma correction] ="); if (pass != 0) pos = safecat(msg, sizeof msg, pos, "]"); } /* This is our calculated encoded_sample which should (but does * not) match od: */ pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " "); pos = safecatd(msg, sizeof msg, pos, is_lo, 1); pos = safecat(msg, sizeof msg, pos, " < "); pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1); pos = safecat(msg, sizeof msg, pos, " (libpng: "); pos = safecatn(msg, sizeof msg, pos, od); pos = safecat(msg, sizeof msg, pos, ")"); pos = safecat(msg, sizeof msg, pos, "/"); pos = safecatn(msg, sizeof msg, pos, outmax); pos = safecat(msg, sizeof msg, pos, " < "); pos = safecatd(msg, sizeof msg, pos, is_hi, 1); if (pass == 0) /* The error condition */ { # ifdef PNG_WARNINGS_SUPPORTED png_warning(vi->pp, msg); # else store_warning(vi->pp, msg); # endif } else /* logging this value */ store_verbose(&vi->dp->pm->this, vi->pp, pass, msg); } } } return i; } static void gamma_image_validate(gamma_display *dp, png_const_structp pp, png_infop pi) { /* Get some constants derived from the input and output file formats: */ const png_store* const ps = dp->this.ps; const png_byte in_ct = dp->this.colour_type; const png_byte in_bd = dp->this.bit_depth; const png_uint_32 w = dp->this.w; const png_uint_32 h = dp->this.h; const size_t cbRow = dp->this.cbRow; const png_byte out_ct = png_get_color_type(pp, pi); const png_byte out_bd = png_get_bit_depth(pp, pi); /* There are three sources of error, firstly the quantization in the * file encoding, determined by sbit and/or the file depth, secondly * the output (screen) gamma and thirdly the output file encoding. * * Since this API receives the screen and file gamma in double * precision it is possible to calculate an exact answer given an input * pixel value. Therefore we assume that the *input* value is exact - * sample/maxsample - calculate the corresponding gamma corrected * output to the limits of double precision arithmetic and compare with * what libpng returns. * * Since the library must quantize the output to 8 or 16 bits there is * a fundamental limit on the accuracy of the output of +/-.5 - this * quantization limit is included in addition to the other limits * specified by the paramaters to the API. (Effectively, add .5 * everywhere.) * * The behavior of the 'sbit' paramter is defined by section 12.5 * (sample depth scaling) of the PNG spec. That section forces the * decoder to assume that the PNG values have been scaled if sBIT is * present: * * png-sample = floor( input-sample * (max-out/max-in) + .5); * * This means that only a subset of the possible PNG values should * appear in the input. However, the spec allows the encoder to use a * variety of approximations to the above and doesn't require any * restriction of the values produced. * * Nevertheless the spec requires that the upper 'sBIT' bits of the * value stored in a PNG file be the original sample bits. * Consequently the code below simply scales the top sbit bits by * (1<this.palette; const int in_is_transparent = dp->this.is_transparent; int process_tRNS; int out_npalette = -1; int out_is_transparent = 0; /* Just refers to the palette case */ store_palette out_palette; validate_info vi; /* Check for row overwrite errors */ store_image_check(dp->this.ps, pp, 0); /* Supply the input and output sample depths here - 8 for an indexed image, * otherwise the bit depth. */ init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd); processing = (vi.gamma_correction > 0 && !dp->threshold_test) || in_bd != out_bd || in_ct != out_ct || vi.do_background; process_tRNS = dp->this.has_tRNS && vi.do_background; /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside * the palette there is no way of finding out, because libpng fails to * update the palette on png_read_update_info. Indeed, libpng doesn't * even do the required work until much later, when it doesn't have any * info pointer. Oops. For the moment 'processing' is turned off if * out_ct is palette. */ if (in_ct == 3 && out_ct == 3) processing = 0; if (processing && out_ct == 3) out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi); for (y=0; ythis.palette[in_index].alpha : sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0); unsigned int output_alpha = 65536 /* as a flag value */; if (out_ct == 3) { if (out_is_transparent) output_alpha = out_palette[out_index].alpha; } else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0) output_alpha = sample(pRow, out_ct, out_bd, x, samples_per_pixel, 0, 0); if (output_alpha != 65536) alpha = gamma_component_validate("alpha", &vi, input_alpha, output_alpha, -1/*alpha*/, 0/*background*/); else /* no alpha in output */ { /* This is a copy of the calculation of 'i' above in order to * have the alpha value to use in the background calculation. */ alpha = input_alpha >> vi.isbit_shift; alpha /= vi.sbit_max; } } else if (process_tRNS) { /* alpha needs to be set appropriately for this pixel, it is * currently 1 and needs to be 0 for an input pixel which matches * the values in tRNS. */ switch (in_ct) { case 0: /* gray */ if (sample(std, in_ct, in_bd, x, 0, 0, 0) == dp->this.transparent.red) alpha = 0; break; case 2: /* RGB */ if (sample(std, in_ct, in_bd, x, 0, 0, 0) == dp->this.transparent.red && sample(std, in_ct, in_bd, x, 1, 0, 0) == dp->this.transparent.green && sample(std, in_ct, in_bd, x, 2, 0, 0) == dp->this.transparent.blue) alpha = 0; break; default: break; } } /* Handle grayscale or RGB components. */ if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */ (void)gamma_component_validate("gray", &vi, sample(std, in_ct, in_bd, x, 0, 0, 0), sample(pRow, out_ct, out_bd, x, 0, 0, 0), alpha/*component*/, vi.background_red); else /* RGB or palette */ { (void)gamma_component_validate("red", &vi, in_ct == 3 ? in_palette[in_index].red : sample(std, in_ct, in_bd, x, 0, 0, 0), out_ct == 3 ? out_palette[out_index].red : sample(pRow, out_ct, out_bd, x, 0, 0, 0), alpha/*component*/, vi.background_red); (void)gamma_component_validate("green", &vi, in_ct == 3 ? in_palette[in_index].green : sample(std, in_ct, in_bd, x, 1, 0, 0), out_ct == 3 ? out_palette[out_index].green : sample(pRow, out_ct, out_bd, x, 1, 0, 0), alpha/*component*/, vi.background_green); (void)gamma_component_validate("blue", &vi, in_ct == 3 ? in_palette[in_index].blue : sample(std, in_ct, in_bd, x, 2, 0, 0), out_ct == 3 ? out_palette[out_index].blue : sample(pRow, out_ct, out_bd, x, 2, 0, 0), alpha/*component*/, vi.background_blue); } } } else if (memcmp(std, pRow, cbRow) != 0) { char msg[64]; /* No transform is expected on the threshold tests. */ sprintf(msg, "gamma: below threshold row %lu changed", (unsigned long)y); png_error(pp, msg); } } /* row (y) loop */ dp->this.ps->validated = 1; } static void PNGCBAPI gamma_end(png_structp ppIn, png_infop pi) { png_const_structp pp = ppIn; gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp)); if (!dp->this.speed) gamma_image_validate(dp, pp, pi); else dp->this.ps->validated = 1; } /* A single test run checking a gamma transformation. * * maxabs: maximum absolute error as a fraction * maxout: maximum output error in the output units * maxpc: maximum percentage error (as a percentage) */ static void gamma_test(png_modifier *pmIn, const png_byte colour_typeIn, const png_byte bit_depthIn, const int palette_numberIn, const int interlace_typeIn, const double file_gammaIn, const double screen_gammaIn, const png_byte sbitIn, const int threshold_testIn, const char *name, const int use_input_precisionIn, const int scale16In, const int expand16In, const int do_backgroundIn, const png_color_16 *bkgd_colorIn, double bkgd_gammaIn) { gamma_display d; context(&pmIn->this, fault); gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn, palette_numberIn, interlace_typeIn, 0, 0, 0), file_gammaIn, screen_gammaIn, sbitIn, threshold_testIn, use_input_precisionIn, scale16In, expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn); Try { png_structp pp; png_infop pi; gama_modification gama_mod; srgb_modification srgb_mod; sbit_modification sbit_mod; /* For the moment don't use the png_modifier support here. */ d.pm->encoding_counter = 0; modifier_set_encoding(d.pm); /* Just resets everything */ d.pm->current_gamma = d.file_gamma; /* Make an appropriate modifier to set the PNG file gamma to the * given gamma value and the sBIT chunk to the given precision. */ d.pm->modifications = NULL; gama_modification_init(&gama_mod, d.pm, d.file_gamma); srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/); if (d.sbit > 0) sbit_modification_init(&sbit_mod, d.pm, d.sbit); modification_reset(d.pm->modifications); /* Get a png_struct for reading the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, name); standard_palette_init(&d.this); /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row, gamma_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ gamma_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) gamma_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); if (d.pm->log && !d.threshold_test && !d.this.speed) fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n", d.this.bit_depth, colour_types[d.this.colour_type], name, d.maxerrout, d.maxerrabs, 100*d.maxerrpc); /* Log the summary values too. */ if (d.this.colour_type == 0 || d.this.colour_type == 4) { switch (d.this.bit_depth) { case 1: break; case 2: if (d.maxerrout > d.pm->error_gray_2) d.pm->error_gray_2 = d.maxerrout; break; case 4: if (d.maxerrout > d.pm->error_gray_4) d.pm->error_gray_4 = d.maxerrout; break; case 8: if (d.maxerrout > d.pm->error_gray_8) d.pm->error_gray_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_gray_16) d.pm->error_gray_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 1)"); } } else if (d.this.colour_type == 2 || d.this.colour_type == 6) { switch (d.this.bit_depth) { case 8: if (d.maxerrout > d.pm->error_color_8) d.pm->error_color_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_color_16) d.pm->error_color_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 2)"); } } else if (d.this.colour_type == 3) { if (d.maxerrout > d.pm->error_indexed) d.pm->error_indexed = d.maxerrout; } } Catch(fault) modifier_reset(voidcast(png_modifier*,(void*)fault)); } static void gamma_threshold_test(png_modifier *pm, png_byte colour_type, png_byte bit_depth, int interlace_type, double file_gamma, double screen_gamma) { size_t pos = 0; char name[64]; pos = safecat(name, sizeof name, pos, "threshold "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "/"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type, file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name, 0 /*no input precision*/, 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/, 0 /*no background gamma*/); } static void perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! * * CHANGED: now test two palettes and, as a side effect, images with and * without tRNS. */ while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_threshold, pm->test_tRNS)) if (palette_number < 2) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); if (fail(pm)) return; } } static void gamma_transform_test(png_modifier *pm, const png_byte colour_type, const png_byte bit_depth, const int palette_number, const int interlace_type, const double file_gamma, const double screen_gamma, const png_byte sbit, const int use_input_precision, const int scale16) { size_t pos = 0; char name[64]; if (sbit != bit_depth && sbit != 0) { pos = safecat(name, sizeof name, pos, "sbit("); pos = safecatn(name, sizeof name, pos, sbit); pos = safecat(name, sizeof name, pos, ") "); } else pos = safecat(name, sizeof name, pos, "gamma "); if (scale16) pos = safecat(name, sizeof name, pos, "16to8 "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "->"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type, file_gamma, screen_gamma, sbit, 0, name, use_input_precision, scale16, pm->test_gamma_expand16, 0 , 0, 0); } static void perform_gamma_transform_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_transform, pm->test_tRNS)) { unsigned int i, j; for (i=0; ingamma_tests; ++i) for (j=0; jngamma_tests; ++j) if (i != j) { gamma_transform_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/, pm->use_input_precision, 0 /*do not scale16*/); if (fail(pm)) return; } } } static void perform_gamma_sbit_tests(png_modifier *pm) { png_byte sbit; /* The only interesting cases are colour and grayscale, alpha is ignored here * for overall speed. Only bit depths where sbit is less than the bit depth * are tested. */ for (sbit=pm->sbitlow; sbit<(1<test_lbg_gamma_sbit, pm->test_tRNS)) if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 && ((colour_type == 3 && sbit < 8) || (colour_type != 3 && sbit < bit_depth))) { unsigned int i; for (i=0; ingamma_tests; ++i) { unsigned int j; for (j=0; jngamma_tests; ++j) if (i != j) { gamma_transform_test(pm, colour_type, bit_depth, npalette, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], sbit, pm->use_input_precision_sbit, 0 /*scale16*/); if (fail(pm)) return; } } } } } /* Note that this requires a 16 bit source image but produces 8 bit output, so * we only need the 16bit write support, but the 16 bit images are only * generated if DO_16BIT is defined. */ #ifdef DO_16BIT static void perform_gamma_scale16_tests(png_modifier *pm) { # ifndef PNG_MAX_GAMMA_8 # define PNG_MAX_GAMMA_8 11 # endif # if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700 # define SBIT_16_TO_8 PNG_MAX_GAMMA_8 # else # define SBIT_16_TO_8 16 # endif /* Include the alpha cases here. Note that sbit matches the internal value * used by the library - otherwise we will get spurious errors from the * internal sbit style approximation. * * The threshold test is here because otherwise the 16 to 8 conversion will * proceed *without* gamma correction, and the tests above will fail (but not * by much) - this could be fixed, it only appears with the -g option. */ unsigned int i, j; for (i=0; ingamma_tests; ++i) { for (j=0; jngamma_tests; ++j) { if (i != j && fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD) { gamma_transform_test(pm, 0, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 2, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 4, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 6, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; } } } } #endif /* 16 to 8 bit conversion */ #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\ defined(PNG_READ_ALPHA_MODE_SUPPORTED) static void gamma_composition_test(png_modifier *pm, const png_byte colour_type, const png_byte bit_depth, const int palette_number, const int interlace_type, const double file_gamma, const double screen_gamma, const int use_input_precision, const int do_background, const int expand_16) { size_t pos = 0; png_const_charp base; double bg; char name[128]; png_color_16 background; /* Make up a name and get an appropriate background gamma value. */ switch (do_background) { default: base = ""; bg = 4; /* should not be used */ break; case PNG_BACKGROUND_GAMMA_SCREEN: base = " bckg(Screen):"; bg = 1/screen_gamma; break; case PNG_BACKGROUND_GAMMA_FILE: base = " bckg(File):"; bg = file_gamma; break; case PNG_BACKGROUND_GAMMA_UNIQUE: base = " bckg(Unique):"; /* This tests the handling of a unique value, the math is such that the * value tends to be <1, but is neither screen nor file (even if they * match!) */ bg = (file_gamma + screen_gamma) / 3; break; #ifdef PNG_READ_ALPHA_MODE_SUPPORTED case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG: base = " alpha(PNG)"; bg = 4; /* should not be used */ break; case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD: base = " alpha(Porter-Duff)"; bg = 4; /* should not be used */ break; case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED: base = " alpha(Optimized)"; bg = 4; /* should not be used */ break; case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN: base = " alpha(Broken)"; bg = 4; /* should not be used */ break; #endif } /* Use random background values - the background is always presented in the * output space (8 or 16 bit components). */ if (expand_16 || bit_depth == 16) { png_uint_32 r = random_32(); background.red = (png_uint_16)r; background.green = (png_uint_16)(r >> 16); r = random_32(); background.blue = (png_uint_16)r; background.gray = (png_uint_16)(r >> 16); /* In earlier libpng versions, those where DIGITIZE is set, any background * gamma correction in the expand16 case was done using 8-bit gamma * correction tables, resulting in larger errors. To cope with those * cases use a 16-bit background value which will handle this gamma * correction. */ # if DIGITIZE if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE || do_background == PNG_BACKGROUND_GAMMA_FILE) && fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD) { /* The background values will be looked up in an 8-bit table to do * the gamma correction, so only select values which are an exact * match for the 8-bit table entries: */ background.red = (png_uint_16)((background.red >> 8) * 257); background.green = (png_uint_16)((background.green >> 8) * 257); background.blue = (png_uint_16)((background.blue >> 8) * 257); background.gray = (png_uint_16)((background.gray >> 8) * 257); } # endif } else /* 8 bit colors */ { png_uint_32 r = random_32(); background.red = (png_byte)r; background.green = (png_byte)(r >> 8); background.blue = (png_byte)(r >> 16); background.gray = (png_byte)(r >> 24); } background.index = 193; /* rgb(193,193,193) to detect errors */ if (!(colour_type & PNG_COLOR_MASK_COLOR)) { /* Because, currently, png_set_background is always called with * 'need_expand' false in this case and because the gamma test itself * doesn't cause an expand to 8-bit for lower bit depths the colour must * be reduced to the correct range. */ if (bit_depth < 8) background.gray &= (png_uint_16)((1U << bit_depth)-1); /* Grayscale input, we do not convert to RGB (TBD), so we must set the * background to gray - else libpng seems to fail. */ background.red = background.green = background.blue = background.gray; } pos = safecat(name, sizeof name, pos, "gamma "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "->"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); pos = safecat(name, sizeof name, pos, base); if (do_background < ALPHA_MODE_OFFSET) { /* Include the background color and gamma in the name: */ pos = safecat(name, sizeof name, pos, "("); /* This assumes no expand gray->rgb - the current code won't handle that! */ if (colour_type & PNG_COLOR_MASK_COLOR) { pos = safecatn(name, sizeof name, pos, background.red); pos = safecat(name, sizeof name, pos, ","); pos = safecatn(name, sizeof name, pos, background.green); pos = safecat(name, sizeof name, pos, ","); pos = safecatn(name, sizeof name, pos, background.blue); } else pos = safecatn(name, sizeof name, pos, background.gray); pos = safecat(name, sizeof name, pos, ")^"); pos = safecatd(name, sizeof name, pos, bg, 3); } gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type, file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision, 0/*strip 16*/, expand_16, do_background, &background, bg); } static void perform_gamma_composition_tests(png_modifier *pm, int do_background, int expand_16) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Skip the non-alpha cases - there is no setting of a transparency colour at * present. * * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do, * however the palette case fails miserably so is commented out below. */ while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_composition, pm->test_tRNS)) if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0 #if 0 /* TODO: FIXME */ /*TODO: FIXME: this should work */ || colour_type == 3 #endif || (colour_type != 3 && palette_number != 0)) { unsigned int i, j; /* Don't skip the i==j case here - it's relevant. */ for (i=0; ingamma_tests; ++i) for (j=0; jngamma_tests; ++j) { gamma_composition_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], pm->use_input_precision, do_background, expand_16); if (fail(pm)) return; } } } #endif /* READ_BACKGROUND || READ_ALPHA_MODE */ static void init_gamma_errors(png_modifier *pm) { /* Use -1 to catch tests that were not actually run */ pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.; pm->error_color_8 = -1.; pm->error_indexed = -1.; pm->error_gray_16 = pm->error_color_16 = -1.; } static void print_one(const char *leader, double err) { if (err != -1.) printf(" %s %.5f\n", leader, err); } static void summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth, int indexed) { fflush(stderr); if (who) printf("\nGamma correction with %s:\n", who); else printf("\nBasic gamma correction:\n"); if (low_bit_depth) { print_one(" 2 bit gray: ", pm->error_gray_2); print_one(" 4 bit gray: ", pm->error_gray_4); print_one(" 8 bit gray: ", pm->error_gray_8); print_one(" 8 bit color:", pm->error_color_8); if (indexed) print_one(" indexed: ", pm->error_indexed); } print_one("16 bit gray: ", pm->error_gray_16); print_one("16 bit color:", pm->error_color_16); fflush(stdout); } static void perform_gamma_test(png_modifier *pm, int summary) { /*TODO: remove this*/ /* Save certain values for the temporary overrides below. */ unsigned int calculations_use_input_precision = pm->calculations_use_input_precision; # ifdef PNG_READ_BACKGROUND_SUPPORTED double maxout8 = pm->maxout8; # endif /* First some arbitrary no-transform tests: */ if (!pm->this.speed && pm->test_gamma_threshold) { perform_gamma_threshold_tests(pm); if (fail(pm)) return; } /* Now some real transforms. */ if (pm->test_gamma_transform) { if (summary) { fflush(stderr); printf("Gamma correction error summary\n\n"); printf("The printed value is the maximum error in the pixel values\n"); printf("calculated by the libpng gamma correction code. The error\n"); printf("is calculated as the difference between the output pixel\n"); printf("value (always an integer) and the ideal value from the\n"); printf("libpng specification (typically not an integer).\n\n"); printf("Expect this value to be less than .5 for 8 bit formats,\n"); printf("less than 1 for formats with fewer than 8 bits and a small\n"); printf("number (typically less than 5) for the 16 bit formats.\n"); printf("For performance reasons the value for 16 bit formats\n"); printf("increases when the image file includes an sBIT chunk.\n"); fflush(stdout); } init_gamma_errors(pm); /*TODO: remove this. Necessary because the current libpng * implementation works in 8 bits: */ if (pm->test_gamma_expand16) pm->calculations_use_input_precision = 1; perform_gamma_transform_tests(pm); if (!calculations_use_input_precision) pm->calculations_use_input_precision = 0; if (summary) summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/); if (fail(pm)) return; } /* The sbit tests produce much larger errors: */ if (pm->test_gamma_sbit) { init_gamma_errors(pm); perform_gamma_sbit_tests(pm); if (summary) summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/); if (fail(pm)) return; } #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */ if (pm->test_gamma_scale16) { /* The 16 to 8 bit strip operations: */ init_gamma_errors(pm); perform_gamma_scale16_tests(pm); if (summary) { fflush(stderr); printf("\nGamma correction with 16 to 8 bit reduction:\n"); printf(" 16 bit gray: %.5f\n", pm->error_gray_16); printf(" 16 bit color: %.5f\n", pm->error_color_16); fflush(stdout); } if (fail(pm)) return; } #endif #ifdef PNG_READ_BACKGROUND_SUPPORTED if (pm->test_gamma_background) { init_gamma_errors(pm); /*TODO: remove this. Necessary because the current libpng * implementation works in 8 bits: */ if (pm->test_gamma_expand16) { pm->calculations_use_input_precision = 1; pm->maxout8 = .499; /* because the 16 bit background is smashed */ } perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE, pm->test_gamma_expand16); if (!calculations_use_input_precision) pm->calculations_use_input_precision = 0; pm->maxout8 = maxout8; if (summary) summarize_gamma_errors(pm, "background", 1, 0/*indexed*/); if (fail(pm)) return; } #endif #ifdef PNG_READ_ALPHA_MODE_SUPPORTED if (pm->test_gamma_alpha_mode) { int do_background; init_gamma_errors(pm); /*TODO: remove this. Necessary because the current libpng * implementation works in 8 bits: */ if (pm->test_gamma_expand16) pm->calculations_use_input_precision = 1; for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD; do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm); ++do_background) perform_gamma_composition_tests(pm, do_background, pm->test_gamma_expand16); if (!calculations_use_input_precision) pm->calculations_use_input_precision = 0; if (summary) summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/); if (fail(pm)) return; } #endif } #endif /* PNG_READ_GAMMA_SUPPORTED */ #endif /* PNG_READ_SUPPORTED */ /* INTERLACE MACRO VALIDATION */ /* This is copied verbatim from the specification, it is simply the pass * number in which each pixel in each 8x8 tile appears. The array must * be indexed adam7[y][x] and notice that the pass numbers are based at * 1, not 0 - the base libpng uses. */ static const png_byte adam7[8][8] = { { 1,6,4,6,2,6,4,6 }, { 7,7,7,7,7,7,7,7 }, { 5,6,5,6,5,6,5,6 }, { 7,7,7,7,7,7,7,7 }, { 3,6,4,6,3,6,4,6 }, { 7,7,7,7,7,7,7,7 }, { 5,6,5,6,5,6,5,6 }, { 7,7,7,7,7,7,7,7 } }; /* This routine validates all the interlace support macros in png.h for * a variety of valid PNG widths and heights. It uses a number of similarly * named internal routines that feed off the above array. */ static png_uint_32 png_pass_start_row(int pass) { int x, y; ++pass; for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass) return y; return 0xf; } static png_uint_32 png_pass_start_col(int pass) { int x, y; ++pass; for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass) return x; return 0xf; } static int png_pass_row_shift(int pass) { int x, y, base=(-1), inc=8; ++pass; for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass) { if (base == (-1)) base = y; else if (base == y) {} else if (inc == y-base) base=y; else if (inc == 8) inc = y-base, base=y; else if (inc != y-base) return 0xff; /* error - more than one 'inc' value! */ } if (base == (-1)) return 0xfe; /* error - no row in pass! */ /* The shift is always 1, 2 or 3 - no pass has all the rows! */ switch (inc) { case 2: return 1; case 4: return 2; case 8: return 3; default: break; } /* error - unrecognized 'inc' */ return (inc << 8) + 0xfd; } static int png_pass_col_shift(int pass) { int x, y, base=(-1), inc=8; ++pass; for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass) { if (base == (-1)) base = x; else if (base == x) {} else if (inc == x-base) base=x; else if (inc == 8) inc = x-base, base=x; else if (inc != x-base) return 0xff; /* error - more than one 'inc' value! */ } if (base == (-1)) return 0xfe; /* error - no row in pass! */ /* The shift is always 1, 2 or 3 - no pass has all the rows! */ switch (inc) { case 1: return 0; /* pass 7 has all the columns */ case 2: return 1; case 4: return 2; case 8: return 3; default: break; } /* error - unrecognized 'inc' */ return (inc << 8) + 0xfd; } static png_uint_32 png_row_from_pass_row(png_uint_32 yIn, int pass) { /* By examination of the array: */ switch (pass) { case 0: return yIn * 8; case 1: return yIn * 8; case 2: return yIn * 8 + 4; case 3: return yIn * 4; case 4: return yIn * 4 + 2; case 5: return yIn * 2; case 6: return yIn * 2 + 1; default: break; } return 0xff; /* bad pass number */ } static png_uint_32 png_col_from_pass_col(png_uint_32 xIn, int pass) { /* By examination of the array: */ switch (pass) { case 0: return xIn * 8; case 1: return xIn * 8 + 4; case 2: return xIn * 4; case 3: return xIn * 4 + 2; case 4: return xIn * 2; case 5: return xIn * 2 + 1; case 6: return xIn; default: break; } return 0xff; /* bad pass number */ } static int png_row_in_interlace_pass(png_uint_32 y, int pass) { /* Is row 'y' in pass 'pass'? */ int x; y &= 7; ++pass; for (x=0; x<8; ++x) if (adam7[y][x] == pass) return 1; return 0; } static int png_col_in_interlace_pass(png_uint_32 x, int pass) { /* Is column 'x' in pass 'pass'? */ int y; x &= 7; ++pass; for (y=0; y<8; ++y) if (adam7[y][x] == pass) return 1; return 0; } static png_uint_32 png_pass_rows(png_uint_32 height, int pass) { png_uint_32 tiles = height>>3; png_uint_32 rows = 0; unsigned int x, y; height &= 7; ++pass; for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass) { rows += tiles; if (y < height) ++rows; break; /* i.e. break the 'x', column, loop. */ } return rows; } static png_uint_32 png_pass_cols(png_uint_32 width, int pass) { png_uint_32 tiles = width>>3; png_uint_32 cols = 0; unsigned int x, y; width &= 7; ++pass; for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass) { cols += tiles; if (x < width) ++cols; break; /* i.e. break the 'y', row, loop. */ } return cols; } static void perform_interlace_macro_validation(void) { /* The macros to validate, first those that depend only on pass: * * PNG_PASS_START_ROW(pass) * PNG_PASS_START_COL(pass) * PNG_PASS_ROW_SHIFT(pass) * PNG_PASS_COL_SHIFT(pass) */ int pass; for (pass=0; pass<7; ++pass) { png_uint_32 m, f, v; m = PNG_PASS_START_ROW(pass); f = png_pass_start_row(pass); if (m != f) { fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f); exit(99); } m = PNG_PASS_START_COL(pass); f = png_pass_start_col(pass); if (m != f) { fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f); exit(99); } m = PNG_PASS_ROW_SHIFT(pass); f = png_pass_row_shift(pass); if (m != f) { fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f); exit(99); } m = PNG_PASS_COL_SHIFT(pass); f = png_pass_col_shift(pass); if (m != f) { fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f); exit(99); } /* Macros that depend on the image or sub-image height too: * * PNG_PASS_ROWS(height, pass) * PNG_PASS_COLS(width, pass) * PNG_ROW_FROM_PASS_ROW(yIn, pass) * PNG_COL_FROM_PASS_COL(xIn, pass) * PNG_ROW_IN_INTERLACE_PASS(y, pass) * PNG_COL_IN_INTERLACE_PASS(x, pass) */ for (v=0;;) { /* First the base 0 stuff: */ m = PNG_ROW_FROM_PASS_ROW(v, pass); f = png_row_from_pass_row(v, pass); if (m != f) { fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n", v, pass, m, f); exit(99); } m = PNG_COL_FROM_PASS_COL(v, pass); f = png_col_from_pass_col(v, pass); if (m != f) { fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n", v, pass, m, f); exit(99); } m = PNG_ROW_IN_INTERLACE_PASS(v, pass); f = png_row_in_interlace_pass(v, pass); if (m != f) { fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n", v, pass, m, f); exit(99); } m = PNG_COL_IN_INTERLACE_PASS(v, pass); f = png_col_in_interlace_pass(v, pass); if (m != f) { fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n", v, pass, m, f); exit(99); } /* Then the base 1 stuff: */ ++v; m = PNG_PASS_ROWS(v, pass); f = png_pass_rows(v, pass); if (m != f) { fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n", v, pass, m, f); exit(99); } m = PNG_PASS_COLS(v, pass); f = png_pass_cols(v, pass); if (m != f) { fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n", v, pass, m, f); exit(99); } /* Move to the next v - the stepping algorithm starts skipping * values above 1024. */ if (v > 1024) { if (v == PNG_UINT_31_MAX) break; v = (v << 1) ^ v; if (v >= PNG_UINT_31_MAX) v = PNG_UINT_31_MAX-1; } } } } /* Test color encodings. These values are back-calculated from the published * chromaticities. The values are accurate to about 14 decimal places; 15 are * given. These values are much more accurate than the ones given in the spec, * which typically don't exceed 4 decimal places. This allows testing of the * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid * used the published errors the 'slack' permitted would have to be +/-.5E-4 or * more.) * * The png_modifier code assumes that encodings[0] is sRGB and treats it * specially: do not change the first entry in this list! */ static const color_encoding test_encodings[] = { /* sRGB: must be first in this list! */ /*gamma:*/ { 1/2.2, /*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 }, /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 }, /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} }, /* Kodak ProPhoto (wide gamut) */ /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/, /*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 }, /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 }, /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} }, /* Adobe RGB (1998) */ /*gamma:*/ { 1/(2+51./256), /*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 }, /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 }, /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} }, /* Adobe Wide Gamut RGB */ /*gamma:*/ { 1/(2+51./256), /*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 }, /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 }, /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} }, /* Fake encoding which selects just the green channel */ /*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */ /*red: */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 }, /*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 }, /*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} }, }; /* signal handler * * This attempts to trap signals and escape without crashing. It needs a * context pointer so that it can throw an exception (call longjmp) to recover * from the condition; this is handled by making the png_modifier used by 'main' * into a global variable. */ static png_modifier pm; static void signal_handler(int signum) { size_t pos = 0; char msg[64]; pos = safecat(msg, sizeof msg, pos, "caught signal: "); switch (signum) { case SIGABRT: pos = safecat(msg, sizeof msg, pos, "abort"); break; case SIGFPE: pos = safecat(msg, sizeof msg, pos, "floating point exception"); break; case SIGILL: pos = safecat(msg, sizeof msg, pos, "illegal instruction"); break; case SIGINT: pos = safecat(msg, sizeof msg, pos, "interrupt"); break; case SIGSEGV: pos = safecat(msg, sizeof msg, pos, "invalid memory access"); break; case SIGTERM: pos = safecat(msg, sizeof msg, pos, "termination request"); break; default: pos = safecat(msg, sizeof msg, pos, "unknown "); pos = safecatn(msg, sizeof msg, pos, signum); break; } store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/); /* And finally throw an exception so we can keep going, unless this is * SIGTERM in which case stop now. */ if (signum != SIGTERM) { struct exception_context *the_exception_context = &pm.this.exception_context; Throw &pm.this; } else exit(1); } /* main program */ int main(int argc, char **argv) { int summary = 1; /* Print the error summary at the end */ int memstats = 0; /* Print memory statistics at the end */ /* Create the given output file on success: */ const char *touch = NULL; /* This is an array of standard gamma values (believe it or not I've seen * every one of these mentioned somewhere.) * * In the following list the most useful values are first! */ static double gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9}; /* This records the command and arguments: */ size_t cp = 0; char command[1024]; anon_context(&pm.this); gnu_volatile(summary) gnu_volatile(memstats) gnu_volatile(touch) /* Add appropriate signal handlers, just the ANSI specified ones: */ signal(SIGABRT, signal_handler); signal(SIGFPE, signal_handler); signal(SIGILL, signal_handler); signal(SIGINT, signal_handler); signal(SIGSEGV, signal_handler); signal(SIGTERM, signal_handler); #ifdef HAVE_FEENABLEEXCEPT /* Only required to enable FP exceptions on platforms where they start off * disabled; this is not necessary but if it is not done pngvalid will likely * end up ignoring FP conditions that other platforms fault. */ feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif modifier_init(&pm); /* Preallocate the image buffer, because we know how big it needs to be, * note that, for testing purposes, it is deliberately mis-aligned by tag * bytes either side. All rows have an additional five bytes of padding for * overwrite checking. */ store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX); /* Don't give argv[0], it's normally some horrible libtool string: */ cp = safecat(command, sizeof command, cp, "pngvalid"); /* Default to error on warning: */ pm.this.treat_warnings_as_errors = 1; /* Default assume_16_bit_calculations appropriately; this tells the checking * code that 16-bit arithmetic is used for 8-bit samples when it would make a * difference. */ pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700; /* Currently 16 bit expansion happens at the end of the pipeline, so the * calculations are done in the input bit depth not the output. * * TODO: fix this */ pm.calculations_use_input_precision = 1U; /* Store the test gammas */ pm.gammas = gammas; pm.ngammas = ARRAY_SIZE(gammas); pm.ngamma_tests = 0; /* default to off */ /* Low bit depth gray images don't do well in the gamma tests, until * this is fixed turn them off for some gamma cases: */ # ifdef PNG_WRITE_tRNS_SUPPORTED pm.test_tRNS = 1; # endif pm.test_lbg = PNG_LIBPNG_VER >= 10600; pm.test_lbg_gamma_threshold = 1; pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600; pm.test_lbg_gamma_sbit = 1; pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700; /* And the test encodings */ pm.encodings = test_encodings; pm.nencodings = ARRAY_SIZE(test_encodings); # if PNG_LIBPNG_VER < 10700 pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */ # else pm.sbitlow = 1U; # endif /* The following allows results to pass if they correspond to anything in the * transformed range [input-.5,input+.5]; this is is required because of the * way libpng treates the 16_TO_8 flag when building the gamma tables in * releases up to 1.6.0. * * TODO: review this */ pm.use_input_precision_16to8 = 1U; pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */ /* Some default values (set the behavior for 'make check' here). * These values simply control the maximum error permitted in the gamma * transformations. The practial limits for human perception are described * below (the setting for maxpc16), however for 8 bit encodings it isn't * possible to meet the accepted capabilities of human vision - i.e. 8 bit * images can never be good enough, regardless of encoding. */ pm.maxout8 = .1; /* Arithmetic error in *encoded* value */ pm.maxabs8 = .00005; /* 1/20000 */ pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */ pm.maxpc8 = .499; /* I.e., .499% fractional error */ pm.maxout16 = .499; /* Error in *encoded* value */ pm.maxabs16 = .00005;/* 1/20000 */ pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */ # if PNG_LIBPNG_VER < 10700 pm.maxcalcG = 1./((1<38149 by the following: */ pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */ /* Now parse the command line options. */ while (--argc >= 1) { int catmore = 0; /* Set if the argument has an argument. */ /* Record each argument for posterity: */ cp = safecat(command, sizeof command, cp, " "); cp = safecat(command, sizeof command, cp, *++argv); if (strcmp(*argv, "-v") == 0) pm.this.verbose = 1; else if (strcmp(*argv, "-l") == 0) pm.log = 1; else if (strcmp(*argv, "-q") == 0) summary = pm.this.verbose = pm.log = 0; else if (strcmp(*argv, "-w") == 0 || strcmp(*argv, "--strict") == 0) pm.this.treat_warnings_as_errors = 1; /* NOTE: this is the default! */ else if (strcmp(*argv, "--nostrict") == 0) pm.this.treat_warnings_as_errors = 0; else if (strcmp(*argv, "--speed") == 0) pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0, summary = 0; else if (strcmp(*argv, "--memory") == 0) memstats = 1; else if (strcmp(*argv, "--size") == 0) pm.test_size = 1; else if (strcmp(*argv, "--nosize") == 0) pm.test_size = 0; else if (strcmp(*argv, "--standard") == 0) pm.test_standard = 1; else if (strcmp(*argv, "--nostandard") == 0) pm.test_standard = 0; else if (strcmp(*argv, "--transform") == 0) pm.test_transform = 1; else if (strcmp(*argv, "--notransform") == 0) pm.test_transform = 0; #ifdef PNG_READ_TRANSFORMS_SUPPORTED else if (strncmp(*argv, "--transform-disable=", sizeof "--transform-disable") == 0) { pm.test_transform = 1; transform_disable(*argv + sizeof "--transform-disable"); } else if (strncmp(*argv, "--transform-enable=", sizeof "--transform-enable") == 0) { pm.test_transform = 1; transform_enable(*argv + sizeof "--transform-enable"); } #endif /* PNG_READ_TRANSFORMS_SUPPORTED */ else if (strcmp(*argv, "--gamma") == 0) { /* Just do two gamma tests here (2.2 and linear) for speed: */ pm.ngamma_tests = 2U; pm.test_gamma_threshold = 1; pm.test_gamma_transform = 1; pm.test_gamma_sbit = 1; pm.test_gamma_scale16 = 1; pm.test_gamma_background = 1; /* composition */ pm.test_gamma_alpha_mode = 1; } else if (strcmp(*argv, "--nogamma") == 0) pm.ngamma_tests = 0; else if (strcmp(*argv, "--gamma-threshold") == 0) pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1; else if (strcmp(*argv, "--nogamma-threshold") == 0) pm.test_gamma_threshold = 0; else if (strcmp(*argv, "--gamma-transform") == 0) pm.ngamma_tests = 2U, pm.test_gamma_transform = 1; else if (strcmp(*argv, "--nogamma-transform") == 0) pm.test_gamma_transform = 0; else if (strcmp(*argv, "--gamma-sbit") == 0) pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1; else if (strcmp(*argv, "--nogamma-sbit") == 0) pm.test_gamma_sbit = 0; else if (strcmp(*argv, "--gamma-16-to-8") == 0) pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1; else if (strcmp(*argv, "--nogamma-16-to-8") == 0) pm.test_gamma_scale16 = 0; else if (strcmp(*argv, "--gamma-background") == 0) pm.ngamma_tests = 2U, pm.test_gamma_background = 1; else if (strcmp(*argv, "--nogamma-background") == 0) pm.test_gamma_background = 0; else if (strcmp(*argv, "--gamma-alpha-mode") == 0) pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1; else if (strcmp(*argv, "--nogamma-alpha-mode") == 0) pm.test_gamma_alpha_mode = 0; else if (strcmp(*argv, "--expand16") == 0) pm.test_gamma_expand16 = 1; else if (strcmp(*argv, "--noexpand16") == 0) pm.test_gamma_expand16 = 0; else if (strcmp(*argv, "--low-depth-gray") == 0) pm.test_lbg = pm.test_lbg_gamma_threshold = pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit = pm.test_lbg_gamma_composition = 1; else if (strcmp(*argv, "--nolow-depth-gray") == 0) pm.test_lbg = pm.test_lbg_gamma_threshold = pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit = pm.test_lbg_gamma_composition = 0; # ifdef PNG_WRITE_tRNS_SUPPORTED else if (strcmp(*argv, "--tRNS") == 0) pm.test_tRNS = 1; # endif else if (strcmp(*argv, "--notRNS") == 0) pm.test_tRNS = 0; else if (strcmp(*argv, "--more-gammas") == 0) pm.ngamma_tests = 3U; else if (strcmp(*argv, "--all-gammas") == 0) pm.ngamma_tests = pm.ngammas; else if (strcmp(*argv, "--progressive-read") == 0) pm.this.progressive = 1; else if (strcmp(*argv, "--use-update-info") == 0) ++pm.use_update_info; /* Can call multiple times */ else if (strcmp(*argv, "--interlace") == 0) { # if CAN_WRITE_INTERLACE pm.interlace_type = PNG_INTERLACE_ADAM7; # else /* !CAN_WRITE_INTERLACE */ fprintf(stderr, "pngvalid: no write interlace support\n"); return SKIP; # endif /* !CAN_WRITE_INTERLACE */ } else if (strcmp(*argv, "--use-input-precision") == 0) pm.use_input_precision = 1U; else if (strcmp(*argv, "--use-calculation-precision") == 0) pm.use_input_precision = 0; else if (strcmp(*argv, "--calculations-use-input-precision") == 0) pm.calculations_use_input_precision = 1U; else if (strcmp(*argv, "--assume-16-bit-calculations") == 0) pm.assume_16_bit_calculations = 1U; else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0) pm.calculations_use_input_precision = pm.assume_16_bit_calculations = 0; else if (strcmp(*argv, "--exhaustive") == 0) pm.test_exhaustive = 1; else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0) --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1; else if (argc > 1 && strcmp(*argv, "--touch") == 0) --argc, touch = *++argv, catmore = 1; else if (argc > 1 && strncmp(*argv, "--max", 5) == 0) { --argc; if (strcmp(5+*argv, "abs8") == 0) pm.maxabs8 = atof(*++argv); else if (strcmp(5+*argv, "abs16") == 0) pm.maxabs16 = atof(*++argv); else if (strcmp(5+*argv, "calc8") == 0) pm.maxcalc8 = atof(*++argv); else if (strcmp(5+*argv, "calc16") == 0) pm.maxcalc16 = atof(*++argv); else if (strcmp(5+*argv, "out8") == 0) pm.maxout8 = atof(*++argv); else if (strcmp(5+*argv, "out16") == 0) pm.maxout16 = atof(*++argv); else if (strcmp(5+*argv, "pc8") == 0) pm.maxpc8 = atof(*++argv); else if (strcmp(5+*argv, "pc16") == 0) pm.maxpc16 = atof(*++argv); else { fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv); exit(99); } catmore = 1; } else if (strcmp(*argv, "--log8") == 0) --argc, pm.log8 = atof(*++argv), catmore = 1; else if (strcmp(*argv, "--log16") == 0) --argc, pm.log16 = atof(*++argv), catmore = 1; #ifdef PNG_SET_OPTION_SUPPORTED else if (strncmp(*argv, "--option=", 9) == 0) { /* Syntax of the argument is