1 /*
2 * wrjpgcom.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 inserts
9 * user-supplied text as a COM (comment) marker 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 #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc() */
18 extern void * malloc ();
19 #endif
20 #include <ctype.h> /* to declare isupper(), tolower() */
21 #ifdef USE_SETMODE
22 #include <fcntl.h> /* to declare setmode()'s parameter macros */
23 /* If you have setmode() but not <io.h>, just delete this line: */
24 #include <io.h> /* to declare setmode() */
25 #endif
26
27 #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
28 #ifdef __MWERKS__
29 #include <SIOUX.h> /* Metrowerks declares it here */
30 #endif
31 #ifdef THINK_C
32 #include <console.h> /* Think declares it here */
33 #endif
34 #endif
35
36 #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
37 #define READ_BINARY "r"
38 #define WRITE_BINARY "w"
39 #else
40 #define READ_BINARY "rb"
41 #define WRITE_BINARY "wb"
42 #endif
43
44 #ifndef EXIT_FAILURE /* define exit() codes if not provided */
45 #define EXIT_FAILURE 1
46 #endif
47 #ifndef EXIT_SUCCESS
48 #ifdef VMS
49 #define EXIT_SUCCESS 1 /* VMS is very nonstandard */
50 #else
51 #define EXIT_SUCCESS 0
52 #endif
53 #endif
54
55 /* Reduce this value if your malloc() can't allocate blocks up to 64K.
56 * On DOS, compiling in large model is usually a better solution.
57 */
58
59 #ifndef MAX_COM_LENGTH
60 #define MAX_COM_LENGTH 65000 /* must be < 65534 in any case */
61 #endif
62
63
64 /*
65 * These macros are used to read the input file and write the output file.
66 * To reuse this code in another application, you might need to change these.
67 */
68
69 static FILE * infile; /* input JPEG file */
70
71 /* Return next input byte, or EOF if no more */
72 #define NEXTBYTE() getc(infile)
73
74 static FILE * outfile; /* output JPEG file */
75
76 /* Emit an output byte */
77 #define PUTBYTE(x) putc((x), outfile)
78
79
80 /* Error exit handler */
81 #define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE))
82
83
84 /* Read one byte, testing for EOF */
85 static int
read_1_byte(void)86 read_1_byte (void)
87 {
88 int c;
89
90 c = NEXTBYTE();
91 if (c == EOF)
92 ERREXIT("Premature EOF in JPEG file");
93 return c;
94 }
95
96 /* Read 2 bytes, convert to unsigned int */
97 /* All 2-byte quantities in JPEG markers are MSB first */
98 static unsigned int
read_2_bytes(void)99 read_2_bytes (void)
100 {
101 int c1, c2;
102
103 c1 = NEXTBYTE();
104 if (c1 == EOF)
105 ERREXIT("Premature EOF in JPEG file");
106 c2 = NEXTBYTE();
107 if (c2 == EOF)
108 ERREXIT("Premature EOF in JPEG file");
109 return (((unsigned int) c1) << 8) + ((unsigned int) c2);
110 }
111
112
113 /* Routines to write data to output file */
114
115 static void
write_1_byte(int c)116 write_1_byte (int c)
117 {
118 PUTBYTE(c);
119 }
120
121 static void
write_2_bytes(unsigned int val)122 write_2_bytes (unsigned int val)
123 {
124 PUTBYTE((val >> 8) & 0xFF);
125 PUTBYTE(val & 0xFF);
126 }
127
128 static void
write_marker(int marker)129 write_marker (int marker)
130 {
131 PUTBYTE(0xFF);
132 PUTBYTE(marker);
133 }
134
135 static void
copy_rest_of_file(void)136 copy_rest_of_file (void)
137 {
138 int c;
139
140 while ((c = NEXTBYTE()) != EOF)
141 PUTBYTE(c);
142 }
143
144
145 /*
146 * JPEG markers consist of one or more 0xFF bytes, followed by a marker
147 * code byte (which is not an FF). Here are the marker codes of interest
148 * in this program. (See jdmarker.c for a more complete list.)
149 */
150
151 #define M_SOF0 0xC0 /* Start Of Frame N */
152 #define M_SOF1 0xC1 /* N indicates which compression process */
153 #define M_SOF2 0xC2 /* Only SOF0 and SOF1 are now in common use */
154 #define M_SOF3 0xC3
155 #define M_SOF5 0xC5
156 #define M_SOF6 0xC6
157 #define M_SOF7 0xC7
158 #define M_SOF9 0xC9
159 #define M_SOF10 0xCA
160 #define M_SOF11 0xCB
161 #define M_SOF13 0xCD
162 #define M_SOF14 0xCE
163 #define M_SOF15 0xCF
164 #define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */
165 #define M_EOI 0xD9 /* End Of Image (end of datastream) */
166 #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
167 #define M_COM 0xFE /* COMment */
168
169
170 /*
171 * Find the next JPEG marker and return its marker code.
172 * We expect at least one FF byte, possibly more if the compressor used FFs
173 * to pad the file. (Padding FFs will NOT be replicated in the output file.)
174 * There could also be non-FF garbage between markers. The treatment of such
175 * garbage is unspecified; we choose to skip over it but emit a warning msg.
176 * NB: this routine must not be used after seeing SOS marker, since it will
177 * not deal correctly with FF/00 sequences in the compressed image data...
178 */
179
180 static int
next_marker(void)181 next_marker (void)
182 {
183 int c;
184 int discarded_bytes = 0;
185
186 /* Find 0xFF byte; count and skip any non-FFs. */
187 c = read_1_byte();
188 while (c != 0xFF) {
189 discarded_bytes++;
190 c = read_1_byte();
191 }
192 /* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs
193 * are legal as pad bytes, so don't count them in discarded_bytes.
194 */
195 do {
196 c = read_1_byte();
197 } while (c == 0xFF);
198
199 if (discarded_bytes != 0) {
200 fprintf(stderr, "Warning: garbage data found in JPEG file\n");
201 }
202
203 return c;
204 }
205
206
207 /*
208 * Read the initial marker, which should be SOI.
209 * For a JFIF file, the first two bytes of the file should be literally
210 * 0xFF M_SOI. To be more general, we could use next_marker, but if the
211 * input file weren't actually JPEG at all, next_marker might read the whole
212 * file and then return a misleading error message...
213 */
214
215 static int
first_marker(void)216 first_marker (void)
217 {
218 int c1, c2;
219
220 c1 = NEXTBYTE();
221 c2 = NEXTBYTE();
222 if (c1 != 0xFF || c2 != M_SOI)
223 ERREXIT("Not a JPEG file");
224 return c2;
225 }
226
227
228 /*
229 * Most types of marker are followed by a variable-length parameter segment.
230 * This routine skips over the parameters for any marker we don't otherwise
231 * want to process.
232 * Note that we MUST skip the parameter segment explicitly in order not to
233 * be fooled by 0xFF bytes that might appear within the parameter segment;
234 * such bytes do NOT introduce new markers.
235 */
236
237 static void
copy_variable(void)238 copy_variable (void)
239 /* Copy an unknown or uninteresting variable-length marker */
240 {
241 unsigned int length;
242
243 /* Get the marker parameter length count */
244 length = read_2_bytes();
245 write_2_bytes(length);
246 /* Length includes itself, so must be at least 2 */
247 if (length < 2)
248 ERREXIT("Erroneous JPEG marker length");
249 length -= 2;
250 /* Skip over the remaining bytes */
251 while (length > 0) {
252 write_1_byte(read_1_byte());
253 length--;
254 }
255 }
256
257 static void
skip_variable(void)258 skip_variable (void)
259 /* Skip over an unknown or uninteresting variable-length marker */
260 {
261 unsigned int length;
262
263 /* Get the marker parameter length count */
264 length = read_2_bytes();
265 /* Length includes itself, so must be at least 2 */
266 if (length < 2)
267 ERREXIT("Erroneous JPEG marker length");
268 length -= 2;
269 /* Skip over the remaining bytes */
270 while (length > 0) {
271 (void) read_1_byte();
272 length--;
273 }
274 }
275
276
277 /*
278 * Parse the marker stream until SOFn or EOI is seen;
279 * copy data to output, but discard COM markers unless keep_COM is true.
280 */
281
282 static int
scan_JPEG_header(int keep_COM)283 scan_JPEG_header (int keep_COM)
284 {
285 int marker;
286
287 /* Expect SOI at start of file */
288 if (first_marker() != M_SOI)
289 ERREXIT("Expected SOI marker first");
290 write_marker(M_SOI);
291
292 /* Scan miscellaneous markers until we reach SOFn. */
293 for (;;) {
294 marker = next_marker();
295 switch (marker) {
296 case M_SOF0: /* Baseline */
297 case M_SOF1: /* Extended sequential, Huffman */
298 case M_SOF2: /* Progressive, Huffman */
299 case M_SOF3: /* Lossless, Huffman */
300 case M_SOF5: /* Differential sequential, Huffman */
301 case M_SOF6: /* Differential progressive, Huffman */
302 case M_SOF7: /* Differential lossless, Huffman */
303 case M_SOF9: /* Extended sequential, arithmetic */
304 case M_SOF10: /* Progressive, arithmetic */
305 case M_SOF11: /* Lossless, arithmetic */
306 case M_SOF13: /* Differential sequential, arithmetic */
307 case M_SOF14: /* Differential progressive, arithmetic */
308 case M_SOF15: /* Differential lossless, arithmetic */
309 return marker;
310
311 case M_SOS: /* should not see compressed data before SOF */
312 ERREXIT("SOS without prior SOFn");
313 break;
314
315 case M_EOI: /* in case it's a tables-only JPEG stream */
316 return marker;
317
318 case M_COM: /* Existing COM: conditionally discard */
319 if (keep_COM) {
320 write_marker(marker);
321 copy_variable();
322 } else {
323 skip_variable();
324 }
325 break;
326
327 default: /* Anything else just gets copied */
328 write_marker(marker);
329 copy_variable(); /* we assume it has a parameter count... */
330 break;
331 }
332 } /* end loop */
333 }
334
335
336 /* Command line parsing code */
337
338 static const char * progname; /* program name for error messages */
339
340
341 static void
usage(void)342 usage (void)
343 /* complain about bad command line */
344 {
345 fprintf(stderr, "wrjpgcom inserts a textual comment in a JPEG file.\n");
346 fprintf(stderr, "You can add to or replace any existing comment(s).\n");
347
348 fprintf(stderr, "Usage: %s [switches] ", progname);
349 #ifdef TWO_FILE_COMMANDLINE
350 fprintf(stderr, "inputfile outputfile\n");
351 #else
352 fprintf(stderr, "[inputfile]\n");
353 #endif
354
355 fprintf(stderr, "Switches (names may be abbreviated):\n");
356 fprintf(stderr, " -replace Delete any existing comments\n");
357 fprintf(stderr, " -comment \"text\" Insert comment with given text\n");
358 fprintf(stderr, " -cfile name Read comment from named file\n");
359 fprintf(stderr, "Notice that you must put quotes around the comment text\n");
360 fprintf(stderr, "when you use -comment.\n");
361 fprintf(stderr, "If you do not give either -comment or -cfile on the command line,\n");
362 fprintf(stderr, "then the comment text is read from standard input.\n");
363 fprintf(stderr, "It can be multiple lines, up to %u characters total.\n",
364 (unsigned int) MAX_COM_LENGTH);
365 #ifndef TWO_FILE_COMMANDLINE
366 fprintf(stderr, "You must specify an input JPEG file name when supplying\n");
367 fprintf(stderr, "comment text from standard input.\n");
368 #endif
369
370 exit(EXIT_FAILURE);
371 }
372
373
374 static int
keymatch(char * arg,const char * keyword,int minchars)375 keymatch (char * arg, const char * keyword, int minchars)
376 /* Case-insensitive matching of (possibly abbreviated) keyword switches. */
377 /* keyword is the constant keyword (must be lower case already), */
378 /* minchars is length of minimum legal abbreviation. */
379 {
380 register int ca, ck;
381 register int nmatched = 0;
382
383 while ((ca = *arg++) != '\0') {
384 if ((ck = *keyword++) == '\0')
385 return 0; /* arg longer than keyword, no good */
386 if (isupper(ca)) /* force arg to lcase (assume ck is already) */
387 ca = tolower(ca);
388 if (ca != ck)
389 return 0; /* no good */
390 nmatched++; /* count matched characters */
391 }
392 /* reached end of argument; fail if it's too short for unique abbrev */
393 if (nmatched < minchars)
394 return 0;
395 return 1; /* A-OK */
396 }
397
398
399 /*
400 * The main program.
401 */
402
403 int
main(int argc,char ** argv)404 main (int argc, char **argv)
405 {
406 int argn;
407 char * arg;
408 int keep_COM = 1;
409 char * comment_arg = NULL;
410 FILE * comment_file = NULL;
411 unsigned int comment_length = 0;
412 int marker;
413
414 /* On Mac, fetch a command line. */
415 #ifdef USE_CCOMMAND
416 argc = ccommand(&argv);
417 #endif
418
419 progname = argv[0];
420 if (progname == NULL || progname[0] == 0)
421 progname = "wrjpgcom"; /* in case C library doesn't provide it */
422
423 /* Parse switches, if any */
424 for (argn = 1; argn < argc; argn++) {
425 arg = argv[argn];
426 if (arg[0] != '-')
427 break; /* not switch, must be file name */
428 arg++; /* advance over '-' */
429 if (keymatch(arg, "replace", 1)) {
430 keep_COM = 0;
431 } else if (keymatch(arg, "cfile", 2)) {
432 if (++argn >= argc) usage();
433 if ((comment_file = fopen(argv[argn], "r")) == NULL) {
434 fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
435 exit(EXIT_FAILURE);
436 }
437 } else if (keymatch(arg, "comment", 1)) {
438 if (++argn >= argc) usage();
439 comment_arg = argv[argn];
440 /* If the comment text starts with '"', then we are probably running
441 * under MS-DOG and must parse out the quoted string ourselves. Sigh.
442 */
443 if (comment_arg[0] == '"') {
444 comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
445 if (comment_arg == NULL)
446 ERREXIT("Insufficient memory");
447 strcpy(comment_arg, argv[argn]+1);
448 for (;;) {
449 comment_length = strlen(comment_arg);
450 if (comment_length > 0 && comment_arg[comment_length-1] == '"') {
451 comment_arg[comment_length-1] = '\0'; /* zap terminating quote */
452 break;
453 }
454 if (++argn >= argc)
455 ERREXIT("Missing ending quote mark");
456 strcat(comment_arg, " ");
457 strcat(comment_arg, argv[argn]);
458 }
459 }
460 comment_length = strlen(comment_arg);
461 } else
462 usage();
463 }
464
465 /* Cannot use both -comment and -cfile. */
466 if (comment_arg != NULL && comment_file != NULL)
467 usage();
468 /* If there is neither -comment nor -cfile, we will read the comment text
469 * from stdin; in this case there MUST be an input JPEG file name.
470 */
471 if (comment_arg == NULL && comment_file == NULL && argn >= argc)
472 usage();
473
474 /* Open the input file. */
475 if (argn < argc) {
476 if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
477 fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
478 exit(EXIT_FAILURE);
479 }
480 } else {
481 /* default input file is stdin */
482 #ifdef USE_SETMODE /* need to hack file mode? */
483 setmode(fileno(stdin), O_BINARY);
484 #endif
485 #ifdef USE_FDOPEN /* need to re-open in binary mode? */
486 if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
487 fprintf(stderr, "%s: can't open stdin\n", progname);
488 exit(EXIT_FAILURE);
489 }
490 #else
491 infile = stdin;
492 #endif
493 }
494
495 /* Open the output file. */
496 #ifdef TWO_FILE_COMMANDLINE
497 /* Must have explicit output file name */
498 if (argn != argc-2) {
499 fprintf(stderr, "%s: must name one input and one output file\n",
500 progname);
501 usage();
502 }
503 if ((outfile = fopen(argv[argn+1], WRITE_BINARY)) == NULL) {
504 fprintf(stderr, "%s: can't open %s\n", progname, argv[argn+1]);
505 exit(EXIT_FAILURE);
506 }
507 #else
508 /* Unix style: expect zero or one file name */
509 if (argn < argc-1) {
510 fprintf(stderr, "%s: only one input file\n", progname);
511 usage();
512 }
513 /* default output file is stdout */
514 #ifdef USE_SETMODE /* need to hack file mode? */
515 setmode(fileno(stdout), O_BINARY);
516 #endif
517 #ifdef USE_FDOPEN /* need to re-open in binary mode? */
518 if ((outfile = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
519 fprintf(stderr, "%s: can't open stdout\n", progname);
520 exit(EXIT_FAILURE);
521 }
522 #else
523 outfile = stdout;
524 #endif
525 #endif /* TWO_FILE_COMMANDLINE */
526
527 /* Collect comment text from comment_file or stdin, if necessary */
528 if (comment_arg == NULL) {
529 FILE * src_file;
530 int c;
531
532 comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
533 if (comment_arg == NULL)
534 ERREXIT("Insufficient memory");
535 comment_length = 0;
536 src_file = (comment_file != NULL ? comment_file : stdin);
537 while ((c = getc(src_file)) != EOF) {
538 if (comment_length >= (unsigned int) MAX_COM_LENGTH) {
539 fprintf(stderr, "Comment text may not exceed %u bytes\n",
540 (unsigned int) MAX_COM_LENGTH);
541 exit(EXIT_FAILURE);
542 }
543 comment_arg[comment_length++] = (char) c;
544 }
545 if (comment_file != NULL)
546 fclose(comment_file);
547 }
548
549 /* Copy JPEG headers until SOFn marker;
550 * we will insert the new comment marker just before SOFn.
551 * This (a) causes the new comment to appear after, rather than before,
552 * existing comments; and (b) ensures that comments come after any JFIF
553 * or JFXX markers, as required by the JFIF specification.
554 */
555 marker = scan_JPEG_header(keep_COM);
556 /* Insert the new COM marker, but only if nonempty text has been supplied */
557 if (comment_length > 0) {
558 write_marker(M_COM);
559 write_2_bytes(comment_length + 2);
560 while (comment_length > 0) {
561 write_1_byte(*comment_arg++);
562 comment_length--;
563 }
564 }
565 /* Duplicate the remainder of the source file.
566 * Note that any COM markers occuring after SOF will not be touched.
567 */
568 write_marker(marker);
569 copy_rest_of_file();
570
571 /* All done. */
572 exit(EXIT_SUCCESS);
573 return 0; /* suppress no-return-value warnings */
574 }
575