Imported Upstream version 2.0.4
[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     printf("ERROR: Could not write to %s.\n%s\n", filename, strerror(errno));
352     BAILOUT()
353   }
354
355 bailout:
356   if (file) fclose(file);
357 }
358
359
360 static void compTest(tjhandle handle, unsigned char **dstBuf,
361                      unsigned long *dstSize, int w, int h, int pf,
362                      char *basename, int subsamp, int jpegQual, int flags)
363 {
364   char tempStr[1024];
365   unsigned char *srcBuf = NULL, *yuvBuf = NULL;
366   const char *pfStr = pixFormatStr[pf];
367   const char *buStrLong =
368     (flags & TJFLAG_BOTTOMUP) ? "Bottom-Up" : "Top-Down ";
369   const char *buStr = (flags & TJFLAG_BOTTOMUP) ? "BU" : "TD";
370
371   if ((srcBuf = (unsigned char *)malloc(w * h * tjPixelSize[pf])) == NULL)
372     THROW("Memory allocation failure");
373   initBuf(srcBuf, w, h, pf, flags);
374
375   if (*dstBuf && *dstSize > 0) memset(*dstBuf, 0, *dstSize);
376
377   if (!alloc) flags |= TJFLAG_NOREALLOC;
378   if (doYUV) {
379     unsigned long yuvSize = tjBufSizeYUV2(w, pad, h, subsamp);
380     tjscalingfactor sf = { 1, 1 };
381     tjhandle handle2 = tjInitCompress();
382
383     if (!handle2) THROW_TJ();
384
385     if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL)
386       THROW("Memory allocation failure");
387     memset(yuvBuf, 0, yuvSize);
388
389     printf("%s %s -> YUV %s ... ", pfStr, buStrLong, subNameLong[subsamp]);
390     TRY_TJ(tjEncodeYUV3(handle2, srcBuf, w, 0, h, pf, yuvBuf, pad, subsamp,
391                         flags));
392     tjDestroy(handle2);
393     if (checkBufYUV(yuvBuf, w, h, subsamp, sf)) printf("Passed.\n");
394     else printf("FAILED!\n");
395
396     printf("YUV %s %s -> JPEG Q%d ... ", subNameLong[subsamp], buStrLong,
397            jpegQual);
398     TRY_TJ(tjCompressFromYUV(handle, yuvBuf, w, pad, h, subsamp, dstBuf,
399                              dstSize, jpegQual, flags));
400   } else {
401     printf("%s %s -> %s Q%d ... ", pfStr, buStrLong, subNameLong[subsamp],
402            jpegQual);
403     TRY_TJ(tjCompress2(handle, srcBuf, w, 0, h, pf, dstBuf, dstSize, subsamp,
404                        jpegQual, flags));
405   }
406
407   snprintf(tempStr, 1024, "%s_enc_%s_%s_%s_Q%d.jpg", basename, pfStr, buStr,
408            subName[subsamp], jpegQual);
409   writeJPEG(*dstBuf, *dstSize, tempStr);
410   printf("Done.\n  Result in %s\n", tempStr);
411
412 bailout:
413   if (yuvBuf) free(yuvBuf);
414   if (srcBuf) free(srcBuf);
415 }
416
417
418 static void _decompTest(tjhandle handle, unsigned char *jpegBuf,
419                         unsigned long jpegSize, int w, int h, int pf,
420                         char *basename, int subsamp, int flags,
421                         tjscalingfactor sf)
422 {
423   unsigned char *dstBuf = NULL, *yuvBuf = NULL;
424   int _hdrw = 0, _hdrh = 0, _hdrsubsamp = -1;
425   int scaledWidth = TJSCALED(w, sf);
426   int scaledHeight = TJSCALED(h, sf);
427   unsigned long dstSize = 0;
428
429   TRY_TJ(tjDecompressHeader2(handle, jpegBuf, jpegSize, &_hdrw, &_hdrh,
430                              &_hdrsubsamp));
431   if (_hdrw != w || _hdrh != h || _hdrsubsamp != subsamp)
432     THROW("Incorrect JPEG header");
433
434   dstSize = scaledWidth * scaledHeight * tjPixelSize[pf];
435   if ((dstBuf = (unsigned char *)malloc(dstSize)) == NULL)
436     THROW("Memory allocation failure");
437   memset(dstBuf, 0, dstSize);
438
439   if (doYUV) {
440     unsigned long yuvSize = tjBufSizeYUV2(scaledWidth, pad, scaledHeight,
441                                           subsamp);
442     tjhandle handle2 = tjInitDecompress();
443
444     if (!handle2) THROW_TJ();
445
446     if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL)
447       THROW("Memory allocation failure");
448     memset(yuvBuf, 0, yuvSize);
449
450     printf("JPEG -> YUV %s ", subNameLong[subsamp]);
451     if (sf.num != 1 || sf.denom != 1)
452       printf("%d/%d ... ", sf.num, sf.denom);
453     else printf("... ");
454     TRY_TJ(tjDecompressToYUV2(handle, jpegBuf, jpegSize, yuvBuf, scaledWidth,
455                               pad, scaledHeight, flags));
456     if (checkBufYUV(yuvBuf, scaledWidth, scaledHeight, subsamp, sf))
457       printf("Passed.\n");
458     else printf("FAILED!\n");
459
460     printf("YUV %s -> %s %s ... ", subNameLong[subsamp], pixFormatStr[pf],
461            (flags & TJFLAG_BOTTOMUP) ? "Bottom-Up" : "Top-Down ");
462     TRY_TJ(tjDecodeYUV(handle2, yuvBuf, pad, subsamp, dstBuf, scaledWidth, 0,
463                        scaledHeight, pf, flags));
464     tjDestroy(handle2);
465   } else {
466     printf("JPEG -> %s %s ", pixFormatStr[pf],
467            (flags & TJFLAG_BOTTOMUP) ? "Bottom-Up" : "Top-Down ");
468     if (sf.num != 1 || sf.denom != 1)
469       printf("%d/%d ... ", sf.num, sf.denom);
470     else printf("... ");
471     TRY_TJ(tjDecompress2(handle, jpegBuf, jpegSize, dstBuf, scaledWidth, 0,
472                          scaledHeight, pf, flags));
473   }
474
475   if (checkBuf(dstBuf, scaledWidth, scaledHeight, pf, subsamp, sf, flags))
476     printf("Passed.");
477   else printf("FAILED!");
478   printf("\n");
479
480 bailout:
481   if (yuvBuf) free(yuvBuf);
482   if (dstBuf) free(dstBuf);
483 }
484
485
486 static void decompTest(tjhandle handle, unsigned char *jpegBuf,
487                        unsigned long jpegSize, int w, int h, int pf,
488                        char *basename, int subsamp, int flags)
489 {
490   int i, n = 0;
491   tjscalingfactor *sf = tjGetScalingFactors(&n);
492
493   if (!sf || !n) THROW_TJ();
494
495   for (i = 0; i < n; i++) {
496     if (subsamp == TJSAMP_444 || subsamp == TJSAMP_GRAY ||
497         (subsamp == TJSAMP_411 && sf[i].num == 1 &&
498          (sf[i].denom == 2 || sf[i].denom == 1)) ||
499         (subsamp != TJSAMP_411 && sf[i].num == 1 &&
500          (sf[i].denom == 4 || sf[i].denom == 2 || sf[i].denom == 1)))
501       _decompTest(handle, jpegBuf, jpegSize, w, h, pf, basename, subsamp,
502                   flags, sf[i]);
503   }
504
505 bailout:
506   return;
507 }
508
509
510 static void doTest(int w, int h, const int *formats, int nformats, int subsamp,
511                    char *basename)
512 {
513   tjhandle chandle = NULL, dhandle = NULL;
514   unsigned char *dstBuf = NULL;
515   unsigned long size = 0;
516   int pfi, pf, i;
517
518   if (!alloc)
519     size = tjBufSize(w, h, subsamp);
520   if (size != 0)
521     if ((dstBuf = (unsigned char *)tjAlloc(size)) == NULL)
522       THROW("Memory allocation failure.");
523
524   if ((chandle = tjInitCompress()) == NULL ||
525       (dhandle = tjInitDecompress()) == NULL)
526     THROW_TJ();
527
528   for (pfi = 0; pfi < nformats; pfi++) {
529     for (i = 0; i < 2; i++) {
530       int flags = 0;
531
532       if (subsamp == TJSAMP_422 || subsamp == TJSAMP_420 ||
533           subsamp == TJSAMP_440 || subsamp == TJSAMP_411)
534         flags |= TJFLAG_FASTUPSAMPLE;
535       if (i == 1) flags |= TJFLAG_BOTTOMUP;
536       pf = formats[pfi];
537       compTest(chandle, &dstBuf, &size, w, h, pf, basename, subsamp, 100,
538                flags);
539       decompTest(dhandle, dstBuf, size, w, h, pf, basename, subsamp, flags);
540       if (pf >= TJPF_RGBX && pf <= TJPF_XRGB) {
541         printf("\n");
542         decompTest(dhandle, dstBuf, size, w, h, pf + (TJPF_RGBA - TJPF_RGBX),
543                    basename, subsamp, flags);
544       }
545       printf("\n");
546     }
547   }
548   printf("--------------------\n\n");
549
550 bailout:
551   if (chandle) tjDestroy(chandle);
552   if (dhandle) tjDestroy(dhandle);
553   if (dstBuf) tjFree(dstBuf);
554 }
555
556
557 #if SIZEOF_SIZE_T == 8
558 #define CHECKSIZE(function) { \
559   if ((unsigned long long)size < (unsigned long long)0xFFFFFFFF) \
560     THROW(#function " overflow"); \
561 }
562 #else
563 #define CHECKSIZE(function) { \
564   if (size != (unsigned long)(-1) || \
565       !strcmp(tjGetErrorStr2(NULL), "No error")) \
566     THROW(#function " overflow"); \
567 }
568 #endif
569
570 static void overflowTest(void)
571 {
572   /* Ensure that the various buffer size functions don't overflow */
573   unsigned long size;
574
575   size = tjBufSize(26755, 26755, TJSAMP_444);
576   CHECKSIZE(tjBufSize());
577   size = TJBUFSIZE(26755, 26755);
578   CHECKSIZE(TJBUFSIZE());
579   size = tjBufSizeYUV2(37838, 1, 37838, TJSAMP_444);
580   CHECKSIZE(tjBufSizeYUV2());
581   size = TJBUFSIZEYUV(37838, 37838, TJSAMP_444);
582   CHECKSIZE(TJBUFSIZEYUV());
583   size = tjBufSizeYUV(37838, 37838, TJSAMP_444);
584   CHECKSIZE(tjBufSizeYUV());
585   size = tjPlaneSizeYUV(0, 65536, 0, 65536, TJSAMP_444);
586   CHECKSIZE(tjPlaneSizeYUV());
587
588 bailout:
589   return;
590 }
591
592
593 static void bufSizeTest(void)
594 {
595   int w, h, i, subsamp;
596   unsigned char *srcBuf = NULL, *dstBuf = NULL;
597   tjhandle handle = NULL;
598   unsigned long dstSize = 0;
599
600   if ((handle = tjInitCompress()) == NULL) THROW_TJ();
601
602   printf("Buffer size regression test\n");
603   for (subsamp = 0; subsamp < TJ_NUMSAMP; subsamp++) {
604     for (w = 1; w < 48; w++) {
605       int maxh = (w == 1) ? 2048 : 48;
606
607       for (h = 1; h < maxh; h++) {
608         if (h % 100 == 0) printf("%.4d x %.4d\b\b\b\b\b\b\b\b\b\b\b", w, h);
609         if ((srcBuf = (unsigned char *)malloc(w * h * 4)) == NULL)
610           THROW("Memory allocation failure");
611         if (!alloc || doYUV) {
612           if (doYUV) dstSize = tjBufSizeYUV2(w, pad, h, subsamp);
613           else dstSize = tjBufSize(w, h, subsamp);
614           if ((dstBuf = (unsigned char *)tjAlloc(dstSize)) == NULL)
615             THROW("Memory allocation failure");
616         }
617
618         for (i = 0; i < w * h * 4; i++) {
619           if (random() < RAND_MAX / 2) srcBuf[i] = 0;
620           else srcBuf[i] = 255;
621         }
622
623         if (doYUV) {
624           TRY_TJ(tjEncodeYUV3(handle, srcBuf, w, 0, h, TJPF_BGRX, dstBuf, pad,
625                               subsamp, 0));
626         } else {
627           TRY_TJ(tjCompress2(handle, srcBuf, w, 0, h, TJPF_BGRX, &dstBuf,
628                              &dstSize, subsamp, 100,
629                              alloc ? 0 : TJFLAG_NOREALLOC));
630         }
631         free(srcBuf);  srcBuf = NULL;
632         if (!alloc || doYUV) {
633           tjFree(dstBuf);  dstBuf = NULL;
634         }
635
636         if ((srcBuf = (unsigned char *)malloc(h * w * 4)) == NULL)
637           THROW("Memory allocation failure");
638         if (!alloc || doYUV) {
639           if (doYUV) dstSize = tjBufSizeYUV2(h, pad, w, subsamp);
640           else dstSize = tjBufSize(h, w, subsamp);
641           if ((dstBuf = (unsigned char *)tjAlloc(dstSize)) == NULL)
642             THROW("Memory allocation failure");
643         }
644
645         for (i = 0; i < h * w * 4; i++) {
646           if (random() < RAND_MAX / 2) srcBuf[i] = 0;
647           else srcBuf[i] = 255;
648         }
649
650         if (doYUV) {
651           TRY_TJ(tjEncodeYUV3(handle, srcBuf, h, 0, w, TJPF_BGRX, dstBuf, pad,
652                               subsamp, 0));
653         } else {
654           TRY_TJ(tjCompress2(handle, srcBuf, h, 0, w, TJPF_BGRX, &dstBuf,
655                              &dstSize, subsamp, 100,
656                              alloc ? 0 : TJFLAG_NOREALLOC));
657         }
658         free(srcBuf);  srcBuf = NULL;
659         if (!alloc || doYUV) {
660           tjFree(dstBuf);  dstBuf = NULL;
661         }
662       }
663     }
664   }
665   printf("Done.      \n");
666
667 bailout:
668   if (srcBuf) free(srcBuf);
669   if (dstBuf) tjFree(dstBuf);
670   if (handle) tjDestroy(handle);
671 }
672
673
674 static void initBitmap(unsigned char *buf, int width, int pitch, int height,
675                        int pf, int flags)
676 {
677   int roffset = tjRedOffset[pf];
678   int goffset = tjGreenOffset[pf];
679   int boffset = tjBlueOffset[pf];
680   int ps = tjPixelSize[pf];
681   int i, j;
682
683   for (j = 0; j < height; j++) {
684     int row = (flags & TJFLAG_BOTTOMUP) ? height - j - 1 : j;
685
686     for (i = 0; i < width; i++) {
687       unsigned char r = (i * 256 / width) % 256;
688       unsigned char g = (j * 256 / height) % 256;
689       unsigned char b = (j * 256 / height + i * 256 / width) % 256;
690
691       memset(&buf[row * pitch + i * ps], 0, ps);
692       if (pf == TJPF_GRAY) buf[row * pitch + i * ps] = b;
693       else if (pf == TJPF_CMYK)
694         rgb_to_cmyk(r, g, b, &buf[row * pitch + i * ps + 0],
695                     &buf[row * pitch + i * ps + 1],
696                     &buf[row * pitch + i * ps + 2],
697                     &buf[row * pitch + i * ps + 3]);
698       else {
699         buf[row * pitch + i * ps + roffset] = r;
700         buf[row * pitch + i * ps + goffset] = g;
701         buf[row * pitch + i * ps + boffset] = b;
702       }
703     }
704   }
705 }
706
707
708 static int cmpBitmap(unsigned char *buf, int width, int pitch, int height,
709                      int pf, int flags, int gray2rgb)
710 {
711   int roffset = tjRedOffset[pf];
712   int goffset = tjGreenOffset[pf];
713   int boffset = tjBlueOffset[pf];
714   int aoffset = tjAlphaOffset[pf];
715   int ps = tjPixelSize[pf];
716   int i, j;
717
718   for (j = 0; j < height; j++) {
719     int row = (flags & TJFLAG_BOTTOMUP) ? height - j - 1 : j;
720
721     for (i = 0; i < width; i++) {
722       unsigned char r = (i * 256 / width) % 256;
723       unsigned char g = (j * 256 / height) % 256;
724       unsigned char b = (j * 256 / height + i * 256 / width) % 256;
725
726       if (pf == TJPF_GRAY) {
727         if (buf[row * pitch + i * ps] != b)
728           return 0;
729       } else if (pf == TJPF_CMYK) {
730         unsigned char rf, gf, bf;
731
732         cmyk_to_rgb(buf[row * pitch + i * ps + 0],
733                     buf[row * pitch + i * ps + 1],
734                     buf[row * pitch + i * ps + 2],
735                     buf[row * pitch + i * ps + 3], &rf, &gf, &bf);
736         if (gray2rgb) {
737           if (rf != b || gf != b || bf != b)
738             return 0;
739         } else if (rf != r || gf != g || bf != b) return 0;
740       } else {
741         if (gray2rgb) {
742           if (buf[row * pitch + i * ps + roffset] != b ||
743               buf[row * pitch + i * ps + goffset] != b ||
744               buf[row * pitch + i * ps + boffset] != b)
745             return 0;
746         } else if (buf[row * pitch + i * ps + roffset] != r ||
747                    buf[row * pitch + i * ps + goffset] != g ||
748                    buf[row * pitch + i * ps + boffset] != b)
749           return 0;
750         if (aoffset >= 0 && buf[row * pitch + i * ps + aoffset] != 0xFF)
751           return 0;
752       }
753     }
754   }
755   return 1;
756 }
757
758
759 static int doBmpTest(const char *ext, int width, int align, int height, int pf,
760                      int flags)
761 {
762   char filename[80], *md5sum, md5buf[65];
763   int ps = tjPixelSize[pf], pitch = PAD(width * ps, align), loadWidth = 0,
764     loadHeight = 0, retval = 0, pixelFormat = pf;
765   unsigned char *buf = NULL;
766   char *md5ref;
767
768   if (pf == TJPF_GRAY) {
769     md5ref = !strcasecmp(ext, "ppm") ? "112c682e82ce5de1cca089e20d60000b" :
770                                        "51976530acf75f02beddf5d21149101d";
771   } else {
772     md5ref = !strcasecmp(ext, "ppm") ? "c0c9f772b464d1896326883a5c79c545" :
773                                        "6d659071b9bfcdee2def22cb58ddadca";
774   }
775
776   if ((buf = (unsigned char *)tjAlloc(pitch * height)) == NULL)
777     THROW("Could not allocate memory");
778   initBitmap(buf, width, pitch, height, pf, flags);
779
780   snprintf(filename, 80, "test_bmp_%s_%d_%s.%s", pixFormatStr[pf], align,
781            (flags & TJFLAG_BOTTOMUP) ? "bu" : "td", ext);
782   TRY_TJ(tjSaveImage(filename, buf, width, pitch, height, pf, flags));
783   md5sum = MD5File(filename, md5buf);
784   if (strcasecmp(md5sum, md5ref))
785     THROW_MD5(filename, md5sum, md5ref);
786
787   tjFree(buf);  buf = NULL;
788   if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight, &pf,
789                          flags)) == NULL)
790     THROW_TJ();
791   if (width != loadWidth || height != loadHeight) {
792     printf("\n   Image dimensions of %s are bogus\n", filename);
793     retval = -1;  goto bailout;
794   }
795   if (!cmpBitmap(buf, width, pitch, height, pf, flags, 0)) {
796     printf("\n   Pixel data in %s is bogus\n", filename);
797     retval = -1;  goto bailout;
798   }
799   if (pf == TJPF_GRAY) {
800     tjFree(buf);  buf = NULL;
801     pf = TJPF_XBGR;
802     if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight, &pf,
803                            flags)) == NULL)
804       THROW_TJ();
805     pitch = PAD(width * tjPixelSize[pf], align);
806     if (!cmpBitmap(buf, width, pitch, height, pf, flags, 1)) {
807       printf("\n   Converting %s to RGB failed\n", filename);
808       retval = -1;  goto bailout;
809     }
810
811     tjFree(buf);  buf = NULL;
812     pf = TJPF_CMYK;
813     if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight, &pf,
814                            flags)) == NULL)
815       THROW_TJ();
816     pitch = PAD(width * tjPixelSize[pf], align);
817     if (!cmpBitmap(buf, width, pitch, height, pf, flags, 1)) {
818       printf("\n   Converting %s to CMYK failed\n", filename);
819       retval = -1;  goto bailout;
820     }
821   }
822   /* Verify that tjLoadImage() returns the proper "preferred" pixel format for
823      the file type. */
824   tjFree(buf);  buf = NULL;
825   pf = pixelFormat;
826   pixelFormat = TJPF_UNKNOWN;
827   if ((buf = tjLoadImage(filename, &loadWidth, align, &loadHeight,
828                          &pixelFormat, flags)) == NULL)
829     THROW_TJ();
830   if ((pf == TJPF_GRAY && pixelFormat != TJPF_GRAY) ||
831       (pf != TJPF_GRAY && !strcasecmp(ext, "bmp") &&
832        pixelFormat != TJPF_BGR) ||
833       (pf != TJPF_GRAY && !strcasecmp(ext, "ppm") &&
834        pixelFormat != TJPF_RGB)) {
835     printf("\n   tjLoadImage() returned unexpected pixel format: %s\n",
836            pixFormatStr[pixelFormat]);
837     retval = -1;
838   }
839   unlink(filename);
840
841 bailout:
842   if (buf) tjFree(buf);
843   if (exitStatus < 0) return exitStatus;
844   return retval;
845 }
846
847
848 static int bmpTest(void)
849 {
850   int align, width = 35, height = 39, format;
851
852   for (align = 1; align <= 8; align *= 2) {
853     for (format = 0; format < TJ_NUMPF; format++) {
854       printf("%s Top-Down BMP (row alignment = %d bytes)  ...  ",
855              pixFormatStr[format], align);
856       if (doBmpTest("bmp", width, align, height, format, 0) == -1)
857         return -1;
858       printf("OK.\n");
859
860       printf("%s Top-Down PPM (row alignment = %d bytes)  ...  ",
861              pixFormatStr[format], align);
862       if (doBmpTest("ppm", width, align, height, format,
863                     TJFLAG_BOTTOMUP) == -1)
864         return -1;
865       printf("OK.\n");
866
867       printf("%s Bottom-Up BMP (row alignment = %d bytes)  ...  ",
868              pixFormatStr[format], align);
869       if (doBmpTest("bmp", width, align, height, format, 0) == -1)
870         return -1;
871       printf("OK.\n");
872
873       printf("%s Bottom-Up PPM (row alignment = %d bytes)  ...  ",
874              pixFormatStr[format], align);
875       if (doBmpTest("ppm", width, align, height, format,
876                     TJFLAG_BOTTOMUP) == -1)
877         return -1;
878       printf("OK.\n");
879     }
880   }
881
882   return 0;
883 }
884
885
886 int main(int argc, char *argv[])
887 {
888   int i, num4bf = 5;
889
890 #ifdef _WIN32
891   srand((unsigned int)time(NULL));
892 #endif
893   if (argc > 1) {
894     for (i = 1; i < argc; i++) {
895       if (!strcasecmp(argv[i], "-yuv")) doYUV = 1;
896       else if (!strcasecmp(argv[i], "-noyuvpad")) pad = 1;
897       else if (!strcasecmp(argv[i], "-alloc")) alloc = 1;
898       else if (!strcasecmp(argv[i], "-bmp")) return bmpTest();
899       else usage(argv[0]);
900     }
901   }
902   if (alloc) printf("Testing automatic buffer allocation\n");
903   if (doYUV) num4bf = 4;
904   overflowTest();
905   doTest(35, 39, _3byteFormats, 2, TJSAMP_444, "test");
906   doTest(39, 41, _4byteFormats, num4bf, TJSAMP_444, "test");
907   doTest(41, 35, _3byteFormats, 2, TJSAMP_422, "test");
908   doTest(35, 39, _4byteFormats, num4bf, TJSAMP_422, "test");
909   doTest(39, 41, _3byteFormats, 2, TJSAMP_420, "test");
910   doTest(41, 35, _4byteFormats, num4bf, TJSAMP_420, "test");
911   doTest(35, 39, _3byteFormats, 2, TJSAMP_440, "test");
912   doTest(39, 41, _4byteFormats, num4bf, TJSAMP_440, "test");
913   doTest(41, 35, _3byteFormats, 2, TJSAMP_411, "test");
914   doTest(35, 39, _4byteFormats, num4bf, TJSAMP_411, "test");
915   doTest(39, 41, _onlyGray, 1, TJSAMP_GRAY, "test");
916   doTest(41, 35, _3byteFormats, 2, TJSAMP_GRAY, "test");
917   doTest(35, 39, _4byteFormats, 4, TJSAMP_GRAY, "test");
918   bufSizeTest();
919   if (doYUV) {
920     printf("\n--------------------\n\n");
921     doTest(48, 48, _onlyRGB, 1, TJSAMP_444, "test_yuv0");
922     doTest(48, 48, _onlyRGB, 1, TJSAMP_422, "test_yuv0");
923     doTest(48, 48, _onlyRGB, 1, TJSAMP_420, "test_yuv0");
924     doTest(48, 48, _onlyRGB, 1, TJSAMP_440, "test_yuv0");
925     doTest(48, 48, _onlyRGB, 1, TJSAMP_411, "test_yuv0");
926     doTest(48, 48, _onlyRGB, 1, TJSAMP_GRAY, "test_yuv0");
927     doTest(48, 48, _onlyGray, 1, TJSAMP_GRAY, "test_yuv0");
928   }
929
930   return exitStatus;
931 }