summaryrefslogtreecommitdiff
path: root/DevIL/src-IL/src/il_jpeg.cpp
blob: 8434464f5212ec87076aca23825df9c20e804e6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//-----------------------------------------------------------------------------
//
// ImageLib Sources
// Copyright (C) 2000-2017 by Denton Woods
// Last modified: 02/14/2009
//
// Filename: src-IL/src/il_jpeg.cpp
//
// Description: Jpeg (.jpg) functions
//
//-----------------------------------------------------------------------------
//
// Most of the comments here are sufficient, as we're just using libjpeg.
//  I have left most of the libjpeg example's comments intact, though.
//

#include "il_internal.h"

#ifndef IL_NO_JPG
	#ifndef IL_USE_IJL
		#ifdef RGB_RED
			#undef RGB_RED
			#undef RGB_GREEN
			#undef RGB_BLUE
		#endif
		#define RGB_RED		0
		#define RGB_GREEN	1
		#define RGB_BLUE	2

		#if defined(_MSC_VER)
			#pragma warning(push)
			#pragma warning(disable : 4005)  // Redefinitions in
			#pragma warning(disable : 4142)  //  jmorecfg.h
		#endif

		#include <jpeglib.h>

		#if JPEG_LIB_VERSION < 62
			#warning DevIL was designed with libjpeg 6b or higher in mind.  Consider upgrading at www.ijg.org
		#endif
	#else
		#include <ijl.h>
		#include <limits.h>
	#endif

#include "il_jpeg.h"
#include <setjmp.h>


#if (defined(_WIN32) || defined(_WIN64)) && defined(IL_USE_PRAGMA_LIBS)
	#if defined(_MSC_VER) || defined(__BORLANDC__)
		#ifdef IL_USE_IJL
			//pragma comment(lib, "ijl15.lib")
		#else
			#ifndef _DEBUG
				#pragma comment(lib, "libjpeg.lib")
			#else
				//#pragma comment(lib, "libjpeg-d.lib")
				#pragma comment(lib, "libjpeg.lib")
			#endif
		#endif//IL_USE_IJL
	#endif
#endif


static ILboolean jpgErrorOccured = IL_FALSE;

// define a protype of ilLoadFromJpegStruct
ILboolean ilLoadFromJpegStruct(void *_JpegInfo);

// Internal function used to get the .jpg header from the current file.
void iGetJpgHead(ILubyte *Header)
{
	Header[0] = igetc();
	Header[1] = igetc();
	return;
}


// Internal function used to check if the HEADER is a valid .Jpg header.
ILboolean iCheckJpg(ILubyte Header[2])
{
	if (Header[0] != 0xFF || Header[1] != 0xD8)
		return IL_FALSE;
	return IL_TRUE;
}


// Internal function to get the header and check it.
ILboolean iIsValidJpeg()
{
	ILubyte Head[2];

	iGetJpgHead(Head);
	iseek(-2, IL_SEEK_CUR);  // Go ahead and restore to previous state

	return iCheckJpg(Head);
}


//! Checks if the file specified in FileName is a valid .jpg file.
ILboolean ilIsValidJpeg(ILconst_string FileName)
{
	ILHANDLE	JpegFile;
	ILboolean	bJpeg = IL_FALSE;

	if (!iCheckExtension(FileName, IL_TEXT("jpg")) &&
		!iCheckExtension(FileName, IL_TEXT("jpe")) &&
		!iCheckExtension(FileName, IL_TEXT("jpeg")) &&
		!iCheckExtension(FileName, IL_TEXT("jif")) &&
		!iCheckExtension(FileName, IL_TEXT("jfif")))
	{
		ilSetError(IL_INVALID_EXTENSION);
		return bJpeg;
	}

	JpegFile = iopenr(FileName);
	if (JpegFile == NULL) {
		ilSetError(IL_COULD_NOT_OPEN_FILE);
		return bJpeg;
	}

	bJpeg = ilIsValidJpegF(JpegFile);
	icloser(JpegFile);

	return bJpeg;
}


