Debian Codegraph @

pTk/mTk/additions/imgJPEG.c

raw
1 /*
2 * imgJPEG.c --
3 *
4 * A photo image file handler for JPEG files.
5 *
6 * This Tk image format handler reads and writes JPEG files in the standard
7 * JFIF file format. ("JPEG" should be the format name.) It can also read
8 * and write strings containing base64-encoded JPEG data.
9 *
10 * Several options can be provided in the format string, for example:
11 *
12 * imageObject read input.jpg -shrink -format "jpeg -grayscale"
13 * imageObject write output.jpg -format "jpeg -quality 50 -progressive"
14 *
15 * The supported options for reading are:
16 * -fast: Fast, low-quality processing
17 * -grayscale: Force incoming image to grayscale
18 * The supported options for writing are:
19 * -quality N: Compression quality (0..100; 5-95 is useful range)
20 * Default value: 75
21 * -smooth N: Perform smoothing (10-30 is enough for most GIF's)
22 * Default value: 0
23 * -grayscale: Create monochrome JPEG file
24 * -optimize: Optimize Huffman table
25 * -progressive: Create progressive JPEG file
26 *
27 *
28 * Copyright (c) 1996-1997 Thomas G. Lane.
29 * This file is based on tkImgPPM.c from the Tk 4.2 distribution.
30 * That file is
31 * Copyright (c) 1994 The Australian National University.
32 * Copyright (c) 1994-1996 Sun Microsystems, Inc.
33 *
34 * See the file "license.terms" for information on usage and redistribution
35 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
36 *
37 * You will need a copy of the IJG JPEG library, version 5 or later,
38 * to use this file. If you didn't receive it with this package, see
39 * ftp://ftp.uu.net/graphics/jpeg/
40 *
41 * Author: Tom Lane ([email protected])
42 *
43 * Modified for dynamical loading and for reading from channels by:
44 * Jan Nijtmans ([email protected])
45 *
46 * SCCS: @(#) imgJPEG.c
47 */
48
49 /* system includes */
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <setjmp.h>
54
55 /* Tk */
56 #include "imgInt.h"
57
58 /* undef Tcl macros that conflict with libjpeg stuff (sigh) */
59 #undef EXTERN
60
61 /* libjpeg */
62 #ifdef MAC_TCL
63 # include "libjpeg:jpeglib.h"
64 # include "libjpeg:jerror.h"
65 #else
66 # include <sys/types.h>
67 #ifdef HAVE_JPEGLIB_H
68 # include <jpeglib.h>
69 # include <jerror.h>
70 #else
71 # include "libjpeg/jpeglib.h"
72 # include "libjpeg/jerror.h"
73 #endif
74 #endif
75
76 #ifdef __WIN32__
77 #define JPEG_LIB_NAME "jpeg.dll"
78 #endif
79
80 #ifndef JPEG_LIB_NAME
81 #define JPEG_LIB_NAME "libjpeg.so"
82 #endif
83
84 /*
85 * The format record for the JPEG file format:
86 */
87
88 static int ChnMatchJPEG _ANSI_ARGS_((Tcl_Channel chan, char *fileName,
89 char *formatString, int *widthPtr, int *heightPtr));
90 static int FileMatchJPEG _ANSI_ARGS_((FILE *f, char *fileName,
91 char *formatString, int *widthPtr, int *heightPtr));
92 static int ObjMatchJPEG _ANSI_ARGS_((struct Tcl_Obj *dataObj,
93 char *formatString, int *widthPtr, int *heightPtr));
94 static int ChnReadJPEG _ANSI_ARGS_((Tcl_Interp *interp,
95 Tcl_Channel chan, char *fileName, char *formatString,
96 Tk_PhotoHandle imageHandle, int destX, int destY,
97 int width, int height, int srcX, int srcY));
98 static int FileReadJPEG _ANSI_ARGS_((Tcl_Interp *interp,
99 FILE *f, char *fileName, char *formatString,
100 Tk_PhotoHandle imageHandle, int destX, int destY,
101 int width, int height, int srcX, int srcY));
102 static int ObjReadJPEG _ANSI_ARGS_((Tcl_Interp *interp,
103 struct Tcl_Obj *dataObj, char *formatString,
104 Tk_PhotoHandle imageHandle, int destX, int destY,
105 int width, int height, int srcX, int srcY));
106 static int FileWriteJPEG _ANSI_ARGS_((Tcl_Interp *interp,
107 char *fileName, char *formatString,
108 Tk_PhotoImageBlock *blockPtr));
109 static int StringWriteJPEG _ANSI_ARGS_((Tcl_Interp *interp,
110 Tcl_DString *dataPtr, char *formatString,
111 Tk_PhotoImageBlock *blockPtr));
112
113 Tk_PhotoImageFormat imgFmtJPEG = {
114 "JPEG", /* name */
115 (Tk_ImageFileMatchProc *) ChnMatchJPEG, /* fileMatchProc */
116 (Tk_ImageStringMatchProc *) ObjMatchJPEG, /* stringMatchProc */
117 (Tk_ImageFileReadProc *) ChnReadJPEG, /* fileReadProc */
118 (Tk_ImageStringReadProc *) ObjReadJPEG, /* stringReadProc */
119 FileWriteJPEG, /* fileWriteProc */
120 (Tk_ImageStringWriteProc *) StringWriteJPEG,/* stringWriteProc */
121 };
122
123 Tk_PhotoImageFormat imgOldFmtJPEG = {
124 "JPEG", /* name */
125 (Tk_ImageFileMatchProc *) FileMatchJPEG, /* fileMatchProc */
126 (Tk_ImageStringMatchProc *) ObjMatchJPEG, /* stringMatchProc */
127 (Tk_ImageFileReadProc *) FileReadJPEG, /* fileReadProc */
128 (Tk_ImageStringReadProc *) ObjReadJPEG, /* stringReadProc */
129 FileWriteJPEG, /* fileWriteProc */
130 (Tk_ImageStringWriteProc *) StringWriteJPEG, /* stringWriteProc */
131 };
132
133 /*
134 * We use Tk_ParseArgv to parse any options supplied in the format string.
135 */
136
137 static int fast; /* static variables hold parse results */
138 static int grayscale; /* ... icky, and not reentrant ... */
139 static int quality;
140 static int smooth;
141 static int optimize;
142 static int progressive;
143
144 static Tk_ArgvInfo readOptTable[] = {
145 {"-fast", TK_ARGV_CONSTANT, (char *) 1, (char *) &fast,
146 "Fast, low-quality processing"},
147 {"-grayscale", TK_ARGV_CONSTANT, (char *) 1, (char *) &grayscale,
148 "Force incoming image to grayscale"},
149 {NULL, TK_ARGV_END, (char *) NULL, (char *) NULL,
150 (char *) NULL}
151 };
152
153 static Tk_ArgvInfo writeOptTable[] = {
154 {"-quality", TK_ARGV_INT, (char *) NULL, (char *) &quality,
155 "Compression quality (0..100; 5-95 is useful range)"},
156 {"-smooth", TK_ARGV_INT, (char *) NULL, (char *) &smooth,
157 "Smoothing factor (default = 0, 10-30 is enough for typical GIFs.)"},
158 {"-grayscale", TK_ARGV_CONSTANT, (char *) 1, (char *) &grayscale,
159 "Create monochrome JPEG file"},
160 {"-optimize", TK_ARGV_CONSTANT, (char *) 1, (char *) &optimize,
161 "Optimize Huffman table"},
162 {"-progressive", TK_ARGV_CONSTANT, (char *) 1, (char *) &progressive,
163 "Create progressive JPEG file"},
164 {NULL, TK_ARGV_END, (char *) NULL, (char *) NULL,
165 (char *) NULL}
166 };
167
168 /*
169 * Declarations for libjpeg source and destination managers to handle
170 * reading and writing base64-encoded strings.
171 */
172
173 #define STRING_BUF_SIZE 4096 /* choose any convenient size */
174
175 typedef struct str_source_mgr { /* Source manager for reading from string */
176 struct jpeg_source_mgr pub; /* public fields */
177
178 MFile handle; /* base64 stream */
179 JOCTET buffer[STRING_BUF_SIZE]; /* buffer for a chunk of decoded data */
180 } *str_src_ptr;
181
182 typedef struct str_destination_mgr { /* Manager for string output */
183 struct jpeg_destination_mgr pub; /* public fields */
184
185 MFile handle; /* base64 stream */
186 JOCTET buffer[STRING_BUF_SIZE]; /* buffer for a chunk of uncoded data */
187 } *str_dest_ptr;
188
189 /*
190 * Declarations for libjpeg source and destination managers to handle
191 * reading and writing channels.
192 */
193
194 typedef struct chan_source_mgr {/* Source manager for reading from channels */
195 struct jpeg_source_mgr pub; /* public fields */
196
197 Tcl_Channel chan; /* channel */
198 JOCTET buffer[STRING_BUF_SIZE]; /* buffer for a chunk of decoded data */
199 } *chan_src_ptr;
200
201 typedef struct chan_destination_mgr { /* Manager for channel output */
202 struct jpeg_destination_mgr pub; /* public fields */
203
204 Tcl_Channel chan; /* channel */
205 JOCTET buffer[STRING_BUF_SIZE]; /* buffer for a chunk of uncoded data */
206 } *chan_dest_ptr;
207
208 /*
209 * Other declarations
210 */
211
212 struct my_error_mgr { /* Extended libjpeg error manager */
213 struct jpeg_error_mgr pub; /* public fields */
214 jmp_buf setjmp_buffer; /* for return to caller from error exit */
215 };
216
217 /*
218 * Prototypes for local procedures defined in this file:
219 */
220
221 static int CommonMatchJPEG _ANSI_ARGS_((MFile *handle,
222 int *widthPtr, int *heightPtr));
223 static int CommonReadJPEG _ANSI_ARGS_((Tcl_Interp *interp,
224 j_decompress_ptr cinfo, char *formatString,
225 Tk_PhotoHandle imageHandle, int destX, int destY,
226 int width, int height, int srcX, int srcY));
227 static int CommonWriteJPEG _ANSI_ARGS_((Tcl_Interp *interp,
228 j_compress_ptr cinfo, char *formatString,
229 Tk_PhotoImageBlock *blockPtr));
230 static void jpeg_obj_src _ANSI_ARGS_((j_decompress_ptr, struct Tcl_Obj *));
231 static boolean str_fill_input_buffer _ANSI_ARGS_((j_decompress_ptr));
232 static void str_skip_input_data _ANSI_ARGS_((j_decompress_ptr, long));
233 static void dummy_source _ANSI_ARGS_((j_decompress_ptr));
234 static void jpeg_channel_src _ANSI_ARGS_((j_decompress_ptr, Tcl_Channel));
235 static void chan_init_source _ANSI_ARGS_((j_decompress_ptr));
236 static boolean chan_fill_input_buffer _ANSI_ARGS_((j_decompress_ptr));
237 static void chan_skip_input_data _ANSI_ARGS_((j_decompress_ptr, long));
238 static void chan_term_source _ANSI_ARGS_((j_decompress_ptr));
239 static void jpeg_string_dest _ANSI_ARGS_((j_compress_ptr, Tcl_DString*));
240 static void str_init_destination _ANSI_ARGS_((j_compress_ptr));
241 static boolean str_empty_output_buffer _ANSI_ARGS_((j_compress_ptr));
242 static void str_term_destination _ANSI_ARGS_((j_compress_ptr));
243 static void my_error_exit _ANSI_ARGS_((j_common_ptr cinfo));
244 static void my_output_message _ANSI_ARGS_((j_common_ptr cinfo));
245 static void append_jpeg_message _ANSI_ARGS_((Tcl_Interp *interp,
246 j_common_ptr cinfo));
247 static int load_jpeg_library _ANSI_ARGS_((Tcl_Interp *interp));
248 static int CreateCompress _ANSI_ARGS_((j_compress_ptr, int, size_t));
249 static int CreateDecompress _ANSI_ARGS_((j_decompress_ptr, int, size_t));
250
251 /*
252 * Stuff to support dynamic loading of libjpeg
253 */
254
255 static struct JpegFunctions {
256 VOID *handle;
257 int (* abort_decompress) _ANSI_ARGS_((j_decompress_ptr));
258 int (* destroy_compress) _ANSI_ARGS_((j_compress_ptr));
259 int (* destroy_decompress) _ANSI_ARGS_((j_decompress_ptr));
260 int (* finish_compress) _ANSI_ARGS_((j_compress_ptr));
261 int (* finish_decompress) _ANSI_ARGS_((j_decompress_ptr));
262 int (* read_header) _ANSI_ARGS_((j_decompress_ptr, int));
263 JDIMENSION (* read_scanlines) _ANSI_ARGS_((j_decompress_ptr,
264 JSAMPARRAY, JDIMENSION));
265 int (* resync_to_restart) _ANSI_ARGS_((j_decompress_ptr, int));
266 int (* set_defaults) _ANSI_ARGS_((j_compress_ptr));
267 int (* start_compress) _ANSI_ARGS_((j_compress_ptr, int));
268 int (* start_decompress) _ANSI_ARGS_((j_decompress_ptr));
269 int (* stdio_dest) _ANSI_ARGS_((j_compress_ptr, FILE *));
270 int (* stdio_src) _ANSI_ARGS_((j_decompress_ptr, FILE *));
271 struct jpeg_error_mgr *(* std_error) _ANSI_ARGS_((struct jpeg_error_mgr *));
272 JDIMENSION (* write_scanlines) _ANSI_ARGS_((j_compress_ptr,
273 JSAMPARRAY, JDIMENSION));
274 int (* set_colorspace) _ANSI_ARGS_((j_compress_ptr, J_COLOR_SPACE));
275 int (* set_quality) _ANSI_ARGS_((j_compress_ptr, int, int));
276 int (* simple_progression) _ANSI_ARGS_((j_compress_ptr));
277 int (* CreateCompress) _ANSI_ARGS_((j_compress_ptr, int, size_t));
278 int (* CreateDecompress) _ANSI_ARGS_((j_decompress_ptr, int, size_t));
279 int (* create_compress) _ANSI_ARGS_((j_compress_ptr));
280 int (* create_decompress) _ANSI_ARGS_((j_decompress_ptr));
281 void (* destroy) _ANSI_ARGS_((j_common_ptr));
282 JDIMENSION (* write_raw_data) _ANSI_ARGS_((j_compress_ptr,
283 JSAMPIMAGE, JDIMENSION));
284 void (* suppress_tables) _ANSI_ARGS_((j_compress_ptr, boolean));
285 void (* write_tables) _ANSI_ARGS_((j_compress_ptr));
286 JDIMENSION (* read_raw_data) _ANSI_ARGS_((j_decompress_ptr,
287 JSAMPIMAGE, JDIMENSION));
288 void (* abort) _ANSI_ARGS_((j_common_ptr));
289 } jpeg = {0};
290
291 static char *symbols[] = {
292 #ifdef NEED_SHORT_EXTERNAL_NAMES
293 "jAbrtDecompress",
294 "jDestCompress",
295 "jDestDecompress",
296 "jFinCompress",
297 "jFinDecompress",
298 "jReadHeader",
299 "jReadScanlines",
300 "jResyncRestart",
301 "jSetDefaults",
302 "jStrtCompress",
303 "jStrtDecompress",
304 "jStdDest",
305 "jStdSrc",
306 "jStdError",
307 "jWrtScanlines",
308 /* the following 3 symbols are not crucial. They implement
309 resp. the "-grayscale", "-quality" and "-progressive"
310 options. If any of the symbols are missing from the
311 library, the corresponding option just has no effect. */
312 "jSetColorspace",
313 "jSetQuality",
314 "jSimProgress",
315 "jCreaCompress",
316 "jCreaDecompress",
317 "jCreaCompress",
318 "jCreaDecompress",
319 "jDestroy",
320 "jWrtRawData",
321 "jSuppressTables",
322 "jWrtTables",
323 "jReadRawData",
324 "jAbort",
325 #else
326 "jpeg_abort_decompress",
327 "jpeg_destroy_compress",
328 "jpeg_destroy_decompress",
329 "jpeg_finish_compress",
330 "jpeg_finish_decompress",
331 "jpeg_read_header",
332 "jpeg_read_scanlines",
333 "jpeg_resync_to_restart",
334 "jpeg_set_defaults",
335 "jpeg_start_compress",
336 "jpeg_start_decompress",
337 "jpeg_stdio_dest",
338 "jpeg_stdio_src",
339 "jpeg_std_error",
340 "jpeg_write_scanlines",
341 /* the following 3 symbols are not crucial. They implement
342 resp. the "-grayscale", "-quality" and "-progressive"
343 options. If any of the symbols are missing from the
344 library, the corresponding option just has no effect. */
345 "jpeg_set_colorspace",
346 "jpeg_set_quality",
347 "jpeg_simple_progression",
348 /* In later versions, jpeg_create_compress and jpeg_create_decompress
349 are macros pointing to jpeg_CreateCompress and jpeg_CreateDecompres.
350 Which one is found depends on the version. */
351 "jpeg_CreateCompress",
352 "jpeg_CreateDecompress",
353 "jpeg_create_compress",
354 "jpeg_create_decompress",
355 "jpeg_destroy",
356 "jpeg_write_raw_data",
357 "jpeg_suppress_tables",
358 "jpeg_write_tables",
359 "jpeg_read_raw_data",
360 "jpeg_abort",
361 #endif
362 (char *) NULL
363 };
364
365
366 static int
367 load_jpeg_library(interp)
368 Tcl_Interp *interp;
369 {
370 struct jpeg_compress_struct *cinfo; /* libjpeg's parameter structure */
371 struct my_error_mgr jerror; /* for controlling libjpeg error handling */
372 int i;
373
374 if (ImgLoadLib(interp, JPEG_LIB_NAME, &jpeg.handle, symbols, 15)
375 != TCL_OK) {
376 return TCL_ERROR;
377 }
378 if (jpeg.CreateCompress == NULL) {
379 if (jpeg.create_compress == NULL) {
380 goto load_failed;
381 }
382 jpeg.CreateCompress = CreateCompress;
383 }
384 if (jpeg.CreateDecompress == NULL) {
385 if (jpeg.create_decompress == NULL) {
386 goto load_failed;
387 }
388 jpeg.CreateDecompress = CreateDecompress;
389 }
390
391 /* The followin code tries to determine if the JPEG library is
392 valid at all. The library might be configured differently,
393 which will produce core dumps. Also it might be that
394 fields appear in different places in jpeg_compress_struct
395 or jpeg_decompress_struct. This will make the library totally
396 unusable. In stead of a core-dump, we better have a proper
397 error message */
398
399 /* overallocat size, so we don't get a core-dump if the library
400 thinks that the structure is much larger */
401 cinfo = (struct jpeg_compress_struct *)
402 ckalloc(8*sizeof(struct jpeg_compress_struct));
403 cinfo->err = jpeg.std_error(&jerror.pub);
404 jerror.pub.error_exit = my_error_exit;
405 jerror.pub.output_message = my_output_message;
406 /* Establish the setjmp return context for my_error_exit to use. */
407 if (setjmp(jerror.setjmp_buffer)) {
408 /* If we get here, the JPEG library is invalid. */
409 jpeg.destroy_compress(cinfo);
410 ckfree(cinfo);
411 load_failed:
412 if (interp) {
413 Tcl_AppendResult(interp, "couldn't load \"", JPEG_LIB_NAME,
414 "\": please upgrade to at least version 6a", (char *) NULL);
415 }
416 ImgLoadFailed(&jpeg.handle);
417 return TCL_ERROR;
418 }
419
420 /* Now we can initialize libjpeg. */
421 ((char *) cinfo)[sizeof(struct jpeg_compress_struct)] = 53;
422 jpeg.CreateCompress(cinfo, JPEG_LIB_VERSION,
423 (size_t) sizeof(struct jpeg_compress_struct));
424 if (((char *) cinfo)[sizeof(struct jpeg_compress_struct)] != 53) {
425 /* Oops. The library changed this value, which is outside the
426 * structure. Definitely, the library is invalid!!!! */
427 ERREXIT(cinfo, JMSG_NOMESSAGE);
428 }
429
430 /* Set up JPEG compression parameters. */
431 cinfo->image_width = 16;
432 cinfo->image_height = 16;
433 cinfo->input_components = 3;
434 cinfo->in_color_space = JCS_RGB;
435 cinfo->data_precision = -1;
436 cinfo->optimize_coding = TRUE;
437 cinfo->dct_method = -1;
438 cinfo->X_density = 0;
439 cinfo->Y_density = 0;
440 jpeg.set_defaults(cinfo);
441
442 if ((cinfo->data_precision != BITS_IN_JSAMPLE) ||
443 (cinfo->optimize_coding != FALSE) ||
444 (cinfo->dct_method != JDCT_DEFAULT) ||
445 (cinfo->X_density != 1) ||
446 (cinfo->Y_density != 1)) {
447 ERREXIT(cinfo, JMSG_NOMESSAGE);
448 }
449 for (i = 0; i < NUM_ARITH_TBLS; i++) {
450 if ((cinfo->arith_dc_L[i] != 0) ||
451 (cinfo->arith_dc_U[i] != 1) ||
452 (cinfo->arith_ac_K[i] != 5)) {
453 ERREXIT(cinfo, JMSG_NOMESSAGE);
454 }
455 }
456 jpeg.destroy_compress(cinfo);
457 ckfree(cinfo);
458 return TCL_OK;
459 }
460
461 int
462 ImgLoadJpegLibrary()
463 {
464 if ((load_jpeg_library(NULL) == TCL_OK)
465 && jpeg.destroy
466 && jpeg.write_raw_data
467 && jpeg.suppress_tables
468 && jpeg.write_tables
469 && jpeg.read_raw_data
470 && jpeg.abort) {
471 return TCL_OK;
472 }
473 return TCL_ERROR;
474 }
475
476 int Imgjpeg_resync_to_restart _ANSI_ARGS_((j_decompress_ptr, int));
477 JDIMENSION Imgjpeg_read_scanlines _ANSI_ARGS_((j_decompress_ptr,
478 JSAMPARRAY, JDIMENSION));
479 int Imgjpeg_set_colorspace _ANSI_ARGS_((j_compress_ptr, J_COLOR_SPACE));
480 int Imgjpeg_set_defaults _ANSI_ARGS_((j_compress_ptr));
481 int Imgjpeg_start_decompress _ANSI_ARGS_((j_decompress_ptr));
482 void Imgjpeg_destroy _ANSI_ARGS_((j_common_ptr));
483 struct jpeg_error_mgr * Imgjpeg_std_error _ANSI_ARGS_((struct jpeg_error_mgr *));
484 int Imgjpeg_CreateDecompress _ANSI_ARGS_((j_decompress_ptr, int, size_t));
485 JDIMENSION Imgjpeg_write_raw_data _ANSI_ARGS_((j_compress_ptr,
486 JSAMPIMAGE, JDIMENSION));
487 void Imgjpeg_suppress_tables _ANSI_ARGS_((j_compress_ptr, boolean));
488 void Imgjpeg_abort _ANSI_ARGS_((j_common_ptr));
489 int Imgjpeg_read_header _ANSI_ARGS_((j_decompress_ptr, int));
490 int Imgjpeg_start_compress _ANSI_ARGS_((j_compress_ptr, int));
491 void Imgjpeg_write_tables _ANSI_ARGS_((j_compress_ptr));
492 int Imgjpeg_finish_decompress _ANSI_ARGS_((j_decompress_ptr));
493 int Imgjpeg_CreateCompress _ANSI_ARGS_((j_compress_ptr, int, size_t));
494 int Imgjpeg_finish_compress _ANSI_ARGS_((j_compress_ptr));
495 JDIMENSION Imgjpeg_read_raw_data _ANSI_ARGS_((j_decompress_ptr,
496 JSAMPIMAGE, JDIMENSION));
497 int Imgjpeg_set_quality _ANSI_ARGS_((j_compress_ptr, int, int));
498 JDIMENSION Imgjpeg_write_scanlines _ANSI_ARGS_((j_compress_ptr,
499 JSAMPARRAY, JDIMENSION));
500
501 static int
502 CreateCompress(cinfo, version, size)
503 j_compress_ptr cinfo;
504 int version;
505 size_t size;
506 {
507 return jpeg.create_compress(cinfo);
508 }
509
510 static int
511 CreateDecompress(cinfo, version, size)
512 j_decompress_ptr cinfo;
513 int version;
514 size_t size;
515 {
516 return jpeg.create_decompress(cinfo);
517 }
518
519 int
520 Imgjpeg_CreateCompress(cinfo, version, size)
521 j_compress_ptr cinfo;
522 int version;
523 size_t size;
524 {
525 return jpeg.CreateCompress(cinfo, version, size);
526 }
527
528 int
529 Imgjpeg_CreateDecompress(cinfo, version, size)
530 j_decompress_ptr cinfo;
531 int version;
532 size_t size;
533 {
534 return jpeg.CreateDecompress(cinfo, version, size);
535 }
536
537 int
538 Imgjpeg_resync_to_restart(a,b)
539 j_decompress_ptr a;
540 int b;
541 {
542 return jpeg.resync_to_restart(a,b);
543 }
544
545 JDIMENSION
546 Imgjpeg_read_scanlines(a,b,c)
547 j_decompress_ptr a;
548 JSAMPARRAY b;
549 JDIMENSION c;
550 {
551 return jpeg.read_scanlines(a,b,c);
552 }
553
554 int
555 Imgjpeg_set_colorspace(a,b)
556 j_compress_ptr a;
557 J_COLOR_SPACE b;
558 {
559 return jpeg.set_colorspace(a,b);
560 }
561
562 int
563 Imgjpeg_set_defaults(a)
564 j_compress_ptr a;
565 {
566 return jpeg.set_defaults(a);
567 }
568
569 int
570 Imgjpeg_start_decompress(a)
571 j_decompress_ptr a;
572 {
573 return jpeg.start_decompress(a);
574 }
575
576 void
577 Imgjpeg_destroy(a)
578 j_common_ptr a;
579 {
580 jpeg.destroy(a);
581 }
582
583 struct jpeg_error_mgr *
584 Imgjpeg_std_error(a)
585 struct jpeg_error_mgr *a;
586 {
587 return jpeg.std_error(a);
588 }
589
590 JDIMENSION Imgjpeg_write_raw_data(a,b,c)
591 j_compress_ptr a;
592 JSAMPIMAGE b;
593 JDIMENSION c;
594 {
595 return jpeg.write_raw_data(a,b,c);
596 }
597
598 void
599 Imgjpeg_suppress_tables(a,b)
600 j_compress_ptr a;
601 boolean b;
602 {
603 jpeg.suppress_tables(a,b);
604 }
605
606 void
607 Imgjpeg_abort(a)
608 j_common_ptr a;
609 {
610 jpeg.abort(a);
611 }
612
613 int
614 Imgjpeg_read_header(a,b)
615 j_decompress_ptr a;
616 int b;
617 {
618 return jpeg.read_header(a,b);
619 }
620
621 int
622 Imgjpeg_start_compress(a,b)
623 j_compress_ptr a;
624 int b;
625 {
626 return jpeg.start_compress(a,b);
627 }
628
629 void
630 Imgjpeg_write_tables(a)
631 j_compress_ptr a;
632 {
633 jpeg.write_tables(a);
634 }
635
636 int
637 Imgjpeg_finish_decompress(a)
638 j_decompress_ptr a;
639 {
640 return jpeg.finish_decompress(a);
641 }
642
643 int
644 Imgjpeg_finish_compress(a)
645 j_compress_ptr a;
646 {
647 return jpeg.finish_compress(a);
648 }
649
650 JDIMENSION
651 Imgjpeg_read_raw_data(a,b,c)
652 j_decompress_ptr a;
653 JSAMPIMAGE b;
654 JDIMENSION c;
655 {
656 return jpeg.read_raw_data(a,b,c);
657 }
658
659 int
660 Imgjpeg_set_quality(a,b,c)
661 j_compress_ptr a;
662 int b;
663 int c;
664 {
665 return jpeg.set_quality(a,b,c);
666 }
667
668 JDIMENSION
669 Imgjpeg_write_scanlines(a,b,c)
670 j_compress_ptr a;
671 JSAMPARRAY b;
672 JDIMENSION c;
673 {
674 return jpeg.write_scanlines(a,b,c);
675 }
676
677 /*
678 *----------------------------------------------------------------------
679 *
680 * FileMatchJPEG --
681 *
682 * This procedure is invoked by the photo image type to see if
683 * a file contains image data in JPEG format.
684 *
685 * Results:
686 * The return value is >0 if the first characters in file "f" look
687 * like JPEG data, and 0 otherwise. For a valid file, the image
688 * dimensions are determined.
689 *
690 * Side effects:
691 * The access position in f may change.
692 *
693 *----------------------------------------------------------------------
694 */
695
696 static int
697 FileMatchJPEG(f, fileName, formatString, widthPtr, heightPtr)
698 FILE *f; /* The image file, open for reading. */
699 char *fileName; /* The name of the image file. */
700 char *formatString; /* User-specified format string, or NULL. */
701 int *widthPtr, *heightPtr; /* The dimensions of the image are
702 * returned here if the file is a valid
703 * JPEG file. */
704 {
705 MFile handle;
706 handle.data = (char *) f;
707 handle.state = IMG_FILE;
708 return CommonMatchJPEG(&handle, widthPtr, heightPtr);
709 }
710
711 /*
712 *----------------------------------------------------------------------
713 *
714 * ChnMatchJPEG --
715 *
716 * This procedure is invoked by the photo image type to see if
717 * a channel contains image data in JPEG format.
718 *
719 * Results:
720 * The return value is >0 if the first characters in channel "chan"
721 * look like JPEG data, and 0 otherwise. For a valid file, the
722 * image dimensions are determined.
723 *
724 * Side effects:
725 * The access position in f may change.
726 *
727 *----------------------------------------------------------------------
728 */
729
730 static int
731 ChnMatchJPEG(chan, fileName, formatString, widthPtr, heightPtr)
732 Tcl_Channel chan; /* The image channel, open for reading. */
733 char *fileName; /* The name of the image file. */
734 char *formatString; /* User-specified format string, or NULL. */
735 int *widthPtr, *heightPtr; /* The dimensions of the image are
736 * returned here if the file is a valid
737 * JPEG file. */
738 {
739 MFile handle;
740 handle.data = (char *) chan;
741 handle.state = IMG_CHAN;
742 return CommonMatchJPEG(&handle, widthPtr, heightPtr);
743 }
744
745 /*
746 *----------------------------------------------------------------------
747 *
748 * ObjMatchJPEG --
749 *
750 * This procedure is invoked by the photo image type to see if
751 * a string contains image data in JPEG format.
752 *
753 * Results:
754 * The return value is >0 if the first characters in the string look
755 * like JPEG data, and 0 otherwise. For a valid image, the image
756 * dimensions are determined.
757 *
758 * Side effects:
759 * the size of the image is placed in widthPtr and heightPtr.
760 *
761 *----------------------------------------------------------------------
762 */
763
764 static int
765 ObjMatchJPEG(dataObj, formatString, widthPtr, heightPtr)
766 struct Tcl_Obj *dataObj; /* the object containing the image data */
767 char *formatString; /* User-specified format string, or NULL. */
768 int *widthPtr, *heightPtr; /* The dimensions of the image are
769 * returned here if the string is a valid
770 * JPEG image. */
771 {
772 MFile handle;
773 ImgReadInit(dataObj, '\377', &handle);
774 return CommonMatchJPEG(&handle, widthPtr, heightPtr);
775 }
776
777 /*
778 *----------------------------------------------------------------------
779 *
780 * CommonMatchJPEG --
781 *
782 * This procedure is invoked by the photo image type to see if
783 * a string contains image data in JPEG format.
784 *
785 * Results:
786 * The return value is >0 if the first characters in the string look
787 * like JPEG data, and 0 otherwise. For a valid image, the image
788 * dimensions are determined.
789 *
790 * Side effects:
791 * the size of the image is placed in widthPtr and heightPtr.
792 *
793 *----------------------------------------------------------------------
794 */
795
796 static int
797 CommonMatchJPEG(handle, widthPtr, heightPtr)
798 MFile *handle; /* the "file" handle */
799 int *widthPtr, *heightPtr; /* The dimensions of the image are
800 * returned here if the string is a valid
801 * JPEG image. */
802 {
803 char buf[256];
804 int i;
805
806 i = ImgRead(handle, buf, 3);
807 if ((i != 3)||strncmp(buf,"\377\330\377", 3)) {
808 return 0;
809 }
810
811 buf[0] = buf[2];
812 /* at top of loop: have just read first FF of a marker into buf[0] */
813 for (;;) {
814 /* get marker type byte, skipping any padding FFs */
815 while (buf[0] == (char) 0xff) {
816 if (ImgRead(handle, buf,1) != 1) {
817 return 0;
818 }
819 }
820 /* look for SOF0, SOF1, or SOF2, which are the only JPEG variants
821 * currently accepted by libjpeg.
822 */
823 if (buf[0] == (char) 0xc0 || buf[0] == (char) 0xc1
824 || buf[0] == (char) 0xc2)
825 break;
826 /* nope, skip the marker parameters */
827 if (ImgRead(handle, buf, 2) != 2) {
828 return 0;
829 }
830 i = ((buf[0] & 0x0ff)<<8) + (buf[1] & 0x0ff) - 1;
831 while (i>256) {
832 ImgRead(handle, buf, 256);
833 i -= 256;
834 }
835 if ((i<1) || (ImgRead(handle, buf, i)) != i) {
836 return 0;
837 }
838 buf[0] = buf[i-1];
839 /* skip any inter-marker junk (there shouldn't be any, really) */
840 while (buf[0] != (char) 0xff) {
841 if (ImgRead(handle, buf,1) != 1) {
842 return 0;
843 }
844 }
845 }
846 /* Found the SOFn marker, get image dimensions */
847 if (ImgRead(handle, buf, 7) != 7) {
848 return 0;
849 }
850 *heightPtr = ((buf[3] & 0x0ff)<<8) + (buf[4] & 0x0ff);
851 *widthPtr = ((buf[5] & 0x0ff)<<8) + (buf[6] & 0x0ff);
852
853 return 1;
854 }
855
856 /*
857 *----------------------------------------------------------------------
858 *
859 * ChnReadJPEG --
860 *
861 * This procedure is called by the photo image type to read
862 * JPEG format data from a channel, and give it to
863 * the photo image.
864 *
865 * Results:
866 * A standard TCL completion code. If TCL_ERROR is returned
867 * then an error message is left in interp->result.
868 *
869 * Side effects:
870 * New data is added to the image given by imageHandle.
871 *
872 *----------------------------------------------------------------------
873 */
874
875 static int
876 ChnReadJPEG(interp, chan, fileName, formatString, imageHandle, destX, destY,
877 width, height, srcX, srcY)
878 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
879 Tcl_Channel chan; /* The image channel, open for reading. */
880 char *fileName; /* The name of the image file. */
881 char *formatString; /* User-specified format string, or NULL. */
882 Tk_PhotoHandle imageHandle; /* The photo image to write into. */
883 int destX, destY; /* Coordinates of top-left pixel in
884 * photo image to be written to. */
885 int width, height; /* Dimensions of block of photo image to
886 * be written to. */
887 int srcX, srcY; /* Coordinates of top-left pixel to be used
888 * in image being read. */
889 {
890 struct jpeg_decompress_struct cinfo; /* libjpeg's parameter structure */
891 struct my_error_mgr jerror; /* for controlling libjpeg error handling */
892 int result;
893
894 if (load_jpeg_library(interp) != TCL_OK) {
895 return TCL_ERROR;
896 }
897
898 /* Initialize JPEG error handler */
899 /* We set up the normal JPEG error routines, then override error_exit. */
900 cinfo.err = jpeg.std_error(&jerror.pub);
901 jerror.pub.error_exit = my_error_exit;
902 jerror.pub.output_message = my_output_message;
903
904 /* Establish the setjmp return context for my_error_exit to use. */
905 if (setjmp(jerror.setjmp_buffer)) {
906 /* If we get here, the JPEG code has signaled an error. */
907 Tcl_AppendResult(interp, "couldn't read JPEG string: ", (char *) NULL);
908 append_jpeg_message(interp, (j_common_ptr) &cinfo);
909 jpeg.destroy_decompress(&cinfo);
910 return TCL_ERROR;
911 }
912
913 /* Now we can initialize libjpeg. */
914 jpeg.CreateDecompress(&cinfo, JPEG_LIB_VERSION,
915 (size_t) sizeof(struct jpeg_decompress_struct));
916 jpeg_channel_src(&cinfo, chan);
917
918 /* Share code with FileReadJPEG. */
919 result = CommonReadJPEG(interp, &cinfo, formatString, imageHandle,
920 destX, destY, width, height, srcX, srcY);
921
922 /* Reclaim libjpeg's internal resources. */
923 jpeg.destroy_decompress(&cinfo);
924
925 return result;
926 }
927
928 /*
929 *----------------------------------------------------------------------
930 *
931 * FileReadJPEG --
932 *
933 * This procedure is called by the photo image type to read
934 * JPEG format data from a file and write it into a given
935 * photo image.
936 *
937 * Results:
938 * A standard TCL completion code. If TCL_ERROR is returned
939 * then an error message is left in interp->result.
940 *
941 * Side effects:
942 * The access position in file f is changed, and new data is
943 * added to the image given by imageHandle.
944 *
945 *----------------------------------------------------------------------
946 */
947
948 static int
949 FileReadJPEG(interp, f, fileName, formatString, imageHandle, destX, destY,
950 width, height, srcX, srcY)
951 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
952 FILE *f; /* The image file, open for reading. */
953 char *fileName; /* The name of the image file. */
954 char *formatString; /* User-specified format string, or NULL. */
955 Tk_PhotoHandle imageHandle; /* The photo image to write into. */
956 int destX, destY; /* Coordinates of top-left pixel in
957 * photo image to be written to. */
958 int width, height; /* Dimensions of block of photo image to
959 * be written to. */
960 int srcX, srcY; /* Coordinates of top-left pixel to be used
961 * in image being read. */
962 {
963 struct jpeg_decompress_struct cinfo; /* libjpeg's parameter structure */
964 struct my_error_mgr jerror; /* for controlling libjpeg error handling */
965 int result;
966
967 if (load_jpeg_library(interp) != TCL_OK) {
968 return TCL_ERROR;
969 }
970
971 /* Initialize JPEG error handler */
972 /* We set up the normal JPEG error routines, then override error_exit. */
973 cinfo.err = jpeg.std_error(&jerror.pub);
974 jerror.pub.error_exit = my_error_exit;
975 jerror.pub.output_message = my_output_message;
976
977 /* Establish the setjmp return context for my_error_exit to use. */
978 if (setjmp(jerror.setjmp_buffer)) {
979 /* If we get here, the JPEG code has signaled an error. */
980 Tcl_AppendResult(interp, "couldn't read JPEG file \"", fileName,
981 "\": ", (char *) NULL);
982 append_jpeg_message(interp, (j_common_ptr) &cinfo);
983 jpeg.destroy_decompress(&cinfo);
984 return TCL_ERROR;
985 }
986
987 /* Now we can initialize libjpeg. */
988 jpeg.CreateDecompress(&cinfo, JPEG_LIB_VERSION,
989 (size_t) sizeof(struct jpeg_decompress_struct));
990 jpeg.stdio_src(&cinfo, f);
991
992 /* Share code with StringReadJPEG. */
993 result = CommonReadJPEG(interp, &cinfo, formatString, imageHandle,
994 destX, destY, width, height, srcX, srcY);
995
996 /* Reclaim libjpeg's internal resources. */
997 jpeg.destroy_decompress(&cinfo);
998
999 return result;
1000 }
1001
1002 /*
1003 *----------------------------------------------------------------------
1004 *
1005 * ObjReadJPEG --
1006 *
1007 * This procedure is called by the photo image type to read
1008 * JPEG format data from a base64 encoded string, and give it to
1009 * the photo image.
1010 *
1011 * Results:
1012 * A standard TCL completion code. If TCL_ERROR is returned
1013 * then an error message is left in interp->result.
1014 *
1015 * Side effects:
1016 * New data is added to the image given by imageHandle.
1017 *
1018 *----------------------------------------------------------------------
1019 */
1020
1021 static int
1022 ObjReadJPEG(interp, dataObj, formatString, imageHandle, destX, destY,
1023 width, height, srcX, srcY)
1024 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
1025 struct Tcl_Obj *dataObj; /* Object containing the image data. */
1026 char *formatString; /* User-specified format string, or NULL. */
1027 Tk_PhotoHandle imageHandle; /* The photo image to write into. */
1028 int destX, destY; /* Coordinates of top-left pixel in
1029 * photo image to be written to. */
1030 int width, height; /* Dimensions of block of photo image to
1031 * be written to. */
1032 int srcX, srcY; /* Coordinates of top-left pixel to be used
1033 * in image being read. */
1034 {
1035 struct jpeg_decompress_struct cinfo; /* libjpeg's parameter structure */
1036 struct my_error_mgr jerror; /* for controlling libjpeg error handling */
1037 int result;
1038
1039 if (load_jpeg_library(interp) != TCL_OK) {
1040 return TCL_ERROR;
1041 }
1042
1043 /* Initialize JPEG error handler */
1044 /* We set up the normal JPEG error routines, then override error_exit. */
1045 cinfo.err = jpeg.std_error(&jerror.pub);
1046 jerror.pub.error_exit = my_error_exit;
1047 jerror.pub.output_message = my_output_message;
1048
1049 /* Establish the setjmp return context for my_error_exit to use. */
1050 if (setjmp(jerror.setjmp_buffer)) {
1051 /* If we get here, the JPEG code has signaled an error. */
1052 Tcl_AppendResult(interp, "couldn't read JPEG string: ", (char *) NULL);
1053 append_jpeg_message(interp, (j_common_ptr) &cinfo);
1054 jpeg.destroy_decompress(&cinfo);
1055 return TCL_ERROR;
1056 }
1057
1058 /* Now we can initialize libjpeg. */
1059 jpeg.CreateDecompress(&cinfo, JPEG_LIB_VERSION,
1060 (size_t) sizeof(struct jpeg_decompress_struct));
1061 jpeg_obj_src(&cinfo, dataObj);
1062
1063 /* Share code with FileReadJPEG. */
1064 result = CommonReadJPEG(interp, &cinfo, formatString, imageHandle,
1065 destX, destY, width, height, srcX, srcY);
1066
1067 /* Reclaim libjpeg's internal resources. */
1068 jpeg.destroy_decompress(&cinfo);
1069
1070 return result;
1071 }
1072
1073 /*
1074 *----------------------------------------------------------------------
1075 *
1076 * CommonReadJPEG --
1077 *
1078 * The common guts of ChnReadJPEG, FileReadJPEG and ObjReadJPEG.
1079 * The decompress struct has already been set up and the
1080 * appropriate data source manager initialized.
1081 * The caller should do jpeg_destroy_decompress upon return.
1082 *
1083 *----------------------------------------------------------------------
1084 */
1085
1086 typedef struct myblock {
1087 Tk_PhotoImageBlock ck;
1088 int dummy; /* extra space for offset[3], if not included already
1089 in Tk_PhotoImageBlock */
1090 } myblock;
1091
1092 static int
1093 CommonReadJPEG(interp, cinfo, formatString, imageHandle, destX, destY,
1094 width, height, srcX, srcY)
1095 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
1096 j_decompress_ptr cinfo; /* Already-constructed decompress struct. */
1097 char *formatString; /* User-specified format string, or NULL. */
1098 Tk_PhotoHandle imageHandle; /* The photo image to write into. */
1099 int destX, destY; /* Coordinates of top-left pixel in
1100 * photo image to be written to. */
1101 int width, height; /* Dimensions of block of photo image to
1102 * be written to. */
1103 int srcX, srcY; /* Coordinates of top-left pixel to be used
1104 * in image being read. */
1105 {
1106 int fileWidth, fileHeight, stopY, curY, outY, outWidth, outHeight;
1107 myblock bl;
1108 #define block bl.ck
1109 JSAMPARRAY buffer; /* Output row buffer */
1110
1111 /* Ready to read header data. */
1112 jpeg.read_header(cinfo, TRUE);
1113
1114 /* This code only supports 8-bit-precision JPEG files. */
1115 if ((cinfo->data_precision != 8) ||
1116 (sizeof(JSAMPLE) != sizeof(unsigned char))) {
1117 Tcl_AppendResult(interp, "Unsupported JPEG precision", (char *) NULL);
1118 return TCL_ERROR;
1119 }
1120
1121 /* Process format parameters to adjust decompression options. */
1122 if (formatString != NULL) {
1123 int argc;
1124 char **argv;
1125 if (Tcl_SplitList(interp, formatString, &argc, &argv) != TCL_OK)
1126 return TCL_ERROR;
1127 fast = 0;
1128 grayscale = 0;
1129 if (Tk_ParseArgv(interp, (Tk_Window) NULL, &argc, argv,
1130 readOptTable, TK_ARGV_NO_LEFTOVERS|TK_ARGV_NO_DEFAULTS)
1131 != TCL_OK) {
1132 ckfree((char *) argv);
1133 return TCL_ERROR;
1134 }
1135 if (fast) {
1136 /* Select recommended processing options for quick-and-dirty output. */
1137 cinfo->two_pass_quantize = FALSE;
1138 cinfo->dither_mode = JDITHER_ORDERED;
1139 cinfo->dct_method = JDCT_FASTEST;
1140 cinfo->do_fancy_upsampling = FALSE;
1141 }
1142 if (grayscale) {
1143 /* Force monochrome output. */
1144 cinfo->out_color_space = JCS_GRAYSCALE;
1145 }
1146 ckfree((char *) argv);
1147 }
1148
1149 jpeg.start_decompress(cinfo);
1150
1151 /* Check dimensions. */
1152 fileWidth = (int) cinfo->output_width;
1153 fileHeight = (int) cinfo->output_height;
1154 if ((srcX + width) > fileWidth) {
1155 outWidth = fileWidth - srcX;
1156 } else {
1157 outWidth = width;
1158 }
1159 if ((srcY + height) > fileHeight) {
1160 outHeight = fileHeight - srcY;
1161 } else {
1162 outHeight = height;
1163 }
1164 if ((outWidth <= 0) || (outHeight <= 0)
1165 || (srcX >= fileWidth) || (srcY >= fileHeight)) {
1166 return TCL_OK;
1167 }
1168
1169 /* Check colorspace. */
1170 switch (cinfo->out_color_space) {
1171 case JCS_GRAYSCALE:
1172 /* a single-sample grayscale pixel is expanded into equal R,G,B values */
1173 block.pixelSize = 1;
1174 block.offset[0] = 0;
1175 block.offset[1] = 0;
1176 block.offset[2] = 0;
1177 break;
1178 case JCS_RGB:
1179 /* note: this pixel layout assumes default configuration of libjpeg. */
1180 block.pixelSize = 3;
1181 block.offset[0] = 0;
1182 block.offset[1] = 1;
1183 block.offset[2] = 2;
1184 break;
1185 default:
1186 Tcl_AppendResult(interp, "Unsupported JPEG color space", (char *) NULL);
1187 return TCL_ERROR;
1188 }
1189 block.width = outWidth;
1190 block.height = 1;
1191 block.pitch = block.pixelSize * fileWidth;
1192 block.offset[3] = 0;
1193
1194 Tk_PhotoExpand(imageHandle, destX + outWidth, destY + outHeight);
1195
1196 /* Make a temporary one-row-high sample array */
1197 buffer = (*cinfo->mem->alloc_sarray)
1198 ((j_common_ptr) cinfo, JPOOL_IMAGE,
1199 cinfo->output_width * cinfo->output_components, 1);
1200 block.pixelPtr = (unsigned char *) buffer[0] + srcX * block.pixelSize;
1201
1202 /* Read as much of the data as we need to */
1203 stopY = srcY + outHeight;
1204 outY = destY;
1205 for (curY = 0; curY < stopY; curY++) {
1206 jpeg.read_scanlines(cinfo, buffer, 1);
1207 if (curY >= srcY) {
1208 Tk_PhotoPutBlock(imageHandle, &block, destX, outY, outWidth, 1);
1209 outY++;
1210 }
1211 }
1212
1213 /* Do normal cleanup if we read the whole image; else early abort */
1214 if (cinfo->output_scanline == cinfo->output_height)
1215 jpeg.finish_decompress(cinfo);
1216 else
1217 jpeg.abort_decompress(cinfo);
1218
1219 return TCL_OK;
1220 }
1221
1222 /*
1223 *----------------------------------------------------------------------
1224 *
1225 * FileWriteJPEG --
1226 *
1227 * This procedure is invoked to write image data to a file in JPEG
1228 * format.
1229 *
1230 * Results:
1231 * A standard TCL completion code. If TCL_ERROR is returned
1232 * then an error message is left in interp->result.
1233 *
1234 * Side effects:
1235 * Data is written to the file given by "fileName".
1236 *
1237 *----------------------------------------------------------------------
1238 */
1239
1240 static int
1241 FileWriteJPEG(interp, fileName, formatString, blockPtr)
1242 Tcl_Interp *interp;
1243 char *fileName;
1244 char *formatString;
1245 Tk_PhotoImageBlock *blockPtr;
1246 {
1247 struct jpeg_compress_struct cinfo; /* libjpeg's parameter structure */
1248 struct my_error_mgr jerror; /* for controlling libjpeg error handling */
1249 Tcl_DString nameBuffer;
1250 char *fullName;
1251 FILE *f;
1252 int result;
1253
1254 if ((fullName=Tcl_TranslateFileName(interp,fileName,&nameBuffer))==NULL) {
1255 return TCL_ERROR;
1256 }
1257 if ((f = fopen(fullName, "wb")) == NULL) {
1258 Tcl_AppendResult(interp, fileName, ": ", Tcl_PosixError(interp),
1259 (char *) NULL);
1260 Tcl_DStringFree(&nameBuffer);
1261 return TCL_ERROR;
1262 }
1263 Tcl_DStringFree(&nameBuffer);
1264
1265 if (load_jpeg_library(interp) != TCL_OK) {
1266 return TCL_ERROR;
1267 }
1268
1269 /* Initialize JPEG error handler */
1270 /* We set up the normal JPEG error routines, then override error_exit. */
1271 cinfo.err = jpeg.std_error(&jerror.pub);
1272 jerror.pub.error_exit = my_error_exit;
1273 jerror.pub.output_message = my_output_message;
1274
1275 /* Establish the setjmp return context for my_error_exit to use. */
1276 if (setjmp(jerror.setjmp_buffer)) {
1277 /* If we get here, the JPEG code has signaled an error. */
1278 Tcl_AppendResult(interp, "couldn't write JPEG file \"", fileName,
1279 "\": ", (char *) NULL);
1280 append_jpeg_message(interp, (j_common_ptr) &cinfo);
1281 jpeg.destroy_compress(&cinfo);
1282 fclose(f);
1283 return TCL_ERROR;
1284 }
1285
1286 /* Now we can initialize libjpeg. */
1287 jpeg.CreateCompress(&cinfo, JPEG_LIB_VERSION,
1288 (size_t) sizeof(struct jpeg_compress_struct));
1289 jpeg.stdio_dest(&cinfo, f);
1290
1291 /* Share code with StringWriteJPEG. */
1292 result = CommonWriteJPEG(interp, &cinfo, formatString, blockPtr);
1293
1294 jpeg.destroy_compress(&cinfo);
1295
1296 fclose(f);
1297 return result;
1298 }
1299
1300 /*
1301 *----------------------------------------------------------------------
1302 *
1303 * StringWriteJPEG --
1304 *
1305 * This procedure is called by the photo image type to write
1306 * JPEG format data to a base-64 encoded string from the photo block.
1307 *
1308 * Results:
1309 * A standard TCL completion code. If TCL_ERROR is returned
1310 * then an error message is left in interp->result.
1311 *
1312 * Side effects:
1313 * None.
1314 *
1315 *----------------------------------------------------------------------
1316 */
1317
1318 static int
1319 StringWriteJPEG(interp, dataPtr, formatString, blockPtr)
1320 Tcl_Interp *interp;
1321 Tcl_DString *dataPtr;
1322 char *formatString;
1323 Tk_PhotoImageBlock *blockPtr;
1324 {
1325 struct jpeg_compress_struct cinfo; /* libjpeg's parameter structure */
1326 struct my_error_mgr jerror; /* for controlling libjpeg error handling */
1327 int result;
1328
1329 if (load_jpeg_library(interp) != TCL_OK) {
1330 return TCL_ERROR;
1331 }
1332
1333 /* Initialize JPEG error handler */
1334 /* We set up the normal JPEG error routines, then override error_exit. */
1335 cinfo.err = jpeg.std_error(&jerror.pub);
1336 jerror.pub.error_exit = my_error_exit;
1337 jerror.pub.output_message = my_output_message;
1338
1339 /* Establish the setjmp return context for my_error_exit to use. */
1340 if (setjmp(jerror.setjmp_buffer)) {
1341 /* If we get here, the JPEG code has signaled an error. */
1342 Tcl_AppendResult(interp, "couldn't write JPEG string: ", (char *) NULL);
1343 append_jpeg_message(interp, (j_common_ptr) &cinfo);
1344 jpeg.destroy_compress(&cinfo);
1345 return TCL_ERROR;
1346 }
1347
1348 /* Now we can initialize libjpeg. */
1349 jpeg.CreateCompress(&cinfo, JPEG_LIB_VERSION,
1350 (size_t) sizeof(struct jpeg_compress_struct));
1351 jpeg_string_dest(&cinfo, dataPtr);
1352
1353 /* Share code with FileWriteJPEG. */
1354 result = CommonWriteJPEG(interp, &cinfo, formatString, blockPtr);
1355
1356 jpeg.destroy_compress(&cinfo);
1357
1358 return result;
1359 }
1360
1361 /*
1362 *----------------------------------------------------------------------
1363 *
1364 * CommonWriteJPEG --
1365 *
1366 * The common guts of FileWriteJPEG and StringWriteJPEG.
1367 * The compress struct has already been set up and the
1368 * appropriate data destination manager initialized.
1369 * The caller should do jpeg_destroy_compress upon return,
1370 * and also close the destination as necessary.
1371 *
1372 *----------------------------------------------------------------------
1373 */
1374
1375 static int
1376 CommonWriteJPEG(interp, cinfo, formatString, blockPtr)
1377 Tcl_Interp *interp;
1378 j_compress_ptr cinfo;
1379 char *formatString;
1380 Tk_PhotoImageBlock *blockPtr;
1381 {
1382 JSAMPROW row_pointer[1]; /* pointer to original data scanlines */
1383 JSAMPARRAY buffer; /* Intermediate row buffer */
1384 JSAMPROW bufferPtr;
1385 int w, h;
1386 int greenOffset, blueOffset, alphaOffset;
1387 unsigned char *pixelPtr, *pixLinePtr;
1388
1389 grayscale = 0;
1390 greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
1391 blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
1392 alphaOffset = blockPtr->offset[0];
1393 if (alphaOffset < blockPtr->offset[2]) {
1394 alphaOffset = blockPtr->offset[2];
1395 }
1396 if (++alphaOffset < blockPtr->pixelSize) {
1397 alphaOffset -= blockPtr->offset[0];
1398 } else {
1399 alphaOffset = 0;
1400 }
1401
1402 /* Set up JPEG compression parameters. */
1403 cinfo->image_width = blockPtr->width;
1404 cinfo->image_height = blockPtr->height;
1405 cinfo->input_components = 3;
1406 cinfo->in_color_space = JCS_RGB;
1407
1408 jpeg.set_defaults(cinfo);
1409
1410 /* Parse options, if any, and alter default parameters */
1411 if (formatString != NULL) {
1412 int argc;
1413 char **argv;
1414 if (Tcl_SplitList(interp, formatString, &argc, &argv) != TCL_OK)
1415 return TCL_ERROR;
1416 quality = 75; /* default values */
1417 smooth = 0;
1418 optimize = 0;
1419 progressive = 0;
1420 if (Tk_ParseArgv(interp, (Tk_Window) NULL, &argc, argv,
1421 writeOptTable, TK_ARGV_NO_LEFTOVERS|TK_ARGV_NO_DEFAULTS)
1422 != TCL_OK) {
1423 ckfree((char *) argv);
1424 return TCL_ERROR;
1425 }
1426 if (jpeg.set_quality != NULL) {
1427 jpeg.set_quality(cinfo, quality, FALSE);
1428 }
1429 cinfo->smoothing_factor = smooth;
1430 if (grayscale && (jpeg.set_colorspace != NULL)) {
1431 /* Force a monochrome JPEG file to be generated. */
1432 jpeg.set_colorspace(cinfo, JCS_GRAYSCALE);
1433 }
1434 if (optimize) {
1435 /* Enable entropy parm optimization. */
1436 cinfo->optimize_coding = TRUE;
1437 }
1438 if (progressive && (jpeg.simple_progression != NULL)) {
1439 /* Select simple progressive mode. */
1440 jpeg.simple_progression(cinfo);
1441 }
1442 ckfree((char *) argv);
1443 }
1444
1445 pixLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
1446 greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
1447 blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
1448 if ((jpeg.set_colorspace != NULL) &&
1449 (grayscale || (!greenOffset && !blueOffset))) {
1450 /* Generate monochrome JPEG file if source block is grayscale. */
1451 jpeg.set_colorspace(cinfo, JCS_GRAYSCALE);
1452 }
1453
1454 jpeg.start_compress(cinfo, TRUE);
1455
1456 /* note: we assume libjpeg is configured for standard RGB pixel order. */
1457 if ((greenOffset == 1) && (blueOffset == 2)
1458 && (blockPtr->pixelSize == 3)) {
1459 /* No need to reformat pixels before passing data to libjpeg */
1460 for (h = blockPtr->height; h > 0; h--) {
1461 row_pointer[0] = (JSAMPROW) pixLinePtr;
1462 jpeg.write_scanlines(cinfo, row_pointer, 1);
1463 pixLinePtr += blockPtr->pitch;
1464 }
1465 } else {
1466 /* Must convert data format. Create a one-scanline work buffer. */
1467 buffer = (*cinfo->mem->alloc_sarray)
1468 ((j_common_ptr) cinfo, JPOOL_IMAGE,
1469 cinfo->image_width * cinfo->input_components, 1);
1470 for (h = blockPtr->height; h > 0; h--) {
1471 pixelPtr = pixLinePtr;
1472 bufferPtr = buffer[0];
1473 for (w = blockPtr->width; w > 0; w--) {
1474 if (alphaOffset && !pixelPtr[alphaOffset]) {
1475 /* if pixel is transparant, better use gray
1476 * than the default black.
1477 */
1478 *bufferPtr++ = 0xd9;
1479 *bufferPtr++ = 0xd9;
1480 *bufferPtr++ = 0xd9;
1481 } else {
1482 *bufferPtr++ = pixelPtr[0];
1483 *bufferPtr++ = pixelPtr[greenOffset];
1484 *bufferPtr++ = pixelPtr[blueOffset];
1485 }
1486 pixelPtr += blockPtr->pixelSize;
1487 }
1488 jpeg.write_scanlines(cinfo, buffer, 1);
1489 pixLinePtr += blockPtr->pitch;
1490 }
1491 }
1492
1493 jpeg.finish_compress(cinfo);
1494
1495 return TCL_OK;
1496 }
1497
1498 /*
1499 * libjpeg source manager for reading from base64-encoded strings.
1500 */
1501 static void
1502 jpeg_obj_src (cinfo, dataObj)
1503 j_decompress_ptr cinfo;
1504 struct Tcl_Obj *dataObj;
1505 {
1506 str_src_ptr src;
1507
1508 src = (str_src_ptr)
1509 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
1510 sizeof(struct str_source_mgr));
1511 cinfo->src = (struct jpeg_source_mgr *) src;
1512
1513 src->pub.init_source = dummy_source;
1514 src->pub.fill_input_buffer = str_fill_input_buffer;
1515 src->pub.skip_input_data = str_skip_input_data;
1516 src->pub.resync_to_restart = jpeg.resync_to_restart; /* use default method */
1517 src->pub.term_source = dummy_source;
1518
1519 ImgReadInit(dataObj, '\377', &src->handle);
1520
1521 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
1522 src->pub.next_input_byte = NULL; /* until buffer loaded */
1523 }
1524
1525 static boolean
1526 str_fill_input_buffer(cinfo)
1527 j_decompress_ptr cinfo;
1528 {
1529 str_src_ptr src = (str_src_ptr) cinfo->src;
1530 int nbytes;
1531 int c;
1532
1533 nbytes = 0;
1534 while (nbytes < STRING_BUF_SIZE &&
1535 (c = ImgGetc(&src->handle)) != IMG_DONE) {
1536 src->buffer[nbytes++] = (JOCTET) c;
1537 }
1538
1539 if (nbytes <= 0) {
1540 /* Insert a fake EOI marker */
1541 src->buffer[0] = (JOCTET) 0xFF;
1542 src->buffer[1] = (JOCTET) JPEG_EOI;
1543 nbytes = 2;
1544 }
1545
1546 src->pub.next_input_byte = src->buffer;
1547 src->pub.bytes_in_buffer = nbytes;
1548
1549 return TRUE;
1550 }
1551
1552 static void
1553 str_skip_input_data(cinfo, num_bytes)
1554 j_decompress_ptr cinfo;
1555 long num_bytes;
1556 {
1557 str_src_ptr src = (str_src_ptr) cinfo->src;
1558
1559 if (num_bytes > 0) {
1560 while (num_bytes > (long) src->pub.bytes_in_buffer) {
1561 num_bytes -= (long) src->pub.bytes_in_buffer;
1562 str_fill_input_buffer(cinfo);
1563 }
1564 src->pub.next_input_byte += (size_t) num_bytes;
1565 src->pub.bytes_in_buffer -= (size_t) num_bytes;
1566 }
1567 }
1568
1569 static void
1570 dummy_source(cinfo)
1571 j_decompress_ptr cinfo;
1572 {
1573 /* no work necessary here */
1574 }
1575
1576 /*
1577 * libjpeg source manager for reading from channels.
1578 */
1579 static void
1580 jpeg_channel_src (cinfo, chan)
1581 j_decompress_ptr cinfo;
1582 Tcl_Channel chan;
1583 {
1584 chan_src_ptr src;
1585
1586 src = (chan_src_ptr)
1587 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
1588 sizeof(struct chan_source_mgr));
1589 cinfo->src = (struct jpeg_source_mgr *) src;
1590
1591 src->pub.init_source = chan_init_source;
1592 src->pub.fill_input_buffer = chan_fill_input_buffer;
1593 src->pub.skip_input_data = chan_skip_input_data;
1594 src->pub.resync_to_restart = jpeg.resync_to_restart; /* use default method */
1595 src->pub.term_source = chan_term_source;
1596
1597 src->chan = chan;
1598
1599 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
1600 src->pub.next_input_byte = NULL; /* until buffer loaded */
1601 }
1602
1603 static void
1604 chan_init_source(cinfo)
1605 j_decompress_ptr cinfo;
1606 {
1607 /* no work necessary here */
1608 }
1609
1610 static boolean
1611 chan_fill_input_buffer(cinfo)
1612 j_decompress_ptr cinfo;
1613 {
1614 chan_src_ptr src = (chan_src_ptr) cinfo->src;
1615 int nbytes;
1616
1617 nbytes = Tcl_Read(src->chan, src->buffer, STRING_BUF_SIZE);
1618
1619 if (nbytes <= 0) {
1620 WARNMS(cinfo, JWRN_JPEG_EOF);
1621 /* Insert a fake EOI marker */
1622 src->buffer[0] = (JOCTET) 0xFF;
1623 src->buffer[1] = (JOCTET) JPEG_EOI;
1624 nbytes = 2;
1625 }
1626
1627 src->pub.next_input_byte = src->buffer;
1628 src->pub.bytes_in_buffer = (size_t) nbytes;
1629
1630 return TRUE;
1631 }
1632
1633 static void
1634 chan_skip_input_data(cinfo, num_bytes)
1635 j_decompress_ptr cinfo;
1636 long num_bytes;
1637 {
1638 chan_src_ptr src = (chan_src_ptr) cinfo->src;
1639
1640 if (num_bytes > 0) {
1641 while (num_bytes > (long) src->pub.bytes_in_buffer) {
1642 num_bytes -= (long) src->pub.bytes_in_buffer;
1643 chan_fill_input_buffer(cinfo);
1644 }
1645 src->pub.next_input_byte += num_bytes;
1646 src->pub.bytes_in_buffer -= num_bytes;
1647 }
1648 }
1649
1650 static void
1651 chan_term_source(cinfo)
1652 j_decompress_ptr cinfo;
1653 {
1654 /* no work necessary here */
1655 }
1656
1657 /*
1658 * libjpeg destination manager for writing to base64-encoded strings.
1659 */
1660 static void
1661 jpeg_string_dest (cinfo, dstring)
1662 j_compress_ptr cinfo;
1663 Tcl_DString* dstring;
1664 {
1665 str_dest_ptr dest;
1666
1667 if (cinfo->dest == NULL) { /* first time for this JPEG object? */
1668 cinfo->dest = (struct jpeg_destination_mgr *)
1669 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
1670 sizeof(struct str_destination_mgr));
1671 }
1672
1673 dest = (str_dest_ptr) cinfo->dest;
1674 dest->pub.init_destination = str_init_destination;
1675 dest->pub.empty_output_buffer = str_empty_output_buffer;
1676 dest->pub.term_destination = str_term_destination;
1677 dest->handle.buffer = dstring;
1678 }
1679
1680 static void
1681 str_init_destination (cinfo)
1682 j_compress_ptr cinfo;
1683 {
1684 str_dest_ptr dest = (str_dest_ptr) cinfo->dest;
1685
1686 Tcl_DStringSetLength(dest->handle.buffer, dest->handle.buffer->spaceAvl);
1687 dest->handle.data = Tcl_DStringValue(dest->handle.buffer);
1688 dest->handle.state = 0;
1689 dest->handle.length = 0;
1690 dest->pub.next_output_byte = dest->buffer;
1691 dest->pub.free_in_buffer = STRING_BUF_SIZE;
1692 }
1693
1694 static boolean
1695 str_empty_output_buffer (cinfo)
1696 j_compress_ptr cinfo;
1697 {
1698 str_dest_ptr dest = (str_dest_ptr) cinfo->dest;
1699
1700 if (ImgWrite(&dest->handle, (char *) dest->buffer, STRING_BUF_SIZE)
1701 != STRING_BUF_SIZE)
1702 ERREXIT(cinfo, JERR_FILE_WRITE);
1703
1704 dest->pub.next_output_byte = dest->buffer;
1705 dest->pub.free_in_buffer = STRING_BUF_SIZE;
1706
1707 return TRUE;
1708 }
1709
1710 static void
1711 str_term_destination (cinfo)
1712 j_compress_ptr cinfo;
1713 {
1714 str_dest_ptr dest = (str_dest_ptr) cinfo->dest;
1715 int datacount = STRING_BUF_SIZE - (int) dest->pub.free_in_buffer;
1716
1717 /* Write any data remaining in the buffer */
1718 if (datacount > 0) {
1719 if (ImgWrite(&dest->handle, (char *) dest->buffer, datacount)
1720 != datacount)
1721 ERREXIT(cinfo, JERR_FILE_WRITE);
1722 }
1723
1724 /* Empty any partial-byte from the base64 encoder */
1725 ImgPutc(IMG_DONE, &dest->handle);
1726 }
1727
1728
1729 /*
1730 * Error handler to replace (or extend, really) libjpeg's default handler
1731 */
1732
1733 static void
1734 my_error_exit (cinfo)
1735 j_common_ptr cinfo;
1736 {
1737 struct my_error_mgr *myerr = (struct my_error_mgr *) cinfo->err;
1738 /* Exit back to outer level */
1739 longjmp(myerr->setjmp_buffer, 1);
1740 }
1741
1742 static void
1743 append_jpeg_message (interp, cinfo)
1744 Tcl_Interp *interp;
1745 j_common_ptr cinfo;
1746 {
1747 /* Append libjpeg error message to interp->result */
1748 char buffer[JMSG_LENGTH_MAX];
1749 (*cinfo->err->format_message) (cinfo, buffer);
1750 Tcl_AppendResult(interp, buffer, (char *) NULL);
1751 }
1752
1753 static void
1754 my_output_message (cinfo)
1755 j_common_ptr cinfo;
1756 {
1757 /* Override libjpeg's output_message to do nothing.
1758 * This ensures that warning messages will not appear on stderr,
1759 * even for a corrupted JPEG file. Too bad there's no way
1760 * to report a "warning" message to the calling Tcl script.
1761 */
1762 }