1 /*
2  * Copyright (C)2009-2016 D. R. Commander.  All Rights Reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * - Redistributions of source code must retain the above copyright notice,
8  *   this list of conditions and the following disclaimer.
9  * - Redistributions in binary form must reproduce the above copyright notice,
10  *   this list of conditions and the following disclaimer in the documentation
11  *   and/or other materials provided with the distribution.
12  * - Neither the name of the libjpeg-turbo Project nor the names of its
13  *   contributors may be used to endorse or promote products derived from this
14  *   software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <math.h>
34 #include <errno.h>
35 #include <cdjpeg.h>
36 #include "./bmp.h"
37 #include "./tjutil.h"
38 #include "./turbojpeg.h"
39 
40 
41 #define _throw(op, err) {  \
42 	printf("ERROR in line %d while %s:\n%s\n", __LINE__, op, err);  \
43   retval=-1;  goto bailout;}
44 #define _throwunix(m) _throw(m, strerror(errno))
45 #define _throwtj(m) _throw(m, tjGetErrorStr())
46 #define _throwbmp(m) _throw(m, bmpgeterr())
47 
48 int flags=TJFLAG_NOREALLOC, componly=0, decomponly=0, doyuv=0, quiet=0,
49 	dotile=0, pf=TJPF_BGR, yuvpad=1, warmup=1, dowrite=1;
50 char *ext="ppm";
51 const char *pixFormatStr[TJ_NUMPF]=
52 {
53 	"RGB", "BGR", "RGBX", "BGRX", "XBGR", "XRGB", "GRAY", "", "", "", "", "CMYK"
54 };
55 const char *subNameLong[TJ_NUMSAMP]=
56 {
57 	"4:4:4", "4:2:2", "4:2:0", "GRAY", "4:4:0", "4:1:1"
58 };
59 const char *csName[TJ_NUMCS]=
60 {
61 	"RGB", "YCbCr", "GRAY", "CMYK", "YCCK"
62 };
63 const char *subName[TJ_NUMSAMP]={"444", "422", "420", "GRAY", "440", "411"};
64 tjscalingfactor *scalingfactors=NULL, sf={1, 1};  int nsf=0;
65 int xformop=TJXOP_NONE, xformopt=0;
66 int (*customFilter)(short *, tjregion, tjregion, int, int, tjtransform *);
67 double benchtime=5.0;
68 
69 
formatName(int subsamp,int cs,char * buf)70 char *formatName(int subsamp, int cs, char *buf)
71 {
72 	if(cs==TJCS_YCbCr) return (char *)subNameLong[subsamp];
73 	else if(cs==TJCS_YCCK)
74 	{
75 		snprintf(buf, 80, "%s %s", csName[cs], subNameLong[subsamp]);
76 		return buf;
77 	}
78 	else return (char *)csName[cs];
79 }
80 
81 
sigfig(double val,int figs,char * buf,int len)82 char *sigfig(double val, int figs, char *buf, int len)
83 {
84 	char format[80];
85 	int digitsafterdecimal=figs-(int)ceil(log10(fabs(val)));
86 	if(digitsafterdecimal<1) snprintf(format, 80, "%%.0f");
87 	else snprintf(format, 80, "%%.%df", digitsafterdecimal);
88 	snprintf(buf, len, format, val);
89 	return buf;
90 }
91 
92 
93 /* Custom DCT filter which produces a negative of the image */
dummyDCTFilter(short * coeffs,tjregion arrayRegion,tjregion planeRegion,int componentIndex,int transformIndex,tjtransform * transform)94 int dummyDCTFilter(short *coeffs, tjregion arrayRegion, tjregion planeRegion,
95 	int componentIndex, int transformIndex, tjtransform *transform)
96 {
97 	int i;
98 	for(i=0; i<arrayRegion.w*arrayRegion.h; i++) coeffs[i]=-coeffs[i];
99 	return 0;
100 }
101 
102 
103 /* Decompression test */
decomp(unsigned char * srcbuf,unsigned char ** jpegbuf,unsigned long * jpegsize,unsigned char * dstbuf,int w,int h,int subsamp,int jpegqual,char * filename,int tilew,int tileh)104 int decomp(unsigned char *srcbuf, unsigned char **jpegbuf,
105 	unsigned long *jpegsize, unsigned char *dstbuf, int w, int h,
106 	int subsamp, int jpegqual, char *filename, int tilew, int tileh)
107 {
108 	char tempstr[1024], sizestr[20]="\0", qualstr[6]="\0", *ptr;
109 	FILE *file=NULL;  tjhandle handle=NULL;
110 	int row, col, iter=0, dstbufalloc=0, retval=0;
111 	double elapsed, elapsedDecode;
112 	int ps=tjPixelSize[pf];
113 	int scaledw=TJSCALED(w, sf);
114 	int scaledh=TJSCALED(h, sf);
115 	int pitch=scaledw*ps;
116 	int ntilesw=(w+tilew-1)/tilew, ntilesh=(h+tileh-1)/tileh;
117 	unsigned char *dstptr, *dstptr2, *yuvbuf=NULL;
118 
119 	if(jpegqual>0)
120 	{
121 		snprintf(qualstr, 6, "_Q%d", jpegqual);
122 		qualstr[5]=0;
123 	}
124 
125 	if((handle=tjInitDecompress())==NULL)
126 		_throwtj("executing tjInitDecompress()");
127 
128 	if(dstbuf==NULL)
129 	{
130 		if((dstbuf=(unsigned char *)malloc(pitch*scaledh))==NULL)
131 			_throwunix("allocating destination buffer");
132 		dstbufalloc=1;
133 	}
134 	/* Set the destination buffer to gray so we know whether the decompressor
135 	   attempted to write to it */
136 	memset(dstbuf, 127, pitch*scaledh);
137 
138 	if(doyuv)
139 	{
140 		int width=dotile? tilew:scaledw;
141 		int height=dotile? tileh:scaledh;
142 		int yuvsize=tjBufSizeYUV2(width, yuvpad, height, subsamp);
143 		if((yuvbuf=(unsigned char *)malloc(yuvsize))==NULL)
144 			_throwunix("allocating YUV buffer");
145 		memset(yuvbuf, 127, yuvsize);
146 	}
147 
148 	/* Benchmark */
149 	iter=-warmup;
150 	elapsed=elapsedDecode=0.;
151 	while(1)
152 	{
153 		int tile=0;
154 		double start=gettime();
155 		for(row=0, dstptr=dstbuf; row<ntilesh; row++, dstptr+=pitch*tileh)
156 		{
157 			for(col=0, dstptr2=dstptr; col<ntilesw; col++, tile++, dstptr2+=ps*tilew)
158 			{
159 				int width=dotile? min(tilew, w-col*tilew):scaledw;
160 				int height=dotile? min(tileh, h-row*tileh):scaledh;
161 				if(doyuv)
162 				{
163 					double startDecode;
164 					if(tjDecompressToYUV2(handle, jpegbuf[tile], jpegsize[tile], yuvbuf,
165 						width, yuvpad, height, flags)==-1)
166 						_throwtj("executing tjDecompressToYUV2()");
167 					startDecode=gettime();
168 					if(tjDecodeYUV(handle, yuvbuf, yuvpad, subsamp, dstptr2, width,
169 						pitch, height, pf, flags)==-1)
170 						_throwtj("executing tjDecodeYUV()");
171 					if(iter>=0) elapsedDecode+=gettime()-startDecode;
172 				}
173 				else
174 					if(tjDecompress2(handle, jpegbuf[tile], jpegsize[tile], dstptr2,
175 						width, pitch, height, pf, flags)==-1)
176 						_throwtj("executing tjDecompress2()");
177 			}
178 		}
179 		iter++;
180 		if(iter>=1)
181 		{
182 			elapsed+=gettime()-start;
183 			if(elapsed>=benchtime) break;
184 		}
185 	}
186 	if(doyuv) elapsed-=elapsedDecode;
187 
188 	if(tjDestroy(handle)==-1) _throwtj("executing tjDestroy()");
189 	handle=NULL;
190 
191 	if(quiet)
192 	{
193 		printf("%-6s%s",
194 			sigfig((double)(w*h)/1000000.*(double)iter/elapsed, 4, tempstr, 1024),
195 			quiet==2? "\n":"  ");
196 		if(doyuv)
197 			printf("%s\n",
198 				sigfig((double)(w*h)/1000000.*(double)iter/elapsedDecode, 4, tempstr,
199 					1024));
200 		else if(quiet!=2) printf("\n");
201 	}
202 	else
203 	{
204 		printf("%s --> Frame rate:         %f fps\n",
205 			doyuv? "Decomp to YUV":"Decompress   ", (double)iter/elapsed);
206 		printf("                  Throughput:         %f Megapixels/sec\n",
207 			(double)(w*h)/1000000.*(double)iter/elapsed);
208 		if(doyuv)
209 		{
210 			printf("YUV Decode    --> Frame rate:         %f fps\n",
211 				(double)iter/elapsedDecode);
212 			printf("                  Throughput:         %f Megapixels/sec\n",
213 				(double)(w*h)/1000000.*(double)iter/elapsedDecode);
214 		}
215 	}
216 
217 	if (!dowrite) goto bailout;
218 
219 	if(sf.num!=1 || sf.denom!=1)
220 		snprintf(sizestr, 20, "%d_%d", sf.num, sf.denom);
221 	else if(tilew!=w || tileh!=h)
222 		snprintf(sizestr, 20, "%dx%d", tilew, tileh);
223 	else snprintf(sizestr, 20, "full");
224 	if(decomponly)
225 		snprintf(tempstr, 1024, "%s_%s.%s", filename, sizestr, ext);
226 	else
227 		snprintf(tempstr, 1024, "%s_%s%s_%s.%s", filename, subName[subsamp],
228 			qualstr, sizestr, ext);
229 
230 	if(savebmp(tempstr, dstbuf, scaledw, scaledh, pf,
231 		(flags&TJFLAG_BOTTOMUP)!=0)==-1)
232 		_throwbmp("saving bitmap");
233 	ptr=strrchr(tempstr, '.');
234 	snprintf(ptr, 1024-(ptr-tempstr), "-err.%s", ext);
235 	if(srcbuf && sf.num==1 && sf.denom==1)
236 	{
237 		if(!quiet) printf("Compression error written to %s.\n", tempstr);
238 		if(subsamp==TJ_GRAYSCALE)
239 		{
240 			int index, index2;
241 			for(row=0, index=0; row<h; row++, index+=pitch)
242 			{
243 				for(col=0, index2=index; col<w; col++, index2+=ps)
244 				{
245 					int rindex=index2+tjRedOffset[pf];
246 					int gindex=index2+tjGreenOffset[pf];
247 					int bindex=index2+tjBlueOffset[pf];
248 					int y=(int)((double)srcbuf[rindex]*0.299
249 						+ (double)srcbuf[gindex]*0.587
250 						+ (double)srcbuf[bindex]*0.114 + 0.5);
251 					if(y>255) y=255;  if(y<0) y=0;
252 					dstbuf[rindex]=abs(dstbuf[rindex]-y);
253 					dstbuf[gindex]=abs(dstbuf[gindex]-y);
254 					dstbuf[bindex]=abs(dstbuf[bindex]-y);
255 				}
256 			}
257 		}
258 		else
259 		{
260 			for(row=0; row<h; row++)
261 				for(col=0; col<w*ps; col++)
262 					dstbuf[pitch*row+col]
263 						=abs(dstbuf[pitch*row+col]-srcbuf[pitch*row+col]);
264 		}
265 		if(savebmp(tempstr, dstbuf, w, h, pf,
266 			(flags&TJFLAG_BOTTOMUP)!=0)==-1)
267 			_throwbmp("saving bitmap");
268 	}
269 
270 	bailout:
271 	if(file) fclose(file);
272 	if(handle) tjDestroy(handle);
273 	if(dstbuf && dstbufalloc) free(dstbuf);
274 	if(yuvbuf) free(yuvbuf);
275 	return retval;
276 }
277 
278 
fullTest(unsigned char * srcbuf,int w,int h,int subsamp,int jpegqual,char * filename)279 int fullTest(unsigned char *srcbuf, int w, int h, int subsamp, int jpegqual,
280 	char *filename)
281 {
282 	char tempstr[1024], tempstr2[80];
283 	FILE *file=NULL;  tjhandle handle=NULL;
284 	unsigned char **jpegbuf=NULL, *yuvbuf=NULL, *tmpbuf=NULL, *srcptr, *srcptr2;
285 	double start, elapsed, elapsedEncode;
286 	int totaljpegsize=0, row, col, i, tilew=w, tileh=h, retval=0;
287 	int iter, yuvsize=0;
288 	unsigned long *jpegsize=NULL;
289 	int ps=tjPixelSize[pf];
290 	int ntilesw=1, ntilesh=1, pitch=w*ps;
291 	const char *pfStr=pixFormatStr[pf];
292 
293 	if((tmpbuf=(unsigned char *)malloc(pitch*h)) == NULL)
294 		_throwunix("allocating temporary image buffer");
295 
296 	if(!quiet)
297 		printf(">>>>>  %s (%s) <--> JPEG %s Q%d  <<<<<\n", pfStr,
298 			(flags&TJFLAG_BOTTOMUP)? "Bottom-up":"Top-down", subNameLong[subsamp],
299 			jpegqual);
300 
301 	for(tilew=dotile? 8:w, tileh=dotile? 8:h; ; tilew*=2, tileh*=2)
302 	{
303 		if(tilew>w) tilew=w;  if(tileh>h) tileh=h;
304 		ntilesw=(w+tilew-1)/tilew;  ntilesh=(h+tileh-1)/tileh;
305 
306 		if((jpegbuf=(unsigned char **)malloc(sizeof(unsigned char *)
307 			*ntilesw*ntilesh))==NULL)
308 			_throwunix("allocating JPEG tile array");
309 		memset(jpegbuf, 0, sizeof(unsigned char *)*ntilesw*ntilesh);
310 		if((jpegsize=(unsigned long *)malloc(sizeof(unsigned long)
311 			*ntilesw*ntilesh))==NULL)
312 			_throwunix("allocating JPEG size array");
313 		memset(jpegsize, 0, sizeof(unsigned long)*ntilesw*ntilesh);
314 
315 		if((flags&TJFLAG_NOREALLOC)!=0)
316 			for(i=0; i<ntilesw*ntilesh; i++)
317 			{
318 				if((jpegbuf[i]=(unsigned char *)tjAlloc(tjBufSize(tilew, tileh,
319 					subsamp)))==NULL)
320 					_throwunix("allocating JPEG tiles");
321 			}
322 
323 		/* Compression test */
324 		if(quiet==1)
325 			printf("%-4s (%s)  %-5s    %-3d   ", pfStr,
326 				(flags&TJFLAG_BOTTOMUP)? "BU":"TD", subNameLong[subsamp], jpegqual);
327 		for(i=0; i<h; i++)
328 			memcpy(&tmpbuf[pitch*i], &srcbuf[w*ps*i], w*ps);
329 		if((handle=tjInitCompress())==NULL)
330 			_throwtj("executing tjInitCompress()");
331 
332 		if(doyuv)
333 		{
334 			yuvsize=tjBufSizeYUV2(tilew, yuvpad, tileh, subsamp);
335 			if((yuvbuf=(unsigned char *)malloc(yuvsize))==NULL)
336 				_throwunix("allocating YUV buffer");
337 			memset(yuvbuf, 127, yuvsize);
338 		}
339 
340 		/* Benchmark */
341 		iter=-warmup;
342 		elapsed=elapsedEncode=0.;
343 		while(1)
344 		{
345 			int tile=0;
346 			totaljpegsize=0;
347 			start=gettime();
348 			for(row=0, srcptr=srcbuf; row<ntilesh; row++, srcptr+=pitch*tileh)
349 			{
350 				for(col=0, srcptr2=srcptr; col<ntilesw; col++, tile++,
351 					srcptr2+=ps*tilew)
352 				{
353 					int width=min(tilew, w-col*tilew);
354 					int height=min(tileh, h-row*tileh);
355 					if(doyuv)
356 					{
357 						double startEncode=gettime();
358 						if(tjEncodeYUV3(handle, srcptr2, width, pitch, height, pf, yuvbuf,
359 							yuvpad, subsamp, flags)==-1)
360 							_throwtj("executing tjEncodeYUV3()");
361 						if(iter>=0) elapsedEncode+=gettime()-startEncode;
362 						if(tjCompressFromYUV(handle, yuvbuf, width, yuvpad, height,
363 							subsamp, &jpegbuf[tile], &jpegsize[tile], jpegqual, flags)==-1)
364 							_throwtj("executing tjCompressFromYUV()");
365 					}
366 					else
367 					{
368 						if(tjCompress2(handle, srcptr2, width, pitch, height, pf,
369 							&jpegbuf[tile], &jpegsize[tile], subsamp, jpegqual, flags)==-1)
370 							_throwtj("executing tjCompress2()");
371 					}
372 					totaljpegsize+=jpegsize[tile];
373 				}
374 			}
375 			iter++;
376 			if(iter>=1)
377 			{
378 				elapsed+=gettime()-start;
379 				if(elapsed>=benchtime) break;
380 			}
381 		}
382 		if(doyuv) elapsed-=elapsedEncode;
383 
384 		if(tjDestroy(handle)==-1) _throwtj("executing tjDestroy()");
385 		handle=NULL;
386 
387 		if(quiet==1) printf("%-5d  %-5d   ", tilew, tileh);
388 		if(quiet)
389 		{
390 			if(doyuv)
391 				printf("%-6s%s",
392 					sigfig((double)(w*h)/1000000.*(double)iter/elapsedEncode, 4, tempstr,
393 						1024), quiet==2? "\n":"  ");
394 			printf("%-6s%s",
395 				sigfig((double)(w*h)/1000000.*(double)iter/elapsed, 4,	tempstr, 1024),
396 				quiet==2? "\n":"  ");
397 			printf("%-6s%s",
398 				sigfig((double)(w*h*ps)/(double)totaljpegsize, 4, tempstr2, 80),
399 				quiet==2? "\n":"  ");
400 		}
401 		else
402 		{
403 			printf("\n%s size: %d x %d\n", dotile? "Tile":"Image", tilew,
404 				tileh);
405 			if(doyuv)
406 			{
407 				printf("Encode YUV    --> Frame rate:         %f fps\n",
408 					(double)iter/elapsedEncode);
409 				printf("                  Output image size:  %d bytes\n", yuvsize);
410 				printf("                  Compression ratio:  %f:1\n",
411 					(double)(w*h*ps)/(double)yuvsize);
412 				printf("                  Throughput:         %f Megapixels/sec\n",
413 					(double)(w*h)/1000000.*(double)iter/elapsedEncode);
414 				printf("                  Output bit stream:  %f Megabits/sec\n",
415 					(double)yuvsize*8./1000000.*(double)iter/elapsedEncode);
416 			}
417 			printf("%s --> Frame rate:         %f fps\n",
418 				doyuv? "Comp from YUV":"Compress     ", (double)iter/elapsed);
419 			printf("                  Output image size:  %d bytes\n",
420 				totaljpegsize);
421 			printf("                  Compression ratio:  %f:1\n",
422 				(double)(w*h*ps)/(double)totaljpegsize);
423 			printf("                  Throughput:         %f Megapixels/sec\n",
424 				(double)(w*h)/1000000.*(double)iter/elapsed);
425 			printf("                  Output bit stream:  %f Megabits/sec\n",
426 				(double)totaljpegsize*8./1000000.*(double)iter/elapsed);
427 		}
428 		if(tilew==w && tileh==h && dowrite)
429 		{
430 			snprintf(tempstr, 1024, "%s_%s_Q%d.jpg", filename, subName[subsamp],
431 				jpegqual);
432 			if((file=fopen(tempstr, "wb"))==NULL)
433 				_throwunix("opening reference image");
434 			if(fwrite(jpegbuf[0], jpegsize[0], 1, file)!=1)
435 				_throwunix("writing reference image");
436 			fclose(file);  file=NULL;
437 			if(!quiet) printf("Reference image written to %s\n", tempstr);
438 		}
439 
440 		/* Decompression test */
441 		if(!componly)
442 		{
443 			if(decomp(srcbuf, jpegbuf, jpegsize, tmpbuf, w, h, subsamp, jpegqual,
444 				filename, tilew, tileh)==-1)
445 				goto bailout;
446 		}
447 
448 		for(i=0; i<ntilesw*ntilesh; i++)
449 		{
450 			if(jpegbuf[i]) tjFree(jpegbuf[i]);  jpegbuf[i]=NULL;
451 		}
452 		free(jpegbuf);  jpegbuf=NULL;
453 		free(jpegsize);  jpegsize=NULL;
454 		if(doyuv)
455 		{
456 			free(yuvbuf);  yuvbuf=NULL;
457 		}
458 
459 		if(tilew==w && tileh==h) break;
460 	}
461 
462 	bailout:
463 	if(file) {fclose(file);  file=NULL;}
464 	if(jpegbuf)
465 	{
466 		for(i=0; i<ntilesw*ntilesh; i++)
467 		{
468 			if(jpegbuf[i]) tjFree(jpegbuf[i]);  jpegbuf[i]=NULL;
469 		}
470 		free(jpegbuf);  jpegbuf=NULL;
471 	}
472 	if(yuvbuf) {free(yuvbuf);  yuvbuf=NULL;}
473 	if(jpegsize) {free(jpegsize);  jpegsize=NULL;}
474 	if(tmpbuf) {free(tmpbuf);  tmpbuf=NULL;}
475 	if(handle) {tjDestroy(handle);  handle=NULL;}
476 	return retval;
477 }
478 
479 
decompTest(char * filename)480 int decompTest(char *filename)
481 {
482 	FILE *file=NULL;  tjhandle handle=NULL;
483 	unsigned char **jpegbuf=NULL, *srcbuf=NULL;
484 	unsigned long *jpegsize=NULL, srcsize, totaljpegsize;
485 	tjtransform *t=NULL;
486 	int w=0, h=0, subsamp=-1, cs=-1, _w, _h, _tilew, _tileh,
487 		_ntilesw, _ntilesh, _subsamp;
488 	char *temp=NULL, tempstr[80], tempstr2[80];
489 	int row, col, i, iter, tilew, tileh, ntilesw=1, ntilesh=1, retval=0;
490 	double start, elapsed;
491 	int ps=tjPixelSize[pf], tile;
492 
493 	if((file=fopen(filename, "rb"))==NULL)
494 		_throwunix("opening file");
495 	if(fseek(file, 0, SEEK_END)<0 || (srcsize=ftell(file))==(unsigned long)-1)
496 		_throwunix("determining file size");
497 	if((srcbuf=(unsigned char *)malloc(srcsize))==NULL)
498 		_throwunix("allocating memory");
499 	if(fseek(file, 0, SEEK_SET)<0)
500 		_throwunix("setting file position");
501 	if(fread(srcbuf, srcsize, 1, file)<1)
502 		_throwunix("reading JPEG data");
503 	fclose(file);  file=NULL;
504 
505 	temp=strrchr(filename, '.');
506 	if(temp!=NULL) *temp='\0';
507 
508 	if((handle=tjInitTransform())==NULL)
509 		_throwtj("executing tjInitTransform()");
510 	if(tjDecompressHeader3(handle, srcbuf, srcsize, &w, &h, &subsamp, &cs)==-1)
511 		_throwtj("executing tjDecompressHeader3()");
512 	if(cs==TJCS_YCCK || cs==TJCS_CMYK)
513 	{
514 		pf=TJPF_CMYK;  ps=tjPixelSize[pf];
515 	}
516 
517 	if(quiet==1)
518 	{
519 		printf("All performance values in Mpixels/sec\n\n");
520 		printf("Bitmap     JPEG   JPEG     %s  %s   Xform   Comp    Decomp  ",
521 			dotile? "Tile ":"Image", dotile? "Tile ":"Image");
522 		if(doyuv) printf("Decode");
523 		printf("\n");
524 		printf("Format     CS     Subsamp  Width  Height  Perf    Ratio   Perf    ");
525 		if(doyuv) printf("Perf");
526 		printf("\n\n");
527 	}
528 	else if(!quiet)
529 		printf(">>>>>  JPEG %s --> %s (%s)  <<<<<\n",
530 			formatName(subsamp, cs, tempstr), pixFormatStr[pf],
531 			(flags&TJFLAG_BOTTOMUP)? "Bottom-up":"Top-down");
532 
533 	for(tilew=dotile? 16:w, tileh=dotile? 16:h; ; tilew*=2, tileh*=2)
534 	{
535 		if(tilew>w) tilew=w;  if(tileh>h) tileh=h;
536 		ntilesw=(w+tilew-1)/tilew;  ntilesh=(h+tileh-1)/tileh;
537 
538 		if((jpegbuf=(unsigned char **)malloc(sizeof(unsigned char *)
539 			*ntilesw*ntilesh))==NULL)
540 			_throwunix("allocating JPEG tile array");
541 		memset(jpegbuf, 0, sizeof(unsigned char *)*ntilesw*ntilesh);
542 		if((jpegsize=(unsigned long *)malloc(sizeof(unsigned long)
543 			*ntilesw*ntilesh))==NULL)
544 			_throwunix("allocating JPEG size array");
545 		memset(jpegsize, 0, sizeof(unsigned long)*ntilesw*ntilesh);
546 
547 		if((flags&TJFLAG_NOREALLOC)!=0 || !dotile)
548 			for(i=0; i<ntilesw*ntilesh; i++)
549 			{
550 				if((jpegbuf[i]=(unsigned char *)tjAlloc(tjBufSize(tilew, tileh,
551 					subsamp)))==NULL)
552 					_throwunix("allocating JPEG tiles");
553 			}
554 
555 		_w=w;  _h=h;  _tilew=tilew;  _tileh=tileh;
556 		if(!quiet)
557 		{
558 			printf("\n%s size: %d x %d", dotile? "Tile":"Image", _tilew,
559 				_tileh);
560 			if(sf.num!=1 || sf.denom!=1)
561 				printf(" --> %d x %d", TJSCALED(_w, sf), TJSCALED(_h, sf));
562 			printf("\n");
563 		}
564 		else if(quiet==1)
565 		{
566 			printf("%-4s (%s)  %-5s  %-5s    ", pixFormatStr[pf],
567 				(flags&TJFLAG_BOTTOMUP)? "BU":"TD", csName[cs], subNameLong[subsamp]);
568 			printf("%-5d  %-5d   ", tilew, tileh);
569 		}
570 
571 		_subsamp=subsamp;
572 		if(dotile || xformop!=TJXOP_NONE || xformopt!=0 || customFilter)
573 		{
574 			if((t=(tjtransform *)malloc(sizeof(tjtransform)*ntilesw*ntilesh))
575 				==NULL)
576 				_throwunix("allocating image transform array");
577 
578 			if(xformop==TJXOP_TRANSPOSE || xformop==TJXOP_TRANSVERSE
579 				|| xformop==TJXOP_ROT90 || xformop==TJXOP_ROT270)
580 			{
581 				_w=h;  _h=w;  _tilew=tileh;  _tileh=tilew;
582 			}
583 
584 			if(xformopt&TJXOPT_GRAY) _subsamp=TJ_GRAYSCALE;
585 			if(xformop==TJXOP_HFLIP || xformop==TJXOP_ROT180)
586 				_w=_w-(_w%tjMCUWidth[_subsamp]);
587 			if(xformop==TJXOP_VFLIP || xformop==TJXOP_ROT180)
588 				_h=_h-(_h%tjMCUHeight[_subsamp]);
589 			if(xformop==TJXOP_TRANSVERSE || xformop==TJXOP_ROT90)
590 				_w=_w-(_w%tjMCUHeight[_subsamp]);
591 			if(xformop==TJXOP_TRANSVERSE || xformop==TJXOP_ROT270)
592 				_h=_h-(_h%tjMCUWidth[_subsamp]);
593 			_ntilesw=(_w+_tilew-1)/_tilew;
594 			_ntilesh=(_h+_tileh-1)/_tileh;
595 
596 			if(xformop==TJXOP_TRANSPOSE || xformop==TJXOP_TRANSVERSE
597 				|| xformop==TJXOP_ROT90 || xformop==TJXOP_ROT270)
598 			{
599 				if(_subsamp==TJSAMP_422) _subsamp=TJSAMP_440;
600 				else if(_subsamp==TJSAMP_440) _subsamp=TJSAMP_422;
601 			}
602 
603 			for(row=0, tile=0; row<_ntilesh; row++)
604 			{
605 				for(col=0; col<_ntilesw; col++, tile++)
606 				{
607 					t[tile].r.w=min(_tilew, _w-col*_tilew);
608 					t[tile].r.h=min(_tileh, _h-row*_tileh);
609 					t[tile].r.x=col*_tilew;
610 					t[tile].r.y=row*_tileh;
611 					t[tile].op=xformop;
612 					t[tile].options=xformopt|TJXOPT_TRIM;
613 					t[tile].customFilter=customFilter;
614 					if(t[tile].options&TJXOPT_NOOUTPUT && jpegbuf[tile])
615 					{
616 						tjFree(jpegbuf[tile]);  jpegbuf[tile]=NULL;
617 					}
618 				}
619 			}
620 
621 			iter=-warmup;
622 			elapsed=0.;
623 			while(1)
624 			{
625 				start=gettime();
626 				if(tjTransform(handle, srcbuf, srcsize, _ntilesw*_ntilesh, jpegbuf,
627 					jpegsize, t, flags)==-1)
628 					_throwtj("executing tjTransform()");
629 				iter++;
630 				if(iter>=1)
631 				{
632 					elapsed+=gettime()-start;
633 					if(elapsed>=benchtime) break;
634 				}
635 			}
636 
637 			free(t);  t=NULL;
638 
639 			for(tile=0, totaljpegsize=0; tile<_ntilesw*_ntilesh; tile++)
640 				totaljpegsize+=jpegsize[tile];
641 
642 			if(quiet)
643 			{
644 				printf("%-6s%s%-6s%s",
645 					sigfig((double)(w*h)/1000000./elapsed, 4, tempstr, 80),
646 					quiet==2? "\n":"  ",
647 					sigfig((double)(w*h*ps)/(double)totaljpegsize, 4, tempstr2, 80),
648 					quiet==2? "\n":"  ");
649 			}
650 			else if(!quiet)
651 			{
652 				printf("Transform     --> Frame rate:         %f fps\n", 1.0/elapsed);
653 				printf("                  Output image size:  %lu bytes\n", totaljpegsize);
654 				printf("                  Compression ratio:  %f:1\n",
655 					(double)(w*h*ps)/(double)totaljpegsize);
656 				printf("                  Throughput:         %f Megapixels/sec\n",
657 					(double)(w*h)/1000000./elapsed);
658 				printf("                  Output bit stream:  %f Megabits/sec\n",
659 					(double)totaljpegsize*8./1000000./elapsed);
660 			}
661 		}
662 		else
663 		{
664 			if(quiet==1) printf("N/A     N/A     ");
665 			jpegsize[0]=srcsize;
666 			memcpy(jpegbuf[0], srcbuf, srcsize);
667 		}
668 
669 		if(w==tilew) _tilew=_w;
670 		if(h==tileh) _tileh=_h;
671 		if(!(xformopt&TJXOPT_NOOUTPUT))
672 		{
673 			if(decomp(NULL, jpegbuf, jpegsize, NULL, _w, _h, _subsamp, 0,
674 				filename, _tilew, _tileh)==-1)
675 				goto bailout;
676 		}
677 		else if(quiet==1) printf("N/A\n");
678 
679 		for(i=0; i<ntilesw*ntilesh; i++)
680 		{
681 			tjFree(jpegbuf[i]);  jpegbuf[i]=NULL;
682 		}
683 		free(jpegbuf);  jpegbuf=NULL;
684 		if(jpegsize) {free(jpegsize);  jpegsize=NULL;}
685 
686 		if(tilew==w && tileh==h) break;
687 	}
688 
689 	bailout:
690 	if(file) {fclose(file);  file=NULL;}
691 	if(jpegbuf)
692 	{
693 		for(i=0; i<ntilesw*ntilesh; i++)
694 		{
695 			if(jpegbuf[i]) tjFree(jpegbuf[i]);  jpegbuf[i]=NULL;
696 		}
697 		free(jpegbuf);  jpegbuf=NULL;
698 	}
699 	if(jpegsize) {free(jpegsize);  jpegsize=NULL;}
700 	if(srcbuf) {free(srcbuf);  srcbuf=NULL;}
701 	if(t) {free(t);  t=NULL;}
702 	if(handle) {tjDestroy(handle);  handle=NULL;}
703 	return retval;
704 }
705 
706 
usage(char * progname)707 void usage(char *progname)
708 {
709 	int i;
710 	printf("USAGE: %s\n", progname);
711 	printf("       <Inputfile (BMP|PPM)> <Quality> [options]\n\n");
712 	printf("       %s\n", progname);
713 	printf("       <Inputfile (JPG)> [options]\n\n");
714 	printf("Options:\n\n");
715 	printf("-alloc = Dynamically allocate JPEG image buffers\n");
716 	printf("-bmp = Generate output images in Windows Bitmap format (default = PPM)\n");
717 	printf("-bottomup = Test bottom-up compression/decompression\n");
718 	printf("-tile = Test performance of the codec when the image is encoded as separate\n");
719 	printf("     tiles of varying sizes.\n");
720 	printf("-rgb, -bgr, -rgbx, -bgrx, -xbgr, -xrgb =\n");
721 	printf("     Test the specified color conversion path in the codec (default = BGR)\n");
722 	printf("-cmyk = Indirectly test YCCK JPEG compression/decompression (the source\n");
723 	printf("     and destination bitmaps are still RGB.  The conversion is done\n");
724 	printf("     internally prior to compression or after decompression.)\n");
725 	printf("-fastupsample = Use the fastest chrominance upsampling algorithm available in\n");
726 	printf("     the underlying codec\n");
727 	printf("-fastdct = Use the fastest DCT/IDCT algorithms available in the underlying\n");
728 	printf("     codec\n");
729 	printf("-accuratedct = Use the most accurate DCT/IDCT algorithms available in the\n");
730 	printf("     underlying codec\n");
731 	printf("-subsamp <s> = When testing JPEG compression, this option specifies the level\n");
732 	printf("     of chrominance subsampling to use (<s> = 444, 422, 440, 420, 411, or\n");
733 	printf("     GRAY).  The default is to test Grayscale, 4:2:0, 4:2:2, and 4:4:4 in\n");
734 	printf("     sequence.\n");
735 	printf("-quiet = Output results in tabular rather than verbose format\n");
736 	printf("-yuv = Test YUV encoding/decoding functions\n");
737 	printf("-yuvpad <p> = If testing YUV encoding/decoding, this specifies the number of\n");
738 	printf("     bytes to which each row of each plane in the intermediate YUV image is\n");
739 	printf("     padded (default = 1)\n");
740 	printf("-scale M/N = Scale down the width/height of the decompressed JPEG image by a\n");
741 	printf("     factor of M/N (M/N = ");
742 	for(i=0; i<nsf; i++)
743 	{
744 		printf("%d/%d", scalingfactors[i].num, scalingfactors[i].denom);
745 		if(nsf==2 && i!=nsf-1) printf(" or ");
746 		else if(nsf>2)
747 		{
748 			if(i!=nsf-1) printf(", ");
749 			if(i==nsf-2) printf("or ");
750 		}
751 		if(i%8==0 && i!=0) printf("\n     ");
752 	}
753 	printf(")\n");
754 	printf("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =\n");
755 	printf("     Perform the corresponding lossless transform prior to\n");
756 	printf("     decompression (these options are mutually exclusive)\n");
757 	printf("-grayscale = Perform lossless grayscale conversion prior to decompression\n");
758 	printf("     test (can be combined with the other transforms above)\n");
759 	printf("-benchtime <t> = Run each benchmark for at least <t> seconds (default = 5.0)\n");
760 	printf("-warmup <w> = Execute each benchmark <w> times to prime the cache before\n");
761 	printf("     taking performance measurements (default = 1)\n");
762 	printf("-componly = Stop after running compression tests.  Do not test decompression.\n");
763 	printf("-nowrite = Do not write reference or output images (improves consistency of\n");
764 	printf("     performance measurements.)\n\n");
765 	printf("NOTE:  If the quality is specified as a range (e.g. 90-100), a separate\n");
766 	printf("test will be performed for all quality values in the range.\n\n");
767 	exit(1);
768 }
769 
770 
main(int argc,char * argv[])771 int main(int argc, char *argv[])
772 {
773 	unsigned char *srcbuf=NULL;  int w=0, h=0, i, j;
774 	int minqual=-1, maxqual=-1;  char *temp;
775 	int minarg=2, retval=0, subsamp=-1;
776 
777 	if((scalingfactors=tjGetScalingFactors(&nsf))==NULL || nsf==0)
778 		_throwtj("executing tjGetScalingFactors()");
779 
780 	if(argc<minarg) usage(argv[0]);
781 
782 	temp=strrchr(argv[1], '.');
783 	if(temp!=NULL)
784 	{
785 		if(!strcasecmp(temp, ".bmp")) ext="bmp";
786 		if(!strcasecmp(temp, ".jpg") || !strcasecmp(temp, ".jpeg")) decomponly=1;
787 	}
788 
789 	printf("\n");
790 
791 	if(!decomponly)
792 	{
793 		minarg=3;
794 		if(argc<minarg) usage(argv[0]);
795 		if((minqual=atoi(argv[2]))<1 || minqual>100)
796 		{
797 			puts("ERROR: Quality must be between 1 and 100.");
798 			exit(1);
799 		}
800 		if((temp=strchr(argv[2], '-'))!=NULL && strlen(temp)>1
801 			&& sscanf(&temp[1], "%d", &maxqual)==1 && maxqual>minqual && maxqual>=1
802 			&& maxqual<=100) {}
803 		else maxqual=minqual;
804 	}
805 
806 	if(argc>minarg)
807 	{
808 		for(i=minarg; i<argc; i++)
809 		{
810 			if(!strcasecmp(argv[i], "-tile"))
811 			{
812 				dotile=1;  xformopt|=TJXOPT_CROP;
813 			}
814 			if(!strcasecmp(argv[i], "-fastupsample"))
815 			{
816 				printf("Using fast upsampling code\n\n");
817 				flags|=TJFLAG_FASTUPSAMPLE;
818 			}
819 			if(!strcasecmp(argv[i], "-fastdct"))
820 			{
821 				printf("Using fastest DCT/IDCT algorithm\n\n");
822 				flags|=TJFLAG_FASTDCT;
823 			}
824 			if(!strcasecmp(argv[i], "-accuratedct"))
825 			{
826 				printf("Using most accurate DCT/IDCT algorithm\n\n");
827 				flags|=TJFLAG_ACCURATEDCT;
828 			}
829 			if(!strcasecmp(argv[i], "-rgb")) pf=TJPF_RGB;
830 			if(!strcasecmp(argv[i], "-rgbx")) pf=TJPF_RGBX;
831 			if(!strcasecmp(argv[i], "-bgr")) pf=TJPF_BGR;
832 			if(!strcasecmp(argv[i], "-bgrx")) pf=TJPF_BGRX;
833 			if(!strcasecmp(argv[i], "-xbgr")) pf=TJPF_XBGR;
834 			if(!strcasecmp(argv[i], "-xrgb")) pf=TJPF_XRGB;
835 			if(!strcasecmp(argv[i], "-cmyk")) pf=TJPF_CMYK;
836 			if(!strcasecmp(argv[i], "-bottomup")) flags|=TJFLAG_BOTTOMUP;
837 			if(!strcasecmp(argv[i], "-quiet")) quiet=1;
838 			if(!strcasecmp(argv[i], "-qq")) quiet=2;
839 			if(!strcasecmp(argv[i], "-scale") && i<argc-1)
840 			{
841 				int temp1=0, temp2=0, match=0;
842 				if(sscanf(argv[++i], "%d/%d", &temp1, &temp2)==2)
843 				{
844 					for(j=0; j<nsf; j++)
845 					{
846 						if((double)temp1/(double)temp2
847 							== (double)scalingfactors[j].num/(double)scalingfactors[j].denom)
848 						{
849 							sf=scalingfactors[j];
850 							match=1;  break;
851 						}
852 					}
853 					if(!match) usage(argv[0]);
854 				}
855 				else usage(argv[0]);
856 			}
857 			if(!strcasecmp(argv[i], "-hflip")) xformop=TJXOP_HFLIP;
858 			if(!strcasecmp(argv[i], "-vflip")) xformop=TJXOP_VFLIP;
859 			if(!strcasecmp(argv[i], "-transpose")) xformop=TJXOP_TRANSPOSE;
860 			if(!strcasecmp(argv[i], "-transverse")) xformop=TJXOP_TRANSVERSE;
861 			if(!strcasecmp(argv[i], "-rot90")) xformop=TJXOP_ROT90;
862 			if(!strcasecmp(argv[i], "-rot180")) xformop=TJXOP_ROT180;
863 			if(!strcasecmp(argv[i], "-rot270")) xformop=TJXOP_ROT270;
864 			if(!strcasecmp(argv[i], "-grayscale")) xformopt|=TJXOPT_GRAY;
865 			if(!strcasecmp(argv[i], "-custom")) customFilter=dummyDCTFilter;
866 			if(!strcasecmp(argv[i], "-nooutput")) xformopt|=TJXOPT_NOOUTPUT;
867 			if(!strcasecmp(argv[i], "-benchtime") && i<argc-1)
868 			{
869 				double temp=atof(argv[++i]);
870 				if(temp>0.0) benchtime=temp;
871 				else usage(argv[0]);
872 			}
873 			if(!strcasecmp(argv[i], "-warmup") && i<argc-1)
874 			{
875 				int temp=atoi(argv[++i]);
876 				if(temp>=0)
877 				{
878 					warmup=temp;
879 					printf("Warmup runs = %d\n\n", warmup);
880 				}
881 				else usage(argv[0]);
882 			}
883 			if(!strcmp(argv[i], "-?")) usage(argv[0]);
884 			if(!strcasecmp(argv[i], "-alloc")) flags&=(~TJFLAG_NOREALLOC);
885 			if(!strcasecmp(argv[i], "-bmp")) ext="bmp";
886 			if(!strcasecmp(argv[i], "-yuv"))
887 			{
888 				printf("Testing YUV planar encoding/decoding\n\n");
889 				doyuv=1;
890 			}
891 			if(!strcasecmp(argv[i], "-yuvpad") && i<argc-1)
892 			{
893 				int temp=atoi(argv[++i]);
894 				if(temp>=1) yuvpad=temp;
895 			}
896 			if(!strcasecmp(argv[i], "-subsamp") && i<argc-1)
897 			{
898 				i++;
899 				if(toupper(argv[i][0])=='G') subsamp=TJSAMP_GRAY;
900 				else
901 				{
902 					int temp=atoi(argv[i]);
903 					switch(temp)
904 					{
905 						case 444:  subsamp=TJSAMP_444;  break;
906 						case 422:  subsamp=TJSAMP_422;  break;
907 						case 440:  subsamp=TJSAMP_440;  break;
908 						case 420:  subsamp=TJSAMP_420;  break;
909 						case 411:  subsamp=TJSAMP_411;  break;
910 					}
911 				}
912 			}
913 			if(!strcasecmp(argv[i], "-componly")) componly=1;
914 			if(!strcasecmp(argv[i], "-nowrite")) dowrite=0;
915 		}
916 	}
917 
918 	if((sf.num!=1 || sf.denom!=1) && dotile)
919 	{
920 		printf("Disabling tiled compression/decompression tests, because those tests do not\n");
921 		printf("work when scaled decompression is enabled.\n");
922 		dotile=0;
923 	}
924 
925 	if((flags&TJFLAG_NOREALLOC)==0 && dotile)
926 	{
927 		printf("Disabling tiled compression/decompression tests, because those tests do not\n");
928 		printf("work when dynamic JPEG buffer allocation is enabled.\n\n");
929 		dotile=0;
930 	}
931 
932 	if(!decomponly)
933 	{
934 		if(loadbmp(argv[1], &srcbuf, &w, &h, pf, (flags&TJFLAG_BOTTOMUP)!=0)==-1)
935 			_throwbmp("loading bitmap");
936 		temp=strrchr(argv[1], '.');
937 		if(temp!=NULL) *temp='\0';
938 	}
939 
940 	if(quiet==1 && !decomponly)
941 	{
942 		printf("All performance values in Mpixels/sec\n\n");
943 		printf("Bitmap     JPEG     JPEG  %s  %s   ",
944 			dotile? "Tile ":"Image", dotile? "Tile ":"Image");
945 		if(doyuv) printf("Encode  ");
946 		printf("Comp    Comp    Decomp  ");
947 		if(doyuv) printf("Decode");
948 		printf("\n");
949 		printf("Format     Subsamp  Qual  Width  Height  ");
950 		if(doyuv) printf("Perf    ");
951 		printf("Perf    Ratio   Perf    ");
952 		if(doyuv) printf("Perf");
953 		printf("\n\n");
954 	}
955 
956 	if(decomponly)
957 	{
958 		decompTest(argv[1]);
959 		printf("\n");
960 		goto bailout;
961 	}
962 	if(subsamp>=0 && subsamp<TJ_NUMSAMP)
963 	{
964 		for(i=maxqual; i>=minqual; i--)
965 			fullTest(srcbuf, w, h, subsamp, i, argv[1]);
966 		printf("\n");
967 	}
968 	else
969 	{
970 		if(pf!=TJPF_CMYK)
971 		{
972 			for(i=maxqual; i>=minqual; i--)
973 				fullTest(srcbuf, w, h, TJSAMP_GRAY, i, argv[1]);
974 			printf("\n");
975 		}
976 		for(i=maxqual; i>=minqual; i--)
977 			fullTest(srcbuf, w, h, TJSAMP_420, i, argv[1]);
978 		printf("\n");
979 		for(i=maxqual; i>=minqual; i--)
980 			fullTest(srcbuf, w, h, TJSAMP_422, i, argv[1]);
981 		printf("\n");
982 		for(i=maxqual; i>=minqual; i--)
983 			fullTest(srcbuf, w, h, TJSAMP_444, i, argv[1]);
984 		printf("\n");
985 	}
986 
987 	bailout:
988 	if(srcbuf) free(srcbuf);
989 	return retval;
990 }
991