• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C)2011-2012, 2014-2015, 2017 D. R. Commander.
3  *                                         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 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <turbojpeg.h>
40 
41 
42 #ifdef _WIN32
43 #define strcasecmp  stricmp
44 #define strncasecmp  strnicmp
45 #endif
46 
47 #define THROW(action, message) { \
48   printf("ERROR in line %d while %s:\n%s\n", __LINE__, action, message); \
49   retval = -1;  goto bailout; \
50 }
51 
52 #define THROW_TJ(action)  THROW(action, tjGetErrorStr2(tjInstance))
53 
54 #define THROW_UNIX(action)  THROW(action, strerror(errno))
55 
56 #define DEFAULT_SUBSAMP  TJSAMP_444
57 #define DEFAULT_QUALITY  95
58 
59 
60 const char *subsampName[TJ_NUMSAMP] = {
61   "4:4:4", "4:2:2", "4:2:0", "Grayscale", "4:4:0", "4:1:1"
62 };
63 
64 const char *colorspaceName[TJ_NUMCS] = {
65   "RGB", "YCbCr", "GRAY", "CMYK", "YCCK"
66 };
67 
68 tjscalingfactor *scalingFactors = NULL;
69 int numScalingFactors = 0;
70 
71 
72 /* DCT filter example.  This produces a negative of the image. */
73 
customFilter(short * coeffs,tjregion arrayRegion,tjregion planeRegion,int componentIndex,int transformIndex,tjtransform * transform)74 int customFilter(short *coeffs, tjregion arrayRegion, tjregion planeRegion,
75                  int componentIndex, int transformIndex,
76                  tjtransform *transform)
77 {
78   int i;
79 
80   for (i = 0; i < arrayRegion.w * arrayRegion.h; i++)
81     coeffs[i] = -coeffs[i];
82 
83   return 0;
84 }
85 
86 
usage(char * programName)87 void usage(char *programName)
88 {
89   int i;
90 
91   printf("\nUSAGE: %s <Input image> <Output image> [options]\n\n",
92          programName);
93 
94   printf("Input and output images can be in Windows BMP or PBMPLUS (PPM/PGM) format.  If\n");
95   printf("either filename ends in a .jpg extension, then the TurboJPEG API will be used\n");
96   printf("to compress or decompress the image.\n\n");
97 
98   printf("Compression Options (used if the output image is a JPEG image)\n");
99   printf("--------------------------------------------------------------\n\n");
100 
101   printf("-subsamp <444|422|420|gray> = Apply this level of chrominance subsampling when\n");
102   printf("     compressing the output image.  The default is to use the same level of\n");
103   printf("     subsampling as in the input image, if the input image is also a JPEG\n");
104   printf("     image, or to use grayscale if the input image is a grayscale non-JPEG\n");
105   printf("     image, or to use %s subsampling otherwise.\n\n",
106          subsampName[DEFAULT_SUBSAMP]);
107 
108   printf("-q <1-100> = Compress the output image with this JPEG quality level\n");
109   printf("     (default = %d).\n\n", DEFAULT_QUALITY);
110 
111   printf("Decompression Options (used if the input image is a JPEG image)\n");
112   printf("---------------------------------------------------------------\n\n");
113 
114   printf("-scale M/N = Scale the input image by a factor of M/N when decompressing it.\n");
115   printf("(M/N = ");
116   for (i = 0; i < numScalingFactors; i++) {
117     printf("%d/%d", scalingFactors[i].num, scalingFactors[i].denom);
118     if (numScalingFactors == 2 && i != numScalingFactors - 1)
119       printf(" or ");
120     else if (numScalingFactors > 2) {
121       if (i != numScalingFactors - 1)
122         printf(", ");
123       if (i == numScalingFactors - 2)
124         printf("or ");
125     }
126   }
127   printf(")\n\n");
128 
129   printf("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =\n");
130   printf("     Perform one of these lossless transform operations on the input image\n");
131   printf("     prior to decompressing it (these options are mutually exclusive.)\n\n");
132 
133   printf("-grayscale = Perform lossless grayscale conversion on the input image prior\n");
134   printf("     to decompressing it (can be combined with the other transform operations\n");
135   printf("     above.)\n\n");
136 
137   printf("-crop WxH+X+Y = Perform lossless cropping on the input image prior to\n");
138   printf("     decompressing it.  X and Y specify the upper left corner of the cropping\n");
139   printf("     region, and W and H specify the width and height of the cropping region.\n");
140   printf("     X and Y must be evenly divible by the MCU block size (8x8 if the input\n");
141   printf("     image was compressed using no subsampling or grayscale, 16x8 if it was\n");
142   printf("     compressed using 4:2:2 subsampling, or 16x16 if it was compressed using\n");
143   printf("     4:2:0 subsampling.)\n\n");
144 
145   printf("General Options\n");
146   printf("---------------\n\n");
147 
148   printf("-fastupsample = Use the fastest chrominance upsampling algorithm available in\n");
149   printf("     the underlying codec.\n\n");
150 
151   printf("-fastdct = Use the fastest DCT/IDCT algorithms available in the underlying\n");
152   printf("     codec.\n\n");
153 
154   printf("-accuratedct = Use the most accurate DCT/IDCT algorithms available in the\n");
155   printf("     underlying codec.\n\n");
156 
157   exit(1);
158 }
159 
160 
main(int argc,char ** argv)161 int main(int argc, char **argv)
162 {
163   tjscalingfactor scalingFactor = { 1, 1 };
164   int outSubsamp = -1, outQual = -1;
165   tjtransform xform;
166   int flags = 0;
167   int width, height;
168   char *inFormat, *outFormat;
169   FILE *jpegFile = NULL;
170   unsigned char *imgBuf = NULL, *jpegBuf = NULL;
171   int retval = 0, i, pixelFormat = TJPF_UNKNOWN;
172   tjhandle tjInstance = NULL;
173 
174   if ((scalingFactors = tjGetScalingFactors(&numScalingFactors)) == NULL)
175     THROW_TJ("getting scaling factors");
176   memset(&xform, 0, sizeof(tjtransform));
177 
178   if (argc < 3)
179     usage(argv[0]);
180 
181   /* Parse arguments. */
182   for (i = 3; i < argc; i++) {
183     if (!strncasecmp(argv[i], "-sc", 3) && i < argc - 1) {
184       int match = 0, temp1 = 0, temp2 = 0, j;
185 
186       if (sscanf(argv[++i], "%d/%d", &temp1, &temp2) < 2)
187         usage(argv[0]);
188       for (j = 0; j < numScalingFactors; j++) {
189         if ((double)temp1 / (double)temp2 == (double)scalingFactors[j].num /
190                                              (double)scalingFactors[j].denom) {
191           scalingFactor = scalingFactors[j];
192           match = 1;
193           break;
194         }
195       }
196       if (match != 1)
197         usage(argv[0]);
198     } else if (!strncasecmp(argv[i], "-su", 3) && i < argc - 1) {
199       i++;
200       if (!strncasecmp(argv[i], "g", 1))
201         outSubsamp = TJSAMP_GRAY;
202       else if (!strcasecmp(argv[i], "444"))
203         outSubsamp = TJSAMP_444;
204       else if (!strcasecmp(argv[i], "422"))
205         outSubsamp = TJSAMP_422;
206       else if (!strcasecmp(argv[i], "420"))
207         outSubsamp = TJSAMP_420;
208       else
209         usage(argv[0]);
210     } else if (!strncasecmp(argv[i], "-q", 2) && i < argc - 1) {
211       outQual = atoi(argv[++i]);
212       if (outQual < 1 || outQual > 100)
213         usage(argv[0]);
214     } else if (!strncasecmp(argv[i], "-g", 2))
215       xform.options |= TJXOPT_GRAY;
216     else if (!strcasecmp(argv[i], "-hflip"))
217       xform.op = TJXOP_HFLIP;
218     else if (!strcasecmp(argv[i], "-vflip"))
219       xform.op = TJXOP_VFLIP;
220     else if (!strcasecmp(argv[i], "-transpose"))
221       xform.op = TJXOP_TRANSPOSE;
222     else if (!strcasecmp(argv[i], "-transverse"))
223       xform.op = TJXOP_TRANSVERSE;
224     else if (!strcasecmp(argv[i], "-rot90"))
225       xform.op = TJXOP_ROT90;
226     else if (!strcasecmp(argv[i], "-rot180"))
227       xform.op = TJXOP_ROT180;
228     else if (!strcasecmp(argv[i], "-rot270"))
229       xform.op = TJXOP_ROT270;
230     else if (!strcasecmp(argv[i], "-custom"))
231       xform.customFilter = customFilter;
232     else if (!strncasecmp(argv[i], "-c", 2) && i < argc - 1) {
233       if (sscanf(argv[++i], "%dx%d+%d+%d", &xform.r.w, &xform.r.h, &xform.r.x,
234                  &xform.r.y) < 4 ||
235           xform.r.x < 0 || xform.r.y < 0 || xform.r.w < 1 || xform.r.h < 1)
236         usage(argv[0]);
237       xform.options |= TJXOPT_CROP;
238     } else if (!strcasecmp(argv[i], "-fastupsample")) {
239       printf("Using fast upsampling code\n");
240       flags |= TJFLAG_FASTUPSAMPLE;
241     } else if (!strcasecmp(argv[i], "-fastdct")) {
242       printf("Using fastest DCT/IDCT algorithm\n");
243       flags |= TJFLAG_FASTDCT;
244     } else if (!strcasecmp(argv[i], "-accuratedct")) {
245       printf("Using most accurate DCT/IDCT algorithm\n");
246       flags |= TJFLAG_ACCURATEDCT;
247     } else usage(argv[0]);
248   }
249 
250   /* Determine input and output image formats based on file extensions. */
251   inFormat = strrchr(argv[1], '.');
252   outFormat = strrchr(argv[2], '.');
253   if (inFormat == NULL || outFormat == NULL || strlen(inFormat) < 2 ||
254       strlen(outFormat) < 2)
255     usage(argv[0]);
256   inFormat = &inFormat[1];
257   outFormat = &outFormat[1];
258 
259   if (!strcasecmp(inFormat, "jpg")) {
260     /* Input image is a JPEG image.  Decompress and/or transform it. */
261     long size;
262     int inSubsamp, inColorspace;
263     int doTransform = (xform.op != TJXOP_NONE || xform.options != 0 ||
264                        xform.customFilter != NULL);
265     unsigned long jpegSize;
266 
267     /* Read the JPEG file into memory. */
268     if ((jpegFile = fopen(argv[1], "rb")) == NULL)
269       THROW_UNIX("opening input file");
270     if (fseek(jpegFile, 0, SEEK_END) < 0 || ((size = ftell(jpegFile)) < 0) ||
271         fseek(jpegFile, 0, SEEK_SET) < 0)
272       THROW_UNIX("determining input file size");
273     if (size == 0)
274       THROW("determining input file size", "Input file contains no data");
275     jpegSize = (unsigned long)size;
276     if ((jpegBuf = (unsigned char *)tjAlloc(jpegSize)) == NULL)
277       THROW_UNIX("allocating JPEG buffer");
278     if (fread(jpegBuf, jpegSize, 1, jpegFile) < 1)
279       THROW_UNIX("reading input file");
280     fclose(jpegFile);  jpegFile = NULL;
281 
282     if (doTransform) {
283       /* Transform it. */
284       unsigned char *dstBuf = NULL;  /* Dynamically allocate the JPEG buffer */
285       unsigned long dstSize = 0;
286 
287       if ((tjInstance = tjInitTransform()) == NULL)
288         THROW_TJ("initializing transformer");
289       xform.options |= TJXOPT_TRIM;
290       if (tjTransform(tjInstance, jpegBuf, jpegSize, 1, &dstBuf, &dstSize,
291                       &xform, flags) < 0)
292         THROW_TJ("transforming input image");
293       tjFree(jpegBuf);
294       jpegBuf = dstBuf;
295       jpegSize = dstSize;
296     } else {
297       if ((tjInstance = tjInitDecompress()) == NULL)
298         THROW_TJ("initializing decompressor");
299     }
300 
301     if (tjDecompressHeader3(tjInstance, jpegBuf, jpegSize, &width, &height,
302                             &inSubsamp, &inColorspace) < 0)
303       THROW_TJ("reading JPEG header");
304 
305     printf("%s Image:  %d x %d pixels, %s subsampling, %s colorspace\n",
306            (doTransform ? "Transformed" : "Input"), width, height,
307            subsampName[inSubsamp], colorspaceName[inColorspace]);
308 
309     if (!strcasecmp(outFormat, "jpg") && doTransform &&
310         scalingFactor.num == 1 && scalingFactor.denom == 1 && outSubsamp < 0 &&
311         outQual < 0) {
312       /* Input image has been transformed, and no re-compression options
313          have been selected.  Write the transformed image to disk and exit. */
314       if ((jpegFile = fopen(argv[2], "wb")) == NULL)
315         THROW_UNIX("opening output file");
316       if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
317         THROW_UNIX("writing output file");
318       fclose(jpegFile);  jpegFile = NULL;
319       goto bailout;
320     }
321 
322     /* Scaling and/or a non-JPEG output image format and/or compression options
323        have been selected, so we need to decompress the input/transformed
324        image. */
325     width = TJSCALED(width, scalingFactor);
326     height = TJSCALED(height, scalingFactor);
327     if (outSubsamp < 0)
328       outSubsamp = inSubsamp;
329 
330     pixelFormat = TJPF_BGRX;
331     if ((imgBuf = (unsigned char *)tjAlloc(width * height *
332                                            tjPixelSize[pixelFormat])) == NULL)
333       THROW_UNIX("allocating uncompressed image buffer");
334 
335     if (tjDecompress2(tjInstance, jpegBuf, jpegSize, imgBuf, width, 0, height,
336                       pixelFormat, flags) < 0)
337       THROW_TJ("decompressing JPEG image");
338     tjFree(jpegBuf);  jpegBuf = NULL;
339     tjDestroy(tjInstance);  tjInstance = NULL;
340   } else {
341     /* Input image is not a JPEG image.  Load it into memory. */
342     if ((imgBuf = tjLoadImage(argv[1], &width, 1, &height, &pixelFormat,
343                               0)) == NULL)
344       THROW_TJ("loading input image");
345     if (outSubsamp < 0) {
346       if (pixelFormat == TJPF_GRAY)
347         outSubsamp = TJSAMP_GRAY;
348       else
349         outSubsamp = TJSAMP_444;
350     }
351     printf("Input Image:  %d x %d pixels\n", width, height);
352   }
353 
354   printf("Output Image (%s):  %d x %d pixels", outFormat, width, height);
355 
356   if (!strcasecmp(outFormat, "jpg")) {
357     /* Output image format is JPEG.  Compress the uncompressed image. */
358     unsigned char *jpegBuf = NULL;  /* Dynamically allocate the JPEG buffer */
359     unsigned long jpegSize = 0;
360 
361     if (outQual < 0)
362       outQual = DEFAULT_QUALITY;
363     printf(", %s subsampling, quality = %d\n", subsampName[outSubsamp],
364            outQual);
365 
366     if ((tjInstance = tjInitCompress()) == NULL)
367       THROW_TJ("initializing compressor");
368     if (tjCompress2(tjInstance, imgBuf, width, 0, height, pixelFormat,
369                     &jpegBuf, &jpegSize, outSubsamp, outQual, flags) < 0)
370       THROW_TJ("compressing image");
371     tjDestroy(tjInstance);  tjInstance = NULL;
372 
373     /* Write the JPEG image to disk. */
374     if ((jpegFile = fopen(argv[2], "wb")) == NULL)
375       THROW_UNIX("opening output file");
376     if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
377       THROW_UNIX("writing output file");
378     tjDestroy(tjInstance);  tjInstance = NULL;
379     fclose(jpegFile);  jpegFile = NULL;
380     tjFree(jpegBuf);  jpegBuf = NULL;
381   } else {
382     /* Output image format is not JPEG.  Save the uncompressed image
383        directly to disk. */
384     printf("\n");
385     if (tjSaveImage(argv[2], imgBuf, width, 0, height, pixelFormat, 0) < 0)
386       THROW_TJ("saving output image");
387   }
388 
389 bailout:
390   if (imgBuf) tjFree(imgBuf);
391   if (tjInstance) tjDestroy(tjInstance);
392   if (jpegBuf) tjFree(jpegBuf);
393   if (jpegFile) fclose(jpegFile);
394   return retval;
395 }
396