Fixed binary search: no more infinite loops when vendor is unknown.
[tangerine.git] / compiler / libjpeg / test / rdjpgcom.c
blob2f26675a7e25effd31b7b291b80107470cfbb18c
1 /*
2 $Id$
3 */
5 /*
6 * rdjpgcom.c
8 * Copyright (C) 1994-1997, Thomas G. Lane.
9 * This file is part of the Independent JPEG Group's software.
10 * For conditions of distribution and use, see the accompanying README file.
12 * This file contains a very simple stand-alone application that displays
13 * the text in COM (comment) markers in a JFIF file.
14 * This may be useful as an example of the minimum logic needed to parse
15 * JPEG markers.
18 #define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */
19 #include "jinclude.h" /* get auto-config symbols, <stdio.h> */
21 #include <ctype.h> /* to declare isupper(), tolower() */
22 #ifdef USE_SETMODE
23 #include <fcntl.h> /* to declare setmode()'s parameter macros */
24 /* If you have setmode() but not <io.h>, just delete this line: */
25 #include <io.h> /* to declare setmode() */
26 #endif
28 #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
29 #ifdef __MWERKS__
30 #include <SIOUX.h> /* Metrowerks needs this */
31 #include <console.h> /* ... and this */
32 #endif
33 #ifdef THINK_C
34 #include <console.h> /* Think declares it here */
35 #endif
36 #endif
38 #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
39 #define READ_BINARY "r"
40 #else
41 #ifdef VMS /* VMS is very nonstandard */
42 #define READ_BINARY "rb", "ctx=stm"
43 #else /* standard ANSI-compliant case */
44 #define READ_BINARY "rb"
45 #endif
46 #endif
48 #ifndef EXIT_FAILURE /* define exit() codes if not provided */
49 #define EXIT_FAILURE 1
50 #endif
51 #ifndef EXIT_SUCCESS
52 #ifdef VMS
53 #define EXIT_SUCCESS 1 /* VMS is very nonstandard */
54 #else
55 #define EXIT_SUCCESS 0
56 #endif
57 #endif
61 * These macros are used to read the input file.
62 * To reuse this code in another application, you might need to change these.
65 static FILE * infile; /* input JPEG file */
67 /* Return next input byte, or EOF if no more */
68 #define NEXTBYTE() getc(infile)
71 /* Error exit handler */
72 #define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE))
75 /* Read one byte, testing for EOF */
76 static int
77 read_1_byte (void)
79 int c;
81 c = NEXTBYTE();
82 if (c == EOF)
83 ERREXIT("Premature EOF in JPEG file");
84 return c;
87 /* Read 2 bytes, convert to unsigned int */
88 /* All 2-byte quantities in JPEG markers are MSB first */
89 static unsigned int
90 read_2_bytes (void)
92 int c1, c2;
94 c1 = NEXTBYTE();
95 if (c1 == EOF)
96 ERREXIT("Premature EOF in JPEG file");
97 c2 = NEXTBYTE();
98 if (c2 == EOF)
99 ERREXIT("Premature EOF in JPEG file");
100 return (((unsigned int) c1) << 8) + ((unsigned int) c2);
105 * JPEG markers consist of one or more 0xFF bytes, followed by a marker
106 * code byte (which is not an FF). Here are the marker codes of interest
107 * in this program. (See jdmarker.c for a more complete list.)
110 #define M_SOF0 0xC0 /* Start Of Frame N */
111 #define M_SOF1 0xC1 /* N indicates which compression process */
112 #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
113 #define M_SOF3 0xC3
114 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
115 #define M_SOF6 0xC6
116 #define M_SOF7 0xC7
117 #define M_SOF9 0xC9
118 #define M_SOF10 0xCA
119 #define M_SOF11 0xCB
120 #define M_SOF13 0xCD
121 #define M_SOF14 0xCE
122 #define M_SOF15 0xCF
123 #define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */
124 #define M_EOI 0xD9 /* End Of Image (end of datastream) */
125 #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
126 #define M_APP0 0xE0 /* Application-specific marker, type N */
127 #define M_APP12 0xEC /* (we don't bother to list all 16 APPn's) */
128 #define M_COM 0xFE /* COMment */
132 * Find the next JPEG marker and return its marker code.
133 * We expect at least one FF byte, possibly more if the compressor used FFs
134 * to pad the file.
135 * There could also be non-FF garbage between markers. The treatment of such
136 * garbage is unspecified; we choose to skip over it but emit a warning msg.
137 * NB: this routine must not be used after seeing SOS marker, since it will
138 * not deal correctly with FF/00 sequences in the compressed image data...
141 static int
142 next_marker (void)
144 int c;
145 int discarded_bytes = 0;
147 /* Find 0xFF byte; count and skip any non-FFs. */
148 c = read_1_byte();
149 while (c != 0xFF) {
150 discarded_bytes++;
151 c = read_1_byte();
153 /* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs
154 * are legal as pad bytes, so don't count them in discarded_bytes.
156 do {
157 c = read_1_byte();
158 } while (c == 0xFF);
160 if (discarded_bytes != 0) {
161 fprintf(stderr, "Warning: garbage data found in JPEG file\n");
164 return c;
169 * Read the initial marker, which should be SOI.
170 * For a JFIF file, the first two bytes of the file should be literally
171 * 0xFF M_SOI. To be more general, we could use next_marker, but if the
172 * input file weren't actually JPEG at all, next_marker might read the whole
173 * file and then return a misleading error message...
176 static int
177 first_marker (void)
179 int c1, c2;
181 c1 = NEXTBYTE();
182 c2 = NEXTBYTE();
183 if (c1 != 0xFF || c2 != M_SOI)
184 ERREXIT("Not a JPEG file");
185 return c2;
190 * Most types of marker are followed by a variable-length parameter segment.
191 * This routine skips over the parameters for any marker we don't otherwise
192 * want to process.
193 * Note that we MUST skip the parameter segment explicitly in order not to
194 * be fooled by 0xFF bytes that might appear within the parameter segment;
195 * such bytes do NOT introduce new markers.
198 static void
199 skip_variable (void)
200 /* Skip over an unknown or uninteresting variable-length marker */
202 unsigned int length;
204 /* Get the marker parameter length count */
205 length = read_2_bytes();
206 /* Length includes itself, so must be at least 2 */
207 if (length < 2)
208 ERREXIT("Erroneous JPEG marker length");
209 length -= 2;
210 /* Skip over the remaining bytes */
211 while (length > 0) {
212 (void) read_1_byte();
213 length--;
219 * Process a COM marker.
220 * We want to print out the marker contents as legible text;
221 * we must guard against non-text junk and varying newline representations.
224 static void
225 process_COM (void)
227 unsigned int length;
228 int ch;
229 int lastch = 0;
231 /* Get the marker parameter length count */
232 length = read_2_bytes();
233 /* Length includes itself, so must be at least 2 */
234 if (length < 2)
235 ERREXIT("Erroneous JPEG marker length");
236 length -= 2;
238 while (length > 0) {
239 ch = read_1_byte();
240 /* Emit the character in a readable form.
241 * Nonprintables are converted to \nnn form,
242 * while \ is converted to \\.
243 * Newlines in CR, CR/LF, or LF form will be printed as one newline.
245 if (ch == '\r') {
246 printf("\n");
247 } else if (ch == '\n') {
248 if (lastch != '\r')
249 printf("\n");
250 } else if (ch == '\\') {
251 printf("\\\\");
252 } else if (isprint(ch)) {
253 putc(ch, stdout);
254 } else {
255 printf("\\%03o", ch);
257 lastch = ch;
258 length--;
260 printf("\n");
265 * Process a SOFn marker.
266 * This code is only needed if you want to know the image dimensions...
269 static void
270 process_SOFn (int marker)
272 unsigned int length;
273 unsigned int image_height, image_width;
274 int data_precision, num_components;
275 const char * process;
276 int ci;
278 length = read_2_bytes(); /* usual parameter length count */
280 data_precision = read_1_byte();
281 image_height = read_2_bytes();
282 image_width = read_2_bytes();
283 num_components = read_1_byte();
285 switch (marker) {
286 case M_SOF0: process = "Baseline"; break;
287 case M_SOF1: process = "Extended sequential"; break;
288 case M_SOF2: process = "Progressive"; break;
289 case M_SOF3: process = "Lossless"; break;
290 case M_SOF5: process = "Differential sequential"; break;
291 case M_SOF6: process = "Differential progressive"; break;
292 case M_SOF7: process = "Differential lossless"; break;
293 case M_SOF9: process = "Extended sequential, arithmetic coding"; break;
294 case M_SOF10: process = "Progressive, arithmetic coding"; break;
295 case M_SOF11: process = "Lossless, arithmetic coding"; break;
296 case M_SOF13: process = "Differential sequential, arithmetic coding"; break;
297 case M_SOF14: process = "Differential progressive, arithmetic coding"; break;
298 case M_SOF15: process = "Differential lossless, arithmetic coding"; break;
299 default: process = "Unknown"; break;
302 printf("JPEG image is %uw * %uh, %d color components, %d bits per sample\n",
303 image_width, image_height, num_components, data_precision);
304 printf("JPEG process: %s\n", process);
306 if (length != (unsigned int) (8 + num_components * 3))
307 ERREXIT("Bogus SOF marker length");
309 for (ci = 0; ci < num_components; ci++) {
310 (void) read_1_byte(); /* Component ID code */
311 (void) read_1_byte(); /* H, V sampling factors */
312 (void) read_1_byte(); /* Quantization table number */
318 * Parse the marker stream until SOS or EOI is seen;
319 * display any COM markers.
320 * While the companion program wrjpgcom will always insert COM markers before
321 * SOFn, other implementations might not, so we scan to SOS before stopping.
322 * If we were only interested in the image dimensions, we would stop at SOFn.
323 * (Conversely, if we only cared about COM markers, there would be no need
324 * for special code to handle SOFn; we could treat it like other markers.)
327 static int
328 scan_JPEG_header (int verbose)
330 int marker;
332 /* Expect SOI at start of file */
333 if (first_marker() != M_SOI)
334 ERREXIT("Expected SOI marker first");
336 /* Scan miscellaneous markers until we reach SOS. */
337 for (;;) {
338 marker = next_marker();
339 switch (marker) {
340 /* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be,
341 * treated as SOFn. C4 in particular is actually DHT.
343 case M_SOF0: /* Baseline */
344 case M_SOF1: /* Extended sequential, Huffman */
345 case M_SOF2: /* Progressive, Huffman */
346 case M_SOF3: /* Lossless, Huffman */
347 case M_SOF5: /* Differential sequential, Huffman */
348 case M_SOF6: /* Differential progressive, Huffman */
349 case M_SOF7: /* Differential lossless, Huffman */
350 case M_SOF9: /* Extended sequential, arithmetic */
351 case M_SOF10: /* Progressive, arithmetic */
352 case M_SOF11: /* Lossless, arithmetic */
353 case M_SOF13: /* Differential sequential, arithmetic */
354 case M_SOF14: /* Differential progressive, arithmetic */
355 case M_SOF15: /* Differential lossless, arithmetic */
356 if (verbose)
357 process_SOFn(marker);
358 else
359 skip_variable();
360 break;
362 case M_SOS: /* stop before hitting compressed data */
363 return marker;
365 case M_EOI: /* in case it's a tables-only JPEG stream */
366 return marker;
368 case M_COM:
369 process_COM();
370 break;
372 case M_APP12:
373 /* Some digital camera makers put useful textual information into
374 * APP12 markers, so we print those out too when in -verbose mode.
376 if (verbose) {
377 printf("APP12 contains:\n");
378 process_COM();
379 } else
380 skip_variable();
381 break;
383 default: /* Anything else just gets skipped */
384 skip_variable(); /* we assume it has a parameter count... */
385 break;
387 } /* end loop */
391 /* Command line parsing code */
393 static const char * progname; /* program name for error messages */
396 static void
397 usage (void)
398 /* complain about bad command line */
400 fprintf(stderr, "rdjpgcom displays any textual comments in a JPEG file.\n");
402 fprintf(stderr, "Usage: %s [switches] [inputfile]\n", progname);
404 fprintf(stderr, "Switches (names may be abbreviated):\n");
405 fprintf(stderr, " -verbose Also display dimensions of JPEG image\n");
407 exit(EXIT_FAILURE);
411 static int
412 keymatch (char * arg, const char * keyword, int minchars)
413 /* Case-insensitive matching of (possibly abbreviated) keyword switches. */
414 /* keyword is the constant keyword (must be lower case already), */
415 /* minchars is length of minimum legal abbreviation. */
417 register int ca, ck;
418 register int nmatched = 0;
420 while ((ca = *arg++) != '\0') {
421 if ((ck = *keyword++) == '\0')
422 return 0; /* arg longer than keyword, no good */
423 if (isupper(ca)) /* force arg to lcase (assume ck is already) */
424 ca = tolower(ca);
425 if (ca != ck)
426 return 0; /* no good */
427 nmatched++; /* count matched characters */
429 /* reached end of argument; fail if it's too short for unique abbrev */
430 if (nmatched < minchars)
431 return 0;
432 return 1; /* A-OK */
437 * The main program.
441 main (int argc, char **argv)
443 int argn;
444 char * arg;
445 int verbose = 0;
447 /* On Mac, fetch a command line. */
448 #ifdef USE_CCOMMAND
449 argc = ccommand(&argv);
450 #endif
452 progname = argv[0];
453 if (progname == NULL || progname[0] == 0)
454 progname = "rdjpgcom"; /* in case C library doesn't provide it */
456 /* Parse switches, if any */
457 for (argn = 1; argn < argc; argn++) {
458 arg = argv[argn];
459 if (arg[0] != '-')
460 break; /* not switch, must be file name */
461 arg++; /* advance over '-' */
462 if (keymatch(arg, "verbose", 1)) {
463 verbose++;
464 } else
465 usage();
468 /* Open the input file. */
469 /* Unix style: expect zero or one file name */
470 if (argn < argc-1) {
471 fprintf(stderr, "%s: only one input file\n", progname);
472 usage();
474 if (argn < argc) {
475 if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
476 fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
477 exit(EXIT_FAILURE);
479 } else {
480 /* default input file is stdin */
481 #ifdef USE_SETMODE /* need to hack file mode? */
482 setmode(fileno(stdin), O_BINARY);
483 #endif
484 #ifdef USE_FDOPEN /* need to re-open in binary mode? */
485 if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
486 fprintf(stderr, "%s: can't open stdin\n", progname);
487 exit(EXIT_FAILURE);
489 #else
490 infile = stdin;
491 #endif
494 /* Scan the JPEG headers. */
495 (void) scan_JPEG_header(verbose);
497 /* All done. */
498 exit(EXIT_SUCCESS);
499 return 0; /* suppress no-return-value warnings */