//! Checks if the ILHANDLE contains a valid .jpg file at the current position.
ILboolean ilIsValidJpegF(ILHANDLE File)
{
	ILuint		FirstPos;
	ILboolean	bRet;

	iSetInputFile(File);
	FirstPos = itell();
	bRet = iIsValidJpeg();
	iseek(FirstPos, IL_SEEK_SET);

	return bRet;
}


ILboolean ilIsValidJpegL(const void *Lump, ILuint Size)
{
	iSetInputLump(Lump, Size);
	return iIsValidJpeg();
}


#ifndef IL_USE_IJL // Use libjpeg instead of the IJL.

// Overrides libjpeg's stupid error/warning handlers. =P
//void ExitErrorHandle (struct jpeg_common_struct *JpegInfo)
void ExitErrorHandle(j_common_ptr cinfo)
{
	ilSetError(IL_LIB_JPEG_ERROR);
	jpgErrorOccured = IL_TRUE;
	return;
}
void OutputMsg(struct jpeg_common_struct *JpegInfo)
{
	return;
}


//! Reads a jpeg file
ILboolean ilLoadJpeg(ILconst_string FileName)
{
	ILHANDLE	JpegFile;
	ILboolean	bJpeg = IL_FALSE;

	JpegFile = iopenr(FileName);
	if (JpegFile == NULL) {
		ilSetError(IL_COULD_NOT_OPEN_FILE);
		return bJpeg;
	}

	bJpeg = ilLoadJpegF(JpegFile);
	icloser(JpegFile);

	return bJpeg;
}


//! Reads an already-opened jpeg file
ILboolean ilLoadJpegF(ILHANDLE File)
{
	ILboolean	bRet;
	ILuint		FirstPos;

	iSetInputFile(File);
	FirstPos = itell();
	bRet = iLoadJpegInternal();
	iseek(FirstPos, IL_SEEK_SET);

	return bRet;
}


// Reads from a memory "lump" containing a jpeg
ILboolean ilLoadJpegL(const void *Lump, ILuint Size)
{
	iSetInputLump(Lump, Size);
	return iLoadJpegInternal();
}


typedef struct {
  struct jpeg_source_mgr pub;	/* public fields */

  JOCTET * buffer;		/* start of buffer */
  boolean start_of_file;	/* have we gotten any data yet? */
} iread_mgr;

typedef iread_mgr * iread_ptr;

#define INPUT_BUF_SIZE  4096  // choose an efficiently iread'able size


METHODDEF(void)
init_source (j_decompress_ptr cinfo)
{
	iread_ptr src = (iread_ptr) cinfo->src;
	src->start_of_file = TRUE;
}


METHODDEF(boolean)
fill_input_buffer (j_decompress_ptr cinfo)
{
	iread_ptr src = (iread_ptr) cinfo->src;
	ILint nbytes;

	nbytes = iread(src->buffer, 1, INPUT_BUF_SIZE);

	if (nbytes <= 0) {
		if (src->start_of_file) {  // Treat empty input file as fatal error
			//ERREXIT(cinfo, JERR_INPUT_EMPTY);
			jpgErrorOccured = IL_TRUE;
		}
		//WARNMS(cinfo, JWRN_JPEG_EOF);
		// Insert a fake EOI marker
		src->buffer[0] = (JOCTET) 0xFF;
		src->buffer[1] = (JOCTET) JPEG_EOI;
		nbytes = 2;
		return IL_FALSE;
	}
	if (nbytes < INPUT_BUF_SIZE) {
		ilGetError();  // Gets rid of the IL_FILE_READ_ERROR.
	}

	src->pub.next_input_byte = src->buffer;
	src->pub.bytes_in_buffer = nbytes;
	src->start_of_file = IL_FALSE;

	return IL_TRUE;
}


METHODDEF(void)
skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
	iread_ptr src = (iread_ptr) cinfo->src;

	if (num_bytes > 0) {
		while (num_bytes > (long) src->pub.bytes_in_buffer) {
			num_bytes -= (long) src->pub.bytes_in_buffer;
			(void) fill_input_buffer(cinfo);
		}
		src->pub.next_input_byte += (size_t) num_bytes;
		src->pub.bytes_in_buffer -= (size_t) num_bytes;
	}
}


