Merge branch 'upstream' into tizen_base
[platform/upstream/libjpeg-turbo.git] / tjexample.c
1 /*
2  * Copyright (C)2011-2012, 2014-2015, 2017, 2019, 2021-2023
3  *           D. R. Commander.  All Rights Reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * - Redistributions of source code must retain the above copyright notice,
9  *   this list of conditions and the following disclaimer.
10  * - Redistributions in binary form must reproduce the above copyright notice,
11  *   this list of conditions and the following disclaimer in the documentation
12  *   and/or other materials provided with the distribution.
13  * - Neither the name of the libjpeg-turbo Project nor the names of its
14  *   contributors may be used to endorse or promote products derived from this
15  *   software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 /*
31  * This program demonstrates how to compress, decompress, and transform JPEG
32  * images using the TurboJPEG C API
33  */
34
35 #ifdef _MSC_VER
36 #define _CRT_SECURE_NO_DEPRECATE
37 #endif
38
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <errno.h>
43 #include <turbojpeg.h>
44
45
46 #ifdef _WIN32
47 #define strcasecmp  stricmp
48 #define strncasecmp  strnicmp
49 #endif
50
51 #define THROW(action, message) { \
52   printf("ERROR in line %d while %s:\n%s\n", __LINE__, action, message); \
53   retval = -1;  goto bailout; \
54 }
55
56 #define THROW_TJ(action)  THROW(action, tj3GetErrorStr(tjInstance))
57
58 #define THROW_UNIX(action)  THROW(action, strerror(errno))
59
60 #define DEFAULT_SUBSAMP  TJSAMP_444
61 #define DEFAULT_QUALITY  95
62
63
64 const char *subsampName[TJ_NUMSAMP] = {
65   "4:4:4", "4:2:2", "4:2:0", "Grayscale", "4:4:0", "4:1:1", "4:4:1"
66 };
67
68 const char *colorspaceName[TJ_NUMCS] = {
69   "RGB", "YCbCr", "GRAY", "CMYK", "YCCK"
70 };
71
72 tjscalingfactor *scalingFactors = NULL;
73 int numScalingFactors = 0;
74
75
76 /* DCT filter example.  This produces a negative of the image. */
77
78 static int customFilter(short *coeffs, tjregion arrayRegion,
79                         tjregion planeRegion, int componentIndex,
80                         int transformIndex, tjtransform *transform)
81 {
82   int i;
83
84   for (i = 0; i < arrayRegion.w * arrayRegion.h; i++)
85     coeffs[i] = -coeffs[i];
86
87   return 0;
88 }
89
90
91 static void usage(char *programName)
92 {
93   int i;
94
95   printf("\nUSAGE: %s <Input image> <Output image> [options]\n\n",
96          programName);
97
98   printf("Input and output images can be in Windows BMP or PBMPLUS (PPM/PGM) format.  If\n");
99   printf("either filename ends in a .jpg extension, then the TurboJPEG API will be used\n");
100   printf("to compress or decompress the image.\n\n");
101
102   printf("Compression Options (used if the output image is a JPEG image)\n");
103   printf("--------------------------------------------------------------\n\n");
104
105   printf("-subsamp <444|422|420|gray> = Apply this level of chrominance subsampling when\n");
106   printf("     compressing the output image.  The default is to use the same level of\n");
107   printf("     subsampling as in the input image, if the input image is also a JPEG\n");
108   printf("     image, or to use grayscale if the input image is a grayscale non-JPEG\n");
109   printf("     image, or to use %s subsampling otherwise.\n\n",
110          subsampName[DEFAULT_SUBSAMP]);
111
112   printf("-q <1-100> = Compress the output image with this JPEG quality level\n");
113   printf("     (default = %d).\n\n", DEFAULT_QUALITY);
114
115   printf("Decompression Options (used if the input image is a JPEG image)\n");
116   printf("---------------------------------------------------------------\n\n");
117
118   printf("-scale M/N = Scale the input image by a factor of M/N when decompressing it.\n");
119   printf("(M/N = ");
120   for (i = 0; i < numScalingFactors; i++) {
121     printf("%d/%d", scalingFactors[i].num, scalingFactors[i].denom);
122     if (numScalingFactors == 2 && i != numScalingFactors - 1)
123       printf(" or ");
124     else if (numScalingFactors > 2) {
125       if (i != numScalingFactors - 1)
126         printf(", ");
127       if (i == numScalingFactors - 2)
128         printf("or ");
129     }
130   }
131   printf(")\n\n");
132
133   printf("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =\n");
134   printf("     Perform one of these lossless transform operations on the input image\n");
135   printf("     prior to decompressing it (these options are mutually exclusive.)\n\n");
136
137   printf("-grayscale = Perform lossless grayscale conversion on the input image prior\n");
138   printf("     to decompressing it (can be combined with the other transform operations\n");
139   printf("     above.)\n\n");
140
141   printf("-crop WxH+X+Y = Perform lossless cropping on the input image prior to\n");
142   printf("     decompressing it.  X and Y specify the upper left corner of the cropping\n");
143   printf("     region, and W and H specify the width and height of the cropping region.\n");
144   printf("     X and Y must be evenly divible by the MCU block size (8x8 if the input\n");
145   printf("     image was compressed using no subsampling or grayscale, 16x8 if it was\n");
146   printf("     compressed using 4:2:2 subsampling, or 16x16 if it was compressed using\n");
147   printf("     4:2:0 subsampling.)\n\n");
148
149   printf("General Options\n");
150   printf("---------------\n\n");
151
152   printf("-fastupsample = Use the fastest chrominance upsampling algorithm available\n\n");
153
154   printf("-fastdct = Use the fastest DCT/IDCT algorithm available\n\n");
155
156   exit(1);
157 }
158
159
160 int main(int argc, char **argv)
161 {
162   tjscalingfactor scalingFactor = TJUNSCALED;
163   int outSubsamp = -1, outQual = -1;
164   tjtransform xform;
165   int fastUpsample = 0, fastDCT = 0;
166   int width, height;
167   char *inFormat, *outFormat;
168   FILE *jpegFile = NULL;
169   unsigned char *imgBuf = NULL, *jpegBuf = NULL;
170   int retval = 0, i, pixelFormat = TJPF_UNKNOWN;
171   tjhandle tjInstance = NULL;
172
173   if ((scalingFactors = tj3GetScalingFactors(&numScalingFactors)) == NULL)
174     THROW_TJ("getting scaling factors");
175   memset(&xform, 0, sizeof(tjtransform));
176
177   if (argc < 3)
178     usage(argv[0]);
179
180   /* Parse arguments. */
181   for (i = 3; i < argc; i++) {
182     if (!strncasecmp(argv[i], "-sc", 3) && i < argc - 1) {
183       int match = 0, temp1 = 0, temp2 = 0, j;
184
185       if (sscanf(argv[++i], "%d/%d", &temp1, &temp2) < 2)
186         usage(argv[0]);
187       for (j = 0; j < numScalingFactors; j++) {
188         if ((double)temp1 / (double)temp2 == (double)scalingFactors[j].num /
189                                              (double)scalingFactors[j].denom) {
190           scalingFactor = scalingFactors[j];
191           match = 1;
192           break;
193         }
194       }
195       if (match != 1)
196         usage(argv[0]);
197     } else if (!strncasecmp(argv[i], "-su", 3) && i < argc - 1) {
198       i++;
199       if (!strncasecmp(argv[i], "g", 1))
200         outSubsamp = TJSAMP_GRAY;
201       else if (!strcasecmp(argv[i], "444"))
202         outSubsamp = TJSAMP_444;
203       else if (!strcasecmp(argv[i], "422"))
204         outSubsamp = TJSAMP_422;
205       else if (!strcasecmp(argv[i], "420"))
206         outSubsamp = TJSAMP_420;
207       else
208         usage(argv[0]);
209     } else if (!strncasecmp(argv[i], "-q", 2) && i < argc - 1) {
210       outQual = atoi(argv[++i]);
211       if (outQual < 1 || outQual > 100)
212         usage(argv[0]);
213     } else if (!strncasecmp(argv[i], "-g", 2))
214       xform.options |= TJXOPT_GRAY;
215     else if (!strcasecmp(argv[i], "-hflip"))
216       xform.op = TJXOP_HFLIP;
217     else if (!strcasecmp(argv[i], "-vflip"))
218       xform.op = TJXOP_VFLIP;
219     else if (!strcasecmp(argv[i], "-transpose"))
220       xform.op = TJXOP_TRANSPOSE;
221     else if (!strcasecmp(argv[i], "-transverse"))
222       xform.op = TJXOP_TRANSVERSE;
223     else if (!strcasecmp(argv[i], "-rot90"))
224       xform.op = TJXOP_ROT90;
225     else if (!strcasecmp(argv[i], "-rot180"))
226       xform.op = TJXOP_ROT180;
227     else if (!strcasecmp(argv[i], "-rot270"))
228       xform.op = TJXOP_ROT270;
229     else if (!strcasecmp(argv[i], "-custom"))
230       xform.customFilter = customFilter;
231     else if (!strncasecmp(argv[i], "-c", 2) && i < argc - 1) {
232       if (sscanf(argv[++i], "%dx%d+%d+%d", &xform.r.w, &xform.r.h, &xform.r.x,
233                  &xform.r.y) < 4 ||
234           xform.r.x < 0 || xform.r.y < 0 || xform.r.w < 1 || xform.r.h < 1)
235         usage(argv[0]);
236       xform.options |= TJXOPT_CROP;
237     } else if (!strcasecmp(argv[i], "-fastupsample")) {
238       printf("Using fast upsampling code\n");
239       fastUpsample = 1;
240     } else if (!strcasecmp(argv[i], "-fastdct")) {
241       printf("Using fastest DCT/IDCT algorithm\n");
242       fastDCT = 1;
243     } else usage(argv[0]);
244   }
245
246   /* Determine input and output image formats based on file extensions. */
247   inFormat = strrchr(argv[1], '.');
248   outFormat = strrchr(argv[2], '.');
249   if (inFormat == NULL || outFormat == NULL || strlen(inFormat) < 2 ||
250       strlen(outFormat) < 2)
251     usage(argv[0]);
252   inFormat = &inFormat[1];
253   outFormat = &outFormat[1];
254
255   if (!strcasecmp(inFormat, "jpg")) {
256     /* Input image is a JPEG image.  Decompress and/or transform it. */
257     long size;
258     int inSubsamp, inColorspace;
259     int doTransform = (xform.op != TJXOP_NONE || xform.options != 0 ||
260                        xform.customFilter != NULL);
261     size_t jpegSize;
262
263     /* Read the JPEG file into memory. */
264     if ((jpegFile = fopen(argv[1], "rb")) == NULL)
265       THROW_UNIX("opening input file");
266     if (fseek(jpegFile, 0, SEEK_END) < 0 || ((size = ftell(jpegFile)) < 0) ||
267         fseek(jpegFile, 0, SEEK_SET) < 0)
268       THROW_UNIX("determining input file size");
269     if (size == 0)
270       THROW("determining input file size", "Input file contains no data");
271     jpegSize = size;
272     if ((jpegBuf = tj3Alloc(jpegSize)) == NULL)
273       THROW_UNIX("allocating JPEG buffer");
274     if (fread(jpegBuf, jpegSize, 1, jpegFile) < 1)
275       THROW_UNIX("reading input file");
276     fclose(jpegFile);  jpegFile = NULL;
277
278     if (doTransform) {
279       /* Transform it. */
280       unsigned char *dstBuf = NULL;  /* Dynamically allocate the JPEG buffer */
281       size_t dstSize = 0;
282
283       if ((tjInstance = tj3Init(TJINIT_TRANSFORM)) == NULL)
284         THROW_TJ("initializing transformer");
285       xform.options |= TJXOPT_TRIM;
286       if (tj3Transform(tjInstance, jpegBuf, jpegSize, 1, &dstBuf, &dstSize,
287                        &xform) < 0) {
288         tj3Free(dstBuf);
289         THROW_TJ("transforming input image");
290       }
291       tj3Free(jpegBuf);
292       jpegBuf = dstBuf;
293       jpegSize = dstSize;
294     } else {
295       if ((tjInstance = tj3Init(TJINIT_DECOMPRESS)) == NULL)
296         THROW_TJ("initializing decompressor");
297     }
298     if (tj3Set(tjInstance, TJPARAM_FASTUPSAMPLE, fastUpsample) < 0)
299       THROW_TJ("setting TJPARAM_FASTUPSAMPLE");
300     if (tj3Set(tjInstance, TJPARAM_FASTDCT, fastDCT) < 0)
301       THROW_TJ("setting TJPARAM_FASTDCT");
302
303     if (tj3DecompressHeader(tjInstance, jpegBuf, jpegSize) < 0)
304       THROW_TJ("reading JPEG header");
305     width = tj3Get(tjInstance, TJPARAM_JPEGWIDTH);
306     height = tj3Get(tjInstance, TJPARAM_JPEGHEIGHT);
307     inSubsamp = tj3Get(tjInstance, TJPARAM_SUBSAMP);
308     inColorspace = tj3Get(tjInstance, TJPARAM_COLORSPACE);
309
310     if (tj3Get(tjInstance, TJPARAM_LOSSLESS))
311       scalingFactor = TJUNSCALED;
312
313     printf("%s Image:  %d x %d pixels, %s subsampling, %s colorspace\n",
314            (doTransform ? "Transformed" : "Input"), width, height,
315            subsampName[inSubsamp], colorspaceName[inColorspace]);
316
317     if (!strcasecmp(outFormat, "jpg") && doTransform &&
318         scalingFactor.num == 1 && scalingFactor.denom == 1 && outSubsamp < 0 &&
319         outQual < 0) {
320       /* Input image has been transformed, and no re-compression options
321          have been selected.  Write the transformed image to disk and exit. */
322       if ((jpegFile = fopen(argv[2], "wb")) == NULL)
323         THROW_UNIX("opening output file");
324       if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
325         THROW_UNIX("writing output file");
326       fclose(jpegFile);  jpegFile = NULL;
327       goto bailout;
328     }
329
330     /* Scaling and/or a non-JPEG output image format and/or compression options
331        have been selected, so we need to decompress the input/transformed
332        image. */
333     if (tj3SetScalingFactor(tjInstance, scalingFactor) < 0)
334       THROW_TJ("setting scaling factor");
335     width = TJSCALED(width, scalingFactor);
336     height = TJSCALED(height, scalingFactor);
337     if (outSubsamp < 0)
338       outSubsamp = inSubsamp;
339
340     pixelFormat = TJPF_BGRX;
341     if ((unsigned long long)width * height * tjPixelSize[pixelFormat] >
342         (unsigned long long)((size_t)-1))
343       THROW("allocating uncompressed image buffer", "Image is too large");
344     if ((imgBuf =
345          (unsigned char *)malloc(sizeof(unsigned char) * width * height *
346                                  tjPixelSize[pixelFormat])) == NULL)
347       THROW_UNIX("allocating uncompressed image buffer");
348
349     if (tj3Decompress8(tjInstance, jpegBuf, jpegSize, imgBuf, 0,
350                        pixelFormat) < 0)
351       THROW_TJ("decompressing JPEG image");
352     tj3Free(jpegBuf);  jpegBuf = NULL;
353     tj3Destroy(tjInstance);  tjInstance = NULL;
354   } else {
355     /* Input image is not a JPEG image.  Load it into memory. */
356     if ((tjInstance = tj3Init(TJINIT_COMPRESS)) == NULL)
357       THROW_TJ("initializing compressor");
358     if ((imgBuf = tj3LoadImage8(tjInstance, argv[1], &width, 1, &height,
359                                 &pixelFormat)) == NULL)
360       THROW_TJ("loading input image");
361     if (outSubsamp < 0) {
362       if (pixelFormat == TJPF_GRAY)
363         outSubsamp = TJSAMP_GRAY;
364       else
365         outSubsamp = TJSAMP_444;
366     }
367     printf("Input Image:  %d x %d pixels\n", width, height);
368   }
369
370   printf("Output Image (%s):  %d x %d pixels", outFormat, width, height);
371
372   if (!strcasecmp(outFormat, "jpg")) {
373     /* Output image format is JPEG.  Compress the uncompressed image. */
374     size_t jpegSize = 0;
375
376     jpegBuf = NULL;  /* Dynamically allocate the JPEG buffer */
377
378     if (outQual < 0)
379       outQual = DEFAULT_QUALITY;
380     printf(", %s subsampling, quality = %d\n", subsampName[outSubsamp],
381            outQual);
382
383     if (!tjInstance && (tjInstance = tj3Init(TJINIT_COMPRESS)) == NULL)
384       THROW_TJ("initializing compressor");
385     if (tj3Set(tjInstance, TJPARAM_SUBSAMP, outSubsamp) < 0)
386       THROW_TJ("setting TJPARAM_SUBSAMP");
387     if (tj3Set(tjInstance, TJPARAM_QUALITY, outQual) < 0)
388       THROW_TJ("setting TJPARAM_QUALITY");
389     if (tj3Set(tjInstance, TJPARAM_FASTDCT, fastDCT) < 0)
390       THROW_TJ("setting TJPARAM_FASTDCT");
391     if (tj3Compress8(tjInstance, imgBuf, width, 0, height, pixelFormat,
392                      &jpegBuf, &jpegSize) < 0)
393       THROW_TJ("compressing image");
394     tj3Destroy(tjInstance);  tjInstance = NULL;
395
396     /* Write the JPEG image to disk. */
397     if ((jpegFile = fopen(argv[2], "wb")) == NULL)
398       THROW_UNIX("opening output file");
399     if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
400       THROW_UNIX("writing output file");
401     tj3Destroy(tjInstance);  tjInstance = NULL;
402     fclose(jpegFile);  jpegFile = NULL;
403     tj3Free(jpegBuf);  jpegBuf = NULL;
404   } else {
405     /* Output image format is not JPEG.  Save the uncompressed image
406        directly to disk. */
407     printf("\n");
408     if (tj3SaveImage8(tjInstance, argv[2], imgBuf, width, 0, height,
409                       pixelFormat) < 0)
410       THROW_TJ("saving output image");
411   }
412
413 bailout:
414   tj3Free(imgBuf);
415   tj3Destroy(tjInstance);
416   tj3Free(jpegBuf);
417   if (jpegFile) fclose(jpegFile);
418   return retval;
419 }