wrjpgcom.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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.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. #define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */
  17. #include "jinclude.h" /* get auto-config symbols, <stdio.h> */
  18. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc() */
  19. extern void *malloc();
  20. #endif
  21. #include <ctype.h> /* to declare isupper(), tolower() */
  22. #ifdef USE_SETMODE
  23. #include <fcntl.h> /* to declare setmode()'s parameter macros */
  24. /* If you have setmode() but not <io.h>, just delete this line: */
  25. #include <io.h> /* to declare setmode() */
  26. #endif
  27. #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
  28. #ifdef __MWERKS__
  29. #include <SIOUX.h> /* Metrowerks needs this */
  30. #include <console.h> /* ... and this */
  31. #endif
  32. #ifdef THINK_C
  33. #include <console.h> /* Think declares it here */
  34. #endif
  35. #endif
  36. #ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
  37. #define READ_BINARY "r"
  38. #define WRITE_BINARY "w"
  39. #else
  40. #define READ_BINARY "rb"
  41. #define WRITE_BINARY "wb"
  42. #endif
  43. #ifndef EXIT_FAILURE /* define exit() codes if not provided */
  44. #define EXIT_FAILURE 1
  45. #endif
  46. #ifndef EXIT_SUCCESS
  47. #define EXIT_SUCCESS 0
  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 65000L /* must be <= 65533 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, "%s\n", 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 file\n");
  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. /* Copy 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. /* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be,
  246. * treated as SOFn. C4 in particular is actually DHT.
  247. */
  248. case M_SOF0: /* Baseline */
  249. case M_SOF1: /* Extended sequential, Huffman */
  250. case M_SOF2: /* Progressive, Huffman */
  251. case M_SOF3: /* Lossless, Huffman */
  252. case M_SOF5: /* Differential sequential, Huffman */
  253. case M_SOF6: /* Differential progressive, Huffman */
  254. case M_SOF7: /* Differential lossless, Huffman */
  255. case M_SOF9: /* Extended sequential, arithmetic */
  256. case M_SOF10: /* Progressive, arithmetic */
  257. case M_SOF11: /* Lossless, arithmetic */
  258. case M_SOF13: /* Differential sequential, arithmetic */
  259. case M_SOF14: /* Differential progressive, arithmetic */
  260. case M_SOF15: /* Differential lossless, arithmetic */
  261. return marker;
  262. case M_SOS: /* should not see compressed data before SOF */
  263. ERREXIT("SOS without prior SOFn");
  264. break;
  265. case M_EOI: /* in case it's a tables-only JPEG stream */
  266. return marker;
  267. case M_COM: /* Existing COM: conditionally discard */
  268. if (keep_COM) {
  269. write_marker(marker);
  270. copy_variable();
  271. } else {
  272. skip_variable();
  273. }
  274. break;
  275. default: /* Anything else just gets copied */
  276. write_marker(marker);
  277. copy_variable(); /* we assume it has a parameter count... */
  278. break;
  279. }
  280. } /* end loop */
  281. }
  282. /* Command line parsing code */
  283. static const char *progname; /* program name for error messages */
  284. static void
  285. usage(void)
  286. /* complain about bad command line */
  287. {
  288. fprintf(stderr, "wrjpgcom inserts a textual comment in a JPEG file.\n");
  289. fprintf(stderr, "You can add to or replace any existing comment(s).\n");
  290. fprintf(stderr, "Usage: %s [switches] ", progname);
  291. #ifdef TWO_FILE_COMMANDLINE
  292. fprintf(stderr, "inputfile outputfile\n");
  293. #else
  294. fprintf(stderr, "[inputfile]\n");
  295. #endif
  296. fprintf(stderr, "Switches (names may be abbreviated):\n");
  297. fprintf(stderr, " -replace Delete any existing comments\n");
  298. fprintf(stderr, " -comment \"text\" Insert comment with given text\n");
  299. fprintf(stderr, " -cfile name Read comment from named file\n");
  300. fprintf(stderr, "Notice that you must put quotes around the comment text\n");
  301. fprintf(stderr, "when you use -comment.\n");
  302. fprintf(stderr, "If you do not give either -comment or -cfile on the command line,\n");
  303. fprintf(stderr, "then the comment text is read from standard input.\n");
  304. fprintf(stderr, "It can be multiple lines, up to %u characters total.\n",
  305. (unsigned int)MAX_COM_LENGTH);
  306. #ifndef TWO_FILE_COMMANDLINE
  307. fprintf(stderr, "You must specify an input JPEG file name when supplying\n");
  308. fprintf(stderr, "comment text from standard input.\n");
  309. #endif
  310. exit(EXIT_FAILURE);
  311. }
  312. static int
  313. keymatch(char *arg, const char *keyword, int minchars)
  314. /* Case-insensitive matching of (possibly abbreviated) keyword switches. */
  315. /* keyword is the constant keyword (must be lower case already), */
  316. /* minchars is length of minimum legal abbreviation. */
  317. {
  318. register int ca, ck;
  319. register int nmatched = 0;
  320. while ((ca = *arg++) != '\0') {
  321. if ((ck = *keyword++) == '\0')
  322. return 0; /* arg longer than keyword, no good */
  323. if (isupper(ca)) /* force arg to lcase (assume ck is already) */
  324. ca = tolower(ca);
  325. if (ca != ck)
  326. return 0; /* no good */
  327. nmatched++; /* count matched characters */
  328. }
  329. /* reached end of argument; fail if it's too short for unique abbrev */
  330. if (nmatched < minchars)
  331. return 0;
  332. return 1; /* A-OK */
  333. }
  334. /*
  335. * The main program.
  336. */
  337. int
  338. main(int argc, char **argv)
  339. {
  340. int argn;
  341. char *arg;
  342. int keep_COM = 1;
  343. char *comment_arg = NULL;
  344. FILE *comment_file = NULL;
  345. unsigned int comment_length = 0;
  346. int marker;
  347. /* On Mac, fetch a command line. */
  348. #ifdef USE_CCOMMAND
  349. argc = ccommand(&argv);
  350. #endif
  351. progname = argv[0];
  352. if (progname == NULL || progname[0] == 0)
  353. progname = "wrjpgcom"; /* in case C library doesn't provide it */
  354. /* Parse switches, if any */
  355. for (argn = 1; argn < argc; argn++) {
  356. arg = argv[argn];
  357. if (arg[0] != '-')
  358. break; /* not switch, must be file name */
  359. arg++; /* advance over '-' */
  360. if (keymatch(arg, "replace", 1)) {
  361. keep_COM = 0;
  362. } else if (keymatch(arg, "cfile", 2)) {
  363. if (++argn >= argc) usage();
  364. if ((comment_file = fopen(argv[argn], "r")) == NULL) {
  365. fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
  366. exit(EXIT_FAILURE);
  367. }
  368. } else if (keymatch(arg, "comment", 1)) {
  369. if (++argn >= argc) usage();
  370. comment_arg = argv[argn];
  371. /* If the comment text starts with '"', then we are probably running
  372. * under MS-DOG and must parse out the quoted string ourselves. Sigh.
  373. */
  374. if (comment_arg[0] == '"') {
  375. comment_arg = (char *)malloc((size_t)MAX_COM_LENGTH);
  376. if (comment_arg == NULL)
  377. ERREXIT("Insufficient memory");
  378. if (strlen(argv[argn]) + 2 >= (size_t)MAX_COM_LENGTH) {
  379. fprintf(stderr, "Comment text may not exceed %u bytes\n",
  380. (unsigned int)MAX_COM_LENGTH);
  381. exit(EXIT_FAILURE);
  382. }
  383. strcpy(comment_arg, argv[argn] + 1);
  384. for (;;) {
  385. comment_length = (unsigned int)strlen(comment_arg);
  386. if (comment_length > 0 && comment_arg[comment_length - 1] == '"') {
  387. comment_arg[comment_length - 1] = '\0'; /* zap terminating quote */
  388. break;
  389. }
  390. if (++argn >= argc)
  391. ERREXIT("Missing ending quote mark");
  392. if (strlen(comment_arg) + strlen(argv[argn]) + 2 >=
  393. (size_t)MAX_COM_LENGTH) {
  394. fprintf(stderr, "Comment text may not exceed %u bytes\n",
  395. (unsigned int)MAX_COM_LENGTH);
  396. exit(EXIT_FAILURE);
  397. }
  398. strcat(comment_arg, " ");
  399. strcat(comment_arg, argv[argn]);
  400. }
  401. } else if (strlen(argv[argn]) >= (size_t)MAX_COM_LENGTH) {
  402. fprintf(stderr, "Comment text may not exceed %u bytes\n",
  403. (unsigned int)MAX_COM_LENGTH);
  404. exit(EXIT_FAILURE);
  405. }
  406. comment_length = (unsigned int)strlen(comment_arg);
  407. } else
  408. usage();
  409. }
  410. /* Cannot use both -comment and -cfile. */
  411. if (comment_arg != NULL && comment_file != NULL)
  412. usage();
  413. /* If there is neither -comment nor -cfile, we will read the comment text
  414. * from stdin; in this case there MUST be an input JPEG file name.
  415. */
  416. if (comment_arg == NULL && comment_file == NULL && argn >= argc)
  417. usage();
  418. /* Open the input file. */
  419. if (argn < argc) {
  420. if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
  421. fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
  422. exit(EXIT_FAILURE);
  423. }
  424. } else {
  425. /* default input file is stdin */
  426. #ifdef USE_SETMODE /* need to hack file mode? */
  427. setmode(fileno(stdin), O_BINARY);
  428. #endif
  429. #ifdef USE_FDOPEN /* need to re-open in binary mode? */
  430. if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
  431. fprintf(stderr, "%s: can't open stdin\n", progname);
  432. exit(EXIT_FAILURE);
  433. }
  434. #else
  435. infile = stdin;
  436. #endif
  437. }
  438. /* Open the output file. */
  439. #ifdef TWO_FILE_COMMANDLINE
  440. /* Must have explicit output file name */
  441. if (argn != argc - 2) {
  442. fprintf(stderr, "%s: must name one input and one output file\n", progname);
  443. usage();
  444. }
  445. if ((outfile = fopen(argv[argn + 1], WRITE_BINARY)) == NULL) {
  446. fprintf(stderr, "%s: can't open %s\n", progname, argv[argn + 1]);
  447. exit(EXIT_FAILURE);
  448. }
  449. #else
  450. /* Unix style: expect zero or one file name */
  451. if (argn < argc - 1) {
  452. fprintf(stderr, "%s: only one input file\n", progname);
  453. usage();
  454. }
  455. /* default output file is stdout */
  456. #ifdef USE_SETMODE /* need to hack file mode? */
  457. setmode(fileno(stdout), O_BINARY);
  458. #endif
  459. #ifdef USE_FDOPEN /* need to re-open in binary mode? */
  460. if ((outfile = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
  461. fprintf(stderr, "%s: can't open stdout\n", progname);
  462. exit(EXIT_FAILURE);
  463. }
  464. #else
  465. outfile = stdout;
  466. #endif
  467. #endif /* TWO_FILE_COMMANDLINE */
  468. /* Collect comment text from comment_file or stdin, if necessary */
  469. if (comment_arg == NULL) {
  470. FILE *src_file;
  471. int c;
  472. comment_arg = (char *)malloc((size_t)MAX_COM_LENGTH);
  473. if (comment_arg == NULL)
  474. ERREXIT("Insufficient memory");
  475. comment_length = 0;
  476. src_file = (comment_file != NULL ? comment_file : stdin);
  477. while ((c = getc(src_file)) != EOF) {
  478. if (comment_length >= (unsigned int)MAX_COM_LENGTH) {
  479. fprintf(stderr, "Comment text may not exceed %u bytes\n",
  480. (unsigned int)MAX_COM_LENGTH);
  481. exit(EXIT_FAILURE);
  482. }
  483. comment_arg[comment_length++] = (char)c;
  484. }
  485. if (comment_file != NULL)
  486. fclose(comment_file);
  487. }
  488. /* Copy JPEG headers until SOFn marker;
  489. * we will insert the new comment marker just before SOFn.
  490. * This (a) causes the new comment to appear after, rather than before,
  491. * existing comments; and (b) ensures that comments come after any JFIF
  492. * or JFXX markers, as required by the JFIF specification.
  493. */
  494. marker = scan_JPEG_header(keep_COM);
  495. /* Insert the new COM marker, but only if nonempty text has been supplied */
  496. if (comment_length > 0) {
  497. write_marker(M_COM);
  498. write_2_bytes(comment_length + 2);
  499. while (comment_length > 0) {
  500. write_1_byte(*comment_arg++);
  501. comment_length--;
  502. }
  503. }
  504. /* Duplicate the remainder of the source file.
  505. * Note that any COM markers occurring after SOF will not be touched.
  506. */
  507. write_marker(marker);
  508. copy_rest_of_file();
  509. /* All done. */
  510. exit(EXIT_SUCCESS);
  511. return 0; /* suppress no-return-value warnings */
  512. }