Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

583 lines
16 KiB

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