METHODDEF(void)
term_source (j_decompress_ptr cinfo)
{
	// no work necessary here
}


GLOBAL(void)
devil_jpeg_read_init (j_decompress_ptr cinfo)
{
	iread_ptr src;

	if ( cinfo->src == NULL ) {  // first time for this JPEG object?
		cinfo->src = (struct jpeg_source_mgr *)
					 (*cinfo->mem->alloc_small)( (j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(iread_mgr) );
		src = (iread_ptr) cinfo->src;
		src->buffer = (JOCTET *)
					  (*cinfo->mem->alloc_small)( (j_common_ptr)cinfo, JPOOL_PERMANENT,
												  INPUT_BUF_SIZE * sizeof(JOCTET) );
	}

	src = (iread_ptr) cinfo->src;
	src->pub.init_source = init_source;
	src->pub.fill_input_buffer = fill_input_buffer;
	src->pub.skip_input_data = skip_input_data;
	src->pub.resync_to_restart = jpeg_resync_to_restart;  // use default method
	src->pub.term_source = term_source;
	src->pub.bytes_in_buffer = 0;  // forces fill_input_buffer on first read
	src->pub.next_input_byte = NULL;  // until buffer loaded
}


jmp_buf	JpegJumpBuffer;

static void iJpegErrorExit( j_common_ptr cinfo )
{
	ilSetError( IL_LIB_JPEG_ERROR );
	jpeg_destroy( cinfo );
	longjmp( JpegJumpBuffer, 1 );
}

// Internal function used to load the jpeg.
ILboolean iLoadJpegInternal()
{
	struct jpeg_error_mgr			Error;
	struct jpeg_decompress_struct	JpegInfo;
	ILboolean						result;

	if (iCurImage == NULL) {
		ilSetError(IL_ILLEGAL_OPERATION);
		return IL_FALSE;
	}

	JpegInfo.err = jpeg_std_error(&Error);		// init standard error handlers
	Error.error_exit = iJpegErrorExit;				// add our exit handler
	Error.output_message = OutputMsg;

	if ((result = setjmp(JpegJumpBuffer) == 0) != IL_FALSE) {
		jpeg_create_decompress(&JpegInfo);
		JpegInfo.do_block_smoothing = IL_TRUE;
		JpegInfo.do_fancy_upsampling = IL_TRUE;

		//jpeg_stdio_src(&JpegInfo, iGetFile());

		devil_jpeg_read_init(&JpegInfo);
		jpeg_read_header(&JpegInfo, IL_TRUE);

		result = ilLoadFromJpegStruct(&JpegInfo);

		jpeg_finish_decompress(&JpegInfo);
		jpeg_destroy_decompress(&JpegInfo);

	}
	else
	{
		jpeg_destroy_decompress(&JpegInfo);
	}

	//return ilFixImage();  // No need to call it again (called first in ilLoadFromJpegStruct).
	return result;
}



typedef struct
{
	struct jpeg_destination_mgr		pub;
	JOCTET							*buffer;
	ILboolean						bah;
} iwrite_mgr;

typedef iwrite_mgr *iwrite_ptr;

#define OUTPUT_BUF_SIZE 4096


METHODDEF(void)
init_destination(j_compress_ptr cinfo)
{
	iwrite_ptr dest = (iwrite_ptr)cinfo->dest;
	dest->buffer = (JOCTET *)
	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				  OUTPUT_BUF_SIZE * sizeof(JOCTET));

	dest->pub.next_output_byte = dest->buffer;
	dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
	return;
}

METHODDEF(boolean)
empty_output_buffer (j_compress_ptr cinfo)
{
	iwrite_ptr dest = (iwrite_ptr)cinfo->dest;
	iwrite(dest->buffer, 1, OUTPUT_BUF_SIZE);
	dest->pub.next_output_byte = dest->buffer;
	dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
	return IL_TRUE;
}

