rpng2-x.c revision 671242f350d172e106580348e24bab66b0d7e6a5
/*---------------------------------------------------------------------------
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:
- 8-bit support
- finish resizable checkerboard-gradient (sizes 4-128?)
- use %.1023s to simplify truncation of title-bar string?
---------------------------------------------------------------------------
Changelog:
- 1.01: initial public release
- 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 small X memory leak (thanks to Francois Petitjean)
- 1.22: fixed XFreeGC() crash bug
---------------------------------------------------------------------------
Copyright (c) 1998-2001 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.
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-
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.
---------------------------------------------------------------------------*/
#define PROGNAME "rpng2-x"
#define LONGNAME "Progressive PNG Viewer for X"
#define VERSION "1.22 of 16 August 2001"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h> /* for jmpbuf declaration in readpng2.h */
#include <time.h>
#include <math.h> /* only for PvdM background code */
#ifdef VMS
# include <unistd.h>
#endif
/* all for PvdM background code: */
#ifndef PI
# define PI 3.141592653589793238
#endif
#define MAX(a,b) (a>b?a:b)
#define MIN(a,b) (a<b?a:b)
#define ABS(a) ((a)<0?-(a):(a))
#define ROUNDF(f) ((int)(f + 0.5))
/* #define DEBUG */ /* this enables the Trace() macros */
#include "readpng2.h" /* typedefs, common macros, readpng2 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);") */
}
* 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_finish_display(void);
static void rpng2_x_cleanup(void);
static char *filename;
static mainprog_info rpng2_info;
static int incount;
static int bg_image = 0;
static int bgscale = 16;
static ulg bg_rowbytes;
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 */
};
/* 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 {
} bg[] = {
{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) */
};
/* X-specific variables */
static char *displayname;
static int depth;
static XVisualInfo *visual_list;
static int have_nondefault_visual = FALSE;
static int have_colormap = FALSE;
static int have_window = FALSE;
{
#ifdef sgi
char tmpline[80];
#endif
int error = 0;
double LUT_exponent; /* just the lookup table */
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;
/* 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 */
/*
if (some_next_function_that_returns_gamma(&next_gamma))
LUT_exponent = 1.0 / next_gamma;
*/
/* there doesn't seem to be any documented function to
* get the "gamma" value, so we do it the hard way */
if (infile) {
double sgi_gamma;
if (sgi_gamma > 0.0)
}
/*
if (some_mac_function_that_returns_gamma(&mac_gamma))
LUT_exponent = mac_gamma / 2.61;
*/
#else
#endif
/* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */
/* 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. */
else
/* Now parse the command line for options and the PNG filename. */
if (!*++argv)
++error;
else
displayname = *argv;
if (!*++argv)
++error;
else {
++error;
}
if (!*++argv)
++error;
else {
++error;
else {
}
}
if (!*++argv)
++error;
else {
++error;
else {
}
}
if (!*++argv)
++error;
else {
demo_timing = TRUE;
}
#endif
} else {
if (**argv != '-') {
++error;
} else
++error; /* not expecting any other options */
}
}
if (!filename) {
++error;
++error;
} else {
": [%s] is not a PNG file: incorrect signature\n",
filename);
++error;
switch (rc) {
case 2:
": [%s] has bad IHDR (libpng longjmp)\n",
filename);
break;
case 4:
break;
default:
": unknown readpng2_init() error\n");
break;
}
++error;
} else {
if (!display) {
++error;
}
}
if (error)
}
/* usage screen */
if (error) {
"Usage: %s [-display xdpy] [-gamma exp] [-bgcolor bg | -bgpat pat]\n"
" %*s [[-nommxfilters] [-nommxcombine] [-nommxinterlace] | -nommx]\n"
#endif
" %*s [-usleep dur | -timing] [-pause] file.png\n\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"
"\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\n"
" pat \tdesired background pattern number (1-%d); used with\n"
"\t\t transparent images; overrides -bgcolor\n"
" -nommx*\tdisable optimized MMX routines for decoding row filters,\n"
"\t\t combining rows, and expanding interlacing, respectively\n"
#endif
" 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 key pressed\n"
"\nPress Q, Esc or mouse button 1 (within image window, after image\n"
"is displayed) to quit.\n"
"\n", PROGNAME,
#endif
exit(1);
}
/* set the title-bar string, but make sure buffer doesn't overflow */
else
/* set some final rpng2_info variables before entering main data loop */
if (have_bg) {
unsigned r, g, b; /* this approach quiets compiler warnings */
} else
/* 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 (;;) {
++error;
break;
if (timing)
sleep(1);
}
/* clean up PNG stuff and report any decoding errors */
if (error) {
exit(3);
}
/* wait for the user to tell us when to quit */
do
XNextEvent(display, &e);
/* we're done: clean up all image and X resources and go away */
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;
if (!rpng2_info.image_data) {
return;
}
if (!rpng2_info.row_pointers) {
return;
}
for (i = 0; i < rpng2_info.height; ++i)
/* 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 longjmp() back to us when png_ptr goes away.
/* we're here via libpng callback, so if window fails, clean and bail */
printf("readpng2_cleanup.\n");
exit(2);
}
}
static int rpng2_x_create_window(void)
{
int need_colormap = FALSE;
XEvent e;
#ifdef DEBUG
#endif
int visuals_matched = 0;
depth))
/* 24-bit first */
if (visuals_matched == 0) {
/* GRR: add 15-, 16- and 32-bit TrueColor visuals (also DirectColor?) */
" 24-bit visuals found\n", depth);
return 2;
}
/*
colormap_size = visual_list[0].colormap_size;
visual_class = visual->class;
visualID = XVisualIDFromVisual(visual);
*/
} else {
}
if (!colormap) {
return 2;
}
if (depth == 8)
}
} else if (depth > 16) {
}
return 2;
}
/*---------------------------------------------------------------------------
Finally, create the window.
---------------------------------------------------------------------------*/
if (have_nondefault_visual) {
attr.background_pixel = 0;
}
return 2;
} else
have_window = TRUE;
if (depth == 8)
pWindowName = NULL;
/* OK if either hints allocation fails; XSetWMProperties() allows NULLs */
/* window will not be resizable */
(int)rpng2_info.height;
}
/* wm_hints->icon_pixmap = icon_pixmap; */
}
/* various properties and hints no longer needed; free memory */
if (pWindowName)
if (pIconName)
if (size_hints)
if (wm_hints)
/*---------------------------------------------------------------------------
Allocate memory for the X- and display-specific version of the image.
---------------------------------------------------------------------------*/
pad = 32;
} else if (depth == 16) {
pad = 16;
} else /* depth == 8 */ {
pad = 8;
}
if (!xdata) {
return 4;
}
if (!ximage) {
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-
* most efficient approach (the giant if-test would be better), but in
* the interest of clarity, we'll take the easy way out... */
/*---------------------------------------------------------------------------
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) {
} else if (depth == 16) {
} else /* depth == 8 */ {
/* GRR: add 8-bit support */
}
}
/*---------------------------------------------------------------------------
Wait for first Expose event to do any drawing, then flush and return.
---------------------------------------------------------------------------*/
do
XNextEvent(display, &e);
return 0;
} /* end function rpng2_x_create_window() */
static int rpng2_x_load_bg_image(void)
{
char *dest;
int invert_column;
/*---------------------------------------------------------------------------
Allocate buffer for fake background image to be used with transparent
images; if this fails, revert to plain background color.
---------------------------------------------------------------------------*/
if (!bg_data) {
": 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).
---------------------------------------------------------------------------*/
for (i = 0; i < rpng2_info.width; ++i) {
if (even_odd == 0) { /* gradient #1 */
if (invert_column) {
} else {
}
} else { /* gradient #2 */
if ((invert_column && invert_gradient2) ||
(!invert_column && !invert_gradient2))
{
} else {
}
}
}
}
/*---------------------------------------------------------------------------
Soft gradient-diamonds with scale = bgscale. Code contributed by Adam
M. Costello.
---------------------------------------------------------------------------*/
for (i = 0; i < rpng2_info.width; ++i) {
}
}
/*---------------------------------------------------------------------------
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).
---------------------------------------------------------------------------*/
PROGNAME);
/* 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
*/
gray = 0.0;
intensity = 0.0;
for (i = 0; i < rpng2_info.width; ++i) {
x = (int)(i - hw);
if (s == 0.0) {
} else {
hue /= 60.0;
p = (1.0 - s) * v;
q = (1.0 - (s * f)) * v;
t = (1.0 - (s * (1.0 - f))) * v;
}
}
}
}
/*---------------------------------------------------------------------------
Blast background image to display buffer before beginning PNG decode.
---------------------------------------------------------------------------*/
for (i = rpng2_info.width; i > 0; --i) {
/* recall that we set ximage->byte_order = MSBFirst above */
/* GRR BUG: this assumes bpp == 32, but may be 24: */
}
}
} else if (depth == 16) {
for (i = rpng2_info.width; i > 0; --i) {
/* recall that we set ximage->byte_order = MSBFirst above */
}
}
} else /* depth == 8 */ {
/* GRR: add 8-bit support */
}
return 0;
} /* end function rpng2_x_load_bg_image() */
{
char *dest;
uch r, g, b, a;
/*---------------------------------------------------------------------------
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.
---------------------------------------------------------------------------*/
XEvent e;
KeySym k;
"%s: end of pass %d of 7; click in image window to continue\n",
do
XNextEvent(display, &e);
|| k == XK_Escape) )) ;
}
}
if (rows == 0)
++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 (bg_image)
for (i = rpng2_info.width; i > 0; --i) {
/* recall that we set ximage->byte_order = MSBFirst above */
/* GRR BUG: this assumes bpp == 32, but may be 24: */
}
} 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) {
}
if (a == 255) {
red = r;
green = g;
blue = b;
} else if (a == 0) {
} else {
/* this macro (from png.h) composites the foreground
* and background values and puts the result into the
* first argument */
}
/* recall that we set ximage->byte_order = MSBFirst above */
/* GRR BUG: this assumes bpp == 32, but may be 24: */
}
}
} else if (depth == 16) {
if (bg_image)
for (i = rpng2_info.width; i > 0; --i) {
++src;
++src;
++src;
/* recall that we set ximage->byte_order = MSBFirst above */
}
} 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) {
}
if (a == 255) {
} else if (a == 0) {
} 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);
}
/* recall that we set ximage->byte_order = MSBFirst above */
}
}
} 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.
---------------------------------------------------------------------------*/
rows = 0;
} else
rows = 0;
}
}
static void rpng2_x_finish_display(void)
{
/* 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 */
"Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n");
}
static void rpng2_x_cleanup(void)
{
}
if (rpng2_info.image_data) {
}
if (rpng2_info.row_pointers) {
}
if (ximage) {
}
}
if (have_gc)
if (have_window)
if (have_colormap)
}
{
int i;
for (i = 31; i >= 0; --i) {
if (u32val & 0x80000000L)
break;
u32val <<= 1;
}
return i;
}