wrjpgcom.c 17 KB

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