Debian Codegraph @

converter/other/pnmtojpeg.c

raw
1 /*****************************************************************************
2 pnmtojpeg
3 ******************************************************************************
4 This program is part of the Netpbm package.
5
6 This program converts from the PNM formats to the JFIF format
7 which is based on JPEG.
8
9 This program is by Bryan Henderson on 2000.03.06, but is derived
10 with permission from the program cjpeg, which is in the Independent
11 Jpeg Group's JPEG library package. Under the terms of that permission,
12 redistribution of this software is restricted as described in the
13 file README.JPEG.
14
15 Copyright (C) 1991-1998, Thomas G. Lane.
16
17 *****************************************************************************/
18
19 #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
20 #define _BSD_SOURCE 1 /* Make sure strdup() is in string.h */
21 #define _XOPEN_SOURCE 500 /* Make sure strdup() is in string.h */
22
23 #include <ctype.h> /* to declare isdigit(), etc. */
24 #include <stdbool.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <assert.h>
30 /* Note: jpeglib.h prerequires stdlib.h and ctype.h. It should include them
31 itself, but doesn't.
32 */
33 #include <jpeglib.h>
34
35 #include "pm_c_util.h"
36 #include "pnm.h"
37 #include "shhopt.h"
38 #include "mallocvar.h"
39 #include "nstring.h"
40
41 #define EXIT_WARNING 2 /* Goes with EXIT_SUCCESS, EXIT_FAILURE in stdlib.h */
42
43 enum RestartUnit {RESTART_MCU, RESTART_ROW, RESTART_NONE};
44 enum DensityUnit {DEN_UNSPECIFIED, DEN_DOTS_PER_INCH, DEN_DOTS_PER_CM};
45
46 struct Density {
47 enum DensityUnit unit;
48 /* The units of density for 'horiz', 'vert' */
49 unsigned short horiz; /* Not 0 */
50 /* Horizontal density, in units specified by 'unit' */
51 unsigned short vert; /* Not 0 */
52 /* Same as 'horiz', but vertical */
53 };
54
55 struct CmdlineInfo {
56 /* All the information the user supplied in the command line,
57 in a form easy for the program to use.
58 */
59 char * inputFileNm;
60 unsigned int verbose;
61 unsigned int quality;
62 unsigned int baseline;
63 unsigned int progressive;
64 unsigned int arithmetic;
65 J_DCT_METHOD dctMethod;
66 unsigned int grayscale;
67 unsigned int rgb;
68 long int maxMemoryToUse;
69 unsigned int tracelevel;
70 char * qslots;
71 char * qtablefile;
72 char * sample;
73 char * scans;
74 int smooth;
75 unsigned int optimize;
76 unsigned int restartValue;
77 enum RestartUnit restartUnit;
78 char * restart;
79 char * comment; /* NULL if none */
80 const char * exif; /* NULL if none */
81 unsigned int densitySpec;
82 /* boolean: JFIF should specify a density. If false, 'density'
83 is undefined.
84 */
85 struct Density density;
86 };
87
88 static void
89 interpretMaxmemory (const char * const maxmemory,
90 long int * const maxMemoryToUseP) {
91 long int lval;
92 char ch;
93
94 if (maxmemory == NULL) {
95 *maxMemoryToUseP = -1; /* unspecified */
96 } else if (sscanf(maxmemory, "%ld%c", &lval, &ch) < 1) {
97 pm_error("Invalid value for --maxmemory option: '%s'.", maxmemory);
98 exit(EXIT_FAILURE);
99 } else {
100 if (ch == 'm' || ch == 'M') lval *= 1000L;
101 *maxMemoryToUseP = lval * 1000L;
102 }
103 }
104
105
106
107 static void
108 interpretRestart(const char * const restartOpt,
109 unsigned int * const restartValueP,
110 enum RestartUnit * const restartUnitP) {
111 /*----------------------------------------------------------------------------
112 Interpret the restart command line option. Return values suitable
113 for plugging into a jpeg_compress_struct to control compression.
114 -----------------------------------------------------------------------------*/
115 if (restartOpt == NULL) {
116 /* No --restart option. Set default */
117 *restartUnitP = RESTART_NONE;
118 } else {
119 /* Restart interval in MCU rows (or in MCUs with 'b'). */
120 long lval;
121 char ch;
122 unsigned int matches;
123
124 matches= sscanf(restartOpt, "%ld%c", &lval, &ch);
125 if (matches == 0)
126 pm_error("Invalid value for the --restart option : '%s'.",
127 restartOpt);
128 else {
129 if (lval < 0 || lval > 65535L) {
130 pm_error("--restart value %ld is out of range.", lval);
131 exit(EXIT_FAILURE);
132 } else {
133 if (matches == 1) {
134 *restartValueP = lval;
135 *restartUnitP = RESTART_ROW;
136 } else {
137 if (ch == 'b' || ch == 'B') {
138 *restartValueP = lval;
139 *restartUnitP = RESTART_MCU;
140 } else
141 pm_error("Invalid --restart value '%s'.", restartOpt);
142 }
143 }
144 }
145 }
146 }
147
148
149
150 static void
151 interpretDensity(const char * const densityString,
152 struct Density * const densityP) {
153 /*----------------------------------------------------------------------------
154 Interpret the value of the "-density" option.
155 -----------------------------------------------------------------------------*/
156 if (strlen(densityString) < 1)
157 pm_error("-density value cannot be null.");
158 else {
159 char * unitName; /* malloc'ed */
160 int matched;
161 int horiz, vert;
162
163 unitName = malloc(strlen(densityString)+1);
164
165 matched = sscanf(densityString, "%dx%d%s", &horiz, &vert, unitName);
166
167 if (matched < 2)
168 pm_error("Invalid format for density option value '%s'. It "
169 "should follow the example '3x2' or '3x2dpi' or "
170 "'3x2dpcm'.", densityString);
171 else {
172 if (horiz <= 0 || horiz >= 1<<16)
173 pm_error("Horizontal density %d is outside the range 1-65535",
174 horiz);
175 else if (vert <= 0 || vert >= 1<<16)
176 pm_error("Vertical density %d is outside the range 1-65535",
177 vert);
178 else {
179 densityP->horiz = horiz;
180 densityP->vert = vert;
181
182 if (matched < 3)
183 densityP->unit = DEN_UNSPECIFIED;
184 else {
185 if (streq(unitName, "dpi") || streq(unitName, "DPI"))
186 densityP->unit = DEN_DOTS_PER_INCH;
187 else if (streq(unitName, "dpcm") ||
188 streq(unitName, "DPCM"))
189 densityP->unit = DEN_DOTS_PER_CM;
190 else
191 pm_error("Unrecognized unit '%s' in the density value "
192 "'%s'. I recognize only 'dpi' and 'dpcm'",
193 unitName, densityString);
194 }
195 }
196 }
197 free(unitName);
198 }
199 }
200
201
202
203 static void
204 parseCommandLine(const int argc, const char ** argv,
205 struct CmdlineInfo * const cmdlineP) {
206 /*----------------------------------------------------------------------------
207 Note that many of the strings that this function returns in the
208 *cmdlineP structure are actually in the supplied argv array. And
209 sometimes, one of these strings is actually just a suffix of an entry
210 in argv!
211
212 On the other hand, unlike other option processing functions, we do
213 not change argv at all.
214 -----------------------------------------------------------------------------*/
215 optEntry * option_def; /* Used by OPTENT3 */
216 optStruct3 opt;
217
218 int i; /* local loop variable */
219
220 const char * dctval;
221 const char * maxmemory;
222 const char * restart;
223 const char * density;
224
225 unsigned int qualitySpec, smoothSpec;
226
227 unsigned int option_def_index;
228
229 int argcParse; /* argc, except we modify it as we parse */
230 const char ** argvParse;
231 /* argv, except we modify it as we parse */
232
233 MALLOCARRAY_NOFAIL(option_def, 100);
234
235 MALLOCARRAY(argvParse, argc + 1); /* +1 for the terminating null ptr */
236
237 option_def_index = 0; /* incremented by OPTENTRY */
238 OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0);
239 OPTENT3(0, "quality", OPT_UINT, &cmdlineP->quality,
240 &qualitySpec, 0);
241 OPTENT3(0, "baseline", OPT_FLAG, NULL, &cmdlineP->baseline, 0);
242 OPTENT3(0, "progressive", OPT_FLAG, NULL, &cmdlineP->progressive, 0);
243 OPTENT3(0, "arithmetic", OPT_FLAG, NULL, &cmdlineP->arithmetic, 0);
244 OPTENT3(0, "dct", OPT_STRING, &dctval, NULL, 0);
245 OPTENT3(0, "grayscale", OPT_FLAG, NULL, &cmdlineP->grayscale, 0);
246 OPTENT3(0, "greyscale", OPT_FLAG, NULL, &cmdlineP->grayscale, 0);
247 OPTENT3(0, "rgb", OPT_FLAG, NULL, &cmdlineP->rgb, 0);
248 OPTENT3(0, "maxmemory", OPT_STRING, &maxmemory, NULL, 0);
249 OPTENT3(0, "tracelevel", OPT_UINT, &cmdlineP->tracelevel, NULL, 0);
250 OPTENT3(0, "qslots", OPT_STRING, &cmdlineP->qslots, NULL, 0);
251 OPTENT3(0, "qtables", OPT_STRING, &cmdlineP->qtablefile, NULL, 0);
252 OPTENT3(0, "sample", OPT_STRING, &cmdlineP->sample, NULL, 0);
253 OPTENT3(0, "scans", OPT_STRING, &cmdlineP->scans, NULL, 0);
254 OPTENT3(0, "smooth", OPT_UINT, &cmdlineP->smooth,
255 &smoothSpec, 0);
256 OPTENT3(0, "optimize", OPT_FLAG, NULL, &cmdlineP->optimize, 0);
257 OPTENT3(0, "optimise", OPT_FLAG, NULL, &cmdlineP->optimize, 0);
258 OPTENT3(0, "restart", OPT_STRING, &restart, NULL, 0);
259 OPTENT3(0, "comment", OPT_STRING, &cmdlineP->comment, NULL, 0);
260 OPTENT3(0, "exif", OPT_STRING, &cmdlineP->exif, NULL, 0);
261 OPTENT3(0, "density", OPT_STRING, &density,
262 &cmdlineP->densitySpec, 0);
263
264
265 /* Set the defaults */
266 dctval = NULL;
267 maxmemory = NULL;
268 cmdlineP->tracelevel = 0;
269 cmdlineP->qslots = NULL;
270 cmdlineP->qtablefile = NULL;
271 cmdlineP->sample = NULL;
272 cmdlineP->scans = NULL;
273 restart = NULL;
274 cmdlineP->comment = NULL;
275 cmdlineP->exif = NULL;
276
277 /* Make private copy of arguments for pm_optParseOptions to corrupt */
278 argcParse = argc;
279 for (i = 0; i < argc+1; ++i)
280 argvParse[i] = argv[i];
281
282 opt.opt_table = option_def;
283 opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
284 opt.allowNegNum = FALSE; /* We have no parms that are negative numbers */
285
286 pm_optParseOptions4(&argcParse, argvParse, opt, sizeof(opt), 0);
287
288 if (!qualitySpec)
289 cmdlineP->quality = -1; /* unspecified */
290
291 if (!smoothSpec)
292 cmdlineP->smooth = -1;
293
294 if (cmdlineP->rgb && cmdlineP->grayscale)
295 pm_error("You can't specify both -rgb and -grayscale");
296
297 if (argcParse - 1 == 0)
298 cmdlineP->inputFileNm = strdup("-"); /* he wants stdin */
299 else if (argcParse - 1 == 1)
300 cmdlineP->inputFileNm = strdup(argvParse[1]);
301 else
302 pm_error("Too many arguments. The only argument accepted "
303 "is the input file specification.");
304 if (dctval == NULL)
305 cmdlineP->dctMethod = JDCT_DEFAULT;
306 else {
307 if (streq(dctval, "int"))
308 cmdlineP->dctMethod = JDCT_ISLOW;
309 else if (streq(dctval, "fast"))
310 cmdlineP->dctMethod = JDCT_IFAST;
311 else if (streq(dctval, "float"))
312 cmdlineP->dctMethod = JDCT_FLOAT;
313 else
314 pm_error("Invalid value for the --dct option: '%s'.", dctval);
315 }
316
317 interpretMaxmemory(maxmemory, &cmdlineP->maxMemoryToUse);
318 interpretRestart(restart, &cmdlineP->restartValue,
319 &cmdlineP->restartUnit);
320 if (cmdlineP->densitySpec)
321 interpretDensity(density, &cmdlineP->density);
322
323 if (cmdlineP->smooth > 100)
324 pm_error("Smoothing factor %d is greater than 100 (%%).",
325 cmdlineP->smooth);
326
327 if (streq(cmdlineP->inputFileNm, "=") &&
328 cmdlineP->exif && streq(cmdlineP->exif, "-"))
329
330 pm_error("Cannot have both input image and exif header be from "
331 "Standard Input.");
332
333
334 free(argvParse);
335 }
336
337
338
339 static void
340 reportCompressor(const struct jpeg_compress_struct cinfo) {
341
342 if (cinfo.scan_info == NULL)
343 pm_message("No scan script is being used");
344 else {
345 unsigned int i;
346 pm_message("A scan script with %d entries is being used:",
347 cinfo.num_scans);
348 for (i = 0; i < cinfo.num_scans; ++i) {
349 unsigned int j;
350 pm_message(" Scan %2d: Ss=%2d Se=%2d Ah=%2d Al=%2d "
351 "%d components",
352 i,
353 cinfo.scan_info[i].Ss,
354 cinfo.scan_info[i].Se,
355 cinfo.scan_info[i].Ah,
356 cinfo.scan_info[i].Al,
357 cinfo.scan_info[i].comps_in_scan
358 );
359 for (j = 0; j < cinfo.scan_info[i].comps_in_scan; ++j)
360 pm_message(" Color component %d index: %d", j,
361 cinfo.scan_info[i].component_index[j]);
362 }
363 }
364 }
365
366
367
368 static void
369 setupJpegSourceParameters(struct jpeg_compress_struct * const cinfoP,
370 unsigned int const width,
371 unsigned int const height,
372 int const format) {
373 /*----------------------------------------------------------------------------
374 Set up in the compressor descriptor *cinfoP the description of the
375 source image as required by the compressor.
376 -----------------------------------------------------------------------------*/
377 switch PNM_FORMAT_TYPE(format) {
378 case PBM_TYPE:
379 case PGM_TYPE:
380 cinfoP->in_color_space = JCS_GRAYSCALE;
381 cinfoP->input_components = 1;
382 break;
383 case PPM_TYPE:
384 cinfoP->in_color_space = JCS_RGB;
385 cinfoP->input_components = 3;
386 break;
387 default:
388 pm_error("INTERNAL ERROR; invalid format in "
389 "setup_jpeg_source_parameters()");
390 }
391 }
392
393
394
395 static void
396 setupJpegDensity(struct jpeg_compress_struct * const cinfoP,
397 struct Density const density) {
398 /*----------------------------------------------------------------------------
399 Set up in the compressor descriptor *cinfoP the density information
400 'density'.
401 -----------------------------------------------------------------------------*/
402 switch(density.unit) {
403 case DEN_UNSPECIFIED: cinfoP->density_unit = 0; break;
404 case DEN_DOTS_PER_INCH: cinfoP->density_unit = 1; break;
405 case DEN_DOTS_PER_CM: cinfoP->density_unit = 2; break;
406 }
407
408 cinfoP->X_density = density.horiz;
409 cinfoP->Y_density = density.vert;
410 }
411
412
413
414 /*----------------------------------------------------------------------------
415 The functions below here are essentially the file rdswitch.c from
416 the JPEG library. They perform the functions specified by the following
417 pnmtojpeg options:
418
419 -qtables file Read quantization tables from text file
420 -scans file Read scan script from text file
421 -qslots N[,N,...] Set component quantization table selectors
422 -sample HxV[,HxV,...] Set component sampling factors
423 -----------------------------------------------------------------------------*/
424
425 static int
426 textGetc (FILE * fileP) {
427 /*----------------------------------------------------------------------------
428 Read next char, skipping over any comments (# to end of line).
429
430 Return a comment/newline sequence as a newline.
431 -----------------------------------------------------------------------------*/
432 int ch;
433
434 ch = getc(fileP);
435 if (ch == '#') {
436 do {
437 ch = getc(fileP);
438 } while (ch != '\n' && ch != EOF);
439 }
440 return ch;
441 }
442
443
444
445 static void
446 readTextInteger(FILE * const fileP,
447 bool * const gotOneP,
448 long * const resultP,
449 int * const termcharP) {
450 /*----------------------------------------------------------------------------
451 Read the next unsigned decimal integer from file 'fileP', skipping
452 white space as necessary. Return it as *resultP.
453
454 Also read one character after the integer and return it as *termcharP.
455
456 If there is no character after the integer, return *termcharP == EOF.
457
458 Iff the next thing in the file is not a valid unsigned decimal integer,
459 return *gotOneP false.
460 -----------------------------------------------------------------------------*/
461 int ch;
462
463 /* Skip any leading whitespace, detect EOF */
464 do {
465 ch = textGetc(fileP);
466 } while (isspace(ch));
467
468 if (!isdigit(ch))
469 *gotOneP = false;
470 else {
471 long val;
472 val = ch - '0'; /* initial value */
473 while ((ch = textGetc(fileP)) != EOF) {
474 if (! isdigit(ch))
475 break;
476 val *= 10;
477 val += ch - '0';
478 }
479 *resultP = val;
480 *gotOneP = true;
481 }
482 *termcharP = ch;
483 }
484
485
486
487 static void
488 readScanInteger(FILE * const fileP,
489 bool * const gotOneP,
490 long * const resultP,
491 int * const termcharP) {
492 /*----------------------------------------------------------------------------
493 Variant of readTextInteger that always looks for a non-space termchar.
494 this simplifies parsing of punctuation in scan scripts.
495 -----------------------------------------------------------------------------*/
496 readTextInteger(fileP, gotOneP, resultP, termcharP);
497
498 if (*gotOneP) {
499 int ch;
500
501 ch = *termcharP; /* initial value */
502
503 while (ch != EOF && isspace(ch))
504 ch = textGetc(fileP);
505
506 if (isdigit(ch)) { /* oops, put it back */
507 if (ungetc(ch, fileP) == EOF)
508 pm_error("Unexpected failure of ungetc");
509 ch = ' ';
510 } else {
511 /* Any separators other than ';' and ':' are ignored;
512 * this allows user to insert commas, etc, if desired.
513 */
514 if (ch != EOF && ch != ';' && ch != ':')
515 ch = ' ';
516 }
517 *termcharP = ch;
518 }
519 }
520
521
522
523 static void
524 readScanScriptComponents(FILE * const fP,
525 jpeg_scan_info * const scanP,
526 int * const termcharP,
527 long * const valP,
528 const char ** const errorP) {
529 /*----------------------------------------------------------------------------
530 Set component table in *scanP, i.e. scanP->component_index and
531 scanP->comps_in_scan.
532
533 *termcharP and *valP at entry are for the value we already read from the
534 file; at exit, they are the value beyond the component table.
535 -----------------------------------------------------------------------------*/
536 unsigned int compCt;
537
538 *errorP = NULL; /* initial value */
539
540 /* First component is value we already read: */
541 scanP->component_index[0] = (int) *valP;
542 compCt = 1;
543
544 /* Rest of components follow, until termchar other than ' ': */
545 while (*termcharP == ' ' && !*errorP) {
546 bool gotOne;
547 if (compCt >= MAX_COMPS_IN_SCAN) {
548 pm_asprintf(errorP, "Too many components in one scan "
549 "(Max allowed is %u)", MAX_COMPS_IN_SCAN);
550 }
551 readScanInteger(fP, &gotOne, valP, termcharP);
552 if (!gotOne)
553 pm_asprintf(errorP, "Invalid scan entry format");
554 else
555 scanP->component_index[compCt++] = (int) *valP;
556 }
557 scanP->comps_in_scan = compCt;
558 }
559
560
561
562 static void
563 readScanScriptProg(FILE * const fP,
564 jpeg_scan_info * const scanP,
565 int * const termcharP,
566 long * const valP,
567 const char ** const errorP) {
568
569 bool gotOne;
570 readScanInteger(fP, &gotOne, valP, termcharP);
571 if (!gotOne || *termcharP != ' ')
572 pm_asprintf(errorP, "Error in Ss");
573 else {
574 bool gotOne;
575 scanP->Ss = (int) *valP;
576 readScanInteger(fP, &gotOne, valP, termcharP);
577 if (!gotOne || *termcharP != ' ')
578 pm_asprintf(errorP, "Error in Se");
579 else {
580 bool gotOne;
581 scanP->Se = (int) *valP;
582 readScanInteger(fP, &gotOne, valP, termcharP);
583 if (!gotOne || *termcharP != ' ')
584 pm_asprintf(errorP, "Error in Ah");
585 else {
586 bool gotOne;
587 scanP->Ah = (int) *valP;
588 readScanInteger(fP, &gotOne, valP, termcharP);
589 if (!gotOne)
590 pm_asprintf(errorP, "Error in Al");
591 else {
592 scanP->Al = (int) *valP;
593 *errorP = NULL;
594 }
595 }
596 }
597 }
598 }
599
600
601
602 static void
603 setScanScriptNonProgressive(jpeg_scan_info * const scanP) {
604
605 scanP->Ss = 0;
606 scanP->Se = DCTSIZE2-1;
607 scanP->Ah = 0;
608 scanP->Al = 0;
609 }
610
611
612
613 static void
614 readScanScript1(FILE * const fP,
615 jpeg_scan_info * const scanP,
616 int * const termcharP,
617 long * const valP,
618 const char ** const errorP) {
619
620 const char * error;
621
622 readScanScriptComponents(fP, scanP, termcharP, valP, &error);
623
624 if (error) {
625 pm_asprintf(errorP, "Error in component table. %s", error);
626 pm_strfree(error);
627 } else {
628 if (*termcharP == ':') {
629 const char * error;
630
631 readScanScriptProg(fP, scanP, termcharP, valP, &error);
632
633 if (error) {
634 pm_asprintf(errorP, "Invalid progressive parameters. %s",
635 error);
636 pm_strfree(error);
637 }
638 } else
639 setScanScriptNonProgressive(scanP);
640
641 if (*termcharP != ';' && *termcharP != EOF) {
642 pm_asprintf(errorP, "Expected ';' or EOF");
643 }
644 }
645 }
646
647
648
649 static void
650 readScanScript(j_compress_ptr const cinfoP,
651 const char * const fileNm,
652 const char ** const errorP) {
653 /*----------------------------------------------------------------------------
654 Read a scan script from the specified text file.
655
656 Each entry in the file defines one scan to be emitted.
657
658 Entries are separated by semicolons ';'.
659
660 An entry contains one to four component indexes, optionally followed by a
661 colon ':' and four progressive-JPEG parameters. The indexes and parameters
662 are separated by spaces.
663
664 The component indexes identify the color components to be transmitted in the
665 current scan. The first component has index 0.
666
667 Sequential JPEG is used if the progressive-JPEG parameters are omitted.
668
669 Any whitespace may appear between numbers and the ':' and ';' punctuation
670 marks. Also, other punctuation (such as commas or dashes) may be placed
671 between numbers.
672
673 Comments preceded by '#' may be included in the file.
674
675 Note: we do very little validity checking here; libjpeg will validate the
676 script parameters.
677
678 The data goes into newly malloc'ed memory pointed to by cinfo->scan_info,
679 with its size as cinfo->num_scans. If there isn't any scan script,
680 cinfo->scan_info is null.
681 -----------------------------------------------------------------------------*/
682 FILE * fP;
683
684 fP = fopen(fileNm, "r");
685 if (!fP)
686 pm_asprintf(errorP, "Can't open file");
687 else {
688 bool notEof;
689 unsigned int scanCt;
690 int termchar;
691 long val;
692 jpeg_scan_info * scan; /* malloc'ed array */
693 /* Index 0 in this array is called "Entry 1" by libjpeg messages */
694
695 for (notEof = true, *errorP = NULL, scanCt = 0, scan = NULL;
696 notEof && !*errorP;
697 ) {
698 readScanInteger(fP, &notEof, &val, &termchar);
699 if (notEof && !*errorP) {
700 ++scanCt; /* We got another scan */
701
702 REALLOCARRAY(scan, scanCt);
703
704 if (!scan)
705 pm_error("Unable to allocate memory for scan table");
706
707 readScanScript1(fP, &scan[scanCt-1], &termchar, &val, errorP);
708 }
709 }
710 if (!*errorP && termchar != EOF)
711 pm_asprintf(errorP, "Non-numeric data in file '%s'", fileNm);
712
713 if (*errorP) {
714 if (scan)
715 free(scan);
716 cinfoP->scan_info = NULL;
717 } else {
718 cinfoP->scan_info = scanCt > 0 ? scan : NULL;
719 cinfoP->num_scans = scanCt;
720 }
721 fclose(fP);
722 }
723 }
724
725
726
727 static bool
728 readQuantTables(j_compress_ptr const cinfo,
729 const char * const fileNm,
730 int const scaleFactor,
731 bool const forceBaseline) {
732 /*----------------------------------------------------------------------------
733 Read a set of quantization tables from the specified file.
734 The file is plain ASCII text: decimal numbers with whitespace between.
735 Comments preceded by '#' may be included in the file.
736 There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
737 The tables are implicitly numbered 0,1,etc.
738 NOTE: does not affect the qslots mapping, which will default to selecting
739 table 0 for luminance (or primary) components, 1 for chrominance components.
740 You must use -qslots if you want a different component->table mapping.
741 -----------------------------------------------------------------------------*/
742 FILE * fp;
743 bool retval;
744
745 fp = fopen(fileNm, "rb");
746 if (fp == NULL) {
747 pm_message("Can't open table file '%s'", fileNm);
748 retval = false;
749 } else {
750 boolean eof, error;
751 unsigned int tblno;
752
753 for (tblno = 0, eof = false, error = false; !eof && !error; ++tblno) {
754 long val;
755 int termchar;
756 bool gotOne;
757
758 readTextInteger(fp, &gotOne, &val, &termchar);
759 if (gotOne) {
760 /* read 1st element of table */
761 if (tblno >= NUM_QUANT_TBLS) {
762 pm_message("Too many tables in file '%s'", fileNm);
763 error = true;
764 } else {
765 unsigned int table[DCTSIZE2];
766 unsigned int i;
767
768 table[0] = (unsigned int) val;
769 for (i = 1; i < DCTSIZE2 && !error; ++i) {
770 bool gotOne;
771 readTextInteger(fp, &gotOne, &val, &termchar);
772 if (!gotOne) {
773 pm_message("Invalid table data in file '%s'",
774 fileNm);
775 error = true;
776 } else
777 table[i] = (unsigned int) val;
778 }
779 if (!error)
780 jpeg_add_quant_table(
781 cinfo, tblno, table, scaleFactor, forceBaseline);
782 }
783 } else {
784 if (termchar == EOF)
785 eof = TRUE;
786 else {
787 pm_message("Non-numeric data in file '%s'", fileNm);
788 error = TRUE;
789 }
790 }
791 }
792
793 fclose(fp);
794 retval = !error;
795 }
796
797 return retval;
798 }
799
800
801
802 static bool
803 setQuantSlots(j_compress_ptr const cinfo,
804 const char * const arg) {
805 /*----------------------------------------------------------------------------
806 Process a quantization-table-selectors parameter string, of the form
807 N[,N,...]
808
809 If there are more components than parameters, the last value is replicated.
810 -----------------------------------------------------------------------------*/
811 int val;
812 int ci;
813 char ch;
814 unsigned int i;
815
816 val = 0; /* initial value - default table */
817
818 for (ci = 0, i = 0; ci < MAX_COMPONENTS; ++ci) {
819 if (arg[i]) {
820 ch = ','; /* if not set by sscanf, will be ',' */
821 if (sscanf(&arg[i], "%d%c", &val, &ch) < 1)
822 return false;
823 if (ch != ',') /* syntax check */
824 return false;
825 if (val < 0 || val >= NUM_QUANT_TBLS) {
826 pm_message("Invalid quantization table number: %d. "
827 "JPEG quantization tables are numbered 0..%d",
828 val, NUM_QUANT_TBLS - 1);
829 return false;
830 }
831 cinfo->comp_info[ci].quant_tbl_no = val;
832 while (arg[i] && arg[i] != ',') {
833 ++i;
834 /* advance to next segment of arg string */
835 }
836 } else {
837 /* reached end of parameter, set remaining components to last tbl*/
838 cinfo->comp_info[ci].quant_tbl_no = val;
839 }
840 }
841 return true;
842 }
843
844
845
846 static bool
847 setSampleFactors (j_compress_ptr const cinfo,
848 const char * const arg) {
849 /*----------------------------------------------------------------------------
850 Process a sample-factors parameter string, of the form
851 HxV[,HxV,...]
852
853 If there are more components than parameters, "1x1" is assumed for the rest.
854 -----------------------------------------------------------------------------*/
855 int val1, val2;
856 char ch1, ch2;
857 unsigned int i;
858 unsigned int ci;
859
860 for (ci = 0, i = 0; ci < MAX_COMPONENTS; ++ci) {
861 if (arg[i]) {
862 ch2 = ','; /* if not set by sscanf, will be ',' */
863 if (sscanf(&arg[i], "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3)
864 return false;
865 if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */
866 return false;
867 if (val1 <= 0 || val1 > 4) {
868 pm_message("Invalid sampling factor: %d. "
869 "JPEG sampling factors must be 1..4", val1);
870 return false;
871 }
872 if (val2 <= 0 || val2 > 4) {
873 pm_message("Invalid sampling factor: %d. "
874 "JPEG sampling factors must be 1..4", val2);
875 return false;
876 }
877 cinfo->comp_info[ci].h_samp_factor = val1;
878 cinfo->comp_info[ci].v_samp_factor = val2;
879
880 while (arg[i] && arg[i] != ',') {
881 /* advance to next segment of arg string */
882 ++i;
883 }
884 } else {
885 /* reached end of parameter, set remaining components
886 to 1x1 sampling */
887 cinfo->comp_info[ci].h_samp_factor = 1;
888 cinfo->comp_info[ci].v_samp_factor = 1;
889 }
890 }
891 return true;
892 }
893
894
895
896 static void
897 setupJpeg(struct jpeg_compress_struct * const cinfoP,
898 struct jpeg_error_mgr * const jerrP,
899 struct CmdlineInfo const cmdline,
900 unsigned int const width,
901 unsigned int const height,
902 pixval const maxval,
903 int const inputFmt,
904 FILE * const ofP) {
905
906 int quality;
907 int qScaleFactor;
908
909 /* Initialize the JPEG compression object with default error handling. */
910 cinfoP->err = jpeg_std_error(jerrP);
911 jpeg_create_compress(cinfoP);
912
913 setupJpegSourceParameters(cinfoP, width, height, inputFmt);
914
915 jpeg_set_defaults(cinfoP);
916
917 cinfoP->data_precision = BITS_IN_JSAMPLE;
918 /* we always rescale data to this */
919 cinfoP->image_width = width;
920 cinfoP->image_height = height;
921
922 cinfoP->arith_code = cmdline.arithmetic;
923 cinfoP->dct_method = cmdline.dctMethod;
924 if (cmdline.tracelevel == 0 && cmdline.verbose)
925 cinfoP->err->trace_level = 1;
926 else cinfoP->err->trace_level = cmdline.tracelevel;
927 if (cmdline.grayscale)
928 jpeg_set_colorspace(cinfoP, JCS_GRAYSCALE);
929 else if (cmdline.rgb)
930 /* This is not legal if the input is not JCS_RGB too, i.e. it's PPM */
931 jpeg_set_colorspace(cinfoP, JCS_RGB);
932 else
933 /* This default will be based on the in_color_space set above */
934 jpeg_default_colorspace(cinfoP);
935 if (cmdline.maxMemoryToUse != -1)
936 cinfoP->mem->max_memory_to_use = cmdline.maxMemoryToUse;
937 cinfoP->optimize_coding = cmdline.optimize;
938 if (cmdline.quality == -1) {
939 quality = 75;
940 qScaleFactor = 100;
941 } else {
942 quality = cmdline.quality;
943 qScaleFactor = jpeg_quality_scaling(cmdline.quality);
944 }
945 if (cmdline.smooth != -1)
946 cinfoP->smoothing_factor = cmdline.smooth;
947
948 /* Set quantization tables for selected quality. */
949 /* Some or all may be overridden if user specified --qtables. */
950 jpeg_set_quality(cinfoP, quality, cmdline.baseline);
951
952 if (cmdline.qtablefile != NULL) {
953 if (! readQuantTables(cinfoP, cmdline.qtablefile,
954 qScaleFactor, cmdline.baseline))
955 pm_error("Can't use quantization table file '%s'.",
956 cmdline.qtablefile);
957 }
958
959 if (cmdline.qslots != NULL) {
960 if (! setQuantSlots(cinfoP, cmdline.qslots))
961 pm_error("Bad quantization-table-selectors parameter string '%s'.",
962 cmdline.qslots);
963 }
964
965 if (cmdline.sample != NULL) {
966 if (! setSampleFactors(cinfoP, cmdline.sample))
967 pm_error("Bad sample-factors parameters string '%s'.",
968 cmdline.sample);
969 }
970
971 if (cmdline.progressive)
972 jpeg_simple_progression(cinfoP);
973
974 if (cmdline.densitySpec)
975 setupJpegDensity(cinfoP, cmdline.density);
976
977 if (cmdline.scans != NULL) {
978 const char * error;
979 readScanScript(cinfoP, cmdline.scans, &error);
980 if (error) {
981 pm_message("Error in scan script '%s'. %s", cmdline.scans, error);
982 pm_strfree(error);
983 }
984 } else
985 cinfoP->scan_info = NULL;
986
987 /* Specify data destination for compression */
988 jpeg_stdio_dest(cinfoP, ofP);
989
990 if (cmdline.verbose)
991 reportCompressor(*cinfoP);
992
993 /* Start compressor */
994 jpeg_start_compress(cinfoP, TRUE);
995
996 }
997
998
999
1000 static void
1001 writeExifHeader(struct jpeg_compress_struct * const cinfoP,
1002 const char * const exifFileNm) {
1003 /*----------------------------------------------------------------------------
1004 Generate an APP1 marker in the JFIF output that is an Exif header.
1005
1006 The contents of the Exif header are in the file with filespec
1007 'exifFileNm' (file spec and contents are not validated).
1008
1009 exifFileNm = "-" means Standard Input.
1010
1011 If the file contains just two bytes of zero, don't write any marker
1012 but don't recognize any error either.
1013 -----------------------------------------------------------------------------*/
1014 FILE * exifFp;
1015 unsigned short length;
1016
1017 exifFp = pm_openr(exifFileNm);
1018
1019 pm_readbigshort(exifFp, (short*)&length);
1020
1021 if (length == 0) {
1022 /* Special value meaning "no header" */
1023 } else if (length < 3)
1024 pm_error("Invalid length %u at start of exif file", length);
1025 else {
1026 unsigned char * exifData;
1027 size_t const dataLength = length - 2;
1028 /* Subtract 2 byte length field*/
1029 size_t rc;
1030
1031 assert(dataLength > 0);
1032
1033 MALLOCARRAY(exifData, dataLength);
1034 if (!exifData)
1035 pm_error("Unable to allocate %u bytes for exif header buffer",
1036 (unsigned)dataLength);
1037
1038 rc = fread(exifData, 1, dataLength, exifFp);
1039
1040 if (rc != dataLength)
1041 pm_error("Premature end of file on exif header file. Should be "
1042 "%u bytes of data, read only %u",
1043 (unsigned)dataLength, (unsigned)rc);
1044
1045 jpeg_write_marker(cinfoP, JPEG_APP0+1,
1046 (const JOCTET *) exifData, dataLength);
1047
1048 free(exifData);
1049 }
1050
1051 pm_close(exifFp);
1052 }
1053
1054
1055
1056 static void
1057 computeRescalingArray(JSAMPLE ** const rescaleP,
1058 pixval const maxval,
1059 struct jpeg_compress_struct const cinfo) {
1060 /*----------------------------------------------------------------------------
1061 Compute the rescaling array for a maximum pixval of 'maxval'.
1062 Allocate the memory for it too.
1063 -----------------------------------------------------------------------------*/
1064 long const halfMaxval = maxval / 2;
1065
1066 JSAMPLE * rescale;
1067 long val;
1068
1069 MALLOCARRAY(rescale, maxval + 1);
1070
1071 if (!rescale)
1072 pm_error("Failed to get memory for map of %u possible sample values",
1073 maxval + 1);
1074
1075 for (val = 0; val <= maxval; ++val) {
1076 /* The multiplication here must be done in 32 bits to avoid overflow */
1077 rescale[val] = (JSAMPLE) ((val*MAXJSAMPLE + halfMaxval)/maxval);
1078 }
1079
1080 *rescaleP = rescale;
1081 }
1082
1083
1084
1085 static void
1086 translateRow(pixel const pnm_buffer[],
1087 unsigned int const width,
1088 unsigned int const inputComponentCt,
1089 JSAMPLE const translate[],
1090 JSAMPLE * const jpegBuffer) {
1091 /*----------------------------------------------------------------------------
1092 Convert the input row, in pnm format, to an output row in JPEG compressor
1093 input format.
1094
1095 This is a byte for byte copy, translated through the array 'translate'.
1096 -----------------------------------------------------------------------------*/
1097 unsigned int col;
1098 /* I'm not sure why the JPEG library data structures don't have some kind
1099 of pixel data structure (such that a row buffer is an array of pixels,
1100 rather than an array of samples). But because of this, we have to
1101 index jpeg_buffer the old fashioned way.
1102 */
1103
1104 switch (inputComponentCt) {
1105 case 1:
1106 for (col = 0; col < width; ++col)
1107 jpegBuffer[col] = translate[(int)PNM_GET1(pnm_buffer[col])];
1108 break;
1109 case 3:
1110 for (col = 0; col < width; ++col) {
1111 jpegBuffer[col * 3 + 0] =
1112 translate[(int)PPM_GETR(pnm_buffer[col])];
1113 jpegBuffer[col * 3 + 1] =
1114 translate[(int)PPM_GETG(pnm_buffer[col])];
1115 jpegBuffer[col * 3 + 2] =
1116 translate[(int)PPM_GETB(pnm_buffer[col])];
1117 }
1118 break;
1119 default:
1120 pm_error("INTERNAL ERROR: invalid number of input components in "
1121 "translate_row()");
1122 }
1123
1124 }
1125
1126
1127
1128 static void
1129 convertScanLines(struct jpeg_compress_struct * const cinfoP,
1130 FILE * const inputFileNm,
1131 pixval const maxval,
1132 int const inputFmt,
1133 const JSAMPLE * const xlateTable){
1134 /*----------------------------------------------------------------------------
1135 Read scan lines from the input file, which is already opened in the
1136 netpbm library sense and ready for reading, and write them to the
1137 output JPEG object. Translate the pnm sample values to JPEG sample
1138 values through the table xlateTable[].
1139 -----------------------------------------------------------------------------*/
1140 xel * pnmBuffer;
1141 /* This malloc'ed array contains the row of the input image currently
1142 being processed, in pnm_readpnmrow format.
1143 */
1144 JSAMPLE * jpegBuffer;
1145 /* This malloc'ed array contains the row of the output image currently
1146 being processed, in JPEG compressor input format.
1147 */
1148
1149 MALLOCARRAY(jpegBuffer, cinfoP->image_width * cinfoP->input_components);
1150 if (!jpegBuffer)
1151 pm_error("Unable to allocate buffer for a row of %u pixels, "
1152 "%u samples each",
1153 cinfoP->image_width, cinfoP->input_components);
1154
1155 pnmBuffer = pnm_allocrow(cinfoP->image_width);
1156
1157 while (cinfoP->next_scanline < cinfoP->image_height) {
1158 if (cinfoP->err->trace_level > 1)
1159 pm_message("Converting Row %d...", cinfoP->next_scanline);
1160 pnm_readpnmrow(inputFileNm, pnmBuffer, cinfoP->image_width,
1161 maxval, inputFmt);
1162 translateRow(pnmBuffer,
1163 cinfoP->image_width, cinfoP->input_components,
1164 xlateTable, jpegBuffer);
1165 jpeg_write_scanlines(cinfoP, &jpegBuffer, 1);
1166 if (cinfoP->err->trace_level > 1)
1167 pm_message("Done.");
1168 }
1169
1170 pnm_freerow(pnmBuffer);
1171 free(jpegBuffer);
1172 }
1173
1174
1175
1176 int
1177 main(int argc,
1178 const char ** argv) {
1179
1180 struct CmdlineInfo cmdline;
1181 struct jpeg_compress_struct cinfo;
1182 struct jpeg_error_mgr jerr;
1183 FILE * ifP;
1184 FILE * ofP;
1185 int height;
1186 /* height of the input image in rows, as specified by its header */
1187 int width;
1188 /* width of the input image in columns, as specified by its header */
1189 pixval maxval;
1190 /* maximum value of an input pixel component, as specified by header */
1191 int inputFmt;
1192 /* The input format, as determined by its header. */
1193 JSAMPLE *rescale; /* => maxval-remapping array, or NULL */
1194 /* This is an array that maps each possible pixval in the input to
1195 a new value such that while the range of the input values is
1196 0 .. maxval, the range of the output values is 0 .. MAXJSAMPLE.
1197 */
1198
1199 pm_proginit(&argc, argv);
1200
1201 parseCommandLine(argc, argv, &cmdline);
1202
1203 ifP = pm_openr(cmdline.inputFileNm);
1204
1205 ofP = stdout;
1206
1207 /* Open the pnm input */
1208 pnm_readpnminit(ifP, &width, &height, &maxval, &inputFmt);
1209 if (cmdline.verbose) {
1210 pm_message("Input file has format %c%c.\n"
1211 "It has %d rows of %d columns of pixels "
1212 "with max sample value of %d.",
1213 (char) (inputFmt/256), (char) (inputFmt % 256),
1214 height, width, maxval);
1215 }
1216
1217 setupJpeg(&cinfo, &jerr, cmdline, width, height, maxval, inputFmt, ofP);
1218
1219 computeRescalingArray(&rescale, maxval, cinfo);
1220
1221 if (cmdline.comment)
1222 jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *) cmdline.comment,
1223 strlen(cmdline.comment));
1224
1225 if (cmdline.exif)
1226 writeExifHeader(&cinfo, cmdline.exif);
1227
1228 /* Translate and copy over the actual scanlines */
1229 convertScanLines(&cinfo, ifP, maxval, inputFmt, rescale);
1230
1231 /* Finish compression and release memory */
1232 jpeg_finish_compress(&cinfo);
1233 jpeg_destroy_compress(&cinfo);
1234
1235 if (cinfo.scan_info) {
1236 free((void*)cinfo.scan_info);
1237 cinfo.scan_info = NULL;
1238 }
1239 free(rescale);
1240
1241 /* Close files, if we opened them */
1242 if (ifP != stdin)
1243 pm_close(ifP);
1244
1245 free(cmdline.inputFileNm);
1246 /* Program may have exited with non-zero completion code via
1247 various function calls above.
1248 */
1249 return jerr.num_warnings > 0 ? EXIT_WARNING : EXIT_SUCCESS;
1250 }
1251
1252
1253