wrjpgcom.c 16 KB

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