Bump to 2.0.6
[platform/upstream/libjpeg-turbo.git] / tjunittest.c
1 /*
2  * Copyright (C)2009-2014, 2017-2019 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 /*
30  * This program tests the various code paths in the TurboJPEG C Wrapper
31  */
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <errno.h>
37 #include "tjutil.h"
38 #include "turbojpeg.h"
39 #include "md5/md5.h"
40 #include "cmyk.h"
41 #ifdef _WIN32
42 #include <time.h>
43 #define random()  rand()
44 #else
45 #include <unistd.h>
46 #endif
47
48
49 static void usage(char *progName)
50 {
51   printf("\nUSAGE: %s [options]\n\n", progName);
52   printf("Options:\n");
53   printf("-yuv = test YUV encoding/decoding support\n");
54   printf("-noyuvpad = do not pad each line of each Y, U, and V plane to the nearest\n");
55   printf("            4-byte boundary\n");
56   printf("-alloc = test automatic buffer allocation\n");
57   printf("-bmp = tjLoadImage()/tjSaveImage() unit test\n\n");
58   exit(1);
59 }
60
61
62 #define THROW_TJ() { \
63   printf("TurboJPEG ERROR:\n%s\n", tjGetErrorStr()); \
64   BAILOUT() \
65 }
66 #define TRY_TJ(f) { if ((f) == -1) THROW_TJ(); }
67 #define THROW(m) { printf("ERROR: %s\n", m);  BAILOUT() }
68 #define THROW_MD5(filename, md5sum, ref) { \
69   printf("\n%s has an MD5 sum of %s.\n   Should be %s.\n", filename, md5sum, \
70          ref); \
71   BAILOUT() \
72 }
73
74 const char *subNameLong[TJ_NUMSAMP] = {
75   "4:4:4", "4:2:2", "4:2:0", "GRAY", "4:4:0", "4:1:1"
76 };
77 const char *subName[TJ_NUMSAMP] = {
78   "444", "422", "420", "GRAY", "440", "411"
79 };
80
81 const char *pixFormatStr[TJ_NUMPF] = {
82   "RGB", "BGR", "RGBX", "BGRX", "XBGR", "XRGB", "Grayscale",
83   "RGBA", "BGRA", "ABGR", "ARGB", "CMYK"
84 };
85
86 const int _3byteFormats[] = { TJPF_RGB, TJPF_BGR };
87 const int _4byteFormats[] = {
88   TJPF_RGBX, TJPF_BGRX, TJPF_XBGR, TJPF_XRGB, TJPF_CMYK
89 };
90 const int _onlyGray[] = { TJPF_GRAY };
91 const int _onlyRGB[] = { TJPF_RGB };
92
93 int doYUV = 0, alloc = 0, pad = 4;
94
95 int exitStatus = 0;
96 #define BAILOUT() { exitStatus = -1;  goto bailout; }
97
98
99 static void initBuf(unsigned char *buf, int w, int h, int pf, int flags)
100 {
101   int roffset = tjRedOffset[pf];
102   int goffset = tjGreenOffset[pf];
103   int boffset = tjBlueOffset[pf];
104   int ps = tjPixelSize[pf];
105   int index, row, col, halfway = 16;
106
107   if (pf == TJPF_GRAY) {
108     memset(buf, 0, w * h * ps);
109     for (row = 0; row < h; row++) {
110       for (col = 0; col < w; col++) {
111         if (flags & TJFLAG_BOTTOMUP) index = (h - row - 1) * w + col;
112         else index = row * w + col;
113         if (((row / 8) + (col / 8)) % 2 == 0)
114           buf[index] = (row < halfway) ? 255 : 0;
115         else buf[index] = (row < halfway) ? 76 : 226;
116       }
117     }
118   } else if (pf == TJPF_CMYK) {
119     memset(buf, 255, w * h * ps);
120     for (row = 0; row < h; row++) {
121       for (col = 0; col < w; col++) {
122         if (flags & TJFLAG_BOTTOMUP) index = (h - row - 1) * w + col;
123         else index = row * w + col;
124         if (((row / 8) + (col / 8)) % 2 == 0) {
125           if (row >= halfway) buf[index * ps + 3] = 0;
126         } else {
127           buf[index * ps + 2] = 0;
128           if (row < halfway) buf[index * ps + 1] = 0;
129         }
130       }
131     }
132   } else {
133     memset(buf, 0, w * h * ps);
134     for (row = 0; row < h; row++) {
135       for (col = 0; col < w; col++) {
136         if (flags & TJFLAG_BOTTOMUP) index = (h - row - 1) * w + col;
137         else index = row * w + col;
138         if (((row / 8) + (col / 8)) % 2 == 0) {
139           if (row < halfway) {
140             buf[index * ps + roffset] = 255;
141             buf[index * ps + goffset] = 255;
142             buf[index * ps + boffset] = 255;
143           }
144         } else {
145           buf[index * ps + roffset] = 255;
146           if (row >= halfway) buf[index * ps + goffset] = 255;
147         }
148       }
149     }
150   }
151 }
152
153
154 #define CHECKVAL(v, cv) { \
155   if (v < cv - 1 || v > cv + 1) { \
156     printf("\nComp. %s at %d,%d should be %d, not %d\n", #v, row, col, cv, \
157            v); \
158     retval = 0;  exitStatus = -1;  goto bailout; \
159   } \
160 }
161
162 #define CHECKVAL0(v) { \
163   if (v > 1) { \
164     printf("\nComp. %s at %d,%d should be 0, not %d\n", #v, row, col, v); \
165     retval = 0;  exitStatus = -1;  goto bailout; \
166   } \
167 }
168
169 #define CHECKVAL255(v) { \
170   if (v < 254) { \
171     printf("\nComp. %s at %d,%d should be 255, not %d\n", #v, row, col, v); \
172     retval = 0;  exitStatus = -1;  goto bailout; \
173   } \
174 }
175
176
177 static int checkBuf(unsigned char *buf, int w, int h, int pf, int subsamp,
178                     tjscalingfactor sf, int flags)
179 {
180   int roffset = tjRedOffset[pf];
181   int goffset = tjGreenOffset[pf];
182   int boffset = tjBlueOffset[pf];
183   int aoffset = tjAlphaOffset[pf];
184   int ps = tjPixelSize[pf];
185   int index, row, col, retval = 1;
186   int halfway = 16 * sf.num / sf.denom;
187   int blocksize = 8 * sf.num / sf.denom;
188
189   if (pf == TJPF_GRAY) roffset = goffset = boffset = 0;
190
191   if (pf == TJPF_CMYK) {
192     for (row = 0; row < h; row++) {
193       for (col = 0; col < w; col++) {
194         unsigned char c, m, y, k;
195
196         if (flags & TJFLAG_BOTTOMUP) index = (h - row - 1) * w + col;
197         else index = row * w + col;
198         c = buf[index * ps];
199         m = buf[index * ps + 1];
200         y = buf[index * ps + 2];
201         k = buf[index * ps + 3];
202         if (((row / blocksize) + (col / blocksize)) % 2 == 0) {
203           CHECKVAL255(c);  CHECKVAL255(m);  CHECKVAL255(y);
204           if (row < halfway) CHECKVAL255(k)
205           else CHECKVAL0(k)
206         } else {
207           CHECKVAL255(c);  CHECKVAL0(y);  CHECKVAL255(k);
208           if (row < halfway) CHECKVAL0(m)
209           else CHECKVAL255(m)
210         }
211       }
212     }
213     return 1;
214   }
215
216   for (row = 0; row < h; row++) {
217     for (col = 0; col < w; col++) {
218       unsigned char r, g, b, a;
219
220       if (flags & TJFLAG_BOTTOMUP) index = (h - row - 1) * w + col;
221       else index = row * w + col;
222       r = buf[index * ps + roffset];
223       g = buf[index * ps + goffset];
224       b = buf[index * ps + boffset];
225       a = aoffset >= 0 ? buf[index * ps + aoffset] : 0xFF;
226       if (((row / blocksize) + (col / blocksize)) % 2 == 0) {
227         if (row < halfway) {
228           CHECKVAL255(r);  CHECKVAL255(g);  CHECKVAL255(b);
229         } else {
230           CHECKVAL0(r);  CHECKVAL0(g);  CHECKVAL0(b);
231         }
232       } else {
233         if (subsamp == TJSAMP_GRAY) {
234           if (row < halfway) {
235             CHECKVAL(r, 76);  CHECKVAL(g, 76);  CHECKVAL(b, 76);
236           } else {
237             CHECKVAL(r, 226);  CHECKVAL(g, 226);  CHECKVAL(b, 226);
238           }
239         } else {
240           if (row < halfway) {
241             CHECKVAL255(r);  CHECKVAL0(g);  CHECKVAL0(b);
242           } else {
243             CHECKVAL255(r);  CHECKVAL255(g);  CHECKVAL0(b);
244           }
245         }
246       }
247       CHECKVAL255(a);
248     }
249   }
250
251 bailout:
252   if (retval == 0) {
253     for (row = 0; row < h; row++) {
254       for (col = 0; col < w; col++) {
255         if (pf == TJPF_CMYK)
256           printf("%.3d/%.3d/%.3d/%.3d ", buf[(row * w + col) * ps],
257                  buf[(row * w + col) * ps + 1], buf[(row * w + col) * ps + 2],
258                  buf[(row * w + col) * ps + 3]);
259         else
260           printf("%.3d/%.3d/%.3d ", buf[(row * w + col) * ps + roffset],
261                  buf[(row * w + col) * ps + goffset],
262                  buf[(row * w + col) * ps + boffset]);
263       }
264       printf("\n");
265     }
266   }
267   return retval;
268 }
269
270
271 #define PAD(v, p)  ((v + (p) - 1) & (~((p) - 1)))
272
273 static int checkBufYUV(unsigned char *buf, int w, int h, int subsamp,
274                        tjscalingfactor sf)
275 {
276   int row, col;
277   int hsf = tjMCUWidth[subsamp] / 8, vsf = tjMCUHeight[subsamp] / 8;
278   int pw = PAD(w, hsf), ph = PAD(h, vsf);
279   int cw = pw / hsf, ch = ph / vsf;
280   int ypitch = PAD(pw, pad), uvpitch = PAD(cw, pad);
281   int retval = 1;
282   int halfway = 16 * sf.num / sf.denom;
283   int blocksize = 8 * sf.num / sf.denom;
284
285   for (row = 0; row < ph; row++) {
286     for (col = 0; col < pw; col++) {
287       unsigned char y = buf[ypitch * row + col];
288
289       if (((row / blocksize) + (col / blocksize)) % 2 == 0) {
290         if (row < halfway) CHECKVAL255(y)
291         else CHECKVAL0(y);
292       } else {
293         if (row < halfway) CHECKVAL(y, 76)
294         else CHECKVAL(y, 226);
295       }
296     }
297   }
298   if (subsamp != TJSAMP_GRAY) {
299     halfway = 16 / vsf * sf.num / sf.denom;
300
301     for (row = 0; row < ch; row++) {
302       for (col = 0; col < cw; col++) {
303         unsigned char u = buf[ypitch * ph + (uvpitch * row + col)],
304           v = buf[ypitch * ph + uvpitch * ch + (uvpitch * row + col)];
305
306         if (((row * vsf / blocksize) + (col * hsf / blocksize)) % 2 == 0) {
307           CHECKVAL(u, 128);  CHECKVAL(v, 128);
308         } else {
309           if (row < halfway) {
310             CHECKVAL(u, 85);  CHECKVAL255(v);
311           } else {
312             CHECKVAL0(u);  CHECKVAL(v, 149);
313           }
314         }
315       }
316     }
317   }
318
319 bailout:
320   if (retval == 0) {
321     for (row = 0; row < ph; row++) {
322       for (col = 0; col < pw; col++)
323         printf("%.3d ", buf[ypitch * row + col]);
324       printf("\n");
325     }
326     printf("\n");
327     for (row = 0; row < ch; row++) {
328       for (col = 0; col < cw; col++)
329         printf("%.3d ", buf[ypitch * ph + (uvpitch * row + col)]);
330       printf("\n");
331     }
332     printf("\n");
333     for (row = 0; row < ch; row++) {
334       for (col = 0; col < cw; col++)
335         printf("%.3d ",
336                buf[ypitch * ph + uvpitch * ch + (uvpitch * row + col)]);
337       printf("\n");
338     }
339   }
340
341   return retval;
342 }
343
344
345 static void writeJPEG(unsigned char *jpegBuf, unsigned long jpegSize,
346                       char *filename)
347 {
348   FILE *file = fopen(filename, "wb");
349
350   if (!file || fwrite(jpegBuf, jpegSize, 1, file) != 1) {
351 #if _USE_PRODUCT_TV
352     char err_str[256];
353     strerror_r(errno, err_str, 256);
354     printf("ERROR: Could not write to %s.\n%s\n", filename, err_str);
355 #else
356     printf("ERROR: Could not write to %s.\n%s\n", filename, strerror(errno));
357 #endif
358     BAILOUT()
359   }
360
361 bailout:
362   if (file) fclose(file);
363 }
364
365
366 static void compTest(tjhandle handle, unsigned char **dstBuf,
367                      unsigned long *dstSize, int w, int h, int pf,
368                      char *basename, int subsamp, int jpegQual, int flags)
369 {
370   char tempStr[1024];
371   unsigned char *srcBuf = NULL, *yuvBuf = NULL;
372   const char *pfStr = pixFormatStr[pf];
373   const char *buStrLong =
374     (flags & TJFLAG_BOTTOMUP) ? "Bottom-Up" : "Top-Down ";
375   const char *buStr = (flags & TJFLAG_BOTTOMUP) ? "BU" : "TD";
376
377   if ((srcBuf = (unsigned char *)malloc(w * h * tjPixelSize[pf])) == NULL)
378     THROW("Memory allocation failure");
379   initBuf(srcBuf, w, h, pf, flags);
380
381   if (*dstBuf && *dstSize > 0) memset(*dstBuf, 0, *dstSize);
382
383   if (!alloc) flags |= TJFLAG_NOREALLOC;
384   if (doYUV) {
385     unsigned long yuvSize = tjBufSizeYUV2(w, pad, h, subsamp);
386     tjscalingfactor sf = { 1, 1 };
387     tjhandle handle2 = tjInitCompress();
388
389     if (!handle2) THROW_TJ();
390
391     if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL)
392       THROW("Memory allocation failure");
393     memset(yuvBuf, 0, yuvSize);
394
395     printf("%s %s -> YUV %s ... ", pfStr, buStrLong, subNameLong[subsamp]);
396     TRY_TJ(tjEncodeYUV3(handle2, srcBuf, w, 0, h, pf, yuvBuf, pad, subsamp,
397                         flags));
398     tjDestroy(handle2);
399     if (checkBufYUV(yuvBuf, w, h, subsamp, sf)) printf("Passed.\n");
400     else printf("FAILED!\n");
401
402     printf("YUV %s %s -> JPEG Q%d ... ", subNameLong[subsamp], buStrLong,
403            jpegQual);
404     TRY_TJ(tjCompressFromYUV(handle, yuvBuf, w, pad, h, subsamp, dstBuf,
405                              dstSize, jpegQual, flags));
406   } else {
407     printf("%s %s -> %s Q%d ... ", pfStr, buStrLong, subNameLong[subsamp],
408            jpegQual);
409     TRY_TJ(tjCompress2(handle, srcBuf, w, 0, h, pf, dstBuf, dstSize, subsamp,
410                        jpegQual, flags));
411   }
412
413   snprintf(tempStr, 1024, "%s_enc_%s_%s_%s_Q%d.jpg", basename, pfStr, buStr,
414            subName[subsamp], jpegQual);
415   writeJPEG(*dstBuf, *dstSize, tempStr);
416   printf("Done.\n  Result in %s\n", tempStr);
417
418 bailout:
419   free(yuvBuf);
420   free(srcBuf);
421 }
422
423
424 static void _decompTest(tjhandle handle, unsigned char *jpegBuf,
425                         unsigned long jpegSize, int w, int h, int pf,
426                         char *basename, int subsamp, int flags,
427                         tjscalingfactor sf)
428 {
429   unsigned char *dstBuf = NULL, *yuvBuf = NULL;
430   int _hdrw = 0, _hdrh = 0, _hdrsubsamp = -1;
431   int scaledWidth = TJSCALED(w, sf);
432   int scaledHeight = TJSCALED(h, sf);
433   unsigned long dstSize = 0;
434
435   TRY_TJ(tjDecompressHeader2(handle, jpegBuf, jpegSize, &_hdrw, &_hdrh,
436                              &_hdrsubsamp));
437   if (_hdrw != w || _hdrh != h || _hdrsubsamp != subsamp)
438     THROW("Incorrect JPEG header");
439
440   dstSize = scaledWidth * scaledHeight * tjPixelSize[pf];
441   if ((dstBuf = (unsigned char *)malloc(dstSize)) == NULL)
442     THROW("Memory allocation failure");
443   memset(dstBuf, 0, dstSize);
444
445   if (doYUV) {
446     unsigned long yuvSize = tjBufSizeYUV2(scaledWidth, pad, scaledHeight,
447                                           subsamp);
448     tjhandle handle2 = tjInitDecompress();
449
450     if (!handle2) THROW_TJ();
451
452     if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL)
453       THROW("Memory allocation failure");
454     memset(yuvBuf, 0, yuvSize);
455
456     printf("JPEG -> YUV %s ", subNameLong[subsamp]);
457     if (sf.num != 1 || sf.denom != 1)
458       printf("%d/%d ... ", sf.num, sf.denom);
459     else printf("... ");
460     TRY_TJ(tjDecompressToYUV2(handle, jpegBuf, jpegSize, yuvBuf, scaledWidth,
461                               pad, scaledHeight, flags));
462     if (checkBufYUV(yuvBuf, scaledWidth, scaledHeight, subsamp, sf))
463       printf("Passed.\n");
464     else printf("FAILED!\n");
465
466     printf("YUV %s -> %s %s ... ", subNameLong[subsamp], pixFormatStr[pf],
467            (flags & TJFLAG_BOTTOMUP) ? "Bottom-Up" : "Top-Down ");
468     TRY_TJ(tjDecodeYUV(handle2, yuvBuf, pad, subsamp, dstBuf, scaledWidth, 0,
469                        scaledHeight, pf, flags));
470     tjDestroy(handle2);
471   } else {
472     printf("JPEG -> %s %s ", pixFormatStr[pf],
473            (flags & TJFLAG_BOTTOMUP) ? "Bottom-Up" : "Top-Down ");
474     if (sf.num != 1 || sf.denom != 1)
475       printf("%d/%d ... ", sf.num, sf.denom);
476     else printf("... ");
477     TRY_TJ(tjDecompress2(handle, jpegBuf, jpegSize, dstBuf, scaledWidth, 0,
478                          scaledHeight, pf, flags));
479   }
480
481   if (checkBuf(dstBuf, scaledWidth, scaledHeight, pf, subsamp, sf, flags))
482     printf("Passed.");
483   else printf("FAILED!");
484   printf("\n");
485
486 bailout:
487   free(yuvBuf);
488   free(dstBuf);
489 }
490
491
492 static void decompTest(tjhandle handle, unsigned char *jpegBuf,
493                        unsigned long jpegSize, int w, int h, int pf,
494                        char *basename, int subsamp, int flags)
495 {
496   int i, n = 0;
497   tjscalingfactor *sf = tjGetScalingFactors(&n);
498
499   if (!sf || !n) THROW_TJ();
500
501   for (i = 0; i < n; i++) {
502     if (subsamp == TJSAMP_444 || subsamp == TJSAMP_GRAY ||
503         (subsamp == TJSAMP_411 && sf[i].num == 1 &&
504          (sf[i].denom == 2 || sf[i].denom == 1)) ||
505         (subsamp != TJSAMP_411 && sf[i].num == 1 &&
506          (sf[i].denom == 4 || sf[i].denom == 2 || sf[i].denom == 1)))
507       _decompTest(handle, jpegBuf, jpegSize, w, h, pf, basename, subsamp,
508                   flags, sf[i]);
509   }
510
511 bailout:
512   return;
513 }
514
515
516 static void doTest(int w, int h, const int *formats, int nformats, int subsamp,
517                    char *basename)
518 {
519   tjhandle chandle = NULL, dhandle = NULL;
520   unsigned char *dstBuf = NULL;
521   unsigned long size = 0;
522   int pfi, pf, i;
523
524   if (!alloc)
525     size = tjBufSize(w, h, subsamp);
526   if (size != 0)
527     if ((dstBuf = (unsigned char *)tjAlloc(size)) == NULL)
528       THROW("Memory allocation failure.");
529
530   if ((chandle = tjInitCompress()) == NULL ||
531       (dhandle = tjInitDecompress()) == NULL)
532     THROW_TJ();
533
534   for (pfi = 0; pfi < nformats; pfi++) {
535     for (i = 0; i < 2; i++) {
536       int flags = 0;
537
538       if (subsamp == TJSAMP_422 || subsamp == TJSAMP_420 ||
539           subsamp == TJSAMP_440 || subsamp == TJSAMP_411)
540         flags |= TJFLAG_FASTUPSAMPLE;
541       if (i == 1) flags |= TJFLAG_BOTTOMUP;
542       pf = formats[pfi];
543       compTest(chandle, &dstBuf, &size, w, h, pf, basename, subsamp, 100,
544                flags);
545       decompTest(dhandle, dstBuf, size, w, h, pf, basename, subsamp, flags);
546       if (pf >= TJPF_RGBX && pf <= TJPF_XRGB) {
547         printf("\n");
548         decompTest(dhandle, dstBuf, size, w, h, pf + (TJPF_RGBA - TJPF_RGBX),
549                    basename, subsamp, flags);
550       }
551       printf("\n");
552     }
553   }
554   printf("--------------------\n\n");
555
556 bailout:
557   if (chandle) tjDestroy(chandle);
558   if (dhandle) tjDestroy(dhandle);
559   tjFree(dstBuf);
560 }
561
562
563 #if SIZEOF_SIZE_T == 8
564 #define CHECKSIZE(function) { \
565   if ((unsigned long long)size < (unsigned long long)0xFFFFFFFF) \
566     THROW(#function " overflow"); \
567 }
568 #else
569 #define CHECKSIZE(function) { \
570   if (size != (unsigned long)(-1) || \
571       !strcmp(tjGetErrorStr2(NULL), "No error")) \
572     THROW(#function " overflow"); \
573 }
574 #endif
575
576 static void overflowTest(void)
577 {
578   /* Ensure that the various buffer size functions don't overflow */
579   unsigned long size;
580
581   size = tjBufSize(26755, 26755, TJSAMP_444);
582   CHECKSIZE(tjBufSize());
583   size = TJBUFSIZE(26755, 26755);
584   CHECKSIZE(TJBUFSIZE());
585   size = tjBufSizeYUV2(37838, 1, 37838, TJSAMP_444);
586   CHECKSIZE(tjBufSizeYUV2());
587   size = TJBUFSIZEYUV(37838, 37838, TJSAMP_444);
588   CHECKSIZE(TJBUFSIZEYUV());
589   size = tjBufSizeYUV(37838, 37838, TJSAMP_444);
590   CHECKSIZE(tjBufSizeYUV());
591   size = tjPlaneSizeYUV(0, 65536, 0, 65536, TJSAMP_444);
592   CHECKSIZE(tjPlaneSizeYUV());
593
594 bailout:
595   return;
596 }
597
598
599 static void bufSizeTest(void)
600 {
601   int w, h, i, subsamp;
602   unsigned char *srcBuf = NULL, *dstBuf = NULL;
603   tjhandle handle = NULL;
604   unsigned long dstSize = 0;
605
606   if ((handle = tjInitCompress()) == NULL) THROW_TJ();
607
608   printf("Buffer size regression test\n");
609   for (subsamp = 0; subsamp < TJ_NUMSAMP; subsamp++) {
610     for (w = 1; w < 48; w++) {
611       int maxh = (w == 1) ? 2048 : 48;
612
613       for (h = 1; h < maxh; h++) {
614         if (h % 100 == 0) printf("%.4d x %.4d\b\b\b\b\b\b\b\b\b\b\b", w, h);
615         if ((srcBuf = (unsigned char *)malloc(w * h * 4)) == NULL)
616           THROW("Memory allocation failure");
617         if (!alloc || doYUV) {
618           if (doYUV) dstSize = tjBufSizeYUV2(w, pad, h, subsamp);
619           else dstSize = tjBufSize(w, h, subsamp);
620           if ((dstBuf = (unsigned char *)tjAlloc(dstSize)) == NULL)
621             THROW("Memory allocation failure");
622         }
623
624         for (i = 0; i < w * h * 4; i++) {
625           if (random() < RAND_MAX / 2) srcBuf[i] = 0;
626           else srcBuf[i] = 255;
627         }
628
629         if (doYUV) {
630           TRY_TJ(tjEncodeYUV3(handle, srcBuf, w, 0, h, TJPF_BGRX, dstBuf, pad,
631                               subsamp, 0));
632         } else {
633           TRY_TJ(tjCompress2(handle, srcBuf, w, 0, h, TJPF_BGRX, &dstBuf,
634                              &dstSize, subsamp, 100,
635                              alloc ? 0 : TJFLAG_NOREALLOC));
636         }
637         free(srcBuf);  srcBuf = NULL;
638         if (!alloc || doYUV) {
639           tjFree(dstBuf);  dstBuf = NULL;
640         }
641
642         if ((srcBuf = (unsigned char *)malloc(h * w * 4)) == NULL)
643           THROW("Memory allocation failure");
644         if (!alloc || doYUV) {
645           if (doYUV) dstSize = tjBufSizeYUV2(h, pad, w, subsamp);
646           else dstSize = tjBufSize(h, w, subsamp);
647           if ((dstBuf = (unsigned char *)tjAlloc(dstSize)) == NULL)
648             THROW("Memory allocation failure");
649         }
650
651         for (i = 0; i < h * w * 4; i++) {
652           if (random() < RAND_MAX / 2) srcBuf[i] = 0;
653           else srcBuf[i] = 255;
654         }
655
656         if (doYUV) {
657           TRY_TJ(tjEncodeYUV3(handle, srcBuf, h, 0, w, TJPF_BGRX, dstBuf, pad,
658                               subsamp, 0));
659         } else {
660           TRY_TJ(tjCompress2(handle, srcBuf, h, 0, w, TJPF_BGRX, &dstBuf,
661                              &dstSize, subsamp, 100,
662                              alloc ? 0 : TJFLAG_NOREALLOC));
663         }
664         free(srcBuf);  srcBuf = NULL;
665         if (!alloc || doYUV) {
666           tjFree(dstBuf);  dstBuf = NULL;
667         }
668       }
669     }
670   }
671   printf("Done.      \n");
672
673 bailout:
674   free(srcBuf);
675   tjFree(dstBuf);
676   if (handle) tjDestroy(handle);
677 }
678
679
680 static void initBitmap(unsigned char *buf, int width, int pitch, int height,
681                        int pf, int flags)
682 {
683   int roffset = tjRedOffset[pf];
684   int goffset = tjGreenOffset[pf];
685   int boffset = tjBlueOffset[pf];
686   int ps = tjPixelSize[pf];
687   int i, j;
688
689   for (j = 0; j < height; j++) {
690     int row = (flags & TJFLAG_BOTTOMUP) ? height - j - 1 : j;
691
692     for (i = 0; i < width; i++) {
693       unsigned char r = (i * 256 / width) % 256;
694       unsigned char g = (j * 256 / height) % 256;
695       unsigned char b = (j * 256 / height + i * 256 / width) % 256;
696
697       memset(&buf[row * pitch + i * ps], 0, ps);
698       if (pf == TJPF_GRAY) buf[row * pitch + i * ps] = b;
699       else if (pf == TJPF_CMYK)
700         rgb_to_cmyk(r, g, b, &buf[row * pitch + i * ps + 0],
701                     &buf[row * pitch + i * ps + 1],
702                     &buf[row * pitch + i * ps + 2],
703                     &buf[row * pitch + i * ps + 3]);
704       else {
705         buf[row * pitch + i * ps + roffset] = r;
706         buf[row * pitch + i * ps + goffset] = g;
707         buf[row * pitch + i * ps + boffset] = b;
708       }
709     }
710   }
711 }
712
713
714 static int cmpBitmap(unsigned char *buf, int width, int pitch, int height,
715                      int pf, int flags, int gray2rgb)
716 {
717   int roffset = tjRedOffset[pf];
718   int goffset = tjGreenOffset[pf];
719   int boffset = tjBlueOffset[pf];
720   int aoffset = tjAlphaOffset[pf];
721   int ps = tjPixelSize[pf];
722   int i, j;
723
724   for (j = 0; j < height; j++) {
725     int row = (flags & TJFLAG_BOTTOMUP) ? height - j - 1 : j;
726
727     for (i = 0; i < width; i++) {
728       unsigned char r = (i * 256 / width) % 256;
729       unsigned char g = (j * 256 / height) % 256;
730       unsigned char b = (j * 256 / height + i * 256 / width) % 256;
731
732       if (pf == TJPF_GRAY) {
733         if (buf[row * pitch + i * ps] != b)
734           return 0;
735       } else if (pf == TJPF_CMYK) {
736         unsigned char rf, gf, bf;
737
738         cmyk_to_rgb(buf[row * pitch + i * ps + 0],
739                     buf[row * pitch + i * ps + 1],
740                     buf[row * pitch + i * ps + 2],
741                     buf[row * pitch + i * ps + 3], &rf, &gf, &bf);
742         if (gray2rgb) {
743           if (rf != b || gf != b || bf != b)
744             return 0;
745         } else if (rf != r || gf != g || bf != b) return 0;
746       } else {
747         if (gray2rgb) {
748           if (buf[row * pitch + i * ps + roffset] != b ||
749               buf[row * pitch + i * ps + goffset] != b ||
750               buf[row * pitch + i * ps + boffset] != b)
751             return 0;
752         } else if (buf[row * pitch + i * ps + roffset] != r ||
753                    buf[row * pitch + i * ps + goffset] != g ||
754                    buf[row * pitch + i * ps + boffset] != b)
755           return 0;
756         if (aoffset >= 0 && buf[row * pitch + i * ps + aoffset] != 0xFF)
757           return 0;
758       }
759     }
760   }
761   return 1;
762 }
763
764
765 static int doBmpTest(const char *ext, int width, int align, int height, int pf,
766                      int flags)
767 {
768   char filename[80], *md5sum, md5buf[65];
769   int ps = tjPixelSize[pf], pitch = PAD(width * ps, align), loadWidth = 0,
770     loadHeight = 0, retval = 0, pixelFormat = pf;
771   unsigned char *buf = NULL;
772   char *md5ref;
773
774   if (pf == TJPF_GRAY) {
775     md5ref = !strcasecmp(ext, "ppm") ? "112c682e82ce5de1cca089e20d60000b" :
776                                        "51976530acf75f02beddf5d21149101d";
777   } else {
778     md5ref = !strcasecmp(ext, "ppm") ? "c0c9f772b464d1896326883a5c79c545" :
779                                        "6d659071b9bfcdee2def22cb58ddadca";
780   }
781
782   if ((buf = (unsigned char *)tjAlloc(pitch * height)) == NULL)
783     THROW("Could not allocate memory");
784   initBitmap(buf, width, pitch, height, pf, flags);
785
786   snprintf(filename, 80, "test_bmp_%s_%d_%s.%s", pixFormatStr[pf], align,
787            (flags & TJFLAG_BOTTOMUP) ? "bu" : "td", ext);
788   TRY_TJ(tjSaveImage(filename, buf, width, pitch, height, pf, flags));
789   md5sum = MD5File(filename, md5buf);
790   if (strcasecmp(md5sum, md5ref))
791     THROW_MD5(filename, md5sum, md5ref);
792
793   tjFree(buf);  buf = NULL;
794   if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight, &pf,
795                          flags)) == NULL)
796     THROW_TJ();
797   if (width != loadWidth || height != loadHeight) {
798     printf("\n   Image dimensions of %s are bogus\n", filename);
799     retval = -1;  goto bailout;
800   }
801   if (!cmpBitmap(buf, width, pitch, height, pf, flags, 0)) {
802     printf("\n   Pixel data in %s is bogus\n", filename);
803     retval = -1;  goto bailout;
804   }
805   if (pf == TJPF_GRAY) {
806     tjFree(buf);  buf = NULL;
807     pf = TJPF_XBGR;
808     if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight, &pf,
809                            flags)) == NULL)
810       THROW_TJ();
811     pitch = PAD(width * tjPixelSize[pf], align);
812     if (!cmpBitmap(buf, width, pitch, height, pf, flags, 1)) {
813       printf("\n   Converting %s to RGB failed\n", filename);
814       retval = -1;  goto bailout;
815     }
816
817     tjFree(buf);  buf = NULL;
818     pf = TJPF_CMYK;
819     if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight, &pf,
820                            flags)) == NULL)
821       THROW_TJ();
822     pitch = PAD(width * tjPixelSize[pf], align);
823     if (!cmpBitmap(buf, width, pitch, height, pf, flags, 1)) {
824       printf("\n   Converting %s to CMYK failed\n", filename);
825       retval = -1;  goto bailout;
826     }
827   }
828   /* Verify that tjLoadImage() returns the proper "preferred" pixel format for
829      the file type. */
830   tjFree(buf);  buf = NULL;
831   pf = pixelFormat;
832   pixelFormat = TJPF_UNKNOWN;
833   if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight,
834                          &pixelFormat, flags)) == NULL)
835     THROW_TJ();
836   if ((pf == TJPF_GRAY && pixelFormat != TJPF_GRAY) ||
837       (pf != TJPF_GRAY && !strcasecmp(ext, "bmp") &&
838        pixelFormat != TJPF_BGR) ||
839       (pf != TJPF_GRAY && !strcasecmp(ext, "ppm") &&
840        pixelFormat != TJPF_RGB)) {
841     printf("\n   tjLoadImage() returned unexpected pixel format: %s\n",
842            pixFormatStr[pixelFormat]);
843     retval = -1;
844   }
845   unlink(filename);
846
847 bailout:
848   tjFree(buf);
849   if (exitStatus < 0) return exitStatus;
850   return retval;
851 }
852
853
854 static int bmpTest(void)
855 {
856   int align, width = 35, height = 39, format;
857
858   for (align = 1; align <= 8; align *= 2) {
859     for (format = 0; format < TJ_NUMPF; format++) {
860       printf("%s Top-Down BMP (row alignment = %d bytes)  ...  ",
861              pixFormatStr[format], align);
862       if (doBmpTest("bmp", width, align, height, format, 0) == -1)
863         return -1;
864       printf("OK.\n");
865
866       printf("%s Top-Down PPM (row alignment = %d bytes)  ...  ",
867              pixFormatStr[format], align);
868       if (doBmpTest("ppm", width, align, height, format,
869                     TJFLAG_BOTTOMUP) == -1)
870         return -1;
871       printf("OK.\n");
872
873       printf("%s Bottom-Up BMP (row alignment = %d bytes)  ...  ",
874              pixFormatStr[format], align);
875       if (doBmpTest("bmp", width, align, height, format, 0) == -1)
876         return -1;
877       printf("OK.\n");
878
879       printf("%s Bottom-Up PPM (row alignment = %d bytes)  ...  ",
880              pixFormatStr[format], align);
881       if (doBmpTest("ppm", width, align, height, format,
882                     TJFLAG_BOTTOMUP) == -1)
883         return -1;
884       printf("OK.\n");
885     }
886   }
887
888   return 0;
889 }
890
891
892 int main(int argc, char *argv[])
893 {
894   int i, num4bf = 5;
895
896 #ifdef _WIN32
897   srand((unsigned int)time(NULL));
898 #endif
899   if (argc > 1) {
900     for (i = 1; i < argc; i++) {
901       if (!strcasecmp(argv[i], "-yuv")) doYUV = 1;
902       else if (!strcasecmp(argv[i], "-noyuvpad")) pad = 1;
903       else if (!strcasecmp(argv[i], "-alloc")) alloc = 1;
904       else if (!strcasecmp(argv[i], "-bmp")) return bmpTest();
905       else usage(argv[0]);
906     }
907   }
908   if (alloc) printf("Testing automatic buffer allocation\n");
909   if (doYUV) num4bf = 4;
910   overflowTest();
911   doTest(35, 39, _3byteFormats, 2, TJSAMP_444, "test");
912   doTest(39, 41, _4byteFormats, num4bf, TJSAMP_444, "test");
913   doTest(41, 35, _3byteFormats, 2, TJSAMP_422, "test");
914   doTest(35, 39, _4byteFormats, num4bf, TJSAMP_422, "test");
915   doTest(39, 41, _3byteFormats, 2, TJSAMP_420, "test");
916   doTest(41, 35, _4byteFormats, num4bf, TJSAMP_420, "test");
917   doTest(35, 39, _3byteFormats, 2, TJSAMP_440, "test");
918   doTest(39, 41, _4byteFormats, num4bf, TJSAMP_440, "test");
919   doTest(41, 35, _3byteFormats, 2, TJSAMP_411, "test");
920   doTest(35, 39, _4byteFormats, num4bf, TJSAMP_411, "test");
921   doTest(39, 41, _onlyGray, 1, TJSAMP_GRAY, "test");
922   doTest(41, 35, _3byteFormats, 2, TJSAMP_GRAY, "test");
923   doTest(35, 39, _4byteFormats, 4, TJSAMP_GRAY, "test");
924   bufSizeTest();
925   if (doYUV) {
926     printf("\n--------------------\n\n");
927     doTest(48, 48, _onlyRGB, 1, TJSAMP_444, "test_yuv0");
928     doTest(48, 48, _onlyRGB, 1, TJSAMP_422, "test_yuv0");
929     doTest(48, 48, _onlyRGB, 1, TJSAMP_420, "test_yuv0");
930     doTest(48, 48, _onlyRGB, 1, TJSAMP_440, "test_yuv0");
931     doTest(48, 48, _onlyRGB, 1, TJSAMP_411, "test_yuv0");
932     doTest(48, 48, _onlyRGB, 1, TJSAMP_GRAY, "test_yuv0");
933     doTest(48, 48, _onlyGray, 1, TJSAMP_GRAY, "test_yuv0");
934   }
935
936   return exitStatus;
937 }