• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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;
252 					if(y<0) y=0;
253 					dstbuf[rindex]=abs(dstbuf[rindex]-y);
254 					dstbuf[gindex]=abs(dstbuf[gindex]-y);
255 					dstbuf[bindex]=abs(dstbuf[bindex]-y);
256 				}
257 			}
258 		}
259 		else
260 		{
261 			for(row=0; row<h; row++)
262 				for(col=0; col<w*ps; col++)
263 					dstbuf[pitch*row+col]
264 						=abs(dstbuf[pitch*row+col]-srcbuf[pitch*row+col]);
265 		}
266 		if(savebmp(tempstr, dstbuf, w, h, pf,
267 			(flags&TJFLAG_BOTTOMUP)!=0)==-1)
268 			_throwbmp("saving bitmap");
269 	}
270 
271 	bailout:
272 	if(file) fclose(file);
273 	if(handle) tjDestroy(handle);
274 	if(dstbuf && dstbufalloc) free(dstbuf);
275 	if(yuvbuf) free(yuvbuf);
276 	return retval;
277 }
278 
279 
fullTest(unsigned char * srcbuf,int w,int h,int subsamp,int jpegqual,char * filename)280 int fullTest(unsigned char *srcbuf, int w, int h, int subsamp, int jpegqual,
281 	char *filename)
282 {
283 	char tempstr[1024], tempstr2[80];
284 	FILE *file=NULL;  tjhandle handle=NULL;
285 	unsigned char **jpegbuf=NULL, *yuvbuf=NULL, *tmpbuf=NULL, *srcptr, *srcptr2;
286 	double start, elapsed, elapsedEncode;
287 	int totaljpegsize=0, row, col, i, tilew=w, tileh=h, retval=0;
288 	int iter, yuvsize=0;
289 	unsigned long *jpegsize=NULL;
290 	int ps=tjPixelSize[pf];
291 	int ntilesw=1, ntilesh=1, pitch=w*ps;
292 	const char *pfStr=pixFormatStr[pf];
293 
294 	if((tmpbuf=(unsigned char *)malloc(pitch*h)) == NULL)
295 		_throwunix("allocating temporary image buffer");
296 
297 	if(!quiet)
298 		printf(">>>>>  %s (%s) <--> JPEG %s Q%d  <<<<<\n", pfStr,
299 			(flags&TJFLAG_BOTTOMUP)? "Bottom-up":"Top-down", subNameLong[subsamp],
300 			jpegqual);
301 
302 	for(tilew=dotile? 8:w, tileh=dotile? 8:h; ; tilew*=2, tileh*=2)
303 	{
304 		if(tilew>w) tilew=w;
305 		if(tileh>h) tileh=h;
306 		ntilesw=(w+tilew-1)/tilew;  ntilesh=(h+tileh-1)/tileh;
307 
308 		if((jpegbuf=(unsigned char **)malloc(sizeof(unsigned char *)
309 			*ntilesw*ntilesh))==NULL)
310 			_throwunix("allocating JPEG tile array");
311 		memset(jpegbuf, 0, sizeof(unsigned char *)*ntilesw*ntilesh);
312 		if((jpegsize=(unsigned long *)malloc(sizeof(unsigned long)
313 			*ntilesw*ntilesh))==NULL)
314 			_throwunix("allocating JPEG size array");
315 		memset(jpegsize, 0, sizeof(unsigned long)*ntilesw*ntilesh);
316 
317 		if((flags&TJFLAG_NOREALLOC)!=0)
318 			for(i=0; i<ntilesw*ntilesh; i++)
319 			{
320 				if((jpegbuf[i]=(unsigned char *)tjAlloc(tjBufSize(tilew, tileh,
321 					subsamp)))==NULL)
322 					_throwunix("allocating JPEG tiles");
323 			}
324 
325 		/* Compression test */
326 		if(quiet==1)
327 			printf("%-4s (%s)  %-5s    %-3d   ", pfStr,
328 				(flags&TJFLAG_BOTTOMUP)? "BU":"TD", subNameLong[subsamp], jpegqual);
329 		for(i=0; i<h; i++)
330 			memcpy(&tmpbuf[pitch*i], &srcbuf[w*ps*i], w*ps);
331 		if((handle=tjInitCompress())==NULL)
332 			_throwtj("executing tjInitCompress()");
333 
334 		if(doyuv)
335 		{
336 			yuvsize=tjBufSizeYUV2(tilew, yuvpad, tileh, subsamp);
337 			if((yuvbuf=(unsigned char *)malloc(yuvsize))==NULL)
338 				_throwunix("allocating YUV buffer");
339 			memset(yuvbuf, 127, yuvsize);
340 		}
341 
342 		/* Benchmark */
343 		iter=-warmup;
344 		elapsed=elapsedEncode=0.;
345 		while(1)
346 		{
347 			int tile=0;
348 			totaljpegsize=0;
349 			start=gettime();
350 			for(row=0, srcptr=srcbuf; row<ntilesh; row++, srcptr+=pitch*tileh)
351 			{
352 				for(col=0, srcptr2=srcptr; col<ntilesw; col++, tile++,
353 					srcptr2+=ps*tilew)
354 				{
355 					int width=min(tilew, w-col*tilew);
356 					int height=min(tileh, h-row*tileh);
357 					if(doyuv)
358 					{
359 						double startEncode=gettime();
360 						if(tjEncodeYUV3(handle, srcptr2, width, pitch, height, pf, yuvbuf,
361 							yuvpad, subsamp, flags)==-1)
362 							_throwtj("executing tjEncodeYUV3()");
363 						if(iter>=0) elapsedEncode+=gettime()-startEncode;
364 						if(tjCompressFromYUV(handle, yuvbuf, width, yuvpad, height,
365 							subsamp, &jpegbuf[tile], &jpegsize[tile], jpegqual, flags)==-1)
366 							_throwtj("executing tjCompressFromYUV()");
367 					}
368 					else
369 					{
370 						if(tjCompress2(handle, srcptr2, width, pitch, height, pf,
371 							&jpegbuf[tile], &jpegsize[tile], subsamp, jpegqual, flags)==-1)
372 							_throwtj("executing tjCompress2()");
373 					}
374 					totaljpegsize+=jpegsize[tile];
375 				}
376 			}
377 			iter++;
378 			if(iter>=1)
379 			{
380 				elapsed+=gettime()-start;
381 				if(elapsed>=benchtime) break;
382 			}
383 		}
384 		if(doyuv) elapsed-=elapsedEncode;
385 
386 		if(tjDestroy(handle)==-1) _throwtj("executing tjDestroy()");
387 		handle=NULL;
388 
389 		if(quiet==1) printf("%-5d  %-5d   ", tilew, tileh);
390 		if(quiet)
391 		{
392 			if(doyuv)
393 				printf("%-6s%s",
394 					sigfig((double)(w*h)/1000000.*(double)iter/elapsedEncode, 4, tempstr,
395 						1024), quiet==2? "\n":"  ");
396 			printf("%-6s%s",
397 				sigfig((double)(w*h)/1000000.*(double)iter/elapsed, 4,	tempstr, 1024),
398 				quiet==2? "\n":"  ");
399 			printf("%-6s%s",
400 				sigfig((double)(w*h*ps)/(double)totaljpegsize, 4, tempstr2, 80),
401 				quiet==2? "\n":"  ");
402 		}
403 		else
404 		{
405 			printf("\n%s size: %d x %d\n", dotile? "Tile":"Image", tilew,
406 				tileh);
407 			if(doyuv)
408 			{
409 				printf("Encode YUV    --> Frame rate:         %f fps\n",
410 					(double)iter/elapsedEncode);
411 				printf("                  Output image size:  %d bytes\n", yuvsize);
412 				printf("                  Compression ratio:  %f:1\n",
413 					(double)(w*h*ps)/(double)yuvsize);
414 				printf("                  Throughput:         %f Megapixels/sec\n",
415 					(double)(w*h)/1000000.*(double)iter/elapsedEncode);
416 				printf("                  Output bit stream:  %f Megabits/sec\n",
417 					(double)yuvsize*8./1000000.*(double)iter/elapsedEncode);
418 			}
419 			printf("%s --> Frame rate:         %f fps\n",
420 				doyuv? "Comp from YUV":"Compress     ", (double)iter/elapsed);
421 			printf("                  Output image size:  %d bytes\n",
422 				totaljpegsize);
423 			printf("                  Compression ratio:  %f:1\n",
424 				(double)(w*h*ps)/(double)totaljpegsize);
425 			printf("                  Throughput:         %f Megapixels/sec\n",
426 				(double)(w*h)/1000000.*(double)iter/elapsed);
427 			printf("                  Output bit stream:  %f Megabits/sec\n",
428 				(double)totaljpegsize*8./1000000.*(double)iter/elapsed);
429 		}
430 		if(tilew==w && tileh==h && dowrite)
431 		{
432 			snprintf(tempstr, 1024, "%s_%s_Q%d.jpg", filename, subName[subsamp],
433 				jpegqual);
434 			if((file=fopen(tempstr, "wb"))==NULL)
435 				_throwunix("opening reference image");
436 			if(fwrite(jpegbuf[0], jpegsize[0], 1, file)!=1)
437 				_throwunix("writing reference image");
438 			fclose(file);  file=NULL;
439 			if(!quiet) printf("Reference image written to %s\n", tempstr);
440 		}
441 
442 		/* Decompression test */
443 		if(!componly)
444 		{
445 			if(decomp(srcbuf, jpegbuf, jpegsize, tmpbuf, w, h, subsamp, jpegqual,
446 				filename, tilew, tileh)==-1)
447 				goto bailout;
448 		}
449 
450 		for(i=0; i<ntilesw*ntilesh; i++)
451 		{
452 			if(jpegbuf[i]) tjFree(jpegbuf[i]);
453 			jpegbuf[i]=NULL;
454 		}
455 		free(jpegbuf);  jpegbuf=NULL;
456 		free(jpegsize);  jpegsize=NULL;
457 		if(doyuv)
458 		{
459 			free(yuvbuf);  yuvbuf=NULL;
460 		}
461 
462 		if(tilew==w && tileh==h) break;
463 	}
464 
465 	bailout:
466 	if(file) {fclose(file);  file=NULL;}
467 	if(jpegbuf)
468 	{
469 		for(i=0; i<ntilesw*ntilesh; i++)
470 		{
471 			if(jpegbuf[i]) tjFree(jpegbuf[i]);
472 			jpegbuf[i]=NULL;
473 		}
474 		free(jpegbuf);  jpegbuf=NULL;
475 	}
476 	if(yuvbuf) {free(yuvbuf);  yuvbuf=NULL;}
477 	if(jpegsize) {free(jpegsize);  jpegsize=NULL;}
478 	if(tmpbuf) {free(tmpbuf);  tmpbuf=NULL;}
479 	if(handle) {tjDestroy(handle);  handle=NULL;}
480 	return retval;
481 }
482 
483 
decompTest(char * filename)484 int decompTest(char *filename)
485 {
486 	FILE *file=NULL;  tjhandle handle=NULL;
487 	unsigned char **jpegbuf=NULL, *srcbuf=NULL;
488 	unsigned long *jpegsize=NULL, srcsize, totaljpegsize;
489 	tjtransform *t=NULL;
490 	int w=0, h=0, subsamp=-1, cs=-1, _w, _h, _tilew, _tileh,
491 		_ntilesw, _ntilesh, _subsamp;
492 	char *temp=NULL, tempstr[80], tempstr2[80];
493 	int row, col, i, iter, tilew, tileh, ntilesw=1, ntilesh=1, retval=0;
494 	double start, elapsed;
495 	int ps=tjPixelSize[pf], tile;
496 
497 	if((file=fopen(filename, "rb"))==NULL)
498 		_throwunix("opening file");
499 	if(fseek(file, 0, SEEK_END)<0 || (srcsize=ftell(file))==(unsigned long)-1)
500 		_throwunix("determining file size");
501 	if((srcbuf=(unsigned char *)malloc(srcsize))==NULL)
502 		_throwunix("allocating memory");
503 	if(fseek(file, 0, SEEK_SET)<0)
504 		_throwunix("setting file position");
505 	if(fread(srcbuf, srcsize, 1, file)<1)
506 		_throwunix("reading JPEG data");
507 	fclose(file);  file=NULL;
508 
509 	temp=strrchr(filename, '.');
510 	if(temp!=NULL) *temp='\0';
511 
512 	if((handle=tjInitTransform())==NULL)
513 		_throwtj("executing tjInitTransform()");
514 	if(tjDecompressHeader3(handle, srcbuf, srcsize, &w, &h, &subsamp, &cs)==-1)
515 		_throwtj("executing tjDecompressHeader3()");
516 	if(cs==TJCS_YCCK || cs==TJCS_CMYK)
517 	{
518 		pf=TJPF_CMYK;  ps=tjPixelSize[pf];
519 	}
520 
521 	if(quiet==1)
522 	{
523 		printf("All performance values in Mpixels/sec\n\n");
524 		printf("Bitmap     JPEG   JPEG     %s  %s   Xform   Comp    Decomp  ",
525 			dotile? "Tile ":"Image", dotile? "Tile ":"Image");
526 		if(doyuv) printf("Decode");
527 		printf("\n");
528 		printf("Format     CS     Subsamp  Width  Height  Perf    Ratio   Perf    ");
529 		if(doyuv) printf("Perf");
530 		printf("\n\n");
531 	}
532 	else if(!quiet)
533 		printf(">>>>>  JPEG %s --> %s (%s)  <<<<<\n",
534 			formatName(subsamp, cs, tempstr), pixFormatStr[pf],
535 			(flags&TJFLAG_BOTTOMUP)? "Bottom-up":"Top-down");
536 
537 	for(tilew=dotile? 16:w, tileh=dotile? 16:h; ; tilew*=2, tileh*=2)
538 	{
539 		if(tilew>w) tilew=w;
540 		if(tileh>h) tileh=h;
541 		ntilesw=(w+tilew-1)/tilew;  ntilesh=(h+tileh-1)/tileh;
542 
543 		if((jpegbuf=(unsigned char **)malloc(sizeof(unsigned char *)
544 			*ntilesw*ntilesh))==NULL)
545 			_throwunix("allocating JPEG tile array");
546 		memset(jpegbuf, 0, sizeof(unsigned char *)*ntilesw*ntilesh);
547 		if((jpegsize=(unsigned long *)malloc(sizeof(unsigned long)
548 			*ntilesw*ntilesh))==NULL)
549 			_throwunix("allocating JPEG size array");
550 		memset(jpegsize, 0, sizeof(unsigned long)*ntilesw*ntilesh);
551 
552 		if((flags&TJFLAG_NOREALLOC)!=0 || !dotile)
553 			for(i=0; i<ntilesw*ntilesh; i++)
554 			{
555 				if((jpegbuf[i]=(unsigned char *)tjAlloc(tjBufSize(tilew, tileh,
556 					subsamp)))==NULL)
557 					_throwunix("allocating JPEG tiles");
558 			}
559 
560 		_w=w;  _h=h;  _tilew=tilew;  _tileh=tileh;
561 		if(!quiet)
562 		{
563 			printf("\n%s size: %d x %d", dotile? "Tile":"Image", _tilew,
564 				_tileh);
565 			if(sf.num!=1 || sf.denom!=1)
566 				printf(" --> %d x %d", TJSCALED(_w, sf), TJSCALED(_h, sf));
567 			printf("\n");
568 		}
569 		else if(quiet==1)
570 		{
571 			printf("%-4s (%s)  %-5s  %-5s    ", pixFormatStr[pf],
572 				(flags&TJFLAG_BOTTOMUP)? "BU":"TD", csName[cs], subNameLong[subsamp]);
573 			printf("%-5d  %-5d   ", tilew, tileh);
574 		}
575 
576 		_subsamp=subsamp;
577 		if(dotile || xformop!=TJXOP_NONE || xformopt!=0 || customFilter)
578 		{
579 			if((t=(tjtransform *)malloc(sizeof(tjtransform)*ntilesw*ntilesh))
580 				==NULL)
581 				_throwunix("allocating image transform array");
582 
583 			if(xformop==TJXOP_TRANSPOSE || xformop==TJXOP_TRANSVERSE
584 				|| xformop==TJXOP_ROT90 || xformop==TJXOP_ROT270)
585 			{
586 				_w=h;  _h=w;  _tilew=tileh;  _tileh=tilew;
587 			}
588 
589 			if(xformopt&TJXOPT_GRAY) _subsamp=TJ_GRAYSCALE;
590 			if(xformop==TJXOP_HFLIP || xformop==TJXOP_ROT180)
591 				_w=_w-(_w%tjMCUWidth[_subsamp]);
592 			if(xformop==TJXOP_VFLIP || xformop==TJXOP_ROT180)
593 				_h=_h-(_h%tjMCUHeight[_subsamp]);
594 			if(xformop==TJXOP_TRANSVERSE || xformop==TJXOP_ROT90)
595 				_w=_w-(_w%tjMCUHeight[_subsamp]);
596 			if(xformop==TJXOP_TRANSVERSE || xformop==TJXOP_ROT270)
597 				_h=_h-(_h%tjMCUWidth[_subsamp]);
598 			_ntilesw=(_w+_tilew-1)/_tilew;
599 			_ntilesh=(_h+_tileh-1)/_tileh;
600 
601 			if(xformop==TJXOP_TRANSPOSE || xformop==TJXOP_TRANSVERSE
602 				|| xformop==TJXOP_ROT90 || xformop==TJXOP_ROT270)
603 			{
604 				if(_subsamp==TJSAMP_422) _subsamp=TJSAMP_440;
605 				else if(_subsamp==TJSAMP_440) _subsamp=TJSAMP_422;
606 			}
607 
608 			for(row=0, tile=0; row<_ntilesh; row++)
609 			{
610 				for(col=0; col<_ntilesw; col++, tile++)
611 				{
612 					t[tile].r.w=min(_tilew, _w-col*_tilew);
613 					t[tile].r.h=min(_tileh, _h-row*_tileh);
614 					t[tile].r.x=col*_tilew;
615 					t[tile].r.y=row*_tileh;
616 					t[tile].op=xformop;
617 					t[tile].options=xformopt|TJXOPT_TRIM;
618 					t[tile].customFilter=customFilter;
619 					if(t[tile].options&TJXOPT_NOOUTPUT && jpegbuf[tile])
620 					{
621 						tjFree(jpegbuf[tile]);  jpegbuf[tile]=NULL;
622 					}
623 				}
624 			}
625 
626 			iter=-warmup;
627 			elapsed=0.;
628 			while(1)
629 			{
630 				start=gettime();
631 				if(tjTransform(handle, srcbuf, srcsize, _ntilesw*_ntilesh, jpegbuf,
632 					jpegsize, t, flags)==-1)
633 					_throwtj("executing tjTransform()");
634 				iter++;
635 				if(iter>=1)
636 				{
637 					elapsed+=gettime()-start;
638 					if(elapsed>=benchtime) break;
639 				}
640 			}
641 
642 			free(t);  t=NULL;
643 
644 			for(tile=0, totaljpegsize=0; tile<_ntilesw*_ntilesh; tile++)
645 				totaljpegsize+=jpegsize[tile];
646 
647 			if(quiet)
648 			{
649 				printf("%-6s%s%-6s%s",
650 					sigfig((double)(w*h)/1000000./elapsed, 4, tempstr, 80),
651 					quiet==2? "\n":"  ",
652 					sigfig((double)(w*h*ps)/(double)totaljpegsize, 4, tempstr2, 80),
653 					quiet==2? "\n":"  ");
654 			}
655 			else if(!quiet)
656 			{
657 				printf("Transform     --> Frame rate:         %f fps\n", 1.0/elapsed);
658 				printf("                  Output image size:  %lu bytes\n", totaljpegsize);
659 				printf("                  Compression ratio:  %f:1\n",
660 					(double)(w*h*ps)/(double)totaljpegsize);
661 				printf("                  Throughput:         %f Megapixels/sec\n",
662 					(double)(w*h)/1000000./elapsed);
663 				printf("                  Output bit stream:  %f Megabits/sec\n",
664 					(double)totaljpegsize*8./1000000./elapsed);
665 			}
666 		}
667 		else
668 		{
669 			if(quiet==1) printf("N/A     N/A     ");
670 			jpegsize[0]=srcsize;
671 			memcpy(jpegbuf[0], srcbuf, srcsize);
672 		}
673 
674 		if(w==tilew) _tilew=_w;
675 		if(h==tileh) _tileh=_h;
676 		if(!(xformopt&TJXOPT_NOOUTPUT))
677 		{
678 			if(decomp(NULL, jpegbuf, jpegsize, NULL, _w, _h, _subsamp, 0,
679 				filename, _tilew, _tileh)==-1)
680 				goto bailout;
681 		}
682 		else if(quiet==1) printf("N/A\n");
683 
684 		for(i=0; i<ntilesw*ntilesh; i++)
685 		{
686 			tjFree(jpegbuf[i]);  jpegbuf[i]=NULL;
687 		}
688 		free(jpegbuf);  jpegbuf=NULL;
689 		if(jpegsize) {free(jpegsize);  jpegsize=NULL;}
690 
691 		if(tilew==w && tileh==h) break;
692 	}
693 
694 	bailout:
695 	if(file) {fclose(file);  file=NULL;}
696 	if(jpegbuf)
697 	{
698 		for(i=0; i<ntilesw*ntilesh; i++)
699 		{
700 			if(jpegbuf[i]) tjFree(jpegbuf[i]);
701 			jpegbuf[i]=NULL;
702 		}
703 		free(jpegbuf);  jpegbuf=NULL;
704 	}
705 	if(jpegsize) {free(jpegsize);  jpegsize=NULL;}
706 	if(srcbuf) {free(srcbuf);  srcbuf=NULL;}
707 	if(t) {free(t);  t=NULL;}
708 	if(handle) {tjDestroy(handle);  handle=NULL;}
709 	return retval;
710 }
711 
712 
usage(char * progname)713 void usage(char *progname)
714 {
715 	int i;
716 	printf("USAGE: %s\n", progname);
717 	printf("       <Inputfile (BMP|PPM)> <Quality> [options]\n\n");
718 	printf("       %s\n", progname);
719 	printf("       <Inputfile (JPG)> [options]\n\n");
720 	printf("Options:\n\n");
721 	printf("-alloc = Dynamically allocate JPEG image buffers\n");
722 	printf("-bmp = Generate output images in Windows Bitmap format (default = PPM)\n");
723 	printf("-bottomup = Test bottom-up compression/decompression\n");
724 	printf("-tile = Test performance of the codec when the image is encoded as separate\n");
725 	printf("     tiles of varying sizes.\n");
726 	printf("-rgb, -bgr, -rgbx, -bgrx, -xbgr, -xrgb =\n");
727 	printf("     Test the specified color conversion path in the codec (default = BGR)\n");
728 	printf("-cmyk = Indirectly test YCCK JPEG compression/decompression (the source\n");
729 	printf("     and destination bitmaps are still RGB.  The conversion is done\n");
730 	printf("     internally prior to compression or after decompression.)\n");
731 	printf("-fastupsample = Use the fastest chrominance upsampling algorithm available in\n");
732 	printf("     the underlying codec\n");
733 	printf("-fastdct = Use the fastest DCT/IDCT algorithms available in the underlying\n");
734 	printf("     codec\n");
735 	printf("-accuratedct = Use the most accurate DCT/IDCT algorithms available in the\n");
736 	printf("     underlying codec\n");
737 	printf("-subsamp <s> = When testing JPEG compression, this option specifies the level\n");
738 	printf("     of chrominance subsampling to use (<s> = 444, 422, 440, 420, 411, or\n");
739 	printf("     GRAY).  The default is to test Grayscale, 4:2:0, 4:2:2, and 4:4:4 in\n");
740 	printf("     sequence.\n");
741 	printf("-quiet = Output results in tabular rather than verbose format\n");
742 	printf("-yuv = Test YUV encoding/decoding functions\n");
743 	printf("-yuvpad <p> = If testing YUV encoding/decoding, this specifies the number of\n");
744 	printf("     bytes to which each row of each plane in the intermediate YUV image is\n");
745 	printf("     padded (default = 1)\n");
746 	printf("-scale M/N = Scale down the width/height of the decompressed JPEG image by a\n");
747 	printf("     factor of M/N (M/N = ");
748 	for(i=0; i<nsf; i++)
749 	{
750 		printf("%d/%d", scalingfactors[i].num, scalingfactors[i].denom);
751 		if(nsf==2 && i!=nsf-1) printf(" or ");
752 		else if(nsf>2)
753 		{
754 			if(i!=nsf-1) printf(", ");
755 			if(i==nsf-2) printf("or ");
756 		}
757 		if(i%8==0 && i!=0) printf("\n     ");
758 	}
759 	printf(")\n");
760 	printf("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =\n");
761 	printf("     Perform the corresponding lossless transform prior to\n");
762 	printf("     decompression (these options are mutually exclusive)\n");
763 	printf("-grayscale = Perform lossless grayscale conversion prior to decompression\n");
764 	printf("     test (can be combined with the other transforms above)\n");
765 	printf("-benchtime <t> = Run each benchmark for at least <t> seconds (default = 5.0)\n");
766 	printf("-warmup <w> = Execute each benchmark <w> times to prime the cache before\n");
767 	printf("     taking performance measurements (default = 1)\n");
768 	printf("-componly = Stop after running compression tests.  Do not test decompression.\n");
769 	printf("-nowrite = Do not write reference or output images (improves consistency of\n");
770 	printf("     performance measurements.)\n\n");
771 	printf("NOTE:  If the quality is specified as a range (e.g. 90-100), a separate\n");
772 	printf("test will be performed for all quality values in the range.\n\n");
773 	exit(1);
774 }
775 
776 
main(int argc,char * argv[])777 int main(int argc, char *argv[])
778 {
779 	unsigned char *srcbuf=NULL;  int w=0, h=0, i, j;
780 	int minqual=-1, maxqual=-1;  char *temp;
781 	int minarg=2, retval=0, subsamp=-1;
782 
783 	if((scalingfactors=tjGetScalingFactors(&nsf))==NULL || nsf==0)
784 		_throwtj("executing tjGetScalingFactors()");
785 
786 	if(argc<minarg) usage(argv[0]);
787 
788 	temp=strrchr(argv[1], '.');
789 	if(temp!=NULL)
790 	{
791 		if(!strcasecmp(temp, ".bmp")) ext="bmp";
792 		if(!strcasecmp(temp, ".jpg") || !strcasecmp(temp, ".jpeg")) decomponly=1;
793 	}
794 
795 	printf("\n");
796 
797 	if(!decomponly)
798 	{
799 		minarg=3;
800 		if(argc<minarg) usage(argv[0]);
801 		if((minqual=atoi(argv[2]))<1 || minqual>100)
802 		{
803 			puts("ERROR: Quality must be between 1 and 100.");
804 			exit(1);
805 		}
806 		if((temp=strchr(argv[2], '-'))!=NULL && strlen(temp)>1
807 			&& sscanf(&temp[1], "%d", &maxqual)==1 && maxqual>minqual && maxqual>=1
808 			&& maxqual<=100) {}
809 		else maxqual=minqual;
810 	}
811 
812 	if(argc>minarg)
813 	{
814 		for(i=minarg; i<argc; i++)
815 		{
816 			if(!strcasecmp(argv[i], "-tile"))
817 			{
818 				dotile=1;  xformopt|=TJXOPT_CROP;
819 			}
820 			if(!strcasecmp(argv[i], "-fastupsample"))
821 			{
822 				printf("Using fast upsampling code\n\n");
823 				flags|=TJFLAG_FASTUPSAMPLE;
824 			}
825 			if(!strcasecmp(argv[i], "-fastdct"))
826 			{
827 				printf("Using fastest DCT/IDCT algorithm\n\n");
828 				flags|=TJFLAG_FASTDCT;
829 			}
830 			if(!strcasecmp(argv[i], "-accuratedct"))
831 			{
832 				printf("Using most accurate DCT/IDCT algorithm\n\n");
833 				flags|=TJFLAG_ACCURATEDCT;
834 			}
835 			if(!strcasecmp(argv[i], "-rgb")) pf=TJPF_RGB;
836 			if(!strcasecmp(argv[i], "-rgbx")) pf=TJPF_RGBX;
837 			if(!strcasecmp(argv[i], "-bgr")) pf=TJPF_BGR;
838 			if(!strcasecmp(argv[i], "-bgrx")) pf=TJPF_BGRX;
839 			if(!strcasecmp(argv[i], "-xbgr")) pf=TJPF_XBGR;
840 			if(!strcasecmp(argv[i], "-xrgb")) pf=TJPF_XRGB;
841 			if(!strcasecmp(argv[i], "-cmyk")) pf=TJPF_CMYK;
842 			if(!strcasecmp(argv[i], "-bottomup")) flags|=TJFLAG_BOTTOMUP;
843 			if(!strcasecmp(argv[i], "-quiet")) quiet=1;
844 			if(!strcasecmp(argv[i], "-qq")) quiet=2;
845 			if(!strcasecmp(argv[i], "-scale") && i<argc-1)
846 			{
847 				int temp1=0, temp2=0, match=0;
848 				if(sscanf(argv[++i], "%d/%d", &temp1, &temp2)==2)
849 				{
850 					for(j=0; j<nsf; j++)
851 					{
852 						if((double)temp1/(double)temp2
853 							== (double)scalingfactors[j].num/(double)scalingfactors[j].denom)
854 						{
855 							sf=scalingfactors[j];
856 							match=1;  break;
857 						}
858 					}
859 					if(!match) usage(argv[0]);
860 				}
861 				else usage(argv[0]);
862 			}
863 			if(!strcasecmp(argv[i], "-hflip")) xformop=TJXOP_HFLIP;
864 			if(!strcasecmp(argv[i], "-vflip")) xformop=TJXOP_VFLIP;
865 			if(!strcasecmp(argv[i], "-transpose")) xformop=TJXOP_TRANSPOSE;
866 			if(!strcasecmp(argv[i], "-transverse")) xformop=TJXOP_TRANSVERSE;
867 			if(!strcasecmp(argv[i], "-rot90")) xformop=TJXOP_ROT90;
868 			if(!strcasecmp(argv[i], "-rot180")) xformop=TJXOP_ROT180;
869 			if(!strcasecmp(argv[i], "-rot270")) xformop=TJXOP_ROT270;
870 			if(!strcasecmp(argv[i], "-grayscale")) xformopt|=TJXOPT_GRAY;
871 			if(!strcasecmp(argv[i], "-custom")) customFilter=dummyDCTFilter;
872 			if(!strcasecmp(argv[i], "-nooutput")) xformopt|=TJXOPT_NOOUTPUT;
873 			if(!strcasecmp(argv[i], "-benchtime") && i<argc-1)
874 			{
875 				double temp=atof(argv[++i]);
876 				if(temp>0.0) benchtime=temp;
877 				else usage(argv[0]);
878 			}
879 			if(!strcasecmp(argv[i], "-warmup") && i<argc-1)
880 			{
881 				int temp=atoi(argv[++i]);
882 				if(temp>=0)
883 				{
884 					warmup=temp;
885 					printf("Warmup runs = %d\n\n", warmup);
886 				}
887 				else usage(argv[0]);
888 			}
889 			if(!strcmp(argv[i], "-?")) usage(argv[0]);
890 			if(!strcasecmp(argv[i], "-alloc")) flags&=(~TJFLAG_NOREALLOC);
891 			if(!strcasecmp(argv[i], "-bmp")) ext="bmp";
892 			if(!strcasecmp(argv[i], "-yuv"))
893 			{
894 				printf("Testing YUV planar encoding/decoding\n\n");
895 				doyuv=1;
896 			}
897 			if(!strcasecmp(argv[i], "-yuvpad") && i<argc-1)
898 			{
899 				int temp=atoi(argv[++i]);
900 				if(temp>=1) yuvpad=temp;
901 			}
902 			if(!strcasecmp(argv[i], "-subsamp") && i<argc-1)
903 			{
904 				i++;
905 				if(toupper(argv[i][0])=='G') subsamp=TJSAMP_GRAY;
906 				else
907 				{
908 					int temp=atoi(argv[i]);
909 					switch(temp)
910 					{
911 						case 444:  subsamp=TJSAMP_444;  break;
912 						case 422:  subsamp=TJSAMP_422;  break;
913 						case 440:  subsamp=TJSAMP_440;  break;
914 						case 420:  subsamp=TJSAMP_420;  break;
915 						case 411:  subsamp=TJSAMP_411;  break;
916 					}
917 				}
918 			}
919 			if(!strcasecmp(argv[i], "-componly")) componly=1;
920 			if(!strcasecmp(argv[i], "-nowrite")) dowrite=0;
921 		}
922 	}
923 
924 	if((sf.num!=1 || sf.denom!=1) && dotile)
925 	{
926 		printf("Disabling tiled compression/decompression tests, because those tests do not\n");
927 		printf("work when scaled decompression is enabled.\n");
928 		dotile=0;
929 	}
930 
931 	if((flags&TJFLAG_NOREALLOC)==0 && dotile)
932 	{
933 		printf("Disabling tiled compression/decompression tests, because those tests do not\n");
934 		printf("work when dynamic JPEG buffer allocation is enabled.\n\n");
935 		dotile=0;
936 	}
937 
938 	if(!decomponly)
939 	{
940 		if(loadbmp(argv[1], &srcbuf, &w, &h, pf, (flags&TJFLAG_BOTTOMUP)!=0)==-1)
941 			_throwbmp("loading bitmap");
942 		temp=strrchr(argv[1], '.');
943 		if(temp!=NULL) *temp='\0';
944 	}
945 
946 	if(quiet==1 && !decomponly)
947 	{
948 		printf("All performance values in Mpixels/sec\n\n");
949 		printf("Bitmap     JPEG     JPEG  %s  %s   ",
950 			dotile? "Tile ":"Image", dotile? "Tile ":"Image");
951 		if(doyuv) printf("Encode  ");
952 		printf("Comp    Comp    Decomp  ");
953 		if(doyuv) printf("Decode");
954 		printf("\n");
955 		printf("Format     Subsamp  Qual  Width  Height  ");
956 		if(doyuv) printf("Perf    ");
957 		printf("Perf    Ratio   Perf    ");
958 		if(doyuv) printf("Perf");
959 		printf("\n\n");
960 	}
961 
962 	if(decomponly)
963 	{
964 		decompTest(argv[1]);
965 		printf("\n");
966 		goto bailout;
967 	}
968 	if(subsamp>=0 && subsamp<TJ_NUMSAMP)
969 	{
970 		for(i=maxqual; i>=minqual; i--)
971 			fullTest(srcbuf, w, h, subsamp, i, argv[1]);
972 		printf("\n");
973 	}
974 	else
975 	{
976 		if(pf!=TJPF_CMYK)
977 		{
978 			for(i=maxqual; i>=minqual; i--)
979 				fullTest(srcbuf, w, h, TJSAMP_GRAY, i, argv[1]);
980 			printf("\n");
981 		}
982 		for(i=maxqual; i>=minqual; i--)
983 			fullTest(srcbuf, w, h, TJSAMP_420, i, argv[1]);
984 		printf("\n");
985 		for(i=maxqual; i>=minqual; i--)
986 			fullTest(srcbuf, w, h, TJSAMP_422, i, argv[1]);
987 		printf("\n");
988 		for(i=maxqual; i>=minqual; i--)
989 			fullTest(srcbuf, w, h, TJSAMP_444, i, argv[1]);
990 		printf("\n");
991 	}
992 
993 	bailout:
994 	if(srcbuf) free(srcbuf);
995 	return retval;
996 }
997