Debian Codegraph @

minorGems/graphics/converters/unix/JPEGImageConverterUnix.cpp

raw
1 /*
2 * Modification History
3 *
4 * 2001-April-27 Jason Rohrer
5 * Created.
6 *
7 * 2001-April-29 Jason Rohrer
8 * Finished implementation.
9 * Added an optimization to formatImage, but it did not improve
10 * performance, so it has been commented out.
11 */
12
13 /**
14 * Unix-specific JPEGImageConverter implementation
15 *
16 * Code for compression and decompression modeled after IJG's
17 * libjpeg example code.
18 *
19 * For now, it use libjpeg to write converted data out to
20 * file, and then reads it back in.
21 */
22
23
24 #include "minorGems/graphics/converters/JPEGImageConverter.h"
25 #include "minorGems/io/file/File.h"
26
27
28 #include <stdio.h>
29 #include <stdlib.h>
30
31 #include <string.h>
32
33 // include the jpeg library as a C file.
34 // (yuk... spent way too much time trying to figure this one out!)
35 extern "C" {
36 #include<jpeglib.h>
37 }
38
39 /*
40 * <setjmp.h> is used for the decompression
41 * error recovery mechanism.
42 */
43
44 #include <setjmp.h>
45
46
47
48 void JPEGImageConverter::formatImage( Image *inImage,
49 OutputStream *inStream ) {
50
51 if( inImage->getNumChannels() != 3 ) {
52 printf( "JPEGImageConverter only works on 3-channel images.\n" );
53 return;
54 }
55
56 // most of this code was copied without modification from
57 // IJG's example.c
58
59 // This struct contains the JPEG compression parameters and pointers to
60 // working space (which is allocated as needed by the JPEG library).
61 // It is possible to have several such structures, representing multiple
62 // compression/decompression processes, in existence at once. We refer
63 // to any one struct (and its associated working data) as a "JPEG object".
64
65 struct jpeg_compress_struct cinfo;
66
67 // This struct represents a JPEG error handler. It is declared separately
68 // because applications often want to supply a specialized error handler
69 // (see the second half of this file for an example). But here we just
70 // take the easy way out and use the standard error handler, which will
71 // print a message on stderr and call exit() if compression fails.
72 // Note that this struct must live as long as the main JPEG parameter
73 // struct, to avoid dangling-pointer problems.
74
75 struct jpeg_error_mgr jerr;
76
77 // More stuff
78 FILE * outfile; // target file
79 JSAMPROW row_pointer[1]; // pointer to JSAMPLE row[s]
80 int row_stride; // physical row width in image buffer
81
82 // Step 1: allocate and initialize JPEG compression object
83
84 // We have to set up the error handler first, in case the initialization
85 // step fails. (Unlikely, but it could happen if you are out of memory.)
86 // This routine fills in the contents of struct jerr, and returns jerr's
87 // address which we place into the link field in cinfo.
88
89 cinfo.err = jpeg_std_error( &jerr );
90 // Now we can initialize the JPEG compression object.
91 jpeg_create_compress( &cinfo );
92
93 // Step 2: specify data destination (eg, a file)
94 // Note: steps 2 and 3 can be done in either order.
95
96 // use a temp file with a random name to make this more
97 // thread-safe
98 char *fileName = new char[99];
99 sprintf( fileName, "temp%d.dat", rand() );
100
101 // Here we use the library-supplied code to send compressed data to a
102 // stdio stream. You can also write your own code to do something else.
103 // VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
104 // requires it in order to write binary files.
105
106 if( ( outfile = fopen( fileName, "wb" ) ) == NULL ) {
107 printf( "can't open jpeg conversion temp file %s\n", fileName );
108 return;
109 }
110
111 jpeg_stdio_dest( &cinfo, outfile );
112
113
114 // Step 3: set parameters for compression
115
116 // First we supply a description of the input image.
117 // Four fields of the cinfo struct must be filled in:
118
119
120 // image width and height, in pixels
121 cinfo.image_width = inImage->getWidth();
122 cinfo.image_height = inImage->getHeight();
123 cinfo.input_components = 3; // # of color components per pixel
124 cinfo.in_color_space = JCS_RGB; // colorspace of input image
125 // Now use the library's routine to set default compression parameters.
126 // (You must set at least cinfo.in_color_space before calling this,
127 // since the defaults depend on the source color space.)
128
129 jpeg_set_defaults( &cinfo );
130 // Now you can set any non-default parameters you wish to.
131 // Here we just illustrate the use of
132 // quality (quantization table) scaling:
133
134 jpeg_set_quality( &cinfo, mQuality,
135 TRUE ); // limit to baseline-JPEG values
136
137 // Step 4: Start compressor
138
139 // TRUE ensures that we will write a complete interchange-JPEG file.
140 // Pass TRUE unless you are very sure of what you're doing.
141
142 jpeg_start_compress( &cinfo, TRUE );
143
144 // Step 5: while (scan lines remain to be written)
145 // jpeg_write_scanlines(...);
146
147 // Here we use the library's state variable cinfo.next_scanline as the
148 // loop counter, so that we don't have to keep track ourselves.
149 // To keep things simple, we pass one scanline per call; you can pass
150 // more if you wish, though.
151
152 // JSAMPLEs per row in image_buffer
153 row_stride = cinfo.image_width * 3;
154
155 // channels of inImage, which we will need to pull pixel values out of
156 double *redChannel = inImage->getChannel(0);
157 double *greenChannel = inImage->getChannel(1);
158 double *blueChannel = inImage->getChannel(2);
159
160 // array that we will copy inImage pixels into
161 // one scanline at a time
162 row_pointer[0] = new JSAMPLE[ row_stride ];
163
164 //int rowNumber = 0;
165
166 while( cinfo.next_scanline < cinfo.image_height ) {
167 // jpeg_write_scanlines expects an array of pointers to scanlines.
168 // Here the array is only one element long, but you could pass
169 // more than one scanline at a time if that's more convenient.
170
171
172 // make a scanline
173
174
175 int yOffset = cinfo.next_scanline * cinfo.image_width;
176
177 // for each pixel in the row
178 for( int p=0; p<cinfo.image_width; p++ ) {
179 // index into inImage
180 int pixelIndex = p + yOffset;
181
182 // index into this row
183 int startRowIndex = p * 3;
184
185 // red
186 row_pointer[0][ startRowIndex ] =
187 (JSAMPLE)( redChannel[ pixelIndex ] * 255 );
188 // green
189 row_pointer[0][ startRowIndex + 1 ] =
190 (JSAMPLE)( greenChannel[ pixelIndex ] * 255 );
191 // blue
192 row_pointer[0][ startRowIndex + 2 ] =
193 (JSAMPLE)( blueChannel[ pixelIndex ] * 255 );
194 }
195
196
197 // now pass the scanline into libjpeg
198 (void) jpeg_write_scanlines( &cinfo, row_pointer, 1 );
199
200 //rowNumber++;
201 }
202
203 delete [] ( row_pointer[0] );
204
205
206 // Step 6: Finish compression
207
208 jpeg_finish_compress( &cinfo );
209 // After finish_compress, we can close the output file.
210 fclose( outfile );
211
212 // Step 7: release JPEG compression object
213
214 // This is an important step since it
215 // will release a good deal of memory.
216
217 jpeg_destroy_compress( &cinfo );
218
219
220 // now read the compressed data back in from file
221 File *file = new File( NULL, fileName, strlen( fileName ) );
222
223 FILE *inFile = fopen( fileName, "rb" );
224
225 if( inFile == NULL ) {
226 printf( "can't open jpeg conversion temp file %s\n", fileName );
227 return;
228 }
229
230 // read entire file into memory
231 int fileLength = file->getLength();
232 unsigned char *fileBuffer = new unsigned char[ fileLength ];
233 fread( fileBuffer, 1, fileLength, inFile );
234
235 // now write the entire buffer to our output stream
236 inStream->write( fileBuffer,
237 fileLength );
238
239 delete [] fileBuffer;
240
241 delete file;
242
243 fclose( inFile );
244
245 // delete this temporary file
246 remove( fileName );
247
248 delete [] fileName;
249
250
251 // And we're done!
252
253 }
254
255
256
257 // copied this directly from IJG's example.c
258 //extern "C" {
259
260 /*
261 * ERROR HANDLING:
262 *
263 * The JPEG library's standard error handler (jerror.c) is divided into
264 * several "methods" which you can override individually. This lets you
265 * adjust the behavior without duplicating a lot of code, which you might
266 * have to update with each future release.
267 *
268 * Our example here shows how to override the "error_exit" method so that
269 * control is returned to the library's caller when a fatal error occurs,
270 * rather than calling exit() as the standard error_exit method does.
271 *
272 * We use C's setjmp/longjmp facility to return
273 * control. This means that the
274 * routine which calls the JPEG library must
275 * first execute a setjmp() call to
276 * establish the return point. We want the replacement error_exit to do a
277 * longjmp(). But we need to make the setjmp buffer accessible to the
278 * error_exit routine. To do this, we make a private extension of the
279 * standard JPEG error handler object. (If we were using C++, we'd say we
280 * were making a subclass of the regular error handler.)
281 *
282 * Here's the extended error handler struct:
283 */
284
285 struct my_error_mgr {
286 struct jpeg_error_mgr pub; /* "public" fields */
287
288 jmp_buf setjmp_buffer; /* for return to caller */
289 };
290
291 typedef struct my_error_mgr * my_error_ptr;
292
293
294 /*
295 * Here's the routine that will replace the standard error_exit method:
296 */
297
298 METHODDEF(void) my_error_exit( j_common_ptr cinfo ) {
299 /* cinfo->err really points to a my_error_mgr struct,
300 so coerce pointer
301 */
302 my_error_ptr myerr = (my_error_ptr)( cinfo->err );
303
304 /* Always display the message. */
305 /* We could postpone this until after returning, if we chose. */
306 (*cinfo->err->output_message)( cinfo );
307
308 /* Return control to the setjmp point */
309 longjmp( myerr->setjmp_buffer, 1 );
310 }
311
312 // }
313
314
315
316 Image *JPEGImageConverter::deformatImage( InputStream *inStream ) {
317
318 // use a temp file with a random name to make this more
319 // thread-safe
320 char *fileName = new char[99];
321 sprintf( fileName, "temp%d.dat", rand() );
322
323 FILE *tempFile = fopen( fileName, "wb" );
324
325 if( tempFile == NULL ) {
326 printf( "can't open jpeg conversion temp file %s\n", fileName );
327 return NULL;
328 }
329
330 // buffer for dumping stream to temp file
331 unsigned char *tempBuffer = new unsigned char[1];
332 unsigned char previousByte = 0;
333
334 // dump the JPEG stream from the input stream into tempFile
335 // so that we can pass this file to libjpeg
336
337 /*
338 // optimization: use a buffer to prevent too many fwrite calls
339 int bufferLength = 5000;
340 unsigned char *fileBuffer = new unsigned char[ bufferLength ];
341 int currentBufferPosition = 0;
342
343 while( !( tempBuffer[0] == 0xD9 && previousByte == 0xFF ) ) {
344 previousByte = tempBuffer[0];
345
346 inStream->read( tempBuffer, 1 );
347
348 fileBuffer[currentBufferPosition] = tempBuffer[0];
349
350 if( currentBufferPosition == bufferLength - 1 ) {
351 // at the end of the file buffer
352 fwrite( fileBuffer, 1, bufferLength, tempFile );
353 currentBufferPosition = 0;
354 }
355 else {
356 // keep filling the fileBuffer
357 currentBufferPosition++;
358 }
359 }
360 // now write remaining fileBuffer data to file
361 fwrite( fileBuffer, 1, currentBufferPosition + 1, tempFile );
362
363 delete [] fileBuffer;
364 */
365
366 // write until EOI sequence seen (0xFFD9)
367 while( !( tempBuffer[0] == 0xD9 && previousByte == 0xFF ) ) {
368 previousByte = tempBuffer[0];
369
370 inStream->read( tempBuffer, 1 );
371
372 fwrite( tempBuffer, 1, 1, tempFile );
373 }
374
375 // end of jpeg stream reached.
376 fclose( tempFile );
377 delete [] tempBuffer;
378
379
380 // the remainder of this method was mostly copied from
381 // IJG's example.c
382
383
384
385 /* This struct contains the JPEG decompression parameters and pointers to
386 * working space (which is allocated as needed by the JPEG library).
387 */
388 struct jpeg_decompress_struct cinfo;
389 /* We use our private extension JPEG error handler.
390 * Note that this struct must live as long as the main JPEG parameter
391 * struct, to avoid dangling-pointer problems.
392 */
393 struct my_error_mgr jerr;
394 /* More stuff */
395 FILE * infile; /* source file */
396 JSAMPARRAY buffer; /* Output row buffer */
397 int row_stride; /* physical row width in output buffer */
398
399 /* In this example we want to open the input
400 * file before doing anything else,
401 * so that the setjmp() error recovery below can assume the file is open.
402 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
403 * requires it in order to read binary files.
404 */
405
406 if( ( infile = fopen( fileName, "rb" ) ) == NULL ) {
407 printf( "can't open jpeg conversion temp file %s\n", fileName );
408 return NULL;
409 }
410
411 /* Step 1: allocate and initialize JPEG decompression object */
412
413 /* We set up the normal JPEG error routines, then override error_exit. */
414 cinfo.err = jpeg_std_error(&jerr.pub);
415 jerr.pub.error_exit = my_error_exit;
416 /* Establish the setjmp return context for my_error_exit to use. */
417 if( setjmp( jerr.setjmp_buffer ) ) {
418 /* If we get here, the JPEG code has signaled an error.
419 * We need to clean up the JPEG object,
420 * close the input file, and return.
421 */
422 jpeg_destroy_decompress( &cinfo );
423 fclose( infile );
424 printf( "error in decompressing jpeg from stream.\n" );
425 return NULL;
426 }
427 /* Now we can initialize the JPEG decompression object. */
428 jpeg_create_decompress( &cinfo );
429
430 /* Step 2: specify data source (eg, a file) */
431
432 jpeg_stdio_src( &cinfo, infile );
433
434 /* Step 3: read file parameters with jpeg_read_header() */
435
436 (void) jpeg_read_header( &cinfo, TRUE );
437 /* We can ignore the return value from jpeg_read_header since
438 * (a) suspension is not possible with the stdio data source, and
439 * (b) we passed TRUE to reject a tables-only JPEG file as an error.
440 * See libjpeg.doc for more info.
441 */
442
443 /* Step 4: set parameters for decompression */
444
445 /* In this example, we don't need to change any of the defaults set by
446 * jpeg_read_header(), so we do nothing here.
447 */
448
449 /* Step 5: Start decompressor */
450
451 (void) jpeg_start_decompress( &cinfo );
452 /* We can ignore the return value since suspension is not possible
453 * with the stdio data source.
454 */
455
456 /* We may need to do some setup of our own at this point before reading
457 * the data. After jpeg_start_decompress() we have the correct scaled
458 * output image dimensions available, as well as the output colormap
459 * if we asked for color quantization.
460 * In this example, we need to make an output work buffer of the right size.
461 */
462 /* JSAMPLEs per row in output buffer */
463
464 int imageWidth = cinfo.output_width;
465 int imageHeight = cinfo.output_height;
466
467 // the return image with 3 channels
468 Image *returnImage = new Image( imageWidth, imageHeight, 3, false );
469
470 // channels of returnImage,
471 // which we will need to put pixel values into of
472 double *redChannel = returnImage->getChannel(0);
473 double *greenChannel = returnImage->getChannel(1);
474 double *blueChannel = returnImage->getChannel(2);
475 int currentIndex = 0;
476
477
478 row_stride = cinfo.output_width * cinfo.output_components;
479 /* Make a one-row-high sample array that
480 * will go away when done with image
481 */
482 buffer = ( *cinfo.mem->alloc_sarray )
483 ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1 );
484
485 /* Step 6: while (scan lines remain to be read) */
486 /* jpeg_read_scanlines(...); */
487
488 /* Here we use the library's state variable cinfo.output_scanline as the
489 * loop counter, so that we don't have to keep track ourselves.
490 */
491 int rowNumber = 0;
492 double inv255 = 1.0 / 255.0;
493
494 while( cinfo.output_scanline < cinfo.output_height ) {
495 /* jpeg_read_scanlines expects an array of pointers to scanlines.
496 * Here the array is only one element long, but you could ask for
497 * more than one scanline at a time if that's more convenient.
498 */
499 (void) jpeg_read_scanlines( &cinfo, buffer, 1 );
500
501 // write the scanline into returnImage
502
503 int yOffset = rowNumber * cinfo.output_width;
504
505 // for each pixel in the row
506 // copy it into the return image channels
507 for( int p=0; p<cinfo.output_width; p++ ) {
508
509 // index into inImage
510 int pixelIndex = p + yOffset;
511
512 // index into this row
513 int startRowIndex = p * 3;
514
515 // red
516 redChannel[ pixelIndex ] =
517 buffer[0][ startRowIndex ] * inv255;
518 // green
519 greenChannel[ pixelIndex ] =
520 buffer[0][ startRowIndex + 1 ] * inv255;
521 // blue
522 blueChannel[ pixelIndex ] =
523 buffer[0][ startRowIndex + 2 ] * inv255;
524 }
525
526 rowNumber++;
527 }
528
529 /* Step 7: Finish decompression */
530
531 (void) jpeg_finish_decompress( &cinfo );
532 /* We can ignore the return value since suspension is not possible
533 * with the stdio data source.
534 */
535
536 /* Step 8: Release JPEG decompression object */
537
538 /* This is an important step since it will
539 * release a good deal of memory.
540 */
541 jpeg_destroy_decompress( &cinfo );
542
543 /* After finish_decompress, we can close the input file.
544 * Here we postpone it until after no more JPEG errors are possible,
545 * so as to simplify the setjmp error logic above. (Actually, I don't
546 * think that jpeg_destroy can do an error exit,
547 * but why assume anything...)
548 */
549 fclose( infile );
550
551 /* At this point you may want to check to see whether any corrupt-data
552 * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
553 */
554
555 // delete this temporary file
556 remove( fileName );
557
558 delete [] fileName;
559
560 /* And we're done! */
561 return returnImage;
562 }
563