wrjpgcom.c
上传用户:zlh9724
上传日期:2007-01-04
资源大小:1991k
文件大小:16k
源码类别:

浏览器

开发平台:

Unix_Linux

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