Imported Upstream version 2.1.4
[platform/upstream/libjpeg-turbo.git] / tjexample.c
1 /*
2  * Copyright (C)2011-2012, 2014-2015, 2017, 2019, 2021-2022
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, tjGetErrorStr2(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"
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 in\n");
153   printf("     the underlying codec.\n\n");
154
155   printf("-fastdct = Use the fastest DCT/IDCT algorithms available in the underlying\n");
156   printf("     codec.\n\n");
157
158   printf("-accuratedct = Use the most accurate DCT/IDCT algorithms available in the\n");
159   printf("     underlying codec.\n\n");
160
161   exit(1);
162 }
163
164
165 int main(int argc, char **argv)
166 {
167   tjscalingfactor scalingFactor = { 1, 1 };
168   int outSubsamp = -1, outQual = -1;
169   tjtransform xform;
170   int flags = 0;
171   int width, height;
172   char *inFormat, *outFormat;
173   FILE *jpegFile = NULL;
174   unsigned char *imgBuf = NULL, *jpegBuf = NULL;
175   int retval = 0, i, pixelFormat = TJPF_UNKNOWN;
176   tjhandle tjInstance = NULL;
177
178   if ((scalingFactors = tjGetScalingFactors(&numScalingFactors)) == NULL)
179     THROW_TJ("getting scaling factors");
180   memset(&xform, 0, sizeof(tjtransform));
181
182   if (argc < 3)
183     usage(argv[0]);
184
185   /* Parse arguments. */
186   for (i = 3; i < argc; i++) {
187     if (!strncasecmp(argv[i], "-sc", 3) && i < argc - 1) {
188       int match = 0, temp1 = 0, temp2 = 0, j;
189
190       if (sscanf(argv[++i], "%d/%d", &temp1, &temp2) < 2)
191         usage(argv[0]);
192       for (j = 0; j < numScalingFactors; j++) {
193         if ((double)temp1 / (double)temp2 == (double)scalingFactors[j].num /
194                                              (double)scalingFactors[j].denom) {
195           scalingFactor = scalingFactors[j];
196           match = 1;
197           break;
198         }
199       }
200       if (match != 1)
201         usage(argv[0]);
202     } else if (!strncasecmp(argv[i], "-su", 3) && i < argc - 1) {
203       i++;
204       if (!strncasecmp(argv[i], "g", 1))
205         outSubsamp = TJSAMP_GRAY;
206       else if (!strcasecmp(argv[i], "444"))
207         outSubsamp = TJSAMP_444;
208       else if (!strcasecmp(argv[i], "422"))
209         outSubsamp = TJSAMP_422;
210       else if (!strcasecmp(argv[i], "420"))
211         outSubsamp = TJSAMP_420;
212       else
213         usage(argv[0]);
214     } else if (!strncasecmp(argv[i], "-q", 2) && i < argc - 1) {
215       outQual = atoi(argv[++i]);
216       if (outQual < 1 || outQual > 100)
217         usage(argv[0]);
218     } else if (!strncasecmp(argv[i], "-g", 2))
219       xform.options |= TJXOPT_GRAY;
220     else if (!strcasecmp(argv[i], "-hflip"))
221       xform.op = TJXOP_HFLIP;
222     else if (!strcasecmp(argv[i], "-vflip"))
223       xform.op = TJXOP_VFLIP;
224     else if (!strcasecmp(argv[i], "-transpose"))
225       xform.op = TJXOP_TRANSPOSE;
226     else if (!strcasecmp(argv[i], "-transverse"))
227       xform.op = TJXOP_TRANSVERSE;
228     else if (!strcasecmp(argv[i], "-rot90"))
229       xform.op = TJXOP_ROT90;
230     else if (!strcasecmp(argv[i], "-rot180"))
231       xform.op = TJXOP_ROT180;
232     else if (!strcasecmp(argv[i], "-rot270"))
233       xform.op = TJXOP_ROT270;
234     else if (!strcasecmp(argv[i], "-custom"))
235       xform.customFilter = customFilter;
236     else if (!strncasecmp(argv[i], "-c", 2) && i < argc - 1) {
237       if (sscanf(argv[++i], "%dx%d+%d+%d", &xform.r.w, &xform.r.h, &xform.r.x,
238                  &xform.r.y) < 4 ||
239           xform.r.x < 0 || xform.r.y < 0 || xform.r.w < 1 || xform.r.h < 1)
240         usage(argv[0]);
241       xform.options |= TJXOPT_CROP;
242     } else if (!strcasecmp(argv[i], "-fastupsample")) {
243       printf("Using fast upsampling code\n");
244       flags |= TJFLAG_FASTUPSAMPLE;
245     } else if (!strcasecmp(argv[i], "-fastdct")) {
246       printf("Using fastest DCT/IDCT algorithm\n");
247       flags |= TJFLAG_FASTDCT;
248     } else if (!strcasecmp(argv[i], "-accuratedct")) {
249       printf("Using most accurate DCT/IDCT algorithm\n");
250       flags |= TJFLAG_ACCURATEDCT;
251     } else usage(argv[0]);
252   }
253
254   /* Determine input and output image formats based on file extensions. */
255   inFormat = strrchr(argv[1], '.');
256   outFormat = strrchr(argv[2], '.');
257   if (inFormat == NULL || outFormat == NULL || strlen(inFormat) < 2 ||
258       strlen(outFormat) < 2)
259     usage(argv[0]);
260   inFormat = &inFormat[1];
261   outFormat = &outFormat[1];
262
263   if (!strcasecmp(inFormat, "jpg")) {
264     /* Input image is a JPEG image.  Decompress and/or transform it. */
265     long size;
266     int inSubsamp, inColorspace;
267     int doTransform = (xform.op != TJXOP_NONE || xform.options != 0 ||
268                        xform.customFilter != NULL);
269     unsigned long jpegSize;
270
271     /* Read the JPEG file into memory. */
272     if ((jpegFile = fopen(argv[1], "rb")) == NULL)
273       THROW_UNIX("opening input file");
274     if (fseek(jpegFile, 0, SEEK_END) < 0 || ((size = ftell(jpegFile)) < 0) ||
275         fseek(jpegFile, 0, SEEK_SET) < 0)
276       THROW_UNIX("determining input file size");
277     if (size == 0)
278       THROW("determining input file size", "Input file contains no data");
279     jpegSize = (unsigned long)size;
280     if ((jpegBuf = (unsigned char *)tjAlloc(jpegSize)) == NULL)
281       THROW_UNIX("allocating JPEG buffer");
282     if (fread(jpegBuf, jpegSize, 1, jpegFile) < 1)
283       THROW_UNIX("reading input file");
284     fclose(jpegFile);  jpegFile = NULL;
285
286     if (doTransform) {
287       /* Transform it. */
288       unsigned char *dstBuf = NULL;  /* Dynamically allocate the JPEG buffer */
289       unsigned long dstSize = 0;
290
291       if ((tjInstance = tjInitTransform()) == NULL)
292         THROW_TJ("initializing transformer");
293       xform.options |= TJXOPT_TRIM;
294       if (tjTransform(tjInstance, jpegBuf, jpegSize, 1, &dstBuf, &dstSize,
295                       &xform, flags) < 0) {
296         tjFree(dstBuf);
297         THROW_TJ("transforming input image");
298       }
299       tjFree(jpegBuf);
300       jpegBuf = dstBuf;
301       jpegSize = dstSize;
302     } else {
303       if ((tjInstance = tjInitDecompress()) == NULL)
304         THROW_TJ("initializing decompressor");
305     }
306
307     if (tjDecompressHeader3(tjInstance, jpegBuf, jpegSize, &width, &height,
308                             &inSubsamp, &inColorspace) < 0)
309       THROW_TJ("reading JPEG header");
310
311     printf("%s Image:  %d x %d pixels, %s subsampling, %s colorspace\n",
312            (doTransform ? "Transformed" : "Input"), width, height,
313            subsampName[inSubsamp], colorspaceName[inColorspace]);
314
315     if (!strcasecmp(outFormat, "jpg") && doTransform &&
316         scalingFactor.num == 1 && scalingFactor.denom == 1 && outSubsamp < 0 &&
317         outQual < 0) {
318       /* Input image has been transformed, and no re-compression options
319          have been selected.  Write the transformed image to disk and exit. */
320       if ((jpegFile = fopen(argv[2], "wb")) == NULL)
321         THROW_UNIX("opening output file");
322       if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
323         THROW_UNIX("writing output file");
324       fclose(jpegFile);  jpegFile = NULL;
325       goto bailout;
326     }
327
328     /* Scaling and/or a non-JPEG output image format and/or compression options
329        have been selected, so we need to decompress the input/transformed
330        image. */
331     width = TJSCALED(width, scalingFactor);
332     height = TJSCALED(height, scalingFactor);
333     if (outSubsamp < 0)
334       outSubsamp = inSubsamp;
335
336     pixelFormat = TJPF_BGRX;
337     if ((imgBuf = (unsigned char *)tjAlloc(width * height *
338                                            tjPixelSize[pixelFormat])) == NULL)
339       THROW_UNIX("allocating uncompressed image buffer");
340
341     if (tjDecompress2(tjInstance, jpegBuf, jpegSize, imgBuf, width, 0, height,
342                       pixelFormat, flags) < 0)
343       THROW_TJ("decompressing JPEG image");
344     tjFree(jpegBuf);  jpegBuf = NULL;
345     tjDestroy(tjInstance);  tjInstance = NULL;
346   } else {
347     /* Input image is not a JPEG image.  Load it into memory. */
348     if ((imgBuf = tjLoadImage(argv[1], &width, 1, &height, &pixelFormat,
349                               0)) == NULL)
350       THROW_TJ("loading input image");
351     if (outSubsamp < 0) {
352       if (pixelFormat == TJPF_GRAY)
353         outSubsamp = TJSAMP_GRAY;
354       else
355         outSubsamp = TJSAMP_444;
356     }
357     printf("Input Image:  %d x %d pixels\n", width, height);
358   }
359
360   printf("Output Image (%s):  %d x %d pixels", outFormat, width, height);
361
362   if (!strcasecmp(outFormat, "jpg")) {
363     /* Output image format is JPEG.  Compress the uncompressed image. */
364     unsigned long jpegSize = 0;
365
366     jpegBuf = NULL;  /* Dynamically allocate the JPEG buffer */
367
368     if (outQual < 0)
369       outQual = DEFAULT_QUALITY;
370     printf(", %s subsampling, quality = %d\n", subsampName[outSubsamp],
371            outQual);
372
373     if ((tjInstance = tjInitCompress()) == NULL)
374       THROW_TJ("initializing compressor");
375     if (tjCompress2(tjInstance, imgBuf, width, 0, height, pixelFormat,
376                     &jpegBuf, &jpegSize, outSubsamp, outQual, flags) < 0)
377       THROW_TJ("compressing image");
378     tjDestroy(tjInstance);  tjInstance = NULL;
379
380     /* Write the JPEG image to disk. */
381     if ((jpegFile = fopen(argv[2], "wb")) == NULL)
382       THROW_UNIX("opening output file");
383     if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
384       THROW_UNIX("writing output file");
385     tjDestroy(tjInstance);  tjInstance = NULL;
386     fclose(jpegFile);  jpegFile = NULL;
387     tjFree(jpegBuf);  jpegBuf = NULL;
388   } else {
389     /* Output image format is not JPEG.  Save the uncompressed image
390        directly to disk. */
391     printf("\n");
392     if (tjSaveImage(argv[2], imgBuf, width, 0, height, pixelFormat, 0) < 0)
393       THROW_TJ("saving output image");
394   }
395
396 bailout:
397   tjFree(imgBuf);
398   if (tjInstance) tjDestroy(tjInstance);
399   tjFree(jpegBuf);
400   if (jpegFile) fclose(jpegFile);
401   return retval;
402 }