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