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