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