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