METHODDEF(void)
term_destination (j_compress_ptr cinfo)
{
	iwrite_ptr dest = (iwrite_ptr)cinfo->dest;
	iwrite(dest->buffer, 1, OUTPUT_BUF_SIZE - (ILuint)dest->pub.free_in_buffer);
	return;
}


GLOBAL(void)
devil_jpeg_write_init(j_compress_ptr cinfo)
{
	iwrite_ptr dest;

	if (cinfo->dest == NULL) {	// first time for this JPEG object?
		cinfo->dest = (struct jpeg_destination_mgr *)
		  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
					  sizeof(iwrite_mgr));
		dest = (iwrite_ptr)cinfo->dest;
	}

	dest = (iwrite_ptr)cinfo->dest;
	dest->pub.init_destination = init_destination;
	dest->pub.empty_output_buffer = empty_output_buffer;
	dest->pub.term_destination = term_destination;

	return;
}


//! Writes a Jpeg file
ILboolean ilSaveJpeg(const ILstring FileName)
{
	ILHANDLE	JpegFile;
	ILuint		JpegSize;

	if (ilGetBoolean(IL_FILE_MODE) == IL_FALSE) {
		if (iFileExists(FileName)) {
			ilSetError(IL_FILE_ALREADY_EXISTS);
			return IL_FALSE;
		}
	}

	JpegFile = iopenw(FileName);
	if (JpegFile == NULL) {
		ilSetError(IL_COULD_NOT_OPEN_FILE);
		return IL_FALSE;
	}

	JpegSize = ilSaveJpegF(JpegFile);
	iclosew(JpegFile);

	if (JpegSize == 0)
		return IL_FALSE;
	return IL_TRUE;
}


//! Writes a Jpeg to an already-opened file
ILuint ilSaveJpegF(ILHANDLE File)
{
	ILuint Pos;
	iSetOutputFile(File);
	Pos = itellw();
	if (iSaveJpegInternal() == IL_FALSE)
		return 0;  // Error occurred
	return itellw() - Pos;  // Return the number of bytes written.
}


//! Writes a Jpeg to a memory "lump"
ILuint ilSaveJpegL(void *Lump, ILuint Size)
{
	ILuint Pos;
	iSetOutputLump(Lump, Size);
	Pos = itellw();
	if (iSaveJpegInternal() == IL_FALSE)
		return 0;  // Error occurred
	return itellw() - Pos;  // Return the number of bytes written.
}


