djpeg.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. /*
  2. * djpeg.c
  3. *
  4. * This file was part of the Independent JPEG Group's software:
  5. * Copyright (C) 1991-1997, Thomas G. Lane.
  6. * Modified 2013 by Guido Vollbeding.
  7. * libjpeg-turbo Modifications:
  8. * Copyright (C) 2010-2011, 2013-2016, D. R. Commander.
  9. * Copyright (C) 2015, Google, Inc.
  10. * For conditions of distribution and use, see the accompanying README.ijg
  11. * file.
  12. *
  13. * This file contains a command-line user interface for the JPEG decompressor.
  14. * It should work on any system with Unix- or MS-DOS-style command lines.
  15. *
  16. * Two different command line styles are permitted, depending on the
  17. * compile-time switch TWO_FILE_COMMANDLINE:
  18. * djpeg [options] inputfile outputfile
  19. * djpeg [options] [inputfile]
  20. * In the second style, output is always to standard output, which you'd
  21. * normally redirect to a file or pipe to some other program. Input is
  22. * either from a named file or from standard input (typically redirected).
  23. * The second style is convenient on Unix but is unhelpful on systems that
  24. * don't support pipes. Also, you MUST use the first style if your system
  25. * doesn't do binary I/O to stdin/stdout.
  26. * To simplify script writing, the "-outfile" switch is provided. The syntax
  27. * djpeg [options] -outfile outputfile inputfile
  28. * works regardless of which command line style is used.
  29. */
  30. #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
  31. #include "jversion.h" /* for version message */
  32. #include "jconfigint.h"
  33. #include "wrppm.h"
  34. #include <ctype.h> /* to declare isprint() */
  35. #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
  36. #ifdef __MWERKS__
  37. #include <SIOUX.h> /* Metrowerks needs this */
  38. #include <console.h> /* ... and this */
  39. #endif
  40. #ifdef THINK_C
  41. #include <console.h> /* Think declares it here */
  42. #endif
  43. #endif
  44. /* Create the add-on message string table. */
  45. #define JMESSAGE(code,string) string ,
  46. static const char * const cdjpeg_message_table[] = {
  47. #include "cderror.h"
  48. NULL
  49. };
  50. /*
  51. * This list defines the known output image formats
  52. * (not all of which need be supported by a given version).
  53. * You can change the default output format by defining DEFAULT_FMT;
  54. * indeed, you had better do so if you undefine PPM_SUPPORTED.
  55. */
  56. typedef enum {
  57. FMT_BMP, /* BMP format (Windows flavor) */
  58. FMT_GIF, /* GIF format */
  59. FMT_OS2, /* BMP format (OS/2 flavor) */
  60. FMT_PPM, /* PPM/PGM (PBMPLUS formats) */
  61. FMT_RLE, /* RLE format */
  62. FMT_TARGA, /* Targa format */
  63. FMT_TIFF /* TIFF format */
  64. } IMAGE_FORMATS;
  65. #ifndef DEFAULT_FMT /* so can override from CFLAGS in Makefile */
  66. #define DEFAULT_FMT FMT_PPM
  67. #endif
  68. static IMAGE_FORMATS requested_fmt;
  69. /*
  70. * Argument-parsing code.
  71. * The switch parser is designed to be useful with DOS-style command line
  72. * syntax, ie, intermixed switches and file names, where only the switches
  73. * to the left of a given file name affect processing of that file.
  74. * The main program in this file doesn't actually use this capability...
  75. */
  76. static const char *progname; /* program name for error messages */
  77. static char *outfilename; /* for -outfile switch */
  78. boolean memsrc; /* for -memsrc switch */
  79. boolean skip, crop;
  80. JDIMENSION skip_start, skip_end;
  81. JDIMENSION crop_x, crop_y, crop_width, crop_height;
  82. #define INPUT_BUF_SIZE 4096
  83. LOCAL(void)
  84. usage (void)
  85. /* complain about bad command line */
  86. {
  87. fprintf(stderr, "usage: %s [switches] ", progname);
  88. #ifdef TWO_FILE_COMMANDLINE
  89. fprintf(stderr, "inputfile outputfile\n");
  90. #else
  91. fprintf(stderr, "[inputfile]\n");
  92. #endif
  93. fprintf(stderr, "Switches (names may be abbreviated):\n");
  94. fprintf(stderr, " -colors N Reduce image to no more than N colors\n");
  95. fprintf(stderr, " -fast Fast, low-quality processing\n");
  96. fprintf(stderr, " -grayscale Force grayscale output\n");
  97. fprintf(stderr, " -rgb Force RGB output\n");
  98. fprintf(stderr, " -rgb565 Force RGB565 output\n");
  99. #ifdef IDCT_SCALING_SUPPORTED
  100. fprintf(stderr, " -scale M/N Scale output image by fraction M/N, eg, 1/8\n");
  101. #endif
  102. #ifdef BMP_SUPPORTED
  103. fprintf(stderr, " -bmp Select BMP output format (Windows style)%s\n",
  104. (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
  105. #endif
  106. #ifdef GIF_SUPPORTED
  107. fprintf(stderr, " -gif Select GIF output format%s\n",
  108. (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
  109. #endif
  110. #ifdef BMP_SUPPORTED
  111. fprintf(stderr, " -os2 Select BMP output format (OS/2 style)%s\n",
  112. (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
  113. #endif
  114. #ifdef PPM_SUPPORTED
  115. fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n",
  116. (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
  117. #endif
  118. #ifdef RLE_SUPPORTED
  119. fprintf(stderr, " -rle Select Utah RLE output format%s\n",
  120. (DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
  121. #endif
  122. #ifdef TARGA_SUPPORTED
  123. fprintf(stderr, " -targa Select Targa output format%s\n",
  124. (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
  125. #endif
  126. fprintf(stderr, "Switches for advanced users:\n");
  127. #ifdef DCT_ISLOW_SUPPORTED
  128. fprintf(stderr, " -dct int Use integer DCT method%s\n",
  129. (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
  130. #endif
  131. #ifdef DCT_IFAST_SUPPORTED
  132. fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
  133. (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
  134. #endif
  135. #ifdef DCT_FLOAT_SUPPORTED
  136. fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
  137. (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
  138. #endif
  139. fprintf(stderr, " -dither fs Use F-S dithering (default)\n");
  140. fprintf(stderr, " -dither none Don't use dithering in quantization\n");
  141. fprintf(stderr, " -dither ordered Use ordered dither (medium speed, quality)\n");
  142. #ifdef QUANT_2PASS_SUPPORTED
  143. fprintf(stderr, " -map FILE Map to colors used in named image file\n");
  144. #endif
  145. fprintf(stderr, " -nosmooth Don't use high-quality upsampling\n");
  146. #ifdef QUANT_1PASS_SUPPORTED
  147. fprintf(stderr, " -onepass Use 1-pass quantization (fast, low quality)\n");
  148. #endif
  149. fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
  150. fprintf(stderr, " -outfile name Specify name for output file\n");
  151. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  152. fprintf(stderr, " -memsrc Load input file into memory before decompressing\n");
  153. #endif
  154. fprintf(stderr, " -skip Y0,Y1 Decompress all rows except those between Y0 and Y1 (inclusive)\n");
  155. fprintf(stderr, " -crop WxH+X+Y Decompress only a rectangular subregion of the image\n");
  156. fprintf(stderr, " -verbose or -debug Emit debug output\n");
  157. fprintf(stderr, " -version Print version information and exit\n");
  158. exit(EXIT_FAILURE);
  159. }
  160. LOCAL(int)
  161. parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
  162. int last_file_arg_seen, boolean for_real)
  163. /* Parse optional switches.
  164. * Returns argv[] index of first file-name argument (== argc if none).
  165. * Any file names with indexes <= last_file_arg_seen are ignored;
  166. * they have presumably been processed in a previous iteration.
  167. * (Pass 0 for last_file_arg_seen on the first or only iteration.)
  168. * for_real is FALSE on the first (dummy) pass; we may skip any expensive
  169. * processing.
  170. */
  171. {
  172. int argn;
  173. char *arg;
  174. /* Set up default JPEG parameters. */
  175. requested_fmt = DEFAULT_FMT; /* set default output file format */
  176. outfilename = NULL;
  177. memsrc = FALSE;
  178. skip = FALSE;
  179. crop = FALSE;
  180. cinfo->err->trace_level = 0;
  181. /* Scan command line options, adjust parameters */
  182. for (argn = 1; argn < argc; argn++) {
  183. arg = argv[argn];
  184. if (*arg != '-') {
  185. /* Not a switch, must be a file name argument */
  186. if (argn <= last_file_arg_seen) {
  187. outfilename = NULL; /* -outfile applies to just one input file */
  188. continue; /* ignore this name if previously processed */
  189. }
  190. break; /* else done parsing switches */
  191. }
  192. arg++; /* advance past switch marker character */
  193. if (keymatch(arg, "bmp", 1)) {
  194. /* BMP output format. */
  195. requested_fmt = FMT_BMP;
  196. } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
  197. keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
  198. /* Do color quantization. */
  199. int val;
  200. if (++argn >= argc) /* advance to next argument */
  201. usage();
  202. if (sscanf(argv[argn], "%d", &val) != 1)
  203. usage();
  204. cinfo->desired_number_of_colors = val;
  205. cinfo->quantize_colors = TRUE;
  206. } else if (keymatch(arg, "dct", 2)) {
  207. /* Select IDCT algorithm. */
  208. if (++argn >= argc) /* advance to next argument */
  209. usage();
  210. if (keymatch(argv[argn], "int", 1)) {
  211. cinfo->dct_method = JDCT_ISLOW;
  212. } else if (keymatch(argv[argn], "fast", 2)) {
  213. cinfo->dct_method = JDCT_IFAST;
  214. } else if (keymatch(argv[argn], "float", 2)) {
  215. cinfo->dct_method = JDCT_FLOAT;
  216. } else
  217. usage();
  218. } else if (keymatch(arg, "dither", 2)) {
  219. /* Select dithering algorithm. */
  220. if (++argn >= argc) /* advance to next argument */
  221. usage();
  222. if (keymatch(argv[argn], "fs", 2)) {
  223. cinfo->dither_mode = JDITHER_FS;
  224. } else if (keymatch(argv[argn], "none", 2)) {
  225. cinfo->dither_mode = JDITHER_NONE;
  226. } else if (keymatch(argv[argn], "ordered", 2)) {
  227. cinfo->dither_mode = JDITHER_ORDERED;
  228. } else
  229. usage();
  230. } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
  231. /* Enable debug printouts. */
  232. /* On first -d, print version identification */
  233. static boolean printed_version = FALSE;
  234. if (! printed_version) {
  235. fprintf(stderr, "%s version %s (build %s)\n",
  236. PACKAGE_NAME, VERSION, BUILD);
  237. fprintf(stderr, "%s\n\n", JCOPYRIGHT);
  238. fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
  239. JVERSION);
  240. printed_version = TRUE;
  241. }
  242. cinfo->err->trace_level++;
  243. } else if (keymatch(arg, "version", 4)) {
  244. fprintf(stderr, "%s version %s (build %s)\n",
  245. PACKAGE_NAME, VERSION, BUILD);
  246. exit(EXIT_SUCCESS);
  247. } else if (keymatch(arg, "fast", 1)) {
  248. /* Select recommended processing options for quick-and-dirty output. */
  249. cinfo->two_pass_quantize = FALSE;
  250. cinfo->dither_mode = JDITHER_ORDERED;
  251. if (! cinfo->quantize_colors) /* don't override an earlier -colors */
  252. cinfo->desired_number_of_colors = 216;
  253. cinfo->dct_method = JDCT_FASTEST;
  254. cinfo->do_fancy_upsampling = FALSE;
  255. } else if (keymatch(arg, "gif", 1)) {
  256. /* GIF output format. */
  257. requested_fmt = FMT_GIF;
  258. } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
  259. /* Force monochrome output. */
  260. cinfo->out_color_space = JCS_GRAYSCALE;
  261. } else if (keymatch(arg, "rgb", 2)) {
  262. /* Force RGB output. */
  263. cinfo->out_color_space = JCS_RGB;
  264. } else if (keymatch(arg, "rgb565", 2)) {
  265. /* Force RGB565 output. */
  266. cinfo->out_color_space = JCS_RGB565;
  267. } else if (keymatch(arg, "map", 3)) {
  268. /* Quantize to a color map taken from an input file. */
  269. if (++argn >= argc) /* advance to next argument */
  270. usage();
  271. if (for_real) { /* too expensive to do twice! */
  272. #ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */
  273. FILE *mapfile;
  274. if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
  275. fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
  276. exit(EXIT_FAILURE);
  277. }
  278. read_color_map(cinfo, mapfile);
  279. fclose(mapfile);
  280. cinfo->quantize_colors = TRUE;
  281. #else
  282. ERREXIT(cinfo, JERR_NOT_COMPILED);
  283. #endif
  284. }
  285. } else if (keymatch(arg, "maxmemory", 3)) {
  286. /* Maximum memory in Kb (or Mb with 'm'). */
  287. long lval;
  288. char ch = 'x';
  289. if (++argn >= argc) /* advance to next argument */
  290. usage();
  291. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  292. usage();
  293. if (ch == 'm' || ch == 'M')
  294. lval *= 1000L;
  295. cinfo->mem->max_memory_to_use = lval * 1000L;
  296. } else if (keymatch(arg, "nosmooth", 3)) {
  297. /* Suppress fancy upsampling */
  298. cinfo->do_fancy_upsampling = FALSE;
  299. } else if (keymatch(arg, "onepass", 3)) {
  300. /* Use fast one-pass quantization. */
  301. cinfo->two_pass_quantize = FALSE;
  302. } else if (keymatch(arg, "os2", 3)) {
  303. /* BMP output format (OS/2 flavor). */
  304. requested_fmt = FMT_OS2;
  305. } else if (keymatch(arg, "outfile", 4)) {
  306. /* Set output file name. */
  307. if (++argn >= argc) /* advance to next argument */
  308. usage();
  309. outfilename = argv[argn]; /* save it away for later use */
  310. } else if (keymatch(arg, "memsrc", 2)) {
  311. /* Use in-memory source manager */
  312. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  313. memsrc = TRUE;
  314. #else
  315. fprintf(stderr, "%s: sorry, in-memory source manager was not compiled in\n",
  316. progname);
  317. exit(EXIT_FAILURE);
  318. #endif
  319. } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
  320. /* PPM/PGM output format. */
  321. requested_fmt = FMT_PPM;
  322. } else if (keymatch(arg, "rle", 1)) {
  323. /* RLE output format. */
  324. requested_fmt = FMT_RLE;
  325. } else if (keymatch(arg, "scale", 2)) {
  326. /* Scale the output image by a fraction M/N. */
  327. if (++argn >= argc) /* advance to next argument */
  328. usage();
  329. if (sscanf(argv[argn], "%u/%u",
  330. &cinfo->scale_num, &cinfo->scale_denom) != 2)
  331. usage();
  332. } else if (keymatch(arg, "skip", 2)) {
  333. if (++argn >= argc)
  334. usage();
  335. if (sscanf(argv[argn], "%u,%u", &skip_start, &skip_end) != 2 ||
  336. skip_start > skip_end)
  337. usage();
  338. skip = TRUE;
  339. } else if (keymatch(arg, "crop", 2)) {
  340. char c;
  341. if (++argn >= argc)
  342. usage();
  343. if (sscanf(argv[argn], "%u%c%u+%u+%u", &crop_width, &c, &crop_height,
  344. &crop_x, &crop_y) != 5 ||
  345. (c != 'X' && c != 'x') || crop_width < 1 || crop_height < 1)
  346. usage();
  347. crop = TRUE;
  348. } else if (keymatch(arg, "targa", 1)) {
  349. /* Targa output format. */
  350. requested_fmt = FMT_TARGA;
  351. } else {
  352. usage(); /* bogus switch */
  353. }
  354. }
  355. return argn; /* return index of next arg (file name) */
  356. }
  357. /*
  358. * Marker processor for COM and interesting APPn markers.
  359. * This replaces the library's built-in processor, which just skips the marker.
  360. * We want to print out the marker as text, to the extent possible.
  361. * Note this code relies on a non-suspending data source.
  362. */
  363. LOCAL(unsigned int)
  364. jpeg_getc (j_decompress_ptr cinfo)
  365. /* Read next byte */
  366. {
  367. struct jpeg_source_mgr *datasrc = cinfo->src;
  368. if (datasrc->bytes_in_buffer == 0) {
  369. if (! (*datasrc->fill_input_buffer) (cinfo))
  370. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  371. }
  372. datasrc->bytes_in_buffer--;
  373. return GETJOCTET(*datasrc->next_input_byte++);
  374. }
  375. METHODDEF(boolean)
  376. print_text_marker (j_decompress_ptr cinfo)
  377. {
  378. boolean traceit = (cinfo->err->trace_level >= 1);
  379. long length;
  380. unsigned int ch;
  381. unsigned int lastch = 0;
  382. length = jpeg_getc(cinfo) << 8;
  383. length += jpeg_getc(cinfo);
  384. length -= 2; /* discount the length word itself */
  385. if (traceit) {
  386. if (cinfo->unread_marker == JPEG_COM)
  387. fprintf(stderr, "Comment, length %ld:\n", (long) length);
  388. else /* assume it is an APPn otherwise */
  389. fprintf(stderr, "APP%d, length %ld:\n",
  390. cinfo->unread_marker - JPEG_APP0, (long) length);
  391. }
  392. while (--length >= 0) {
  393. ch = jpeg_getc(cinfo);
  394. if (traceit) {
  395. /* Emit the character in a readable form.
  396. * Nonprintables are converted to \nnn form,
  397. * while \ is converted to \\.
  398. * Newlines in CR, CR/LF, or LF form will be printed as one newline.
  399. */
  400. if (ch == '\r') {
  401. fprintf(stderr, "\n");
  402. } else if (ch == '\n') {
  403. if (lastch != '\r')
  404. fprintf(stderr, "\n");
  405. } else if (ch == '\\') {
  406. fprintf(stderr, "\\\\");
  407. } else if (isprint(ch)) {
  408. putc(ch, stderr);
  409. } else {
  410. fprintf(stderr, "\\%03o", ch);
  411. }
  412. lastch = ch;
  413. }
  414. }
  415. if (traceit)
  416. fprintf(stderr, "\n");
  417. return TRUE;
  418. }
  419. /*
  420. * The main program.
  421. */
  422. int
  423. main (int argc, char **argv)
  424. {
  425. struct jpeg_decompress_struct cinfo;
  426. struct jpeg_error_mgr jerr;
  427. #ifdef PROGRESS_REPORT
  428. struct cdjpeg_progress_mgr progress;
  429. #endif
  430. int file_index;
  431. djpeg_dest_ptr dest_mgr = NULL;
  432. FILE *input_file;
  433. FILE *output_file;
  434. unsigned char *inbuffer = NULL;
  435. unsigned long insize = 0;
  436. JDIMENSION num_scanlines;
  437. /* On Mac, fetch a command line. */
  438. #ifdef USE_CCOMMAND
  439. argc = ccommand(&argv);
  440. #endif
  441. progname = argv[0];
  442. if (progname == NULL || progname[0] == 0)
  443. progname = "djpeg"; /* in case C library doesn't provide it */
  444. /* Initialize the JPEG decompression object with default error handling. */
  445. cinfo.err = jpeg_std_error(&jerr);
  446. jpeg_create_decompress(&cinfo);
  447. /* Add some application-specific error messages (from cderror.h) */
  448. jerr.addon_message_table = cdjpeg_message_table;
  449. jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  450. jerr.last_addon_message = JMSG_LASTADDONCODE;
  451. /* Insert custom marker processor for COM and APP12.
  452. * APP12 is used by some digital camera makers for textual info,
  453. * so we provide the ability to display it as text.
  454. * If you like, additional APPn marker types can be selected for display,
  455. * but don't try to override APP0 or APP14 this way (see libjpeg.txt).
  456. */
  457. jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
  458. jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);
  459. /* Scan command line to find file names. */
  460. /* It is convenient to use just one switch-parsing routine, but the switch
  461. * values read here are ignored; we will rescan the switches after opening
  462. * the input file.
  463. * (Exception: tracing level set here controls verbosity for COM markers
  464. * found during jpeg_read_header...)
  465. */
  466. file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
  467. #ifdef TWO_FILE_COMMANDLINE
  468. /* Must have either -outfile switch or explicit output file name */
  469. if (outfilename == NULL) {
  470. if (file_index != argc-2) {
  471. fprintf(stderr, "%s: must name one input and one output file\n",
  472. progname);
  473. usage();
  474. }
  475. outfilename = argv[file_index+1];
  476. } else {
  477. if (file_index != argc-1) {
  478. fprintf(stderr, "%s: must name one input and one output file\n",
  479. progname);
  480. usage();
  481. }
  482. }
  483. #else
  484. /* Unix style: expect zero or one file name */
  485. if (file_index < argc-1) {
  486. fprintf(stderr, "%s: only one input file\n", progname);
  487. usage();
  488. }
  489. #endif /* TWO_FILE_COMMANDLINE */
  490. /* Open the input file. */
  491. if (file_index < argc) {
  492. if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
  493. fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
  494. exit(EXIT_FAILURE);
  495. }
  496. } else {
  497. /* default input file is stdin */
  498. input_file = read_stdin();
  499. }
  500. /* Open the output file. */
  501. if (outfilename != NULL) {
  502. if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
  503. fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
  504. exit(EXIT_FAILURE);
  505. }
  506. } else {
  507. /* default output file is stdout */
  508. output_file = write_stdout();
  509. }
  510. #ifdef PROGRESS_REPORT
  511. start_progress_monitor((j_common_ptr) &cinfo, &progress);
  512. #endif
  513. /* Specify data source for decompression */
  514. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  515. if (memsrc) {
  516. size_t nbytes;
  517. do {
  518. inbuffer = (unsigned char *)realloc(inbuffer, insize + INPUT_BUF_SIZE);
  519. if (inbuffer == NULL) {
  520. fprintf(stderr, "%s: memory allocation failure\n", progname);
  521. exit(EXIT_FAILURE);
  522. }
  523. nbytes = JFREAD(input_file, &inbuffer[insize], INPUT_BUF_SIZE);
  524. if (nbytes < INPUT_BUF_SIZE && ferror(input_file)) {
  525. if (file_index < argc)
  526. fprintf(stderr, "%s: can't read from %s\n", progname,
  527. argv[file_index]);
  528. else
  529. fprintf(stderr, "%s: can't read from stdin\n", progname);
  530. }
  531. insize += (unsigned long)nbytes;
  532. } while (nbytes == INPUT_BUF_SIZE);
  533. fprintf(stderr, "Compressed size: %lu bytes\n", insize);
  534. jpeg_mem_src(&cinfo, inbuffer, insize);
  535. } else
  536. #endif
  537. jpeg_stdio_src(&cinfo, input_file);
  538. /* Read file header, set default decompression parameters */
  539. (void) jpeg_read_header(&cinfo, TRUE);
  540. /* Adjust default decompression parameters by re-parsing the options */
  541. file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
  542. /* Initialize the output module now to let it override any crucial
  543. * option settings (for instance, GIF wants to force color quantization).
  544. */
  545. switch (requested_fmt) {
  546. #ifdef BMP_SUPPORTED
  547. case FMT_BMP:
  548. dest_mgr = jinit_write_bmp(&cinfo, FALSE);
  549. break;
  550. case FMT_OS2:
  551. dest_mgr = jinit_write_bmp(&cinfo, TRUE);
  552. break;
  553. #endif
  554. #ifdef GIF_SUPPORTED
  555. case FMT_GIF:
  556. dest_mgr = jinit_write_gif(&cinfo);
  557. break;
  558. #endif
  559. #ifdef PPM_SUPPORTED
  560. case FMT_PPM:
  561. dest_mgr = jinit_write_ppm(&cinfo);
  562. break;
  563. #endif
  564. #ifdef RLE_SUPPORTED
  565. case FMT_RLE:
  566. dest_mgr = jinit_write_rle(&cinfo);
  567. break;
  568. #endif
  569. #ifdef TARGA_SUPPORTED
  570. case FMT_TARGA:
  571. dest_mgr = jinit_write_targa(&cinfo);
  572. break;
  573. #endif
  574. default:
  575. ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
  576. break;
  577. }
  578. dest_mgr->output_file = output_file;
  579. /* Start decompressor */
  580. (void) jpeg_start_decompress(&cinfo);
  581. /* Skip rows */
  582. if (skip) {
  583. JDIMENSION tmp;
  584. /* Check for valid skip_end. We cannot check this value until after
  585. * jpeg_start_decompress() is called. Note that we have already verified
  586. * that skip_start <= skip_end.
  587. */
  588. if (skip_end > cinfo.output_height - 1) {
  589. fprintf(stderr, "%s: skip region exceeds image height %d\n", progname,
  590. cinfo.output_height);
  591. exit(EXIT_FAILURE);
  592. }
  593. /* Write output file header. This is a hack to ensure that the destination
  594. * manager creates an output image of the proper size.
  595. */
  596. tmp = cinfo.output_height;
  597. cinfo.output_height -= (skip_end - skip_start + 1);
  598. (*dest_mgr->start_output) (&cinfo, dest_mgr);
  599. cinfo.output_height = tmp;
  600. /* Process data */
  601. while (cinfo.output_scanline < skip_start) {
  602. num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
  603. dest_mgr->buffer_height);
  604. (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
  605. }
  606. jpeg_skip_scanlines(&cinfo, skip_end - skip_start + 1);
  607. while (cinfo.output_scanline < cinfo.output_height) {
  608. num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
  609. dest_mgr->buffer_height);
  610. (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
  611. }
  612. /* Decompress a subregion */
  613. } else if (crop) {
  614. JDIMENSION tmp;
  615. /* Check for valid crop dimensions. We cannot check these values until
  616. * after jpeg_start_decompress() is called.
  617. */
  618. if (crop_x + crop_width > cinfo.output_width ||
  619. crop_y + crop_height > cinfo.output_height) {
  620. fprintf(stderr, "%s: crop dimensions exceed image dimensions %d x %d\n",
  621. progname, cinfo.output_width, cinfo.output_height);
  622. exit(EXIT_FAILURE);
  623. }
  624. jpeg_crop_scanline(&cinfo, &crop_x, &crop_width);
  625. ((ppm_dest_ptr) dest_mgr)->buffer_width = cinfo.output_width *
  626. cinfo.out_color_components *
  627. sizeof(JSAMPLE);
  628. /* Write output file header. This is a hack to ensure that the destination
  629. * manager creates an output image of the proper size.
  630. */
  631. tmp = cinfo.output_height;
  632. cinfo.output_height = crop_height;
  633. (*dest_mgr->start_output) (&cinfo, dest_mgr);
  634. cinfo.output_height = tmp;
  635. /* Process data */
  636. jpeg_skip_scanlines(&cinfo, crop_y);
  637. while (cinfo.output_scanline < crop_y + crop_height) {
  638. num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
  639. dest_mgr->buffer_height);
  640. (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
  641. }
  642. jpeg_skip_scanlines(&cinfo, cinfo.output_height - crop_y - crop_height);
  643. /* Normal full-image decompress */
  644. } else {
  645. /* Write output file header */
  646. (*dest_mgr->start_output) (&cinfo, dest_mgr);
  647. /* Process data */
  648. while (cinfo.output_scanline < cinfo.output_height) {
  649. num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
  650. dest_mgr->buffer_height);
  651. (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
  652. }
  653. }
  654. #ifdef PROGRESS_REPORT
  655. /* Hack: count final pass as done in case finish_output does an extra pass.
  656. * The library won't have updated completed_passes.
  657. */
  658. progress.pub.completed_passes = progress.pub.total_passes;
  659. #endif
  660. /* Finish decompression and release memory.
  661. * I must do it in this order because output module has allocated memory
  662. * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
  663. */
  664. (*dest_mgr->finish_output) (&cinfo, dest_mgr);
  665. (void) jpeg_finish_decompress(&cinfo);
  666. jpeg_destroy_decompress(&cinfo);
  667. /* Close files, if we opened them */
  668. if (input_file != stdin)
  669. fclose(input_file);
  670. if (output_file != stdout)
  671. fclose(output_file);
  672. #ifdef PROGRESS_REPORT
  673. end_progress_monitor((j_common_ptr) &cinfo);
  674. #endif
  675. if (memsrc && inbuffer != NULL)
  676. free(inbuffer);
  677. /* All done. */
  678. exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  679. return 0; /* suppress no-return-value warnings */
  680. }