/usr/share/doc/png-definitive-guide/html/chapter14.html is in png-definitive-guide 20060430-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>Reading PNG Images Progressively (PNG: The Definitive Guide)</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<!-- http://www.w3.org/TR/REC-CSS2/box.html -->
<STYLE TYPE="text/css">
P { margin-bottom: 0em }
UL {
margin-bottom: 0em;
margin-top: 0em;
list-style: disc;
}
LI {
padding: 0px 0px 0px 0px;
margin: 0px 0px 0px 0px;
}
</STYLE>
<LINK REV="made" HREF="http://pobox.com/~newt/greg_contact.html">
<!-- Copyright (c) 1999 O'Reilly and Associates. -->
<!-- Copyright (c) 2002-2006 Greg Roelofs. -->
</HEAD>
<body bgcolor="#ffffff" text="#000000">
<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->
<a href="chapter13.html"><img width=24 height=13 border=0 align="left"
src="images/prev.png" alt="<-"></a>
<a href="chapter15.html"><img width=24 height=13 border=0 align="right"
src="images/next.png" alt="->"></a>
<div align="center">
<a href="chapter13.html"><font size="-1" color="#000000"
><b>PREVIOUS</b></font></a> <a
href="toc.html"><font size="-1" color="#000000"
><b>CONTENTS</b></font></a> <a
href="chapter15.html"><font size="-1" color="#000000"
><b>NEXT</b></font></a>
</div>
<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->
<h1 class="chapter">Chapter 14. Reading PNG Images Progressively</h1>
<div class="htmltoc"><h4 class="tochead">Contents:</h4><p>
<a href="#png.ch14.div.1">14.1. Preliminaries</a><br />
<a href="#png.ch14.div.2">14.2. readpng2_init()</a><br />
<a href="#png.ch14.div.3">14.3. readpng2_decode_data()</a><br />
<a href="#png.ch14.div.4">14.4. readpng2_info_callback()</a><br />
<a href="#png.ch14.div.5">14.5. readpng2_row_callback()</a><br />
<a href="#png.ch14.div.6">14.6. Compositing and Displaying the Image</a><br />
<a href="#png.ch14.div.7">14.7. readpng2_end_callback()</a><br />
<a href="#png.ch14.div.8">14.8. readpng2_cleanup()</a><br />
<a href="#png.ch14.div.9">14.9. Getting the Source Code</a><br />
</p></div>
<p>As I noted in <a href="chapter13.html">Chapter 13, "Reading PNG Images"</a>, the basic style of PNG viewer that reads each
image from a file in a single gulp is appropriate to some
applications, but not all. In particular, web browsers and the like
tend to read images from a network, and they often download more than
one image at the same time. It is usually desirable for them to
display whatever is available at regular intervals so the user
can get some idea of the contents of the page as quickly as possible.
The alternative--waiting the minute or more that some web pages take
to download--went out of style almost as soon as Netscape Navigator
became available late in 1994.</p>
<p><a name="INDEX-1073" />
<a name="INDEX-1074" />
<a name="INDEX-1075" />
<a name="INDEX-1076" />
<a name="INDEX-1077" />
<a name="INDEX-1078" />This style of display is known as <em class="emphasis">progressive</em>, and as one might
imagine, it places strong constraints on the structure of the program.
In fact, in many ways a progressive reader is completely inverted from
the basic design showed in the last chapter: instead of giving the image
library control for the duration of the decoding process, in a progressive
reader, the main program retains control, effectively throttling the library
by restricting the amount of encoded image data it makes available per call.
This will become much clearer with a concrete example, so let us jump right in.</p>
<div class="sect1"><a name="png.ch14.div.1" />
<h2 class="sect1">14.1. Preliminaries</h2>
<p>
<a name="INDEX-1079" />
As in the first demo program, I have divided this program into a PNG-specific
file (<em class="emphasis">readpng2.c</em> this time) and a platform-dependent
file whose
filename, logically enough, depends on the platform. I refer to these
two parts as the ``back end'' and ``front end,'' respectively; I'll once
again concentrate on the libpng-specific back end. This time through, I'll
skim over many of the most basic libpng concepts, however. Indeed, most
of the individual blocks of PNG code are virtually identical to their
counterparts in the basic reader. What has changed is their overall order
in the grand scheme of things.</p>
<p>I'll first note some of the things that haven't changed. As before,
our overall design choices include a desire to deal only with 24-bit RGB
or 32-bit RGBA data; I will instruct libpng to transform
the PNG image data exactly as before. I will also make a game attempt at
doing proper gamma correction; the main program not only calculates
reasonable defaults based on the platform but also gives the user a chance
to specify things precisely. The code for this is unchanged and will not
be presented again. Likewise, I will continue to use the abbreviated
typedefs <b class="emphasis-bold">uch</b>, <b class="emphasis-bold">ush</b>, and <b class="emphasis-bold">ulg</b> in place of the more
unwieldy <b class="emphasis-bold">unsigned char</b>, <b class="emphasis-bold">unsigned short</b>, and <b class="emphasis-bold">unsigned
long</b>, respectively.</p>
<p><a name="INDEX-1080" />
<a name="INDEX-1081" />Within the PNG-specific module, I will once again begin with the inclusion of
the libpng header file, <em class="emphasis">png.h</em>, which in turn includes the
<em class="emphasis">zlib.h</em> header file. (The latest releases at the time of this writing
are libpng 1.0.3 and zlib 1.1.3, which are the versions used by the demo
programs.) The four-line <b class="emphasis-bold">readpng2_version_info()</b> routine is no
different from that in the first demo program.
</p>
<p>Because this style of PNG reader is intended for the kind of application
that decodes multiple images simultaneously (read: browsers), one difference
from the first program is the lack of global or static variables in the PNG
code. Instead, all image-specific variables are embedded in a structure, which
could be allocated repeatedly for as many images as desired. Although some
globals are still used in the front-end code, they are all either truly
global (that is, they could be used in a multi-image program without problems),
or else they could be moved into the per-image struct, too.</p>
</div>
</div>
<div class="sect1"><a name="png.ch14.div.2" />
<h2 class="sect1">14.2. readpng2_init()</h2>
<p><a name="INDEX-1082" />
<a name="INDEX-1083" />The serious PNG code once again begins with the main program opening
the PNG file, and I emphasize that it is opened in <em class="emphasis">binary</em>
mode--hence the ``<b class="emphasis-bold">b</b>'' flag in the second argument to <b class="emphasis-bold">fopen()</b>
(<b class="emphasis-bold">"rb"</b>). A real browser would open an HTTP connection to a remote
server and request the image instead of opening it as a local file. Rather
than immediately jumping into our PNG initialization routine,
<b class="emphasis-bold">readpng2_init()</b>, as was the case in the first demo, this version
first reads a block of data from the file and checks the first eight bytes
for the PNG signature:</p>
<blockquote>
<pre class="code"> if (!(infile = fopen(filename, "rb")))
/* report an error and exit */
} else {
incount = fread(inbuf, 1, INBUFSIZE, infile);
if (incount < 8 || !readpng2_check_sig(inbuf, 8)) {
/* report an error and exit */
} else {
rc = readpng2_init(&rpng2_info);
[etc.]
}
}</pre>
</blockquote>
<p><a name="INDEX-1084" />
<a name="INDEX-1085" />
<a name="INDEX-1086" />The <b class="emphasis-bold">readpng2_check_sig()</b> function is nothing more than a wrapper to
call <b class="emphasis-bold">png_check_sig()</b>. It would also have been possible to call the
libpng routine directly; libpng is unique in that it does not require any special
setup or datatypes, and it returns an integer value, which is the
default for C functions. But that would violate our separation of libpng and
non-libpng code, if only in a tiny way, and it would prevent the compiler
from checking the argument and return types against a prototype, in case
the libpng function should ever change.</p>
<p>Sharp-eyed readers will have noticed that I call <b class="emphasis-bold">readpng2_init()</b>
with a different argument than last time:</p>
<blockquote>
<pre class="code">int readpng2_init(mainprog_info *mainprog_ptr)</pre>
</blockquote>
<p><a name="INDEX-1087" />The difference from the first version is that the function now has only one
argument, a pointer to an object type called <b class="emphasis-bold">mainprog_info</b>. This is
just the per-image struct mentioned earlier. It is defined as follows:</p>
<blockquote>
<pre class="code">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;
int rowbytes;
int channels;
int need_bgcolor;
int done;
uch bg_red;
uch bg_green;
uch bg_blue;
} mainprog_info;</pre>
</blockquote>
<p>I'll explain each member as we need it, but it is clear that many of the
variables that were formerly global or passed as arguments to functions
now reside in this struct. Note that similar variable types
have been grouped, with the smallest ones at the end, so that the
larger types will be aligned on even memory boundaries by default, minimizing
the amount of padding the compiler has to add to the
<?hypen-place ?>structure.</p>
<p><b class="emphasis-bold">readpng2_init()</b> begins by calling libpng to allocate the two PNG
structs:</p>
<blockquote>
<pre class="code"> png_structp png_ptr;
png_infop info_ptr;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
mainprog_ptr, readpng2_error_handler, 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 */
}</pre>
</blockquote>
<p>I have used a pair of local variables here, <b class="emphasis-bold">png_ptr</b> and
<b class="emphasis-bold">info_ptr</b>, for convenience. The <b class="emphasis-bold">mainprog_info</b> struct also
includes these variables, but because it's used in the main program,
which has no knowledge of libpng datatypes, the struct versions of the
two variables are simply declared as pointers to void. To use
them directly in <b class="emphasis-bold">readpng2_init()</b>, we would need to typecast them
repeatedly, which is annoying and makes the program harder to read and
somewhat slower. So I spent a few bytes on the temporary (local)
variables to make life easier.</p>
<blockquote>
<table border="1" cellpadding="6"><tr><td><h4 class="objtitle">readpng2_error_handler()</h4>
<?x-space -2p?><p><a name="INDEX-1088" />
<a name="INDEX-1089" />
<a name="INDEX-1090" />In addition to the new local variables, I replaced two of the NULL
arguments to <b class="emphasis-bold">png_create_read_struct()</b> with meaningful
pointers. This allows us to set up our own error handler and thereby
avoid the ugly problem discussed in the previous chapter, where the
size of the
<a name="INDEX-1091" />
<a name="INDEX-1092" />
<a name="INDEX-1093" />
<a name="INDEX-1094" /><b class="emphasis-bold">setjmp()</b> buffer (<b class="emphasis-bold">jmp_buf</b>) could differ between the
application and the PNG library. All we've really done is duplicate
libpng's error-handling code in the demo program: our
<b class="emphasis-bold">mainprog_info</b> struct now includes a <b class="emphasis-bold">jmp_buf</b> to replace
the one in the main PNG struct, and we've created a
<b class="emphasis-bold">readpng2_error_handler()</b> function that is almost identical to
libpng's default error handler. Because the <b class="emphasis-bold">jmp_buf</b> problem
doesn't affect libpng's warning handler, we left that alone; thus the
fourth argument to <b class="emphasis-bold">png_create_read_struct()</b> is still NULL.
<?x-space -2p?></p>
<p>Our version of libpng's error handler looks like this:
<?x-space -2p?></p>
<blockquote>
<pre class="code">static void readpng2_error_handler(png_structp png_ptr,
png_const_charp msg)
{
mainprog_info *mainprog_ptr;
fprintf(stderr, "readpng2 libpng error: %s\n", msg);
fflush(stderr);
mainprog_ptr = png_get_error_ptr(png_ptr);
if (mainprog_ptr == NULL) {
fprintf(stderr,
"readpng2 severe error: jmpbuf not recoverable;
terminating.\n");
fflush(stderr);
exit(99);
}
longjmp(mainprog_ptr->jmpbuf, 1);
}</pre>
</blockquote>
<?x-space -2p?><p>The main difference is that, unlike libpng, we have to retrieve the pointer
to our error struct (which happens to be the same as our main struct) as an
additional step. And since we know <em class="emphasis">something</em> went wrong (or we wouldn't
be executing this code), it is particularly important to make sure the pointer
is valid--or at least not NULL. If it is NULL, we're in big trouble:
we have no way to retrieve our <b class="emphasis-bold">jmp_buf</b> and therefore no way to return
to the main application code and exit somewhat cleanly. In that case, we
simply print an error message and give up. Otherwise, we retrieve
<a name="INDEX-1095" /><b class="emphasis-bold">mainprog_ptr->jmpbuf</b> and <b class="emphasis-bold">longjmp()</b> back to the most recently
invoked <b class="emphasis-bold">setjmp()</b>, just as libpng would do.
</p>
</td></tr></table>
</blockquote><p>
The next step is to set up one of those <b class="emphasis-bold">setjmp()</b> calls. This
differs from the previous version only in that now we're using our own
struct's <b class="emphasis-bold">jmpbuf</b> member instead of the one in the main PNG
struct:
<a name="INDEX-1096" /></p>
<blockquote>
<pre class="code"> if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 2;
}</pre>
</blockquote>
<p>The second big difference from the basic PNG reader is what comes next:
<a name="INDEX-1097" /></p>
<blockquote>
<pre class="code"> png_set_progressive_read_fn(png_ptr, mainprog_ptr,
readpng2_info_callback, readpng2_row_callback,
readpng2_end_callback);</pre>
</blockquote>
<p>Here we get a glimpse of the inversion of the program logic. The original
approach was to call libpng and wait for it to return the requested image
data, whether header information or actual pixels. That doesn't really work in
a progressive program--if you give the library a hunk of data and wait
for it to return, you may end up with nothing if the hunk was too small,
or you may get the entire image back. More commonly, it is impossible to
return a completely sensible result, due to the way compression works.
The end of a buffer of compressed data may correspond to the first two
bits of the red sample of a single pixel, for example, or it may cut off
a piece of a compressed token that is therefore meaningless. Either way,
what we really want is a way for the decoding library to provide us with
data in a more controlled manner. Callbacks are the answer.</p>
<p><a name="INDEX-1098" />A callback is just what it sounds like: if our main routine calls the
library with a chunk of data, the library will call us back when a
certain amount has been processed--say, one row of image pixels. The
function it calls (back in the main program, presumably) can then
handle the decoded data, return, possibly get called again, and so
forth. Eventually the library will exhaust the data it was given and
return to the original routine. That routine can then read some more
data from the network and pass it back to libpng, go and decode part
of another image, respond to user input, or do anything else that
needs doing.</p>
<p>The progressive handler in libpng is set up to work with three callback
functions: one to be called when all of the header information has been
read (i.e., everything prior to the first IDAT), one for when each row of
the image is decoded (which includes ``short'' rows if the image is
interlaced), and one for when the complete PNG stream has been read. These
are the last three arguments to <b class="emphasis-bold">png_set_progressive_read_fn()</b>, and
<a name="INDEX-1099" />
<a name="INDEX-1100" />
<a name="INDEX-1101" />
<a name="INDEX-1102" />
<a name="INDEX-1103" />
<a name="INDEX-1104" />our versions are called <b class="emphasis-bold">readpng2_info_callback()</b>,
<b class="emphasis-bold">readpng2_row_callback()</b>, and <b class="emphasis-bold">readpng2_end_callback()</b>, respectively.
They are all required to have the same two arguments: <b class="emphasis-bold">png_ptr</b> and
<b class="emphasis-bold">info_ptr</b>, the pointers to the two standard PNG structs. But in
order for the application to associate image-specific data with each callback,
libpng makes available a user-specified pointer, embedded somewhere within
the PNG structs; it can be retrieved via a libpng function. In our case,
we provide a pointer to the <b class="emphasis-bold">mainprog_info</b> struct for the image. This
is the second argument to <b class="emphasis-bold">png_set_progressive_read_fn()</b>. (The first
argument is just the <b class="emphasis-bold">png_ptr</b> itself.)</p>
<p>As it turns out, the call to <b class="emphasis-bold">png_set_progressive_read_fn()</b> is
essentially the whole point of our readpng2 initialization routine. The
only remaining detail is to save the two temporary pointers into the
<b class="emphasis-bold">mainprog_info</b> struct before returning to the main program:</p>
<blockquote>
<pre class="code"> mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
return 0;</pre>
</blockquote>
<p>These pointers will be used in the readpng2 decoding routine that calls libpng,
which in turn sends the pointers back to the callback functions.
<a name="INDEX-1105" />
<a name="INDEX-1106" />
</p>
</div>
<div class="sect1"><a name="png.ch14.div.3" />
<h2 class="sect1">14.3. readpng2_decode_data()</h2>
<p><a name="INDEX-1107" />
<a name="INDEX-1108" />Back in the main program, after dealing with various windowing-system
chores, the code sets a few variables in the <b class="emphasis-bold">mainprog_info</b> struct.
The following excerpt is from the X version of the code, but the Windows
code is the same, aside from prefixing function names with <b class="emphasis-bold">rpng2_win_</b>
instead of <b class="emphasis-bold">rpng2_x_</b>:</p>
<blockquote>
<pre class="code"> if (user_did_not_specify_a_background_color_or_pattern)
rpng2_info.need_bgcolor = TRUE;
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;</pre>
</blockquote>
<p>Unlike the basic viewer, where the main program called a special function
to check for and retrieve the image's background color, the progressive
viewer simply sets the <b class="emphasis-bold">need_bgcolor</b> flag in the struct. It also
sets three function pointers corresponding to the three readpng2 callbacks.
The reason for this apparent duplication will become clear when we look at
the callbacks in detail.</p>
<p>Having prepared everything for decoding, the main program begins the data
loop that is at its core, reading file data into a buffer and passing it
to the PNG-decoding function:</p>
<blockquote>
<pre class="code"> for (;;) {
if (readpng2_decode_data(&rpng2_info, inbuf, incount))
++error;
if (error || feof(infile) || rpng2_info.done)
break;
if (timing)
sleep(1);
incount = fread(inbuf, 1, INBUFSIZE, infile);
}</pre>
</blockquote>
<p>Note the call to <b class="emphasis-bold">readpng2_decode_data()</b> at the beginning of the
loop, before <b class="emphasis-bold">fread()</b>; it handles the initial chunk of data we read
prior to calling <b class="emphasis-bold">readpng2_init()</b>.</p>
<p><a name="INDEX-1109" />The only remarkable feature of the loop itself is the conditional call to
the <b class="emphasis-bold">sleep()</b> function. Because this is a demo program, and because
it is intended to be a rough simulation of how a web browser functions,
I chose to give the user the option of simulating how an image download
over a fast modem would appear. The <b class="emphasis-bold">sleep()</b> function is an extremely
crude method of doing this--it has only one-second precision, which is
too coarse to allow for a smooth simulation--but it is relatively portable
and ubiquitous. Less portable but more precise alternatives include
<a name="INDEX-1110" /><b class="emphasis-bold">usleep()</b> and various Windows API calls. But since no sane programmer
would intentionally add a delay like this to the inner loop of a program
except for demonstration purposes, I judged that <b class="emphasis-bold">sleep()</b> was
good enough for this. The combination of a one-second sleep interval and
the default buffer size of 4096 bytes results in an apparent download speed
that is 10% to 20% faster than a 33.6K modem can manage. In fact, it's
close to the average connection speed of a 56K modem over typical phone
lines.</p>
<p><a name="INDEX-1111" />As to <b class="emphasis-bold">readpng2_decode_data()</b> itself, it is little more than a
wrapper function for the libpng routine <b class="emphasis-bold">png_process_data()</b>. Its
arguments include a pointer to our <b class="emphasis-bold">mainprog_info</b> struct, a pointer
to the input buffer, and the number of bytes of input data; the only things
it does besides calling libpng are copy the struct pointers and set up
the usual error-handling code:</p>
<blockquote>
<pre class="code">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;
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;
}
png_process_data(png_ptr, info_ptr, rawbuf, length);
return 0;
}</pre>
</blockquote>
<p>The struct pointers are copied merely because the alternative is to typedef
them; the latter may be more efficient (though not necessarily, due to the
extra level of indirection inherent in the <b class="emphasis-bold">-></b> operator), but it
is also uglier and makes the code somewhat less readable.<a href="#FOOTNOTE-101">[101]</a>
<a name="INDEX-1112" />
<a name="INDEX-1113" />
</p><blockquote class="footnote">
<a name="FOOTNOTE-101" /><p>[101] Clarity and expediency, that's what we like.
Well, we like efficiency, too,
but not at the cost of clarity when writing a book on programming PNG.</p>
</blockquote>
</div>
<div class="sect1"><a name="png.ch14.div.4" />
<h2 class="sect1">14.4. readpng2_info_callback()</h2>
<p><a name="INDEX-1114" />
<a name="INDEX-1115" /><b class="emphasis-bold">png_process_data()</b> is, in some sense, the last real libpng function
that the main program calls--yet so far we haven't set any
transformations and have virtually no information about the PNG image except
that its signature is correct. The solution to these little mysteries lies
within the first of the callback routines, <b class="emphasis-bold">readpng2_info_callback()</b>.
In most respects, it functions as the second half of our libpng initialization
routine: it gets the PNG image's header information, including the image
dimensions and perhaps the background color; it sets all of the
transformations, including gamma correction; and it calls a routine in the
main program to initialize the viewing window. In short, it does everything
except handle actual pixels.</p>
<p>One important thing it does <em class="emphasis">not</em> do, however, is set up the usual
error-handling code via the <b class="emphasis-bold">setjmp()</b> function. The reason for
this is simple: libpng requires that control never return to it when
an error occurs; ordinarily, it longjumps to a user routine, which then
returns an error value to the main program. But in this case it is
libpng itself that calls <b class="emphasis-bold">readpng2_info_callback()</b>, so a
longjump back to here would make no sense--the only things we could
do would be to return to libpng or call <b class="emphasis-bold">exit()</b> without
cleaning up, which is a rather brutal method of handling an error.
(Well, actually we could do our own longjump back to the main program,
but that's effectively what we are already doing. And in the last
chapter I noted my dislike of big <b class="emphasis-bold">goto</b> statements.) By not
calling <b class="emphasis-bold">setjmp()</b> within the callback, any errors will return
to the location of the previous <b class="emphasis-bold">setjmp()</b> call, which was in
<b class="emphasis-bold">readpng2_decode_data()</b>. It can then return a proper error
value to the main program.</p>
<p>There is a feature in the callback routine that has no analogue in the
basic PNG reader, however:</p>
<blockquote>
<pre class="code"> mainprog_info *mainprog_ptr;
mainprog_ptr = (mainprog_info *)png_get_progressive_ptr(png_ptr);
if (mainprog_ptr == NULL) {
fprintf(stderr, "readpng2 error: "
"main struct not recoverable in info_callback.\n");
fflush(stderr);
return;
}</pre>
</blockquote>
<p>This is the way we retrieve our image-specific pointer from the bowels
of the PNG structs. (If it's invalid, we're in big trouble already, but
there's no need to compound the problem by dereferencing a NULL pointer and
crashing immediately.) Having done so, we can now stuff the image dimensions
into it, where they'll be used by the main program very shortly:
<a name="INDEX-1116" />
<a name="INDEX-1117" /></p>
<blockquote>
<pre class="code"> int color_type, bit_depth;
png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width,
&mainprog_ptr->height, &bit_depth, &color_type, NULL, NULL, NULL);</pre>
</blockquote>
<p>As before, we called a libpng utility routine to retrieve information
about the image. There are also so-called easy access functions to
retrieve each item separately; the choice of one function call or
several is purely a matter of taste.</p>
<div align="center">
<p>
<table width="502" border="1">
<tr>
<td>
<table border="0">
<tr>
<td><img width=56 height=48 src="images/warning.png" alt="[!]" /></td>
<td>
<h4 class="objtitle">CAUTION</h4>
<a name="INDEX-1118" />
<a name="INDEX-1119" />
This is an appropriate point at which to comment once again on the
evils of accessing PNG structures directly, so let us all repeat
our favorite mantra: Friends don't let friends access elements of
PNG structs directly. Bad, bad, bad!
</td>
</tr>
</table>
</td>
</tr>
</table>
</p>
</div>
<!-- 0000000000000000000000000000000000000000000000000000000000000000000000 -->
<!-- GRR 20030701: WHAT THE HECK HAPPENED HERE?? -->
<!-- (lines 525-623 of troff source were MISSING in HTML version) -->
<p>
See <a href="chapter13.html">Chapter 13</a> for the detailed explanation,
but trust me: it's not good karma.
</p>
<p>
As soon as we know the bit depth and color type of the image (via the
<b class="emphasis-bold">png_get_IHDR()</b> call we just made), we can check
for a PNG bKGD
chunk and, if it's found, adjust its values in exactly the same way as
before:
<a name="INDEX-1119.01-missing" /> <!-- .XX "png_get_bKGD(\ )" -->
<a name="INDEX-1119.02-missing" /> <!-- .XX "bKGD (background color) chunk" -->
</p>
<blockquote>
<pre class="code"> if (mainprog_ptr->need_bgcolor &&
png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD))
{
/* do the same png_get_bKGD() call and scale the RGB values as
* required; put results in mainprog_ptr->bg_red, bg_green,
* and bg_blue */
}</pre>
</blockquote>
<p>
This time, instead of passing the red, green, and blue values back through
the arguments to a readpng2 function, we place them into the
<b class="emphasis-bold">bg_red</b>,
<b class="emphasis-bold">bg_green</b>, and <b class="emphasis-bold">bg_blue</b>
elements of our <b class="emphasis-bold">mainprog_info</b> struct.
</p>
<p>
The next step is to set up the desired libpng transformations; this is
completely identical to the code in the first demo program. It is followed
by the gamma-correction setup, but here we depart slightly from the previous
example:
<a name="INDEX-1119.03-missing" /> <!-- .XX "png_get_gAMA(\ )" -->
<a name="INDEX-1119.04-missing" /> <!-- .XX "gamma correction" "gAMA chunk" -->
<a name="INDEX-1119.05-missing" /> <!-- .XX "gAMA chunk" -->
<a name="INDEX-1119.06-missing" /> <!-- .XX "png_set_gamma" -->
</p>
<blockquote>
<pre class="code"> 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);</pre>
</blockquote>
<!-- .\" libpng will return gamma = 1/2.2 if sRGB chunk is present -->
<p>
Because this program is intended to provide an example of how to write a
PNG reader for a web browser, we imagine that the files it will be viewing
are coming from the Internet--even though the front ends we provide only
read from local files, just as in the basic version. Because images from
the Internet are more likely to have been either created on PC-like systems
or intended for display on PC-like systems, we follow the recommendation
of the sRGB proposal (see
<a href="chapter10.html">Chapter 10, "Gamma Correction and Precision Color"</a>)
and assume that all unlabeled images
live in the sRGB color space--which, among other things, means they have
a gamma of 1/2.2 or 0.45455, the same as most PCs and workstations. This
does mean that unlabeled images created on a Macintosh, SGI, or NeXT
workstation and intended for display on one of these systems will appear
too dark. But that, of course, is why including a gamma value in the image
file is so vitally important.
</p>
<p>
There is one last ``transformation'' to register after the gamma handling
is out of the way; we want libpng to expand interlaced passes for us. This
<a name="INDEX-1119.07-missing" /> <!-- .XX "png_set_interlace_handling(\^)" -->
is signaled by calling
<b class="emphasis-bold">png_set_interlace_handling()</b>. It returns
the number of passes in the image,
which we save in case the main program wants to report to the user
whether the image is interlaced (seven passes) or not (one pass):
</p>
<blockquote>
<pre class="code"> mainprog_ptr->passes = png_set_interlace_handling(png_ptr);</pre>
</blockquote>
<p>
Then we have libpng update the PNG struct information and return to us the final
number of channels in the image and the size of each row:
<a name="INDEX-1119.08-missing" /> <!-- .XX "png_read_update_info(\^)" -->
</p>
<blockquote>
<pre class="code"> png_read_update_info(png_ptr, info_ptr);
mainprog_ptr->rowbytes = png_get_rowbytes(png_ptr, info_ptr);
mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr);</pre>
</blockquote>
<p>
The very last thing <b class="emphasis-bold">readpng2_info_callback()</b>
does is call its
corresponding function in the main program, which allocates the image memory,
initializes the windowing system, and creates the display window with the
proper dimensions:
</p>
<blockquote>
<pre class="code"> (*mainprog_ptr->mainprog_init)();
return;</pre>
</blockquote>
<p>
Recall that we saved pointers to three functions in the
<b class="emphasis-bold">mainprog_info</b>
struct; this calls the first of the three. If we didn't care about separating
PNG code from the main program routines, we could use just one routine per
callback. But this way is a bit cleaner, and the performance hit is minimal.
<a name="INDEX-1119.09-missing" /> <!-- .XE "readpng2_info_callback(\^)" -->
<a name="INDEX-1119.10-missing" /> <!-- .XE "rpng2 demo program" "readpng2_info_callback(\^)" -->
</p>
<!-- 0000000000000000000000000000000000000000000000000000000000000000000000 -->
</div>
<div class="sect1"><a name="png.ch14.div.5" />
<h2 class="sect1">14.5. readpng2_row_callback()</h2>
<p>
<a name="INDEX-1120" />
<a name="INDEX-1121" />
The heart of the progressive reader is the row-callback function. As with
the other two callbacks, it is called by
<b class="emphasis-bold">png_process_data()</b> after
some amount of image data is read; unlike them, it gets called multiple
times, at least once for every row in the image.<a href="#FOOTNOTE-102">[102]</a>
<b class="emphasis-bold">readpng2_row_callback()</b> has four arguments: the main PNG struct pointer,
a pointer to the row of image data, the row number, and the pass number.
Its structure is actually quite simple; most of the action occurs within
libpng or back in the main program:</p><blockquote class="footnote">
<a name="FOOTNOTE-102" /><p>[102] For interlaced images, it gets called (with real data) an average of 1.875
times per row and at most 4 times per row (for a one-row image that is
more than four pixels wide). Once per row is still a possibility, however,
if the image has only one column.</p>
</blockquote>
<blockquote>
<pre class="code">static void readpng2_row_callback(png_structp png_ptr,
png_bytep new_row,
png_uint_32 row_num,
int pass)
{
mainprog_info *mainprog_ptr;
if (!new_row)
return;
mainprog_ptr = (mainprog_info *)png_get_progressive_ptr(png_ptr);
png_progressive_combine_row(png_ptr,
mainprog_ptr->row_pointers[row_num], new_row);
(*mainprog_ptr->mainprog_display_row)(row_num);
return;
}</pre>
</blockquote>
<p>The first thing the routine does is check whether libpng provided any
row data; if not, it returns immediately. Otherwise the function
needs access to our <b class="emphasis-bold">mainprog_info</b> struct, so it retrieves the
pointer to that. Recall that the definition of this struct included
two members that should look familiar: <b class="emphasis-bold">image_data</b> and
<b class="emphasis-bold">row_pointers</b>. The first is the pointer to our image buffer;
the second is an array of pointers giving the locations of every row
within the buffer. Both were allocated and initialized when
<b class="emphasis-bold">readpng2_info_callback()</b> called its corresponding function in
the main program. libpng does not require a row-pointers array in a
progressive reader, but it happens to be a convenient and reasonably
efficient way to access the image buffer.</p>
<p>In any case, the row-callback function calls
<a name="INDEX-1122" /><b class="emphasis-bold">png_progressive_combine_row()</b> to combine the new image data with
the existing pixels or, in the case of a noninterlaced image, to copy
the row of data into the image buffer. Then it transfers control to its
counterpart in the main program in order to composite the new pixels with
the background, convert the row to a platform-dependent format, and
optionally display it.
<a name="INDEX-1123" />
<a name="INDEX-1124" />
</p>
</div>
<div class="sect1"><a name="png.ch14.div.6" />
<h2 class="sect1">14.6. Compositing and Displaying the Image</h2>
<p><a name="INDEX-1125" />
<a name="INDEX-1126" />
The main-program code to do all of this is almost identical to that in
the first demo program, but this time around we've added a small
twist: the code now supports not only a user-defined background color
but also a background image of sorts. Specifically, the user has
the option of choosing one of a set of predefined background patterns
that simulate a tiled background image. The patterns currently
include gradient-filled checkerboards (three of which are shown in the
<a href="fig_C5.html#png.color.fig.5-row2">second row of Figure C-5</a>
in the color insert), smoothly interpolated diamonds
(<a href="fig_C5.html#png.color.fig.5-row3">third row of Figure C-5</a>),
and radial waves (<a href="fig_C1.html">Figure C-1</a> and
<a href="fig_C5.html#png.color.fig.5-row4">fourth row of Figure C-5</a>);
eventually, other patterns may be defined. This approach is simple
enough that it could be generated on the fly, as the image is displayed,
but in the interests of speed and <?x-need 10?>simplicity, I chose to
define a second complete image buffer in the
<b class="emphasis-bold">mainprog_init()</b> function. The background
buffer is filled as follows for the diamond pattern (contributed by
Adam M. Costello):
<a name="INDEX-1127" /></p>
<blockquote>
<pre class="code"> hmax = (bgscale-1)/2; /* half the max weight of a color */
max = 2*hmax; /* the max weight of a color */
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;
}
}</pre>
</blockquote>
<p>With this approach, the inner display loop requires only a tiny change to
support the background image instead of just a background color:</p>
<blockquote>
<pre class="code"> r = *src++;
g = *src++;
b = *src++;
a = *src++;
if (bg_image) { /* NEW */
bg_red = *src2++; /* NEW */
bg_green = *src2++; /* NEW */
bg_blue = *src2++; /* NEW */
} /* NEW */
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 (copied 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);
}</pre>
</blockquote>
<p>In other words, the background color used for compositing is now changed
once per pixel. (Note that the <b class="emphasis-bold">src2</b> pointer is initialized just
once per call. That's the only other change to the display routine to
support the background image.) The cases in which the alpha component is either
255 or 0 are handled separately for performance reasons only; using the
<a name="INDEX-1128" /><b class="emphasis-bold">alpha_composite()</b> macro would produce identical results. But because
the macro employs multiplication, addition, and bit-shifting for every pixel
(in fact, three times per pixel) and because fully opaque and fully transparent
pixels are generally by far the most numerous, the difference in speed would
probably be noticeable. It therefore makes sense to handle the two special
cases separately. Whether full opacity or full transparency is handled first
is less obvious; I guessed that opaque pixels are likely to be more common in
images with transparency, so the 255 case is checked first.</p>
<p>The results, using one of the more exotic radial-wave patterns as the
background, are shown in <a href="fig_C1.html">Figure C-1</a> in the color
insert. The base image
consists of partially transparent icicles hanging from opaque tree branches,
seen against a completely transparent sky. The figure is a composite of the
appearance after the first PNG pass (left half) and the final pass (right
half).</p>
</div>
<div class="sect1"><a name="png.ch14.div.7" />
<h2 class="sect1">14.7. readpng2_end_callback()</h2>
<p><a name="INDEX-1129" />
<a name="INDEX-1130" />Once the last row-callback has been made, the program is basically done.
Because of the way the main program's row-display code was written to deal
with interlaced images, when the last row of pixels is sent, it is guaranteed
to be flushed to the display immediately. Thus, when libpng calls our final
callback routine, <b class="emphasis-bold">readpng2_end_callback()</b>, it does nothing more than
retrieve the pointer to our <b class="emphasis-bold">mainprog_info</b> struct and call the
corresponding <b class="emphasis-bold">mainprog_finish_display()</b> function, which in turn merely
sets a ``done'' flag and lets the user know that the image is complete:</p>
<blockquote>
<pre class="code">static void rpng2_x_finish_display()
{
rpng2_info.done = TRUE;
printf("Done. Press Q, Esc or mouse button 1 to quit.\n");
}</pre>
</blockquote>
<p>It would also have been reasonable to free both the <b class="emphasis-bold">image_data</b> and
<b class="emphasis-bold">bg_data</b> buffers at this point, and a memory-constrained application
certainly would do so--or, more likely, it would never have allocated full
buffers in the first place, instead handling everything on a per-row basis
and calculating the background pattern on the fly. Regardless, I chose to
free <em class="emphasis">all</em> front-end buffers in the
front-end cleanup routine, which is
the last function called before the program exits.</p>
</div>
<div class="sect1"><a name="png.ch14.div.8" />
<h2 class="sect1">14.8. readpng2_cleanup()</h2>
<p><a name="INDEX-1131" />
<a name="INDEX-1132" />Before that happens, though, the <b class="emphasis-bold">mainprog_finish_display()</b> routine
returns control through <b class="emphasis-bold">readpng2_end_callback()</b> to libpng and
eventually back to the main program loop, which is now finished. The
main program then closes the PNG file and calls <b class="emphasis-bold">readpng2_cleanup()</b> to
deallocate the PNG structs:</p>
<blockquote>
<pre class="code">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;
}</pre>
</blockquote>
<p>Once that is done, the program waits for user input to terminate, then it exits.</p>
</div>
<div class="sect1"><a name="png.ch14.div.9" />
<h2 class="sect1">14.9. Getting the Source Code</h2>
<p><a name="INDEX-1133" />All of the source files for the <em class="emphasis">rpng2</em> demo program (<em class="emphasis">rpng2-x.c</em>,
<em class="emphasis">rpng2-win.c</em>, <em class="emphasis">readpng2.c</em>, <em class="emphasis">readpng2.h</em>, and makefiles) are
available via the web, under a BSD-like Open Source
license. The files will
be available for download from the following URL for the foreseeable future:</p>
<blockquote>
<pre class="code"><a href="http://www.libpng.org/pub/png/pngbook.html">http://www.libpng.org/pub/png/pngbook.html</a></pre>
</blockquote><p>Bug fixes, new features and ports, and other contributions may be integrated
into the code, time permitting.
<a name="INDEX-1134" />
<a name="INDEX-1135" />
<a name="INDEX-1136" />
<a name="INDEX-1137" />
<a name="INDEX-1138" />
<a name="INDEX-1139" />
</p>
</div>
<PRE>
</PRE>
<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->
<a href="chapter13.html"><img width=24 height=13 border=0 align="left"
src="images/prev.png" alt="<-"></a>
<a href="chapter15.html"><img width=24 height=13 border=0 align="right"
src="images/next.png" alt="->"></a>
<div align="center">
<a href="chapter13.html"><font size="-1" color="#000000"
><b>PREVIOUS</b></font></a> <a
href="toc.html"><font size="-1" color="#000000"
><b>CONTENTS</b></font></a> <a
href="chapter15.html"><font size="-1" color="#000000"
><b>NEXT</b></font></a>
</div>
<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->
</body></html>
|