// Internal function used to save the Jpeg.
ILboolean iSaveJpegInternal()
{
	struct		jpeg_compress_struct JpegInfo;
	struct		jpeg_error_mgr Error;
	JSAMPROW	row_pointer[1];
	ILimage		*TempImage;
	ILubyte		*TempData;
	ILenum		Type = 0;

	if (iCurImage == NULL) {
		ilSetError(IL_ILLEGAL_OPERATION);
		return IL_FALSE;
	}

	/*if (iGetHint(IL_COMPRESSION_HINT) == IL_USE_COMPRESSION)
		Quality = 85;  // Not sure how low we should dare go...
	else
		Quality = 99;*/

	if ((iCurImage->Format != IL_RGB && iCurImage->Format != IL_LUMINANCE) || iCurImage->Bpc != 1) {
		TempImage = iConvertImage(iCurImage, IL_RGB, IL_UNSIGNED_BYTE);
		if (TempImage == NULL) {
			return IL_FALSE;
		}
	}
	else {
		TempImage = iCurImage;
	}

	if (TempImage->Origin == IL_ORIGIN_LOWER_LEFT) {
		TempData = iGetFlipped(TempImage);
		if (TempData == NULL) {
			if (TempImage != iCurImage)
				ilCloseImage(TempImage);
			return IL_FALSE;
		}
	}
	else {
		TempData = TempImage->Data;
	}


	JpegInfo.err = jpeg_std_error(&Error);
	// Now we can initialize the JPEG compression object.
	jpeg_create_compress(&JpegInfo);

	//jpeg_stdio_dest(&JpegInfo, JpegFile);
	devil_jpeg_write_init(&JpegInfo);

	JpegInfo.image_width = TempImage->Width;  // image width and height, in pixels
	JpegInfo.image_height = TempImage->Height;
	JpegInfo.input_components = TempImage->Bpp;  // # of color components per pixel

	// John Villar's addition
	if (TempImage->Bpp == 1)
		JpegInfo.in_color_space = JCS_GRAYSCALE;
	else
		JpegInfo.in_color_space = JCS_RGB;

	jpeg_set_defaults(&JpegInfo);

/*#ifndef IL_USE_JPEGLIB_UNMODIFIED
	Type = iGetInt(IL_JPG_SAVE_FORMAT);
	if (Type == IL_EXIF) {
		JpegInfo.write_JFIF_header = FALSE;
		JpegInfo.write_EXIF_header = TRUE;
	}
	else if (Type == IL_JFIF) {
		JpegInfo.write_JFIF_header = TRUE;
		JpegInfo.write_EXIF_header = FALSE;
	} //EXIF not present in libjpeg...
#else*/
	Type = Type;
	JpegInfo.write_JFIF_header = TRUE;
//#endif//IL_USE_JPEGLIB_UNMODIFIED

	// Set the quality output
	jpeg_set_quality(&JpegInfo, iGetInt(IL_JPG_QUALITY), IL_TRUE);
	// Sets progressive saving here
	if (ilGetBoolean(IL_JPG_PROGRESSIVE))
		jpeg_simple_progression(&JpegInfo);

	jpeg_start_compress(&JpegInfo, IL_TRUE);

	//row_stride = image_width * 3;	// JSAMPLEs per row in image_buffer

	while (JpegInfo.next_scanline < JpegInfo.image_height) {
		// jpeg_write_scanlines expects an array of pointers to scanlines.
		// Here the array is only one element long, but you could pass
		// more than one scanline at a time if that's more convenient.
		row_pointer[0] = &TempData[JpegInfo.next_scanline * TempImage->Bps];
		(void) jpeg_write_scanlines(&JpegInfo, row_pointer, 1);
	}

	// Step 6: Finish compression
	jpeg_finish_compress(&JpegInfo);

	// Step 7: release JPEG compression object

	// This is an important step since it will release a good deal of memory.
	jpeg_destroy_compress(&JpegInfo);

	if (TempImage->Origin == IL_ORIGIN_LOWER_LEFT)
		ifree(TempData);
	if (TempImage != iCurImage)
		ilCloseImage(TempImage);

	return IL_TRUE;
}



#else // Use the IJL instead of libjpeg.



//! Reads a jpeg file
ILboolean ilLoadJpeg(ILconst_string FileName)
{
	if (!iFileExists(FileName)) {
		ilSetError(IL_COULD_NOT_OPEN_FILE);
		return IL_FALSE;
	}
	return iLoadJpegInternal(FileName, NULL, 0);
}


// Reads from a memory "lump" containing a jpeg
ILboolean ilLoadJpegL(void *Lump, ILuint Size)
{
	return iLoadJpegInternal(NULL, Lump, Size);
}


