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