// Internal function used to load the jpeg.
ILboolean iLoadJpegInternal(ILstring FileName, void *Lump, ILuint Size)
{
    JPEG_CORE_PROPERTIES Image;

	if (iCurImage == NULL) {
		ilSetError(IL_ILLEGAL_OPERATION);
		return IL_FALSE;
	}

	if (ijlInit(&Image) != IJL_OK) {
		ilSetError(IL_LIB_JPEG_ERROR);
		return IL_FALSE;
	}

	if (FileName != NULL) {
		Image.JPGFile = FileName;
		if (ijlRead(&Image, IJL_JFILE_READPARAMS) != IJL_OK) {
			ilSetError(IL_LIB_JPEG_ERROR);
			return IL_FALSE;
		}
	}
	else {
		Image.JPGBytes = Lump;
		Image.JPGSizeBytes = Size > 0 ? Size : UINT_MAX;
		if (ijlRead(&Image, IJL_JBUFF_READPARAMS) != IJL_OK) {
			ilSetError(IL_LIB_JPEG_ERROR);
			return IL_FALSE;
		}
	}

	switch (Image.JPGChannels)
	{
		case 1:
			Image.JPGColor		= IJL_G;
			Image.DIBChannels	= 1;
			Image.DIBColor		= IJL_G;
			iCurImage->Format	= IL_LUMINANCE;
			break;

		case 3:
			Image.JPGColor		= IJL_YCBCR;
			Image.DIBChannels	= 3;
			Image.DIBColor		= IJL_RGB;
			iCurImage->Format	= IL_RGB;
			break;

        case 4:
			Image.JPGColor		= IJL_YCBCRA_FPX;
			Image.DIBChannels	= 4;
			Image.DIBColor		= IJL_RGBA_FPX;
			iCurImage->Format	= IL_RGBA;
			break;

        default:
			// This catches everything else, but no
			// color twist will be performed by the IJL.
			/*Image.DIBColor = (IJL_COLOR)IJL_OTHER;
			Image.JPGColor = (IJL_COLOR)IJL_OTHER;
			Image.DIBChannels = Image.JPGChannels;
			break;*/
			ijlFree(&Image);
			ilSetError(IL_LIB_JPEG_ERROR);
			return IL_FALSE;
	}

	if (!ilTexImage(Image.JPGWidth, Image.JPGHeight, 1, (ILubyte)Image.DIBChannels, iCurImage->Format, IL_UNSIGNED_BYTE, NULL)) {
		ijlFree(&Image);
		return IL_FALSE;
	}
	iCurImage->Origin = IL_ORIGIN_UPPER_LEFT;

	Image.DIBWidth		= Image.JPGWidth;
	Image.DIBHeight		= Image.JPGHeight;
	Image.DIBPadBytes	= 0;
	Image.DIBBytes		= iCurImage->Data;

	if (FileName != NULL) {
		if (ijlRead(&Image, IJL_JFILE_READWHOLEIMAGE) != IJL_OK) {
			ijlFree(&Image);
			ilSetError(IL_LIB_JPEG_ERROR);
			return IL_FALSE;
		}
	}
	else {
		if (ijlRead(&Image, IJL_JBUFF_READWHOLEIMAGE) != IJL_OK) {
			ijlFree(&Image);
			ilSetError(IL_LIB_JPEG_ERROR);
			return IL_FALSE;
		}
	}

	ijlFree(&Image);
	return ilFixImage();
}


//! Writes a Jpeg file
ILboolean ilSaveJpeg(ILconst_string FileName)
{
	if (ilGetBoolean(IL_FILE_MODE) == IL_FALSE) {
		if (iFileExists(FileName)) {
			ilSetError(IL_FILE_ALREADY_EXISTS);
			return IL_FALSE;
		}
	}

	return iSaveJpegInternal(FileName, NULL, 0);
}


//! Writes a Jpeg to a memory "lump"
ILboolean ilSaveJpegL(void *Lump, ILuint Size)
{
	return iSaveJpegInternal(NULL, Lump, Size);
}


// Internal function used to save the Jpeg.
ILboolean iSaveJpegInternal(ILstring FileName, void *Lump, ILuint Size)
{
	JPEG_CORE_PROPERTIES	Image;
	ILuint	Quality;
	ILimage	*TempImage;
	ILubyte	*TempData;

	imemclear(&Image, sizeof(JPEG_CORE_PROPERTIES));

	if (iCurImage == NULL) {
		ilSetError(IL_ILLEGAL_OPERATION);
		return IL_FALSE;
	}
	if (FileName == NULL && Lump == NULL) {
		ilSetError(IL_INVALID_PARAM);
		return IL_FALSE;
	}

	if (iGetHint(IL_COMPRESSION_HINT) == IL_USE_COMPRESSION)
		Quality = 85;  // Not sure how low we should dare go...
	else
		Quality = 99;

	if (ijlInit(&Image) != IJL_OK) {
		ilSetError(IL_LIB_JPEG_ERROR);
		return IL_FALSE;
	}

	if ((iCurImage->Format != IL_RGB && iCurImage->Format != IL_RGBA && iCurImage->Format != IL_LUMINANCE)
		|| iCurImage->Bpc != 1) {
		if (iCurImage->Format == IL_BGRA)
			Temp = iConvertImage(iCurImage, IL_RGBA, IL_UNSIGNED_BYTE);
		else
			Temp = iConvertImage(iCurImage, IL_RGB, IL_UNSIGNED_BYTE);
		if (Temp == NULL) {
			return IL_FALSE;
		}
	}
	else {
		Temp = iCurImage;
	}

	if (TempImage->Origin == IL_ORIGIN_LOWER_LEFT) {
		TempData = iGetFlipped(TempImage);
		if (TempData == NULL) {
			if (TempImage != iCurImage)
				ilCloseImage(TempImage);
			return IL_FALSE;
		}
	}
	else {
		TempData = TempImage->Data;
	}

	// Setup DIB
	Image.DIBWidth		= TempImage->Width;
	Image.DIBHeight		= TempImage->Height;
	Image.DIBChannels	= TempImage->Bpp;
	Image.DIBBytes		= TempData;
	Image.DIBPadBytes	= 0;

	// Setup JPEG
	Image.JPGWidth		= TempImage->Width;
	Image.JPGHeight		= TempImage->Height;
	Image.JPGChannels	= TempImage->Bpp;

	switch (Temp->Bpp)
	{
		case 1:
			Image.DIBColor			= IJL_G;
			Image.JPGColor			= IJL_G;
			Image.JPGSubsampling	= IJL_NONE;
			break;
		case 3:
			Image.DIBColor			= IJL_RGB;
			Image.JPGColor			= IJL_YCBCR;
			Image.JPGSubsampling	= IJL_411;
			break;
		case 4:
			Image.DIBColor			= IJL_RGBA_FPX;
			Image.JPGColor			= IJL_YCBCRA_FPX;
			Image.JPGSubsampling	= IJL_4114;
			break;
	}

	if (FileName != NULL) {
		Image.JPGFile = FileName;
		if (ijlWrite(&Image, IJL_JFILE_WRITEWHOLEIMAGE) != IJL_OK) {
			if (TempImage != iCurImage)
				ilCloseImage(TempImage);
			ilSetError(IL_LIB_JPEG_ERROR);
			return IL_FALSE;
		}
	}
	else {
		Image.JPGBytes = Lump;
		Image.JPGSizeBytes = Size;
		if (ijlWrite(&Image, IJL_JBUFF_WRITEWHOLEIMAGE) != IJL_OK) {
			if (TempImage != iCurImage)
				ilCloseImage(TempImage);
			ilSetError(IL_LIB_JPEG_ERROR);
			return IL_FALSE;
		}
	}

	ijlFree(&Image);

	if (TempImage->Origin == IL_ORIGIN_LOWER_LEFT)
		ifree(TempData);
	if (Temp != iCurImage)
		ilCloseImage(Temp);

	return IL_TRUE;
}

#endif//IL_USE_IJL


// Access point for applications wishing to use the jpeg library directly in
// conjunction with DevIL.
//
// The decompressor must be set up with an input source and all desired parameters
// this function is called. The caller must call jpeg_finish_decompress because
// the caller may still need decompressor after calling this for e.g. examining
// saved markers.
ILboolean ilLoadFromJpegStruct(void *_JpegInfo)
{
#ifndef IL_NO_JPG
#ifndef IL_USE_IJL
	// sam. void (*errorHandler)(j_common_ptr);
	ILubyte	*TempPtr[1];
	ILuint	Returned;
	j_decompress_ptr JpegInfo = (j_decompress_ptr)_JpegInfo;

	//added on 2003-08-31 as explained in sf bug 596793
	jpgErrorOccured = IL_FALSE;

	// sam. errorHandler = JpegInfo->err->error_exit;
	// sam. JpegInfo->err->error_exit = ExitErrorHandle;
	jpeg_start_decompress((j_decompress_ptr)JpegInfo);

	if (!ilTexImage(JpegInfo->output_width, JpegInfo->output_height, 1, (ILubyte)JpegInfo->output_components, 0, IL_UNSIGNED_BYTE, NULL)) {
		return IL_FALSE;
	}
	iCurImage->Origin = IL_ORIGIN_UPPER_LEFT;

	switch (iCurImage->Bpp)
	{
		case 1:
			iCurImage->Format = IL_LUMINANCE;
			break;
		case 3:
			iCurImage->Format = IL_RGB;
			break;
		case 4:
			iCurImage->Format = IL_RGBA;
			break;
		default:
			//@TODO: Anyway to get here?  Need to error out or something...
			break;
	}

	TempPtr[0] = iCurImage->Data;
	while (JpegInfo->output_scanline < JpegInfo->output_height) {
		Returned = jpeg_read_scanlines(JpegInfo, TempPtr, 1);  // anyway to make it read all at once?
		TempPtr[0] += iCurImage->Bps;
		if (Returned == 0)
			break;
	}

	// sam. JpegInfo->err->error_exit = errorHandler;

	if (jpgErrorOccured)
		return IL_FALSE;

	return ilFixImage();
#endif
#endif
	return IL_FALSE;
}



// Access point for applications wishing to use the jpeg library directly in
// conjunction with DevIL.
//
// The caller must set up the desired parameters by e.g. calling
// jpeg_set_defaults and overriding the parameters the caller wishes
// to change, such as quality, before calling this function. The caller
// is also responsible for calling jpeg_finish_compress in case the
// caller still needs to compressor for something.
// 
ILboolean ilSaveFromJpegStruct(void *_JpegInfo)
{
#ifndef IL_NO_JPG
#ifndef IL_USE_IJL
	void (*errorHandler)(j_common_ptr);
	JSAMPROW	row_pointer[1];
	ILimage		*TempImage;
	ILubyte		*TempData;
	j_compress_ptr JpegInfo = (j_compress_ptr)_JpegInfo;

	if (iCurImage == NULL) {
		ilSetError(IL_ILLEGAL_OPERATION);
		return IL_FALSE;
	}

	//added on 2003-08-31 as explained in SF bug 596793
	jpgErrorOccured = IL_FALSE;

	errorHandler = JpegInfo->err->error_exit;
	JpegInfo->err->error_exit = ExitErrorHandle;


	if ((iCurImage->Format != IL_RGB && iCurImage->Format != IL_LUMINANCE) || iCurImage->Bpc != 1) {
		TempImage = iConvertImage(iCurImage, IL_RGB, IL_UNSIGNED_BYTE);
		if (TempImage == NULL) {
			return IL_FALSE;
		}
	}
	else {
		TempImage = iCurImage;
	}

	if (TempImage->Origin == IL_ORIGIN_LOWER_LEFT) {
		TempData = iGetFlipped(TempImage);
		if (TempData == NULL) {
			if (TempImage != iCurImage)
				ilCloseImage(TempImage);
			return IL_FALSE;
		}
	}
	else {
		TempData = TempImage->Data;
	}

	JpegInfo->image_width = TempImage->Width;  // image width and height, in pixels
	JpegInfo->image_height = TempImage->Height;
	JpegInfo->input_components = TempImage->Bpp;  // # of color components per pixel

	jpeg_start_compress(JpegInfo, IL_TRUE);

	//row_stride = image_width * 3;	// JSAMPLEs per row in image_buffer

	while (JpegInfo->next_scanline < JpegInfo->image_height) {
		// jpeg_write_scanlines expects an array of pointers to scanlines.
		// Here the array is only one element long, but you could pass
		// more than one scanline at a time if that's more convenient.
		row_pointer[0] = &TempData[JpegInfo->next_scanline * TempImage->Bps];
		(void) jpeg_write_scanlines(JpegInfo, row_pointer, 1);
	}

	if (TempImage->Origin == IL_ORIGIN_LOWER_LEFT)
		ifree(TempData);
	if (TempImage != iCurImage)
		ilCloseImage(TempImage);

	return (!jpgErrorOccured);
#endif//IL_USE_IJL
#endif//IL_NO_JPG
	return IL_FALSE;
}


#if defined(_MSC_VER)
	#pragma warning(pop)
	//#pragma warning(disable : 4756)  // Disables 'named type definition in parentheses' warning
#endif

#endif//IL_NO_JPG