Coverage Report

Created: 2026-07-30 07:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjpeg-turbo.3.0.x/turbojpeg.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2009-2026 D. R. Commander.  All Rights Reserved.
3
 * Copyright (C) 2021 Alex Richardson.  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
/* TurboJPEG/LJT:  this implements the TurboJPEG API using libjpeg or
31
   libjpeg-turbo */
32
33
#include <ctype.h>
34
#include <limits.h>
35
#if !defined(_MSC_VER) || _MSC_VER > 1600
36
#include <stdint.h>
37
#endif
38
#include "jinclude.h"
39
#define JPEG_INTERNALS
40
#include "jpeglib.h"
41
#include "jerror.h"
42
#include <setjmp.h>
43
#include <errno.h>
44
#include "turbojpeg.h"
45
#include "tjutil.h"
46
#include "transupp.h"
47
#include "jpegapicomp.h"
48
#include "cdjpeg.h"
49
50
extern void jpeg_mem_dest_tj(j_compress_ptr, unsigned char **, size_t *,
51
                             boolean);
52
extern void jpeg_mem_src_tj(j_decompress_ptr, const unsigned char *, size_t);
53
54
2.62M
#define PAD(v, p)  ((v + (p) - 1) & (~((p) - 1)))
55
336k
#define IS_POW2(x)  (((x) & (x - 1)) == 0)
56
57
58
/* Error handling (based on example in example.c) */
59
60
static THREAD_LOCAL char errStr[JMSG_LENGTH_MAX] = "No error";
61
62
struct my_error_mgr {
63
  struct jpeg_error_mgr pub;
64
  jmp_buf setjmp_buffer;
65
  void (*emit_message) (j_common_ptr, int);
66
  boolean warning, stopOnWarning;
67
};
68
typedef struct my_error_mgr *my_error_ptr;
69
70
#define JMESSAGE(code, string)  string,
71
static const char *turbojpeg_message_table[] = {
72
#include "cderror.h"
73
  NULL
74
};
75
76
static void my_error_exit(j_common_ptr cinfo)
77
460k
{
78
460k
  my_error_ptr myerr = (my_error_ptr)cinfo->err;
79
80
460k
  (*cinfo->err->output_message) (cinfo);
81
460k
  longjmp(myerr->setjmp_buffer, 1);
82
460k
}
83
84
/* Based on output_message() in jerror.c */
85
86
static void my_output_message(j_common_ptr cinfo)
87
306k
{
88
306k
  (*cinfo->err->format_message) (cinfo, errStr);
89
306k
}
90
91
static void my_emit_message(j_common_ptr cinfo, int msg_level)
92
654M
{
93
654M
  my_error_ptr myerr = (my_error_ptr)cinfo->err;
94
95
654M
  myerr->emit_message(cinfo, msg_level);
96
654M
  if (msg_level < 0) {
97
483M
    myerr->warning = TRUE;
98
483M
    if (myerr->stopOnWarning) longjmp(myerr->setjmp_buffer, 1);
99
483M
  }
100
654M
}
101
102
103
/********************** Global structures, macros, etc. **********************/
104
105
enum { COMPRESS = 1, DECOMPRESS = 2 };
106
107
typedef struct _tjinstance {
108
  struct jpeg_compress_struct cinfo;
109
  struct jpeg_decompress_struct dinfo;
110
  struct my_error_mgr jerr;
111
  int init;
112
  char errStr[JMSG_LENGTH_MAX];
113
  boolean isInstanceError;
114
  /* Parameters */
115
  boolean bottomUp;
116
  boolean noRealloc;
117
  int quality;
118
  int subsamp;
119
  int jpegWidth;
120
  int jpegHeight;
121
  int precision;
122
  int colorspace;
123
  boolean fastUpsample;
124
  boolean fastDCT;
125
  boolean optimize;
126
  boolean progressive;
127
  int scanLimit;
128
  boolean arithmetic;
129
  boolean lossless;
130
  int losslessPSV;
131
  int losslessPt;
132
  int restartIntervalBlocks;
133
  int restartIntervalRows;
134
  int xDensity;
135
  int yDensity;
136
  int densityUnits;
137
  tjscalingfactor scalingFactor;
138
  tjregion croppingRegion;
139
  int maxMemory;
140
  int maxPixels;
141
} tjinstance;
142
143
static tjhandle _tjInitCompress(tjinstance *this);
144
static tjhandle _tjInitDecompress(tjinstance *this);
145
146
struct my_progress_mgr {
147
  struct jpeg_progress_mgr pub;
148
  tjinstance *this;
149
};
150
typedef struct my_progress_mgr *my_progress_ptr;
151
152
static void my_progress_monitor(j_common_ptr dinfo)
153
498M
{
154
498M
  my_error_ptr myerr = (my_error_ptr)dinfo->err;
155
498M
  my_progress_ptr myprog = (my_progress_ptr)dinfo->progress;
156
157
498M
  if (dinfo->is_decompressor) {
158
498M
    int scan_no = ((j_decompress_ptr)dinfo)->input_scan_number;
159
160
498M
    if (scan_no > myprog->this->scanLimit) {
161
2.05k
      SNPRINTF(myprog->this->errStr, JMSG_LENGTH_MAX,
162
2.05k
               "Progressive JPEG image has more than %d scans",
163
2.05k
               myprog->this->scanLimit);
164
2.05k
      SNPRINTF(errStr, JMSG_LENGTH_MAX,
165
2.05k
               "Progressive JPEG image has more than %d scans",
166
2.05k
               myprog->this->scanLimit);
167
2.05k
      myprog->this->isInstanceError = TRUE;
168
2.05k
      myerr->warning = FALSE;
169
2.05k
      longjmp(myerr->setjmp_buffer, 1);
170
2.05k
    }
171
498M
  }
172
498M
}
173
174
#if TRANSFORMS_SUPPORTED
175
176
static const JXFORM_CODE xformtypes[TJ_NUMXOP] = {
177
  JXFORM_NONE, JXFORM_FLIP_H, JXFORM_FLIP_V, JXFORM_TRANSPOSE,
178
  JXFORM_TRANSVERSE, JXFORM_ROT_90, JXFORM_ROT_180, JXFORM_ROT_270
179
};
180
181
#endif
182
183
#ifdef IDCT_SCALING_SUPPORTED
184
185
1.14M
#define NUMSF  16
186
static const tjscalingfactor sf[NUMSF] = {
187
  { 2, 1 },
188
  { 15, 8 },
189
  { 7, 4 },
190
  { 13, 8 },
191
  { 3, 2 },
192
  { 11, 8 },
193
  { 5, 4 },
194
  { 9, 8 },
195
  { 1, 1 },
196
  { 7, 8 },
197
  { 3, 4 },
198
  { 5, 8 },
199
  { 1, 2 },
200
  { 3, 8 },
201
  { 1, 4 },
202
  { 1, 8 }
203
};
204
205
#else
206
207
#define NUMSF  1
208
static const tjscalingfactor sf[NUMSF] = {
209
  { 1, 1 },
210
};
211
212
#endif
213
214
static J_COLOR_SPACE pf2cs[TJ_NUMPF] = {
215
  JCS_EXT_RGB, JCS_EXT_BGR, JCS_EXT_RGBX, JCS_EXT_BGRX, JCS_EXT_XBGR,
216
  JCS_EXT_XRGB, JCS_GRAYSCALE, JCS_EXT_RGBA, JCS_EXT_BGRA, JCS_EXT_ABGR,
217
  JCS_EXT_ARGB, JCS_CMYK
218
};
219
220
static int cs2pf[JPEG_NUMCS] = {
221
  TJPF_UNKNOWN, TJPF_GRAY,
222
#if RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 3
223
  TJPF_RGB,
224
#elif RGB_RED == 2 && RGB_GREEN == 1 && RGB_BLUE == 0 && RGB_PIXELSIZE == 3
225
  TJPF_BGR,
226
#elif RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 4
227
  TJPF_RGBX,
228
#elif RGB_RED == 2 && RGB_GREEN == 1 && RGB_BLUE == 0 && RGB_PIXELSIZE == 4
229
  TJPF_BGRX,
230
#elif RGB_RED == 3 && RGB_GREEN == 2 && RGB_BLUE == 1 && RGB_PIXELSIZE == 4
231
  TJPF_XBGR,
232
#elif RGB_RED == 1 && RGB_GREEN == 2 && RGB_BLUE == 3 && RGB_PIXELSIZE == 4
233
  TJPF_XRGB,
234
#endif
235
  TJPF_UNKNOWN, TJPF_CMYK, TJPF_UNKNOWN, TJPF_RGB, TJPF_RGBX, TJPF_BGR,
236
  TJPF_BGRX, TJPF_XBGR, TJPF_XRGB, TJPF_RGBA, TJPF_BGRA, TJPF_ABGR, TJPF_ARGB,
237
  TJPF_UNKNOWN
238
};
239
240
0
#define THROWG(m, rv) { \
241
18.4E
  SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): %s", FUNCTION_NAME, m); \
242
0
  retval = rv;  goto bailout; \
243
18.4E
}
244
#ifdef _MSC_VER
245
#define THROW_UNIX(m) { \
246
  char strerrorBuf[80] = { 0 }; \
247
  strerror_s(strerrorBuf, 80, errno); \
248
  SNPRINTF(this->errStr, JMSG_LENGTH_MAX, "%s(): %s\n%s", FUNCTION_NAME, m, \
249
           strerrorBuf); \
250
  this->isInstanceError = TRUE; \
251
  SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): %s\n%s", FUNCTION_NAME, m, \
252
           strerrorBuf); \
253
  retval = -1;  goto bailout; \
254
}
255
#else
256
0
#define THROW_UNIX(m) { \
257
0
  SNPRINTF(this->errStr, JMSG_LENGTH_MAX, "%s(): %s\n%s", FUNCTION_NAME, m, \
258
0
           strerror(errno)); \
259
0
  this->isInstanceError = TRUE; \
260
0
  SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): %s\n%s", FUNCTION_NAME, m, \
261
0
           strerror(errno)); \
262
0
  retval = -1;  goto bailout; \
263
0
}
264
#endif
265
0
#define THROW(m) { \
266
18.4E
  SNPRINTF(this->errStr, JMSG_LENGTH_MAX, "%s(): %s", FUNCTION_NAME, m); \
267
18.4E
  this->isInstanceError = TRUE;  THROWG(m, -1) \
268
18.4E
}
269
9
#define THROWI(format, val1, val2) { \
270
9
  SNPRINTF(this->errStr, JMSG_LENGTH_MAX, "%s(): " format, FUNCTION_NAME, \
271
9
           val1, val2); \
272
9
  this->isInstanceError = TRUE; \
273
9
  SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): " format, FUNCTION_NAME, val1, \
274
9
           val2); \
275
9
  retval = -1;  goto bailout; \
276
9
}
277
278
379k
#define CATCH_LIBJPEG(this) { \
279
379k
  if (setjmp(this->jerr.setjmp_buffer)) { \
280
71.0k
    /* If we get here, the JPEG code has signaled an error. */ \
281
71.0k
    retval = -1;  goto bailout; \
282
71.0k
  } \
283
379k
}
284
285
/* Catch a libjpeg error from the secondary TurboJPEG instance and copy the
286
   error message and state to the primary instance.  This is used by
287
   the packed-pixel image I/O functions. */
288
221k
#define CATCH_LIBJPEG2() { \
289
221k
  if (setjmp(this2->jerr.setjmp_buffer)) { \
290
56.1k
    memcpy(this->errStr, this2->errStr, JMSG_LENGTH_MAX); \
291
56.1k
    this->jerr.warning = this2->jerr.warning; \
292
56.1k
    this->isInstanceError = this2->isInstanceError; \
293
56.1k
    retval = -1;  goto bailout; \
294
56.1k
  } \
295
221k
}
296
297
#define GET_INSTANCE(handle) \
298
0
  tjinstance *this = (tjinstance *)handle; \
299
0
  j_compress_ptr cinfo = NULL; \
300
0
  j_decompress_ptr dinfo = NULL; \
301
0
  \
302
0
  if (!this) { \
303
0
    SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): Invalid handle", FUNCTION_NAME); \
304
0
    return -1; \
305
0
  } \
306
0
  cinfo = &this->cinfo;  dinfo = &this->dinfo; \
307
0
  this->jerr.warning = FALSE; \
308
0
  this->isInstanceError = FALSE;
309
310
#define GET_CINSTANCE(handle) \
311
90.7k
  tjinstance *this = (tjinstance *)handle; \
312
90.7k
  j_compress_ptr cinfo = NULL; \
313
90.7k
  \
314
90.7k
  if (!this) { \
315
0
    SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): Invalid handle", FUNCTION_NAME); \
316
0
    return -1; \
317
0
  } \
318
90.7k
  cinfo = &this->cinfo; \
319
90.7k
  this->jerr.warning = FALSE; \
320
90.7k
  this->isInstanceError = FALSE;
321
322
#define GET_DINSTANCE(handle) \
323
173k
  tjinstance *this = (tjinstance *)handle; \
324
173k
  j_decompress_ptr dinfo = NULL; \
325
173k
  \
326
173k
  if (!this) { \
327
0
    SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): Invalid handle", FUNCTION_NAME); \
328
0
    return -1; \
329
0
  } \
330
173k
  dinfo = &this->dinfo; \
331
173k
  this->jerr.warning = FALSE; \
332
173k
  this->isInstanceError = FALSE;
333
334
#define GET_TJINSTANCE(handle, errorReturn) \
335
1.26M
  tjinstance *this = (tjinstance *)handle; \
336
1.26M
  \
337
1.26M
  if (!this) { \
338
0
    SNPRINTF(errStr, JMSG_LENGTH_MAX, "%s(): Invalid handle", FUNCTION_NAME); \
339
0
    return errorReturn; \
340
0
  } \
341
1.26M
  this->jerr.warning = FALSE; \
342
1.26M
  this->isInstanceError = FALSE;
343
344
static int getPixelFormat(int pixelSize, int flags)
345
0
{
346
0
  if (pixelSize == 1) return TJPF_GRAY;
347
0
  if (pixelSize == 3) {
348
0
    if (flags & TJ_BGR) return TJPF_BGR;
349
0
    else return TJPF_RGB;
350
0
  }
351
0
  if (pixelSize == 4) {
352
0
    if (flags & TJ_ALPHAFIRST) {
353
0
      if (flags & TJ_BGR) return TJPF_XBGR;
354
0
      else return TJPF_XRGB;
355
0
    } else {
356
0
      if (flags & TJ_BGR) return TJPF_BGRX;
357
0
      else return TJPF_RGBX;
358
0
    }
359
0
  }
360
0
  return -1;
361
0
}
362
363
static void setCompDefaults(tjinstance *this, int pixelFormat, boolean yuv)
364
267k
{
365
267k
  int colorspace = yuv ? -1 : this->colorspace;
366
367
267k
  this->cinfo.in_color_space = pf2cs[pixelFormat];
368
267k
  this->cinfo.input_components = tjPixelSize[pixelFormat];
369
267k
  jpeg_set_defaults(&this->cinfo);
370
371
267k
  this->cinfo.restart_interval = this->restartIntervalBlocks;
372
267k
  this->cinfo.restart_in_rows = this->restartIntervalRows;
373
267k
  this->cinfo.X_density = (UINT16)this->xDensity;
374
267k
  this->cinfo.Y_density = (UINT16)this->yDensity;
375
267k
  this->cinfo.density_unit = (UINT8)this->densityUnits;
376
267k
  this->cinfo.mem->max_memory_to_use = (long)this->maxMemory * 1048576L;
377
378
267k
  if (this->lossless && !yuv) {
379
86.0k
#ifdef C_LOSSLESS_SUPPORTED
380
86.0k
    jpeg_enable_lossless(&this->cinfo, this->losslessPSV, this->losslessPt);
381
86.0k
#endif
382
86.0k
    return;
383
86.0k
  }
384
385
181k
  jpeg_set_quality(&this->cinfo, this->quality, TRUE);
386
181k
  this->cinfo.dct_method = this->fastDCT ? JDCT_FASTEST : JDCT_ISLOW;
387
388
181k
  switch (colorspace) {
389
11.1k
  case TJCS_RGB:
390
11.1k
    jpeg_set_colorspace(&this->cinfo, JCS_RGB);  break;
391
19.7k
  case TJCS_YCbCr:
392
19.7k
    jpeg_set_colorspace(&this->cinfo, JCS_YCbCr);  break;
393
15.1k
  case TJCS_GRAY:
394
15.1k
    jpeg_set_colorspace(&this->cinfo, JCS_GRAYSCALE);  break;
395
0
  case TJCS_CMYK:
396
0
    jpeg_set_colorspace(&this->cinfo, JCS_CMYK);  break;
397
10.9k
  case TJCS_YCCK:
398
10.9k
    jpeg_set_colorspace(&this->cinfo, JCS_YCCK);  break;
399
123k
  default:
400
123k
    if (this->subsamp == TJSAMP_GRAY)
401
40.9k
      jpeg_set_colorspace(&this->cinfo, JCS_GRAYSCALE);
402
83.0k
    else if (pixelFormat == TJPF_CMYK)
403
4.20k
      jpeg_set_colorspace(&this->cinfo, JCS_YCCK);
404
78.7k
    else
405
78.7k
      jpeg_set_colorspace(&this->cinfo, JCS_YCbCr);
406
181k
  }
407
408
181k
  if (this->cinfo.data_precision == 8)
409
130k
    this->cinfo.optimize_coding = this->optimize;
410
181k
#ifdef C_PROGRESSIVE_SUPPORTED
411
181k
  if (this->progressive) jpeg_simple_progression(&this->cinfo);
412
181k
#endif
413
181k
  this->cinfo.arith_code = this->arithmetic;
414
415
181k
  this->cinfo.comp_info[0].h_samp_factor = tjMCUWidth[this->subsamp] / 8;
416
181k
  this->cinfo.comp_info[1].h_samp_factor = 1;
417
181k
  this->cinfo.comp_info[2].h_samp_factor = 1;
418
181k
  if (this->cinfo.num_components > 3)
419
15.1k
    this->cinfo.comp_info[3].h_samp_factor = tjMCUWidth[this->subsamp] / 8;
420
181k
  this->cinfo.comp_info[0].v_samp_factor = tjMCUHeight[this->subsamp] / 8;
421
181k
  this->cinfo.comp_info[1].v_samp_factor = 1;
422
181k
  this->cinfo.comp_info[2].v_samp_factor = 1;
423
181k
  if (this->cinfo.num_components > 3)
424
15.1k
    this->cinfo.comp_info[3].v_samp_factor = tjMCUHeight[this->subsamp] / 8;
425
181k
}
426
427
428
static int getSubsamp(j_decompress_ptr dinfo)
429
267k
{
430
267k
  int retval = TJSAMP_UNKNOWN, i, k;
431
432
  /* The sampling factors actually have no meaning with grayscale JPEG files,
433
     and in fact it's possible to generate grayscale JPEGs with sampling
434
     factors > 1 (even though those sampling factors are ignored by the
435
     decompressor.)  Thus, we need to treat grayscale as a special case. */
436
267k
  if (dinfo->num_components == 1 && dinfo->jpeg_color_space == JCS_GRAYSCALE)
437
140k
    return TJSAMP_GRAY;
438
439
704k
  for (i = 0; i < TJ_NUMSAMP; i++) {
440
651k
    if (i == TJSAMP_GRAY) continue;
441
442
585k
    if (dinfo->num_components == 3 ||
443
59.5k
        ((dinfo->jpeg_color_space == JCS_YCCK ||
444
52.6k
          dinfo->jpeg_color_space == JCS_CMYK) &&
445
574k
         dinfo->num_components == 4)) {
446
574k
      if (dinfo->comp_info[0].h_samp_factor == tjMCUWidth[i] / 8 &&
447
247k
          dinfo->comp_info[0].v_samp_factor == tjMCUHeight[i] / 8) {
448
112k
        int match = 0;
449
450
345k
        for (k = 1; k < dinfo->num_components; k++) {
451
232k
          int href = 1, vref = 1;
452
453
232k
          if ((dinfo->jpeg_color_space == JCS_YCCK ||
454
229k
               dinfo->jpeg_color_space == JCS_CMYK) && k == 3) {
455
7.36k
            href = tjMCUWidth[i] / 8;  vref = tjMCUHeight[i] / 8;
456
7.36k
          }
457
232k
          if (dinfo->comp_info[k].h_samp_factor == href &&
458
197k
              dinfo->comp_info[k].v_samp_factor == vref)
459
164k
            match++;
460
232k
        }
461
112k
        if (match == dinfo->num_components - 1) {
462
69.6k
          retval = i;  break;
463
69.6k
        }
464
112k
      }
465
      /* Handle 4:2:2 and 4:4:0 images whose sampling factors are specified
466
         in non-standard ways. */
467
504k
      if (dinfo->comp_info[0].h_samp_factor == 2 &&
468
288k
          dinfo->comp_info[0].v_samp_factor == 2 &&
469
152k
          (i == TJSAMP_422 || i == TJSAMP_440)) {
470
68.3k
        int match = 0;
471
472
207k
        for (k = 1; k < dinfo->num_components; k++) {
473
139k
          int href = tjMCUHeight[i] / 8, vref = tjMCUWidth[i] / 8;
474
475
139k
          if ((dinfo->jpeg_color_space == JCS_YCCK ||
476
138k
               dinfo->jpeg_color_space == JCS_CMYK) && k == 3) {
477
2.56k
            href = vref = 2;
478
2.56k
          }
479
139k
          if (dinfo->comp_info[k].h_samp_factor == href &&
480
116k
              dinfo->comp_info[k].v_samp_factor == vref)
481
13.6k
            match++;
482
139k
        }
483
68.3k
        if (match == dinfo->num_components - 1) {
484
4.85k
          retval = i;  break;
485
4.85k
        }
486
68.3k
      }
487
      /* Handle 4:4:4 images whose sampling factors are specified in
488
         non-standard ways. */
489
500k
      if (dinfo->comp_info[0].h_samp_factor *
490
500k
          dinfo->comp_info[0].v_samp_factor <=
491
500k
          D_MAX_BLOCKS_IN_MCU / 3 && i == TJSAMP_444) {
492
40.6k
        int match = 0;
493
125k
        for (k = 1; k < dinfo->num_components; k++) {
494
85.9k
          if (dinfo->comp_info[k].h_samp_factor ==
495
85.9k
              dinfo->comp_info[0].h_samp_factor &&
496
22.6k
              dinfo->comp_info[k].v_samp_factor ==
497
22.6k
              dinfo->comp_info[0].v_samp_factor)
498
7.40k
            match++;
499
85.9k
          if (match == dinfo->num_components - 1) {
500
1.47k
            retval = i;  break;
501
1.47k
          }
502
85.9k
        }
503
40.6k
      }
504
500k
    }
505
585k
  }
506
127k
  return retval;
507
267k
}
508
509
510
static void setDecompParameters(tjinstance *this)
511
231k
{
512
231k
  this->subsamp = getSubsamp(&this->dinfo);
513
231k
  this->jpegWidth = this->dinfo.image_width;
514
231k
  this->jpegHeight = this->dinfo.image_height;
515
231k
  this->precision = this->dinfo.data_precision;
516
231k
  switch (this->dinfo.jpeg_color_space) {
517
117k
  case JCS_GRAYSCALE:  this->colorspace = TJCS_GRAY;  break;
518
45.6k
  case JCS_RGB:        this->colorspace = TJCS_RGB;  break;
519
61.6k
  case JCS_YCbCr:      this->colorspace = TJCS_YCbCr;  break;
520
5.42k
  case JCS_CMYK:       this->colorspace = TJCS_CMYK;  break;
521
1.00k
  case JCS_YCCK:       this->colorspace = TJCS_YCCK;  break;
522
603
  default:             this->colorspace = -1;  break;
523
231k
  }
524
231k
  this->progressive = this->dinfo.progressive_mode;
525
231k
  this->arithmetic = this->dinfo.arith_code;
526
231k
  this->lossless = this->dinfo.master->lossless;
527
231k
  this->losslessPSV = this->dinfo.Ss;
528
231k
  this->losslessPt = this->dinfo.Al;
529
231k
  this->xDensity = this->dinfo.X_density;
530
231k
  this->yDensity = this->dinfo.Y_density;
531
231k
  this->densityUnits = this->dinfo.density_unit;
532
231k
}
533
534
535
static void processFlags(tjhandle handle, int flags, int operation)
536
0
{
537
0
  tjinstance *this = (tjinstance *)handle;
538
539
0
  this->bottomUp = !!(flags & TJFLAG_BOTTOMUP);
540
541
0
#ifndef NO_PUTENV
542
0
  if (flags & TJFLAG_FORCEMMX) PUTENV_S("JSIMD_FORCEMMX", "1");
543
0
  else if (flags & TJFLAG_FORCESSE) PUTENV_S("JSIMD_FORCESSE", "1");
544
0
  else if (flags & TJFLAG_FORCESSE2) PUTENV_S("JSIMD_FORCESSE2", "1");
545
0
#endif
546
547
0
  this->fastUpsample = !!(flags & TJFLAG_FASTUPSAMPLE);
548
0
  this->noRealloc = !!(flags & TJFLAG_NOREALLOC);
549
550
0
  if (operation == COMPRESS) {
551
0
    if (this->quality >= 96 || flags & TJFLAG_ACCURATEDCT)
552
0
      this->fastDCT = FALSE;
553
0
    else
554
0
      this->fastDCT = TRUE;
555
0
  } else
556
0
    this->fastDCT = !!(flags & TJFLAG_FASTDCT);
557
558
0
  this->jerr.stopOnWarning = !!(flags & TJFLAG_STOPONWARNING);
559
0
  this->progressive = !!(flags & TJFLAG_PROGRESSIVE);
560
561
0
  if (flags & TJFLAG_LIMITSCANS) this->scanLimit = 500;
562
0
}
563
564
565
/*************************** General API functions ***************************/
566
567
/* TurboJPEG 3+ */
568
DLLEXPORT tjhandle tj3Init(int initType)
569
296k
{
570
296k
  static const char FUNCTION_NAME[] = "tj3Init";
571
296k
  tjinstance *this = NULL;
572
296k
  tjhandle retval = NULL;
573
574
296k
  if (initType < 0 || initType >= TJ_NUMINIT)
575
296k
    THROWG("Invalid argument", NULL);
576
577
296k
  if ((this = (tjinstance *)malloc(sizeof(tjinstance))) == NULL)
578
296k
    THROWG("Memory allocation failure", NULL);
579
296k
  memset(this, 0, sizeof(tjinstance));
580
296k
  SNPRINTF(this->errStr, JMSG_LENGTH_MAX, "No error");
581
582
296k
  this->quality = -1;
583
296k
  this->subsamp = TJSAMP_UNKNOWN;
584
296k
  this->jpegWidth = -1;
585
296k
  this->jpegHeight = -1;
586
296k
  this->precision = 8;
587
296k
  this->colorspace = -1;
588
296k
  this->losslessPSV = 1;
589
296k
  this->xDensity = 1;
590
296k
  this->yDensity = 1;
591
296k
  this->scalingFactor = TJUNSCALED;
592
593
296k
  switch (initType) {
594
262k
  case TJINIT_COMPRESS:  return _tjInitCompress(this);
595
27.7k
  case TJINIT_DECOMPRESS:  return _tjInitDecompress(this);
596
6.51k
  case TJINIT_TRANSFORM:
597
6.51k
    retval = _tjInitCompress(this);
598
6.51k
    if (!retval) return NULL;
599
6.51k
    retval = _tjInitDecompress(this);
600
6.51k
    return retval;
601
296k
  }
602
603
0
bailout:
604
0
  return retval;
605
296k
}
606
607
608
/* TurboJPEG 3+ */
609
DLLEXPORT void tj3Destroy(tjhandle handle)
610
643k
{
611
643k
  tjinstance *this = (tjinstance *)handle;
612
643k
  j_compress_ptr cinfo = NULL;
613
643k
  j_decompress_ptr dinfo = NULL;
614
615
643k
  if (!this) return;
616
617
643k
  cinfo = &this->cinfo;  dinfo = &this->dinfo;
618
643k
  this->jerr.warning = FALSE;
619
643k
  this->isInstanceError = FALSE;
620
621
  /* NOTE: jpeg_destroy_*() can never throw a libjpeg error in libjpeg-turbo's
622
     implementation, so this is a belt-and-suspenders measure. */
623
643k
  if (setjmp(this->jerr.setjmp_buffer)) goto destroy_decompress;
624
643k
  if (this->init & COMPRESS) jpeg_destroy_compress(cinfo);
625
643k
destroy_decompress:
626
643k
  if (setjmp(this->jerr.setjmp_buffer)) goto bailout;
627
643k
  if (this->init & DECOMPRESS) jpeg_destroy_decompress(dinfo);
628
643k
bailout:
629
643k
  free(this);
630
643k
}
631
632
/* TurboJPEG 1.0+ */
633
DLLEXPORT int tjDestroy(tjhandle handle)
634
0
{
635
0
  static const char FUNCTION_NAME[] = "tjDestroy";
636
0
  int retval = 0;
637
638
0
  if (!handle) THROWG("Invalid handle", -1);
639
640
0
  SNPRINTF(errStr, JMSG_LENGTH_MAX, "No error");
641
0
  tj3Destroy(handle);
642
0
  if (strcmp(errStr, "No error")) retval = -1;
643
644
0
bailout:
645
0
  return retval;
646
0
}
647
648
649
/* TurboJPEG 3+ */
650
DLLEXPORT char *tj3GetErrorStr(tjhandle handle)
651
171k
{
652
171k
  tjinstance *this = (tjinstance *)handle;
653
654
171k
  if (this && this->isInstanceError) {
655
65.7k
    this->isInstanceError = FALSE;
656
65.7k
    return this->errStr;
657
65.7k
  } else
658
105k
    return errStr;
659
171k
}
660
661
/* TurboJPEG 2.0+ */
662
DLLEXPORT char *tjGetErrorStr2(tjhandle handle)
663
0
{
664
0
  return tj3GetErrorStr(handle);
665
0
}
666
667
/* TurboJPEG 1.0+ */
668
DLLEXPORT char *tjGetErrorStr(void)
669
0
{
670
0
  return errStr;
671
0
}
672
673
674
/* TurboJPEG 3+ */
675
DLLEXPORT int tj3GetErrorCode(tjhandle handle)
676
0
{
677
0
  tjinstance *this = (tjinstance *)handle;
678
679
0
  if (this && this->jerr.warning) return TJERR_WARNING;
680
0
  else return TJERR_FATAL;
681
0
}
682
683
/* TurboJPEG 2.0+ */
684
DLLEXPORT int tjGetErrorCode(tjhandle handle)
685
0
{
686
0
  return tj3GetErrorCode(handle);
687
0
}
688
689
690
369k
#define SET_PARAM(field, minValue, maxValue) { \
691
369k
  if (value < minValue || (maxValue > 0 && value > maxValue)) \
692
369k
    THROW("Parameter value out of range"); \
693
369k
  this->field = value; \
694
369k
}
695
696
591k
#define SET_BOOL_PARAM(field) { \
697
591k
  if (value < 0 || value > 1) \
698
591k
    THROW("Parameter value out of range"); \
699
591k
  this->field = (boolean)value; \
700
591k
}
701
702
/* TurboJPEG 3+ */
703
DLLEXPORT int tj3Set(tjhandle handle, int param, int value)
704
960k
{
705
960k
  static const char FUNCTION_NAME[] = "tj3Set";
706
960k
  int retval = 0;
707
708
960k
  GET_TJINSTANCE(handle, -1);
709
710
960k
  switch (param) {
711
0
  case TJPARAM_STOPONWARNING:
712
0
    SET_BOOL_PARAM(jerr.stopOnWarning);
713
0
    break;
714
145k
  case TJPARAM_BOTTOMUP:
715
145k
    SET_BOOL_PARAM(bottomUp);
716
145k
    break;
717
111k
  case TJPARAM_NOREALLOC:
718
111k
    if (!(this->init & COMPRESS))
719
111k
      THROW("TJPARAM_NOREALLOC is not applicable to decompression instances.");
720
111k
    SET_BOOL_PARAM(noRealloc);
721
111k
    break;
722
40.4k
  case TJPARAM_QUALITY:
723
40.4k
    if (!(this->init & COMPRESS))
724
40.4k
      THROW("TJPARAM_QUALITY is not applicable to decompression instances.");
725
40.4k
    SET_PARAM(quality, 1, 100);
726
40.4k
    break;
727
40.4k
  case TJPARAM_SUBSAMP:
728
40.4k
    SET_PARAM(subsamp, 0, TJ_NUMSAMP - 1);
729
40.4k
    break;
730
0
  case TJPARAM_JPEGWIDTH:
731
0
    if (!(this->init & DECOMPRESS))
732
0
      THROW("TJPARAM_JPEGWIDTH is not applicable to compression instances.");
733
0
    THROW("TJPARAM_JPEGWIDTH is read-only in decompression instances.");
734
0
    break;
735
0
  case TJPARAM_JPEGHEIGHT:
736
0
    if (!(this->init & DECOMPRESS))
737
0
      THROW("TJPARAM_JPEGHEIGHT is not applicable to compression instances.");
738
0
    THROW("TJPARAM_JPEGHEIGHT is read-only in decompression instances.");
739
0
    break;
740
0
  case TJPARAM_PRECISION:
741
0
    if (!(this->init & DECOMPRESS))
742
0
      THROW("TJPARAM_PRECISION is not applicable to compression instances.");
743
0
    THROW("TJPARAM_PRECISION is read-only in decompression instances.");
744
0
    break;
745
0
  case TJPARAM_COLORSPACE:
746
0
    if (!(this->init & COMPRESS))
747
0
      THROW("TJPARAM_COLORSPACE is read-only in decompression instances.");
748
0
    SET_PARAM(colorspace, 0, TJ_NUMCS - 1);
749
0
    break;
750
34.0k
  case TJPARAM_FASTUPSAMPLE:
751
34.0k
    if (!(this->init & DECOMPRESS))
752
34.0k
      THROW("TJPARAM_FASTUPSAMPLE is not applicable to compression instances.");
753
34.0k
    SET_BOOL_PARAM(fastUpsample);
754
34.0k
    break;
755
97.6k
  case TJPARAM_FASTDCT:
756
97.6k
    SET_BOOL_PARAM(fastDCT);
757
97.6k
    break;
758
49.3k
  case TJPARAM_OPTIMIZE:
759
49.3k
    if (!(this->init & COMPRESS))
760
49.3k
      THROW("TJPARAM_OPTIMIZE is not applicable to decompression instances.");
761
49.3k
    SET_BOOL_PARAM(optimize);
762
49.3k
    break;
763
70.4k
  case TJPARAM_PROGRESSIVE:
764
70.4k
    if (!(this->init & COMPRESS))
765
70.4k
      THROW("TJPARAM_PROGRESSIVE is read-only in decompression instances.");
766
70.4k
    SET_BOOL_PARAM(progressive);
767
70.4k
    break;
768
38.8k
  case TJPARAM_SCANLIMIT:
769
38.8k
    if (!(this->init & DECOMPRESS))
770
38.8k
      THROW("TJPARAM_SCANLIMIT is not applicable to compression instances.");
771
38.8k
    SET_PARAM(scanLimit, 0, -1);
772
38.8k
    break;
773
70.4k
  case TJPARAM_ARITHMETIC:
774
70.4k
    if (!(this->init & COMPRESS))
775
70.4k
      THROW("TJPARAM_ARITHMETIC is read-only in decompression instances.");
776
70.4k
    SET_BOOL_PARAM(arithmetic);
777
70.4k
    break;
778
13.6k
  case TJPARAM_LOSSLESS:
779
13.6k
    if (!(this->init & COMPRESS))
780
13.6k
      THROW("TJPARAM_LOSSLESS is read-only in decompression instances.");
781
13.6k
    SET_BOOL_PARAM(lossless);
782
13.6k
    break;
783
13.6k
  case TJPARAM_LOSSLESSPSV:
784
13.6k
    if (!(this->init & COMPRESS))
785
13.6k
      THROW("TJPARAM_LOSSLESSPSV is read-only in decompression instances.");
786
13.6k
    SET_PARAM(losslessPSV, 1, 7);
787
13.6k
    break;
788
13.6k
  case TJPARAM_LOSSLESSPT:
789
13.6k
    if (!(this->init & COMPRESS))
790
13.6k
      THROW("TJPARAM_LOSSLESSPT is read-only in decompression instances.");
791
13.6k
    SET_PARAM(losslessPt, 0, 15);
792
13.6k
    break;
793
21.8k
  case TJPARAM_RESTARTBLOCKS:
794
21.8k
    if (!(this->init & COMPRESS))
795
21.8k
      THROW("TJPARAM_RESTARTBLOCKS is not applicable to decompression instances.");
796
21.8k
    SET_PARAM(restartIntervalBlocks, 0, 65535);
797
21.8k
    if (value != 0) this->restartIntervalRows = 0;
798
21.8k
    break;
799
89.2k
  case TJPARAM_RESTARTROWS:
800
89.2k
    if (!(this->init & COMPRESS))
801
89.2k
      THROW("TJPARAM_RESTARTROWS is not applicable to decompression instances.");
802
89.2k
    SET_PARAM(restartIntervalRows, 0, 65535);
803
89.2k
    if (value != 0) this->restartIntervalBlocks = 0;
804
89.2k
    break;
805
0
  case TJPARAM_XDENSITY:
806
0
    if (!(this->init & COMPRESS))
807
0
      THROW("TJPARAM_XDENSITY is read-only in decompression instances.");
808
0
    SET_PARAM(xDensity, 1, 65535);
809
0
    break;
810
0
  case TJPARAM_YDENSITY:
811
0
    if (!(this->init & COMPRESS))
812
0
      THROW("TJPARAM_YDENSITY is read-only in decompression instances.");
813
0
    SET_PARAM(yDensity, 1, 65535);
814
0
    break;
815
0
  case TJPARAM_DENSITYUNITS:
816
0
    if (!(this->init & COMPRESS))
817
0
      THROW("TJPARAM_DENSITYUNITS is read-only in decompression instances.");
818
0
    SET_PARAM(densityUnits, 0, 2);
819
0
    break;
820
0
  case TJPARAM_MAXMEMORY:
821
0
    SET_PARAM(maxMemory, 0, (int)(min(LONG_MAX / 1048576L, (long)INT_MAX)));
822
0
    break;
823
111k
  case TJPARAM_MAXPIXELS:
824
111k
    SET_PARAM(maxPixels, 0, -1);
825
111k
    break;
826
0
  default:
827
0
    THROW("Invalid parameter");
828
960k
  }
829
830
960k
bailout:
831
960k
  return retval;
832
960k
}
833
834
835
/* TurboJPEG 3+ */
836
DLLEXPORT int tj3Get(tjhandle handle, int param)
837
121k
{
838
121k
  tjinstance *this = (tjinstance *)handle;
839
121k
  if (!this) return -1;
840
841
121k
  switch (param) {
842
0
  case TJPARAM_STOPONWARNING:
843
0
    return this->jerr.stopOnWarning;
844
0
  case TJPARAM_BOTTOMUP:
845
0
    return this->bottomUp;
846
42.4k
  case TJPARAM_NOREALLOC:
847
42.4k
    return this->noRealloc;
848
0
  case TJPARAM_QUALITY:
849
0
    return this->quality;
850
6.32k
  case TJPARAM_SUBSAMP:
851
6.32k
    return this->subsamp;
852
13.5k
  case TJPARAM_JPEGWIDTH:
853
13.5k
    return this->jpegWidth;
854
13.5k
  case TJPARAM_JPEGHEIGHT:
855
13.5k
    return this->jpegHeight;
856
7.26k
  case TJPARAM_PRECISION:
857
7.26k
    return this->precision;
858
0
  case TJPARAM_COLORSPACE:
859
0
    return this->colorspace;
860
0
  case TJPARAM_FASTUPSAMPLE:
861
0
    return this->fastUpsample;
862
0
  case TJPARAM_FASTDCT:
863
0
    return this->fastDCT;
864
0
  case TJPARAM_OPTIMIZE:
865
0
    return this->optimize;
866
0
  case TJPARAM_PROGRESSIVE:
867
0
    return this->progressive;
868
0
  case TJPARAM_SCANLIMIT:
869
0
    return this->scanLimit;
870
0
  case TJPARAM_ARITHMETIC:
871
0
    return this->arithmetic;
872
38.8k
  case TJPARAM_LOSSLESS:
873
38.8k
    return this->lossless;
874
0
  case TJPARAM_LOSSLESSPSV:
875
0
    return this->losslessPSV;
876
0
  case TJPARAM_LOSSLESSPT:
877
0
    return this->losslessPt;
878
0
  case TJPARAM_RESTARTBLOCKS:
879
0
    return this->restartIntervalBlocks;
880
0
  case TJPARAM_RESTARTROWS:
881
0
    return this->restartIntervalRows;
882
0
  case TJPARAM_XDENSITY:
883
0
    return this->xDensity;
884
0
  case TJPARAM_YDENSITY:
885
0
    return this->yDensity;
886
0
  case TJPARAM_DENSITYUNITS:
887
0
    return this->densityUnits;
888
0
  case TJPARAM_MAXMEMORY:
889
0
    return this->maxMemory;
890
0
  case TJPARAM_MAXPIXELS:
891
0
    return this->maxPixels;
892
121k
  }
893
894
0
  return -1;
895
121k
}
896
897
898
/* These are exposed mainly because Windows can't malloc() and free() across
899
   DLL boundaries except when the CRT DLL is used, and we don't use the CRT DLL
900
   with turbojpeg.dll for compatibility reasons.  However, these functions
901
   can potentially be used for other purposes by different implementations. */
902
903
/* TurboJPEG 3+ */
904
DLLEXPORT void *tj3Alloc(size_t bytes)
905
418k
{
906
418k
  return MALLOC(bytes);
907
418k
}
908
909
/* TurboJPEG 1.2+ */
910
DLLEXPORT unsigned char *tjAlloc(int bytes)
911
0
{
912
0
  return (unsigned char *)tj3Alloc((size_t)bytes);
913
0
}
914
915
916
/* TurboJPEG 3+ */
917
DLLEXPORT void tj3Free(void *buf)
918
909k
{
919
909k
  free(buf);
920
909k
}
921
922
/* TurboJPEG 1.2+ */
923
DLLEXPORT void tjFree(unsigned char *buf)
924
0
{
925
0
  tj3Free(buf);
926
0
}
927
928
929
/* TurboJPEG 3+ */
930
DLLEXPORT size_t tj3JPEGBufSize(int width, int height, int jpegSubsamp)
931
305k
{
932
305k
  static const char FUNCTION_NAME[] = "tj3JPEGBufSize";
933
305k
  unsigned long long retval = 0;
934
305k
  int mcuw, mcuh, chromasf;
935
936
305k
  if (width < 1 || height < 1 || jpegSubsamp < TJSAMP_UNKNOWN ||
937
305k
      jpegSubsamp >= TJ_NUMSAMP)
938
305k
    THROWG("Invalid argument", 0);
939
940
305k
  if (jpegSubsamp == TJSAMP_UNKNOWN)
941
16.6k
    jpegSubsamp = TJSAMP_444;
942
943
  /* This allows for rare corner cases in which a JPEG image can actually be
944
     larger than the uncompressed input (we wouldn't mention it if it hadn't
945
     happened before.) */
946
305k
  mcuw = tjMCUWidth[jpegSubsamp];
947
305k
  mcuh = tjMCUHeight[jpegSubsamp];
948
305k
  chromasf = jpegSubsamp == TJSAMP_GRAY ? 0 : 4 * 64 / (mcuw * mcuh);
949
305k
  retval = (unsigned long long)PAD(width, mcuw) * PAD(height, mcuh) *
950
305k
           (2ULL + chromasf) + 2048ULL;
951
#if ULLONG_MAX > ULONG_MAX
952
  if (retval > (unsigned long long)((unsigned long)-1))
953
    THROWG("Image is too large", 0);
954
#endif
955
956
305k
bailout:
957
305k
  return (size_t)retval;
958
305k
}
959
960
/* TurboJPEG 1.2+ */
961
DLLEXPORT unsigned long tjBufSize(int width, int height, int jpegSubsamp)
962
0
{
963
0
  static const char FUNCTION_NAME[] = "tjBufSize";
964
0
  size_t retval;
965
966
0
  if (jpegSubsamp < 0)
967
0
    THROWG("Invalid argument", 0);
968
969
0
  retval = tj3JPEGBufSize(width, height, jpegSubsamp);
970
971
0
bailout:
972
0
  return (retval == 0) ? (unsigned long)-1 : (unsigned long)retval;
973
0
}
974
975
/* TurboJPEG 1.0+ */
976
DLLEXPORT unsigned long TJBUFSIZE(int width, int height)
977
0
{
978
0
  static const char FUNCTION_NAME[] = "TJBUFSIZE";
979
0
  unsigned long long retval = 0;
980
981
0
  if (width < 1 || height < 1)
982
0
    THROWG("Invalid argument", (unsigned long)-1);
983
984
  /* This allows for rare corner cases in which a JPEG image can actually be
985
     larger than the uncompressed input (we wouldn't mention it if it hadn't
986
     happened before.) */
987
0
  retval = (unsigned long long)PAD(width, 16) * PAD(height, 16) * 6ULL +
988
0
           2048ULL;
989
#if ULLONG_MAX > ULONG_MAX
990
  if (retval > (unsigned long long)((unsigned long)-1))
991
    THROWG("Image is too large", (unsigned long)-1);
992
#endif
993
994
0
bailout:
995
0
  return (unsigned long)retval;
996
0
}
997
998
999
/* TurboJPEG 3+ */
1000
DLLEXPORT size_t tj3YUVBufSize(int width, int align, int height, int subsamp)
1001
86.4k
{
1002
86.4k
  static const char FUNCTION_NAME[] = "tj3YUVBufSize";
1003
86.4k
  unsigned long long retval = 0;
1004
86.4k
  int nc, i;
1005
1006
86.4k
  if (align < 1 || !IS_POW2(align) || subsamp < 0 || subsamp >= TJ_NUMSAMP)
1007
85.4k
    THROWG("Invalid argument", 0);
1008
1009
85.4k
  nc = (subsamp == TJSAMP_GRAY ? 1 : 3);
1010
1011
272k
  for (i = 0; i < nc; i++) {
1012
187k
    int pw = tj3YUVPlaneWidth(i, width, subsamp);
1013
187k
    unsigned long long stride = PAD((unsigned long long)pw, align);
1014
187k
    int ph = tj3YUVPlaneHeight(i, height, subsamp);
1015
1016
187k
    if (pw == 0 || ph == 0) return 0;
1017
187k
    else retval += stride * ph;
1018
187k
  }
1019
#if ULLONG_MAX > ULONG_MAX
1020
  if (retval > (unsigned long long)((unsigned long)-1))
1021
    THROWG("Image is too large", 0);
1022
#endif
1023
1024
86.4k
bailout:
1025
86.4k
  return (size_t)retval;
1026
85.4k
}
1027
1028
/* TurboJPEG 1.4+ */
1029
DLLEXPORT unsigned long tjBufSizeYUV2(int width, int align, int height,
1030
                                      int subsamp)
1031
0
{
1032
0
  size_t retval = tj3YUVBufSize(width, align, height, subsamp);
1033
0
  return (retval == 0) ? (unsigned long)-1 : (unsigned long)retval;
1034
0
}
1035
1036
/* TurboJPEG 1.2+ */
1037
DLLEXPORT unsigned long tjBufSizeYUV(int width, int height, int subsamp)
1038
0
{
1039
0
  return tjBufSizeYUV2(width, 4, height, subsamp);
1040
0
}
1041
1042
/* TurboJPEG 1.1+ */
1043
DLLEXPORT unsigned long TJBUFSIZEYUV(int width, int height, int subsamp)
1044
0
{
1045
0
  return tjBufSizeYUV(width, height, subsamp);
1046
0
}
1047
1048
1049
/* TurboJPEG 3+ */
1050
DLLEXPORT size_t tj3YUVPlaneSize(int componentID, int width, int stride,
1051
                                 int height, int subsamp)
1052
0
{
1053
0
  static const char FUNCTION_NAME[] = "tj3YUVPlaneSize";
1054
0
  unsigned long long retval = 0;
1055
0
  int pw, ph;
1056
1057
0
  if (width < 1 || height < 1 || subsamp < 0 || subsamp >= TJ_NUMSAMP)
1058
0
    THROWG("Invalid argument", 0);
1059
1060
0
  pw = tj3YUVPlaneWidth(componentID, width, subsamp);
1061
0
  ph = tj3YUVPlaneHeight(componentID, height, subsamp);
1062
0
  if (pw == 0 || ph == 0) return 0;
1063
1064
0
  if (stride == 0) stride = pw;
1065
0
  else stride = abs(stride);
1066
1067
0
  retval = (unsigned long long)stride * (ph - 1) + pw;
1068
#if ULLONG_MAX > ULONG_MAX
1069
  if (retval > (unsigned long long)((unsigned long)-1))
1070
    THROWG("Image is too large", 0);
1071
#endif
1072
1073
0
bailout:
1074
0
  return (size_t)retval;
1075
0
}
1076
1077
/* TurboJPEG 1.4+ */
1078
DLLEXPORT unsigned long tjPlaneSizeYUV(int componentID, int width, int stride,
1079
                                       int height, int subsamp)
1080
0
{
1081
0
  size_t retval = tj3YUVPlaneSize(componentID, width, stride, height, subsamp);
1082
0
  return (retval == 0) ? -1 : (unsigned long)retval;
1083
0
}
1084
1085
1086
/* TurboJPEG 3+ */
1087
DLLEXPORT int tj3YUVPlaneWidth(int componentID, int width, int subsamp)
1088
490k
{
1089
490k
  static const char FUNCTION_NAME[] = "tj3YUVPlaneWidth";
1090
490k
  unsigned long long pw, retval = 0;
1091
490k
  int nc;
1092
1093
490k
  if (width < 1 || subsamp < 0 || subsamp >= TJ_NUMSAMP)
1094
490k
    THROWG("Invalid argument", 0);
1095
490k
  nc = (subsamp == TJSAMP_GRAY ? 1 : 3);
1096
490k
  if (componentID < 0 || componentID >= nc)
1097
490k
    THROWG("Invalid argument", 0);
1098
1099
490k
  pw = PAD((unsigned long long)width, tjMCUWidth[subsamp] / 8);
1100
490k
  if (componentID == 0)
1101
258k
    retval = pw;
1102
231k
  else
1103
231k
    retval = pw * 8 / tjMCUWidth[subsamp];
1104
1105
490k
  if (retval > (unsigned long long)INT_MAX)
1106
490k
    THROWG("Width is too large", 0);
1107
1108
490k
bailout:
1109
490k
  return (int)retval;
1110
490k
}
1111
1112
/* TurboJPEG 1.4+ */
1113
DLLEXPORT int tjPlaneWidth(int componentID, int width, int subsamp)
1114
24.2k
{
1115
24.2k
  int retval = tj3YUVPlaneWidth(componentID, width, subsamp);
1116
24.2k
  return (retval == 0) ? -1 : retval;
1117
24.2k
}
1118
1119
1120
/* TurboJPEG 3+ */
1121
DLLEXPORT int tj3YUVPlaneHeight(int componentID, int height, int subsamp)
1122
490k
{
1123
490k
  static const char FUNCTION_NAME[] = "tj3YUVPlaneHeight";
1124
490k
  unsigned long long ph, retval = 0;
1125
490k
  int nc;
1126
1127
490k
  if (height < 1 || subsamp < 0 || subsamp >= TJ_NUMSAMP)
1128
490k
    THROWG("Invalid argument", 0);
1129
490k
  nc = (subsamp == TJSAMP_GRAY ? 1 : 3);
1130
490k
  if (componentID < 0 || componentID >= nc)
1131
490k
    THROWG("Invalid argument", 0);
1132
1133
490k
  ph = PAD((unsigned long long)height, tjMCUHeight[subsamp] / 8);
1134
490k
  if (componentID == 0)
1135
258k
    retval = ph;
1136
231k
  else
1137
231k
    retval = ph * 8 / tjMCUHeight[subsamp];
1138
1139
490k
  if (retval > (unsigned long long)INT_MAX)
1140
490k
    THROWG("Height is too large", 0);
1141
1142
490k
bailout:
1143
490k
  return (int)retval;
1144
490k
}
1145
1146
/* TurboJPEG 1.4+ */
1147
DLLEXPORT int tjPlaneHeight(int componentID, int height, int subsamp)
1148
24.2k
{
1149
24.2k
  int retval = tj3YUVPlaneHeight(componentID, height, subsamp);
1150
24.2k
  return (retval == 0) ? -1 : retval;
1151
24.2k
}
1152
1153
1154
/******************************** Compressor *********************************/
1155
1156
static tjhandle _tjInitCompress(tjinstance *this)
1157
602k
{
1158
602k
  static unsigned char buffer[1];
1159
602k
  unsigned char *buf = buffer;
1160
602k
  size_t size = 1;
1161
1162
  /* This is also straight out of example.c */
1163
602k
  this->cinfo.err = jpeg_std_error(&this->jerr.pub);
1164
602k
  this->jerr.pub.error_exit = my_error_exit;
1165
602k
  this->jerr.pub.output_message = my_output_message;
1166
602k
  this->jerr.emit_message = this->jerr.pub.emit_message;
1167
602k
  this->jerr.pub.emit_message = my_emit_message;
1168
602k
  this->jerr.pub.addon_message_table = turbojpeg_message_table;
1169
602k
  this->jerr.pub.first_addon_message = JMSG_FIRSTADDONCODE;
1170
602k
  this->jerr.pub.last_addon_message = JMSG_LASTADDONCODE;
1171
1172
602k
  if (setjmp(this->jerr.setjmp_buffer)) {
1173
    /* If we get here, the JPEG code has signaled an error. */
1174
0
    free(this);
1175
0
    return NULL;
1176
0
  }
1177
1178
602k
  jpeg_create_compress(&this->cinfo);
1179
  /* Make an initial call so it will create the destination manager */
1180
602k
  jpeg_mem_dest_tj(&this->cinfo, &buf, &size, 0);
1181
1182
602k
  this->init |= COMPRESS;
1183
602k
  return (tjhandle)this;
1184
602k
}
1185
1186
/* TurboJPEG 1.0+ */
1187
DLLEXPORT tjhandle tjInitCompress(void)
1188
0
{
1189
0
  return tj3Init(TJINIT_COMPRESS);
1190
0
}
1191
1192
1193
/* tj3Compress*() is implemented in turbojpeg-mp.c */
1194
67.4k
#define BITS_IN_JSAMPLE  8
1195
#include "turbojpeg-mp.c"
1196
#undef BITS_IN_JSAMPLE
1197
47.0k
#define BITS_IN_JSAMPLE  12
1198
#include "turbojpeg-mp.c"
1199
#undef BITS_IN_JSAMPLE
1200
14.1k
#define BITS_IN_JSAMPLE  16
1201
#include "turbojpeg-mp.c"
1202
#undef BITS_IN_JSAMPLE
1203
1204
/* TurboJPEG 1.2+ */
1205
DLLEXPORT int tjCompress2(tjhandle handle, const unsigned char *srcBuf,
1206
                          int width, int pitch, int height, int pixelFormat,
1207
                          unsigned char **jpegBuf, unsigned long *jpegSize,
1208
                          int jpegSubsamp, int jpegQual, int flags)
1209
0
{
1210
0
  static const char FUNCTION_NAME[] = "tjCompress2";
1211
0
  int retval = 0;
1212
0
  size_t size;
1213
1214
0
  GET_TJINSTANCE(handle, -1);
1215
1216
0
  if (jpegSize == NULL || jpegSubsamp < 0 || jpegSubsamp >= TJ_NUMSAMP ||
1217
0
      jpegQual < 0 || jpegQual > 100)
1218
0
    THROW("Invalid argument");
1219
1220
0
  this->quality = jpegQual;
1221
0
  this->subsamp = jpegSubsamp;
1222
0
  processFlags(handle, flags, COMPRESS);
1223
1224
0
  size = (size_t)(*jpegSize);
1225
0
  retval = tj3Compress8(handle, srcBuf, width, pitch, height, pixelFormat,
1226
0
                        jpegBuf, &size);
1227
0
  *jpegSize = (unsigned long)size;
1228
1229
0
bailout:
1230
0
  return retval;
1231
0
}
1232
1233
/* TurboJPEG 1.0+ */
1234
DLLEXPORT int tjCompress(tjhandle handle, unsigned char *srcBuf, int width,
1235
                         int pitch, int height, int pixelSize,
1236
                         unsigned char *jpegBuf, unsigned long *jpegSize,
1237
                         int jpegSubsamp, int jpegQual, int flags)
1238
0
{
1239
0
  int retval = 0;
1240
0
  unsigned long size = jpegSize ? *jpegSize : 0;
1241
1242
0
  if (flags & TJ_YUV) {
1243
0
    size = tjBufSizeYUV(width, height, jpegSubsamp);
1244
0
    retval = tjEncodeYUV2(handle, srcBuf, width, pitch, height,
1245
0
                          getPixelFormat(pixelSize, flags), jpegBuf,
1246
0
                          jpegSubsamp, flags);
1247
0
  } else {
1248
0
    retval = tjCompress2(handle, srcBuf, width, pitch, height,
1249
0
                         getPixelFormat(pixelSize, flags), &jpegBuf, &size,
1250
0
                         jpegSubsamp, jpegQual, flags | TJFLAG_NOREALLOC);
1251
0
  }
1252
0
  *jpegSize = size;
1253
0
  return retval;
1254
0
}
1255
1256
1257
/* TurboJPEG 3+ */
1258
DLLEXPORT int tj3CompressFromYUVPlanes8(tjhandle handle,
1259
                                        const unsigned char * const *srcPlanes,
1260
                                        int width, const int *strides,
1261
                                        int height, unsigned char **jpegBuf,
1262
                                        size_t *jpegSize)
1263
11.7k
{
1264
11.7k
  static const char FUNCTION_NAME[] = "tj3CompressFromYUVPlanes8";
1265
11.7k
  int i, row, retval = 0;
1266
11.7k
  boolean alloc = TRUE;
1267
11.7k
  int pw[MAX_COMPONENTS], ph[MAX_COMPONENTS], iw[MAX_COMPONENTS],
1268
11.7k
    tmpbufsize = 0, usetmpbuf = 0, th[MAX_COMPONENTS];
1269
11.7k
  JSAMPLE *_tmpbuf = NULL, *ptr;
1270
11.7k
  JSAMPROW *inbuf[MAX_COMPONENTS], *tmpbuf[MAX_COMPONENTS];
1271
1272
11.7k
  GET_CINSTANCE(handle)
1273
1274
129k
  for (i = 0; i < MAX_COMPONENTS; i++) {
1275
117k
    tmpbuf[i] = NULL;  inbuf[i] = NULL;
1276
117k
  }
1277
1278
11.7k
  if ((this->init & COMPRESS) == 0)
1279
11.7k
    THROW("Instance has not been initialized for compression");
1280
1281
11.7k
  if (!srcPlanes || !srcPlanes[0] || width <= 0 || height <= 0 ||
1282
11.7k
      jpegBuf == NULL || jpegSize == NULL)
1283
11.7k
    THROW("Invalid argument");
1284
11.7k
  if (this->subsamp != TJSAMP_GRAY && (!srcPlanes[1] || !srcPlanes[2]))
1285
11.7k
    THROW("Invalid argument");
1286
1287
11.7k
  if (this->quality == -1)
1288
11.7k
    THROW("TJPARAM_QUALITY must be specified");
1289
11.7k
  if (this->subsamp == TJSAMP_UNKNOWN)
1290
11.7k
    THROW("TJPARAM_SUBSAMP must be specified");
1291
1292
11.7k
  CATCH_LIBJPEG(this);
1293
1294
11.7k
  cinfo->image_width = width;
1295
11.7k
  cinfo->image_height = height;
1296
11.7k
  cinfo->data_precision = 8;
1297
1298
11.7k
  if (this->noRealloc) {
1299
11.7k
    alloc = FALSE;  *jpegSize = tj3JPEGBufSize(width, height, this->subsamp);
1300
11.7k
  }
1301
11.7k
  jpeg_mem_dest_tj(cinfo, jpegBuf, jpegSize, alloc);
1302
11.7k
  setCompDefaults(this, TJPF_RGB, TRUE);
1303
11.7k
  cinfo->raw_data_in = TRUE;
1304
1305
11.7k
  jpeg_start_compress(cinfo, TRUE);
1306
39.6k
  for (i = 0; i < cinfo->num_components; i++) {
1307
27.8k
    jpeg_component_info *compptr = &cinfo->comp_info[i];
1308
27.8k
    int ih;
1309
1310
27.8k
    iw[i] = compptr->width_in_blocks * DCTSIZE;
1311
27.8k
    ih = compptr->height_in_blocks * DCTSIZE;
1312
27.8k
    pw[i] = PAD(cinfo->image_width, cinfo->max_h_samp_factor) *
1313
27.8k
            compptr->h_samp_factor / cinfo->max_h_samp_factor;
1314
27.8k
    if (strides && strides[i] != 0 && strides[i] < pw[i])
1315
27.8k
      THROW("Invalid argument");
1316
27.8k
    ph[i] = PAD(cinfo->image_height, cinfo->max_v_samp_factor) *
1317
27.8k
            compptr->v_samp_factor / cinfo->max_v_samp_factor;
1318
27.8k
    if (iw[i] != pw[i] || ih != ph[i]) usetmpbuf = 1;
1319
27.8k
    th[i] = compptr->v_samp_factor * DCTSIZE;
1320
27.8k
    tmpbufsize += iw[i] * th[i];
1321
27.8k
    if ((inbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i])) == NULL)
1322
27.8k
      THROW("Memory allocation failure");
1323
27.8k
    ptr = (JSAMPLE *)srcPlanes[i];
1324
81.4M
    for (row = 0; row < ph[i]; row++) {
1325
81.4M
      inbuf[i][row] = ptr;
1326
81.4M
      ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
1327
81.4M
    }
1328
27.8k
  }
1329
11.7k
  if (usetmpbuf) {
1330
11.7k
    if ((_tmpbuf = (JSAMPLE *)malloc(sizeof(JSAMPLE) * tmpbufsize)) == NULL)
1331
11.7k
      THROW("Memory allocation failure");
1332
11.7k
    ptr = _tmpbuf;
1333
39.4k
    for (i = 0; i < cinfo->num_components; i++) {
1334
27.7k
      if ((tmpbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * th[i])) == NULL)
1335
27.7k
        THROW("Memory allocation failure");
1336
265k
      for (row = 0; row < th[i]; row++) {
1337
238k
        tmpbuf[i][row] = ptr;
1338
238k
        ptr += iw[i];
1339
238k
      }
1340
27.7k
    }
1341
11.7k
  }
1342
1343
11.7k
  CATCH_LIBJPEG(this);
1344
1345
4.31M
  for (row = 0; row < (int)cinfo->image_height;
1346
4.30M
       row += cinfo->max_v_samp_factor * DCTSIZE) {
1347
4.30M
    JSAMPARRAY yuvptr[MAX_COMPONENTS];
1348
4.30M
    int crow[MAX_COMPONENTS];
1349
1350
14.1M
    for (i = 0; i < cinfo->num_components; i++) {
1351
9.80M
      jpeg_component_info *compptr = &cinfo->comp_info[i];
1352
1353
9.80M
      crow[i] = row * compptr->v_samp_factor / cinfo->max_v_samp_factor;
1354
9.80M
      if (usetmpbuf) {
1355
9.80M
        int j, k;
1356
1357
91.2M
        for (j = 0; j < MIN(th[i], ph[i] - crow[i]); j++) {
1358
81.4M
          memcpy(tmpbuf[i][j], inbuf[i][crow[i] + j], pw[i]);
1359
          /* Duplicate last sample in row to fill out MCU */
1360
619M
          for (k = pw[i]; k < iw[i]; k++)
1361
538M
            tmpbuf[i][j][k] = tmpbuf[i][j][pw[i] - 1];
1362
81.4M
        }
1363
        /* Duplicate last row to fill out MCU */
1364
9.96M
        for (j = ph[i] - crow[i]; j < th[i]; j++)
1365
152k
          memcpy(tmpbuf[i][j], tmpbuf[i][ph[i] - crow[i] - 1], iw[i]);
1366
9.80M
        yuvptr[i] = tmpbuf[i];
1367
9.80M
      } else
1368
366
        yuvptr[i] = &inbuf[i][crow[i]];
1369
9.80M
    }
1370
4.30M
    jpeg_write_raw_data(cinfo, yuvptr, cinfo->max_v_samp_factor * DCTSIZE);
1371
4.30M
  }
1372
11.7k
  jpeg_finish_compress(cinfo);
1373
1374
11.7k
bailout:
1375
11.7k
  if (cinfo->global_state > CSTATE_START && alloc)
1376
0
    (*cinfo->dest->term_destination) (cinfo);
1377
11.7k
  if (cinfo->global_state > CSTATE_START || retval == -1)
1378
0
    jpeg_abort_compress(cinfo);
1379
129k
  for (i = 0; i < MAX_COMPONENTS; i++) {
1380
117k
    free(tmpbuf[i]);
1381
117k
    free(inbuf[i]);
1382
117k
  }
1383
11.7k
  free(_tmpbuf);
1384
11.7k
  if (this->jerr.warning) retval = -1;
1385
11.7k
  return retval;
1386
11.7k
}
1387
1388
/* TurboJPEG 1.4+ */
1389
DLLEXPORT int tjCompressFromYUVPlanes(tjhandle handle,
1390
                                      const unsigned char **srcPlanes,
1391
                                      int width, const int *strides,
1392
                                      int height, int subsamp,
1393
                                      unsigned char **jpegBuf,
1394
                                      unsigned long *jpegSize, int jpegQual,
1395
                                      int flags)
1396
0
{
1397
0
  static const char FUNCTION_NAME[] = "tjCompressFromYUVPlanes";
1398
0
  int retval = 0;
1399
0
  size_t size;
1400
1401
0
  GET_TJINSTANCE(handle, -1);
1402
1403
0
  if (subsamp < 0 || subsamp >= TJ_NUMSAMP || jpegSize == NULL ||
1404
0
      jpegQual < 0 || jpegQual > 100)
1405
0
    THROW("Invalid argument");
1406
1407
0
  this->quality = jpegQual;
1408
0
  this->subsamp = subsamp;
1409
0
  processFlags(handle, flags, COMPRESS);
1410
1411
0
  size = (size_t)(*jpegSize);
1412
0
  retval = tj3CompressFromYUVPlanes8(handle, srcPlanes, width, strides, height,
1413
0
                                     jpegBuf, &size);
1414
0
  *jpegSize = (unsigned long)size;
1415
1416
0
bailout:
1417
0
  return retval;
1418
0
}
1419
1420
1421
/* TurboJPEG 3+ */
1422
DLLEXPORT int tj3CompressFromYUV8(tjhandle handle,
1423
                                  const unsigned char *srcBuf, int width,
1424
                                  int align, int height,
1425
                                  unsigned char **jpegBuf, size_t *jpegSize)
1426
36.5k
{
1427
36.5k
  static const char FUNCTION_NAME[] = "tj3CompressFromYUV8";
1428
36.5k
  const unsigned char *srcPlanes[3];
1429
36.5k
  int pw0, ph0, strides[3], retval = -1;
1430
1431
36.5k
  GET_TJINSTANCE(handle, -1);
1432
1433
36.5k
  if (srcBuf == NULL || width <= 0 || align < 1 || !IS_POW2(align) ||
1434
36.5k
      height <= 0)
1435
36.5k
    THROW("Invalid argument");
1436
1437
36.5k
  if (this->subsamp == TJSAMP_UNKNOWN)
1438
36.5k
    THROW("TJPARAM_SUBSAMP must be specified");
1439
1440
36.5k
  pw0 = tj3YUVPlaneWidth(0, width, this->subsamp);
1441
36.5k
  ph0 = tj3YUVPlaneHeight(0, height, this->subsamp);
1442
36.5k
  srcPlanes[0] = srcBuf;
1443
36.5k
  strides[0] = (int)PAD((unsigned long long)pw0, align);
1444
36.5k
  if (this->subsamp == TJSAMP_GRAY) {
1445
12.3k
    strides[1] = strides[2] = 0;
1446
12.3k
    srcPlanes[1] = srcPlanes[2] = NULL;
1447
24.2k
  } else {
1448
24.2k
    int pw1 = tjPlaneWidth(1, width, this->subsamp);
1449
24.2k
    int ph1 = tjPlaneHeight(1, height, this->subsamp);
1450
1451
24.2k
    strides[1] = strides[2] = (int)PAD((unsigned long long)pw1, align);
1452
24.2k
    if ((unsigned long long)strides[0] * (unsigned long long)ph0 >
1453
24.2k
        (unsigned long long)INT_MAX ||
1454
24.2k
        (unsigned long long)strides[1] * (unsigned long long)ph1 >
1455
24.2k
        (unsigned long long)INT_MAX)
1456
24.2k
      THROW("Image or row alignment is too large");
1457
24.2k
    srcPlanes[1] = srcPlanes[0] + strides[0] * ph0;
1458
24.2k
    srcPlanes[2] = srcPlanes[1] + strides[1] * ph1;
1459
24.2k
  }
1460
1461
36.5k
  return tj3CompressFromYUVPlanes8(handle, srcPlanes, width, strides, height,
1462
36.5k
                                   jpegBuf, jpegSize);
1463
1464
0
bailout:
1465
0
  return retval;
1466
36.5k
}
1467
1468
/* TurboJPEG 1.4+ */
1469
DLLEXPORT int tjCompressFromYUV(tjhandle handle, const unsigned char *srcBuf,
1470
                                int width, int align, int height, int subsamp,
1471
                                unsigned char **jpegBuf,
1472
                                unsigned long *jpegSize, int jpegQual,
1473
                                int flags)
1474
0
{
1475
0
  static const char FUNCTION_NAME[] = "tjCompressFromYUV";
1476
0
  int retval = -1;
1477
0
  size_t size;
1478
1479
0
  GET_TJINSTANCE(handle, -1);
1480
1481
0
  if (subsamp < 0 || subsamp >= TJ_NUMSAMP)
1482
0
    THROW("Invalid argument");
1483
1484
0
  this->quality = jpegQual;
1485
0
  this->subsamp = subsamp;
1486
0
  processFlags(handle, flags, COMPRESS);
1487
1488
0
  size = (size_t)(*jpegSize);
1489
0
  retval = tj3CompressFromYUV8(handle, srcBuf, width, align, height, jpegBuf,
1490
0
                               &size);
1491
0
  *jpegSize = (unsigned long)size;
1492
1493
0
bailout:
1494
0
  return retval;
1495
0
}
1496
1497
1498
/* TurboJPEG 3+ */
1499
DLLEXPORT int tj3EncodeYUVPlanes8(tjhandle handle, const unsigned char *srcBuf,
1500
                                  int width, int pitch, int height,
1501
                                  int pixelFormat, unsigned char **dstPlanes,
1502
                                  int *strides)
1503
36.5k
{
1504
36.5k
  static const char FUNCTION_NAME[] = "tj3EncodeYUVPlanes8";
1505
36.5k
  JSAMPROW *row_pointer = NULL;
1506
36.5k
  JSAMPLE *_tmpbuf[MAX_COMPONENTS], *_tmpbuf2[MAX_COMPONENTS];
1507
36.5k
  JSAMPROW *tmpbuf[MAX_COMPONENTS], *tmpbuf2[MAX_COMPONENTS];
1508
36.5k
  JSAMPROW *outbuf[MAX_COMPONENTS];
1509
36.5k
  int i, retval = 0, row, pw0, ph0, pw[MAX_COMPONENTS], ph[MAX_COMPONENTS];
1510
36.5k
  JSAMPLE *ptr;
1511
36.5k
  jpeg_component_info *compptr;
1512
1513
36.5k
  GET_CINSTANCE(handle)
1514
1515
402k
  for (i = 0; i < MAX_COMPONENTS; i++) {
1516
365k
    tmpbuf[i] = NULL;  _tmpbuf[i] = NULL;
1517
365k
    tmpbuf2[i] = NULL;  _tmpbuf2[i] = NULL;  outbuf[i] = NULL;
1518
365k
  }
1519
1520
36.5k
  if ((this->init & COMPRESS) == 0)
1521
36.5k
    THROW("Instance has not been initialized for compression");
1522
1523
36.5k
  if (srcBuf == NULL || width <= 0 || pitch < 0 || height <= 0 ||
1524
36.5k
      pixelFormat < 0 || pixelFormat >= TJ_NUMPF || !dstPlanes ||
1525
36.5k
      !dstPlanes[0])
1526
36.5k
    THROW("Invalid argument");
1527
36.5k
  if (this->subsamp != TJSAMP_GRAY && (!dstPlanes[1] || !dstPlanes[2]))
1528
36.5k
    THROW("Invalid argument");
1529
1530
36.5k
  if (this->subsamp == TJSAMP_UNKNOWN)
1531
36.5k
    THROW("TJPARAM_SUBSAMP must be specified");
1532
36.5k
  if (pixelFormat == TJPF_CMYK)
1533
36.5k
    THROW("Cannot generate YUV images from packed-pixel CMYK images");
1534
1535
36.5k
  if (pitch == 0) pitch = width * tjPixelSize[pixelFormat];
1536
0
  else if (pitch < width * tjPixelSize[pixelFormat])
1537
36.5k
    THROW("Invalid argument");
1538
1539
36.5k
  CATCH_LIBJPEG(this);
1540
1541
36.5k
  cinfo->image_width = width;
1542
36.5k
  cinfo->image_height = height;
1543
36.5k
  cinfo->data_precision = 8;
1544
1545
36.5k
  setCompDefaults(this, pixelFormat, TRUE);
1546
1547
  /* Execute only the parts of jpeg_start_compress() that we need.  If we
1548
     were to call the whole jpeg_start_compress() function, then it would try
1549
     to write the file headers, which could overflow the output buffer if the
1550
     YUV image were very small. */
1551
36.5k
  if (cinfo->global_state != CSTATE_START)
1552
36.5k
    THROW("libjpeg API is in the wrong state");
1553
36.5k
  (*cinfo->err->reset_error_mgr) ((j_common_ptr)cinfo);
1554
36.5k
  jinit_c_master_control(cinfo, FALSE);
1555
36.5k
  jinit_color_converter(cinfo);
1556
36.5k
  jinit_downsampler(cinfo);
1557
36.5k
  (*cinfo->cconvert->start_pass) (cinfo);
1558
1559
36.5k
  pw0 = PAD(width, cinfo->max_h_samp_factor);
1560
36.5k
  ph0 = PAD(height, cinfo->max_v_samp_factor);
1561
1562
36.5k
  if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph0)) == NULL)
1563
36.5k
    THROW("Memory allocation failure");
1564
102M
  for (i = 0; i < height; i++) {
1565
102M
    if (this->bottomUp)
1566
16.7M
      row_pointer[i] = (JSAMPROW)&srcBuf[(height - i - 1) * (size_t)pitch];
1567
85.7M
    else
1568
85.7M
      row_pointer[i] = (JSAMPROW)&srcBuf[i * (size_t)pitch];
1569
102M
  }
1570
36.5k
  if (height < ph0)
1571
6.60k
    for (i = height; i < ph0; i++) row_pointer[i] = row_pointer[height - 1];
1572
1573
121k
  for (i = 0; i < cinfo->num_components; i++) {
1574
85.0k
    compptr = &cinfo->comp_info[i];
1575
85.0k
    _tmpbuf[i] = (JSAMPLE *)MALLOC(
1576
85.0k
      PAD((compptr->width_in_blocks * cinfo->max_h_samp_factor * DCTSIZE) /
1577
85.0k
          compptr->h_samp_factor, 32) *
1578
85.0k
      cinfo->max_v_samp_factor + 32);
1579
85.0k
    if (!_tmpbuf[i])
1580
85.0k
      THROW("Memory allocation failure");
1581
85.0k
    tmpbuf[i] =
1582
85.0k
      (JSAMPROW *)malloc(sizeof(JSAMPROW) * cinfo->max_v_samp_factor);
1583
85.0k
    if (!tmpbuf[i])
1584
85.0k
      THROW("Memory allocation failure");
1585
188k
    for (row = 0; row < cinfo->max_v_samp_factor; row++) {
1586
103k
      unsigned char *_tmpbuf_aligned =
1587
103k
        (unsigned char *)PAD((JUINTPTR)_tmpbuf[i], 32);
1588
1589
103k
      tmpbuf[i][row] = &_tmpbuf_aligned[
1590
103k
        PAD((compptr->width_in_blocks * cinfo->max_h_samp_factor * DCTSIZE) /
1591
103k
            compptr->h_samp_factor, 32) * row];
1592
103k
    }
1593
85.0k
    _tmpbuf2[i] =
1594
85.0k
      (JSAMPLE *)MALLOC(PAD(compptr->width_in_blocks * DCTSIZE, 32) *
1595
85.0k
                        compptr->v_samp_factor + 32);
1596
85.0k
    if (!_tmpbuf2[i])
1597
85.0k
      THROW("Memory allocation failure");
1598
85.0k
    tmpbuf2[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * compptr->v_samp_factor);
1599
85.0k
    if (!tmpbuf2[i])
1600
85.0k
      THROW("Memory allocation failure");
1601
176k
    for (row = 0; row < compptr->v_samp_factor; row++) {
1602
91.1k
      unsigned char *_tmpbuf2_aligned =
1603
91.1k
        (unsigned char *)PAD((JUINTPTR)_tmpbuf2[i], 32);
1604
1605
91.1k
      tmpbuf2[i][row] =
1606
91.1k
        &_tmpbuf2_aligned[PAD(compptr->width_in_blocks * DCTSIZE, 32) * row];
1607
91.1k
    }
1608
85.0k
    pw[i] = pw0 * compptr->h_samp_factor / cinfo->max_h_samp_factor;
1609
85.0k
    if (strides && strides[i] != 0 && strides[i] < pw[i])
1610
85.0k
      THROW("Invalid argument");
1611
85.0k
    ph[i] = ph0 * compptr->v_samp_factor / cinfo->max_v_samp_factor;
1612
85.0k
    outbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i]);
1613
85.0k
    if (!outbuf[i])
1614
85.0k
      THROW("Memory allocation failure");
1615
85.0k
    ptr = dstPlanes[i];
1616
222M
    for (row = 0; row < ph[i]; row++) {
1617
222M
      outbuf[i][row] = ptr;
1618
222M
      ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
1619
222M
    }
1620
85.0k
  }
1621
1622
36.5k
  CATCH_LIBJPEG(this);
1623
1624
93.8M
  for (row = 0; row < ph0; row += cinfo->max_v_samp_factor) {
1625
93.8M
    (*cinfo->cconvert->color_convert) (cinfo, &row_pointer[row], tmpbuf, 0,
1626
93.8M
                                       cinfo->max_v_samp_factor);
1627
93.8M
    (cinfo->downsample->downsample) (cinfo, tmpbuf, 0, tmpbuf2, 0);
1628
307M
    for (i = 0, compptr = cinfo->comp_info; i < cinfo->num_components;
1629
214M
         i++, compptr++)
1630
214M
      jcopy_sample_rows(tmpbuf2[i], 0, outbuf[i],
1631
214M
        row * compptr->v_samp_factor / cinfo->max_v_samp_factor,
1632
214M
        compptr->v_samp_factor, pw[i]);
1633
93.8M
  }
1634
36.5k
  cinfo->next_scanline += height;
1635
36.5k
  jpeg_abort_compress(cinfo);
1636
1637
36.5k
bailout:
1638
36.5k
  if (cinfo->global_state > CSTATE_START) jpeg_abort_compress(cinfo);
1639
36.5k
  free(row_pointer);
1640
402k
  for (i = 0; i < MAX_COMPONENTS; i++) {
1641
365k
    free(tmpbuf[i]);
1642
365k
    free(_tmpbuf[i]);
1643
365k
    free(tmpbuf2[i]);
1644
365k
    free(_tmpbuf2[i]);
1645
365k
    free(outbuf[i]);
1646
365k
  }
1647
36.5k
  if (this->jerr.warning) retval = -1;
1648
36.5k
  return retval;
1649
36.5k
}
1650
1651
/* TurboJPEG 1.4+ */
1652
DLLEXPORT int tjEncodeYUVPlanes(tjhandle handle, const unsigned char *srcBuf,
1653
                                int width, int pitch, int height,
1654
                                int pixelFormat, unsigned char **dstPlanes,
1655
                                int *strides, int subsamp, int flags)
1656
0
{
1657
0
  static const char FUNCTION_NAME[] = "tjEncodeYUVPlanes";
1658
0
  int retval = 0;
1659
1660
0
  GET_TJINSTANCE(handle, -1);
1661
1662
0
  if (subsamp < 0 || subsamp >= TJ_NUMSAMP)
1663
0
    THROW("Invalid argument");
1664
1665
0
  this->subsamp = subsamp;
1666
0
  processFlags(handle, flags, COMPRESS);
1667
1668
0
  return tj3EncodeYUVPlanes8(handle, srcBuf, width, pitch, height, pixelFormat,
1669
0
                             dstPlanes, strides);
1670
1671
0
bailout:
1672
0
  return retval;
1673
0
}
1674
1675
1676
/* TurboJPEG 3+ */
1677
DLLEXPORT int tj3EncodeYUV8(tjhandle handle, const unsigned char *srcBuf,
1678
                            int width, int pitch, int height, int pixelFormat,
1679
                            unsigned char *dstBuf, int align)
1680
36.5k
{
1681
36.5k
  static const char FUNCTION_NAME[] = "tj3EncodeYUV8";
1682
36.5k
  unsigned char *dstPlanes[3];
1683
36.5k
  int pw0, ph0, strides[3], retval = -1;
1684
1685
36.5k
  GET_TJINSTANCE(handle, -1);
1686
1687
36.5k
  if (width <= 0 || height <= 0 || dstBuf == NULL || align < 1 ||
1688
36.5k
      !IS_POW2(align))
1689
36.5k
    THROW("Invalid argument");
1690
1691
36.5k
  if (this->subsamp == TJSAMP_UNKNOWN)
1692
36.5k
    THROW("TJPARAM_SUBSAMP must be specified");
1693
1694
36.5k
  pw0 = tj3YUVPlaneWidth(0, width, this->subsamp);
1695
36.5k
  ph0 = tj3YUVPlaneHeight(0, height, this->subsamp);
1696
36.5k
  dstPlanes[0] = dstBuf;
1697
36.5k
  strides[0] = (int)PAD((unsigned long long)pw0, align);
1698
36.5k
  if (this->subsamp == TJSAMP_GRAY) {
1699
12.3k
    strides[1] = strides[2] = 0;
1700
12.3k
    dstPlanes[1] = dstPlanes[2] = NULL;
1701
24.2k
  } else {
1702
24.2k
    int pw1 = tj3YUVPlaneWidth(1, width, this->subsamp);
1703
24.2k
    int ph1 = tj3YUVPlaneHeight(1, height, this->subsamp);
1704
1705
24.2k
    strides[1] = strides[2] = (int)PAD((unsigned long long)pw1, align);
1706
24.2k
    if ((unsigned long long)strides[0] * (unsigned long long)ph0 >
1707
24.2k
        (unsigned long long)INT_MAX ||
1708
24.2k
        (unsigned long long)strides[1] * (unsigned long long)ph1 >
1709
24.2k
        (unsigned long long)INT_MAX)
1710
24.2k
      THROW("Image or row alignment is too large");
1711
24.2k
    dstPlanes[1] = dstPlanes[0] + strides[0] * ph0;
1712
24.2k
    dstPlanes[2] = dstPlanes[1] + strides[1] * ph1;
1713
24.2k
  }
1714
1715
36.5k
  return tj3EncodeYUVPlanes8(handle, srcBuf, width, pitch, height, pixelFormat,
1716
36.5k
                             dstPlanes, strides);
1717
1718
0
bailout:
1719
0
  return retval;
1720
36.5k
}
1721
1722
/* TurboJPEG 1.4+ */
1723
DLLEXPORT int tjEncodeYUV3(tjhandle handle, const unsigned char *srcBuf,
1724
                           int width, int pitch, int height, int pixelFormat,
1725
                           unsigned char *dstBuf, int align, int subsamp,
1726
                           int flags)
1727
0
{
1728
0
  static const char FUNCTION_NAME[] = "tjEncodeYUV3";
1729
0
  int retval = 0;
1730
1731
0
  GET_TJINSTANCE(handle, -1);
1732
1733
0
  if (subsamp < 0 || subsamp >= TJ_NUMSAMP)
1734
0
    THROW("Invalid argument");
1735
1736
0
  this->subsamp = subsamp;
1737
0
  processFlags(handle, flags, COMPRESS);
1738
1739
0
  return tj3EncodeYUV8(handle, srcBuf, width, pitch, height, pixelFormat,
1740
0
                       dstBuf, align);
1741
1742
0
bailout:
1743
0
  return retval;
1744
0
}
1745
1746
/* TurboJPEG 1.2+ */
1747
DLLEXPORT int tjEncodeYUV2(tjhandle handle, unsigned char *srcBuf, int width,
1748
                           int pitch, int height, int pixelFormat,
1749
                           unsigned char *dstBuf, int subsamp, int flags)
1750
0
{
1751
0
  return tjEncodeYUV3(handle, srcBuf, width, pitch, height, pixelFormat,
1752
0
                      dstBuf, 4, subsamp, flags);
1753
0
}
1754
1755
/* TurboJPEG 1.1+ */
1756
DLLEXPORT int tjEncodeYUV(tjhandle handle, unsigned char *srcBuf, int width,
1757
                          int pitch, int height, int pixelSize,
1758
                          unsigned char *dstBuf, int subsamp, int flags)
1759
0
{
1760
0
  return tjEncodeYUV2(handle, srcBuf, width, pitch, height,
1761
0
                      getPixelFormat(pixelSize, flags), dstBuf, subsamp,
1762
0
                      flags);
1763
0
}
1764
1765
1766
/******************************* Decompressor ********************************/
1767
1768
static tjhandle _tjInitDecompress(tjinstance *this)
1769
54.1k
{
1770
54.1k
  static unsigned char buffer[1];
1771
1772
  /* This is also straight out of example.c */
1773
54.1k
  this->dinfo.err = jpeg_std_error(&this->jerr.pub);
1774
54.1k
  this->jerr.pub.error_exit = my_error_exit;
1775
54.1k
  this->jerr.pub.output_message = my_output_message;
1776
54.1k
  this->jerr.emit_message = this->jerr.pub.emit_message;
1777
54.1k
  this->jerr.pub.emit_message = my_emit_message;
1778
54.1k
  this->jerr.pub.addon_message_table = turbojpeg_message_table;
1779
54.1k
  this->jerr.pub.first_addon_message = JMSG_FIRSTADDONCODE;
1780
54.1k
  this->jerr.pub.last_addon_message = JMSG_LASTADDONCODE;
1781
1782
54.1k
  if (setjmp(this->jerr.setjmp_buffer)) {
1783
    /* If we get here, the JPEG code has signaled an error. */
1784
0
    free(this);
1785
0
    return NULL;
1786
0
  }
1787
1788
54.1k
  jpeg_create_decompress(&this->dinfo);
1789
  /* Make an initial call so it will create the source manager */
1790
54.1k
  jpeg_mem_src_tj(&this->dinfo, buffer, 1);
1791
1792
54.1k
  this->init |= DECOMPRESS;
1793
54.1k
  return (tjhandle)this;
1794
54.1k
}
1795
1796
/* TurboJPEG 1.0+ */
1797
DLLEXPORT tjhandle tjInitDecompress(void)
1798
0
{
1799
0
  return tj3Init(TJINIT_DECOMPRESS);
1800
0
}
1801
1802
1803
/* TurboJPEG 3+ */
1804
DLLEXPORT int tj3DecompressHeader(tjhandle handle,
1805
                                  const unsigned char *jpegBuf,
1806
                                  size_t jpegSize)
1807
13.5k
{
1808
13.5k
  static const char FUNCTION_NAME[] = "tj3DecompressHeader";
1809
13.5k
  int retval = 0;
1810
1811
13.5k
  GET_DINSTANCE(handle);
1812
13.5k
  if ((this->init & DECOMPRESS) == 0)
1813
13.5k
    THROW("Instance has not been initialized for decompression");
1814
1815
13.5k
  if (jpegBuf == NULL || jpegSize <= 0)
1816
13.5k
    THROW("Invalid argument");
1817
1818
13.5k
  CATCH_LIBJPEG(this);
1819
1820
12.3k
  jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
1821
1822
  /* jpeg_read_header() calls jpeg_abort() and returns JPEG_HEADER_TABLES_ONLY
1823
     if the datastream is a tables-only datastream.  Since we aren't using a
1824
     suspending data source, the only other value it can return is
1825
     JPEG_HEADER_OK. */
1826
12.3k
  if (jpeg_read_header(dinfo, FALSE) == JPEG_HEADER_TABLES_ONLY)
1827
1.11k
    return 0;
1828
1829
11.1k
  setDecompParameters(this);
1830
1831
11.1k
  jpeg_abort_decompress(dinfo);
1832
1833
11.1k
  if (this->colorspace < 0)
1834
11.1k
    THROW("Could not determine colorspace of JPEG image");
1835
11.1k
  if (this->jpegWidth < 1 || this->jpegHeight < 1)
1836
11.1k
    THROW("Invalid data returned in header");
1837
1838
12.4k
bailout:
1839
12.4k
  if (this->jerr.warning) retval = -1;
1840
12.4k
  return retval;
1841
11.1k
}
1842
1843
/* TurboJPEG 1.4+ */
1844
DLLEXPORT int tjDecompressHeader3(tjhandle handle,
1845
                                  const unsigned char *jpegBuf,
1846
                                  unsigned long jpegSize, int *width,
1847
                                  int *height, int *jpegSubsamp,
1848
                                  int *jpegColorspace)
1849
0
{
1850
0
  static const char FUNCTION_NAME[] = "tjDecompressHeader3";
1851
0
  int retval = 0;
1852
1853
0
  GET_TJINSTANCE(handle, -1);
1854
1855
0
  if (width == NULL || height == NULL || jpegSubsamp == NULL ||
1856
0
      jpegColorspace == NULL)
1857
0
    THROW("Invalid argument");
1858
1859
0
  retval = tj3DecompressHeader(handle, jpegBuf, jpegSize);
1860
1861
0
  *width = tj3Get(handle, TJPARAM_JPEGWIDTH);
1862
0
  *height = tj3Get(handle, TJPARAM_JPEGHEIGHT);
1863
0
  *jpegSubsamp = tj3Get(handle, TJPARAM_SUBSAMP);
1864
0
  if (*jpegSubsamp == TJSAMP_UNKNOWN)
1865
0
    THROW("Could not determine subsampling level of JPEG image");
1866
0
  *jpegColorspace = tj3Get(handle, TJPARAM_COLORSPACE);
1867
1868
0
bailout:
1869
0
  return retval;
1870
0
}
1871
1872
/* TurboJPEG 1.1+ */
1873
DLLEXPORT int tjDecompressHeader2(tjhandle handle, unsigned char *jpegBuf,
1874
                                  unsigned long jpegSize, int *width,
1875
                                  int *height, int *jpegSubsamp)
1876
0
{
1877
0
  int jpegColorspace;
1878
1879
0
  return tjDecompressHeader3(handle, jpegBuf, jpegSize, width, height,
1880
0
                             jpegSubsamp, &jpegColorspace);
1881
0
}
1882
1883
/* TurboJPEG 1.0+ */
1884
DLLEXPORT int tjDecompressHeader(tjhandle handle, unsigned char *jpegBuf,
1885
                                 unsigned long jpegSize, int *width,
1886
                                 int *height)
1887
0
{
1888
0
  int jpegSubsamp;
1889
1890
0
  return tjDecompressHeader2(handle, jpegBuf, jpegSize, width, height,
1891
0
                             &jpegSubsamp);
1892
0
}
1893
1894
1895
/* TurboJPEG 3+ */
1896
DLLEXPORT tjscalingfactor *tj3GetScalingFactors(int *numScalingFactors)
1897
0
{
1898
0
  static const char FUNCTION_NAME[] = "tj3GetScalingFactors";
1899
0
  tjscalingfactor *retval = (tjscalingfactor *)sf;
1900
1901
0
  if (numScalingFactors == NULL)
1902
0
    THROWG("Invalid argument", NULL);
1903
1904
0
  *numScalingFactors = NUMSF;
1905
1906
0
bailout:
1907
0
  return retval;
1908
0
}
1909
1910
/* TurboJPEG 1.2+ */
1911
DLLEXPORT tjscalingfactor *tjGetScalingFactors(int *numScalingFactors)
1912
0
{
1913
0
  return tj3GetScalingFactors(numScalingFactors);
1914
0
}
1915
1916
1917
/* TurboJPEG 3+ */
1918
DLLEXPORT int tj3SetScalingFactor(tjhandle handle,
1919
                                  tjscalingfactor scalingFactor)
1920
97.3k
{
1921
97.3k
  static const char FUNCTION_NAME[] = "tj3SetScalingFactor";
1922
97.3k
  int i, retval = 0;
1923
1924
97.3k
  GET_TJINSTANCE(handle, -1);
1925
97.3k
  if ((this->init & DECOMPRESS) == 0)
1926
97.3k
    THROW("Instance has not been initialized for decompression");
1927
1928
1.04M
  for (i = 0; i < NUMSF; i++) {
1929
1.04M
    if (scalingFactor.num == sf[i].num && scalingFactor.denom == sf[i].denom)
1930
97.3k
      break;
1931
1.04M
  }
1932
97.3k
  if (i >= NUMSF)
1933
97.3k
    THROW("Unsupported scaling factor");
1934
1935
97.3k
  this->scalingFactor = scalingFactor;
1936
1937
97.3k
bailout:
1938
97.3k
  return retval;
1939
97.3k
}
1940
1941
1942
/* TurboJPEG 3+ */
1943
DLLEXPORT int tj3SetCroppingRegion(tjhandle handle, tjregion croppingRegion)
1944
16.9k
{
1945
16.9k
  static const char FUNCTION_NAME[] = "tj3SetCroppingRegion";
1946
16.9k
  int retval = 0, scaledWidth, scaledHeight;
1947
1948
16.9k
  GET_TJINSTANCE(handle, -1);
1949
16.9k
  if ((this->init & DECOMPRESS) == 0)
1950
16.9k
    THROW("Instance has not been initialized for decompression");
1951
1952
16.9k
  if (croppingRegion.x == 0 && croppingRegion.y == 0 &&
1953
15.9k
      croppingRegion.w == 0 && croppingRegion.h == 0) {
1954
15.9k
    this->croppingRegion = croppingRegion;
1955
15.9k
    return 0;
1956
15.9k
  }
1957
1958
1.03k
  if (croppingRegion.x < 0 || croppingRegion.y < 0 || croppingRegion.w < 0 ||
1959
1.03k
      croppingRegion.h < 0)
1960
1.03k
    THROW("Invalid cropping region");
1961
1.03k
  if (this->jpegWidth < 0 || this->jpegHeight < 0)
1962
1.03k
    THROW("JPEG header has not yet been read");
1963
1.03k
  if (this->precision == 16 || this->lossless)
1964
1.02k
    THROW("Cannot partially decompress lossless JPEG images");
1965
1.02k
  if (this->subsamp == TJSAMP_UNKNOWN)
1966
921
    THROW("Could not determine subsampling level of JPEG image");
1967
1968
921
  scaledWidth = TJSCALED(this->jpegWidth, this->scalingFactor);
1969
921
  scaledHeight = TJSCALED(this->jpegHeight, this->scalingFactor);
1970
1971
921
  if (croppingRegion.x %
1972
921
      TJSCALED(tjMCUWidth[this->subsamp], this->scalingFactor) != 0)
1973
0
    THROWI("The left boundary of the cropping region (%d) is not\n"
1974
921
           "divisible by the scaled iMCU width (%d)",
1975
921
           croppingRegion.x,
1976
921
           TJSCALED(tjMCUWidth[this->subsamp], this->scalingFactor));
1977
921
  if (croppingRegion.w == 0)
1978
0
    croppingRegion.w = scaledWidth - croppingRegion.x;
1979
921
  if (croppingRegion.h == 0)
1980
0
    croppingRegion.h = scaledHeight - croppingRegion.y;
1981
921
  if (croppingRegion.w <= 0 || croppingRegion.h <= 0 ||
1982
921
      croppingRegion.x + croppingRegion.w > scaledWidth ||
1983
921
      croppingRegion.y + croppingRegion.h > scaledHeight)
1984
921
    THROW("The cropping region exceeds the scaled image dimensions");
1985
1986
921
  this->croppingRegion = croppingRegion;
1987
1988
1.03k
bailout:
1989
1.03k
  return retval;
1990
921
}
1991
1992
1993
/* tj3Decompress*() is implemented in turbojpeg-mp.c */
1994
1995
/* TurboJPEG 1.2+ */
1996
DLLEXPORT int tjDecompress2(tjhandle handle, const unsigned char *jpegBuf,
1997
                            unsigned long jpegSize, unsigned char *dstBuf,
1998
                            int width, int pitch, int height, int pixelFormat,
1999
                            int flags)
2000
0
{
2001
0
  static const char FUNCTION_NAME[] = "tjDecompress2";
2002
0
  int i, retval = 0, jpegwidth, jpegheight, scaledw, scaledh;
2003
2004
0
  GET_DINSTANCE(handle);
2005
0
  if ((this->init & DECOMPRESS) == 0)
2006
0
    THROW("Instance has not been initialized for decompression");
2007
2008
0
  if (jpegBuf == NULL || jpegSize <= 0 || width < 0 || height < 0)
2009
0
    THROW("Invalid argument");
2010
2011
0
  CATCH_LIBJPEG(this);
2012
2013
0
  jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
2014
0
  jpeg_read_header(dinfo, TRUE);
2015
0
  jpegwidth = dinfo->image_width;  jpegheight = dinfo->image_height;
2016
0
  if (width == 0) width = jpegwidth;
2017
0
  if (height == 0) height = jpegheight;
2018
0
  for (i = 0; i < NUMSF; i++) {
2019
0
    scaledw = TJSCALED(jpegwidth, sf[i]);
2020
0
    scaledh = TJSCALED(jpegheight, sf[i]);
2021
0
    if (scaledw <= width && scaledh <= height)
2022
0
      break;
2023
0
  }
2024
0
  if (i >= NUMSF)
2025
0
    THROW("Could not scale down to desired image dimensions");
2026
0
  if (dinfo->master->lossless && ((JDIMENSION)scaledw != dinfo->image_width ||
2027
0
                                  (JDIMENSION)scaledh != dinfo->image_height))
2028
0
    THROW("Cannot use decompression scaling with lossless JPEG images");
2029
2030
0
  processFlags(handle, flags, DECOMPRESS);
2031
2032
0
  if (tj3SetScalingFactor(handle, sf[i]) == -1)
2033
0
    return -1;
2034
0
  if (tj3SetCroppingRegion(handle, TJUNCROPPED) == -1)
2035
0
    return -1;
2036
0
  return tj3Decompress8(handle, jpegBuf, jpegSize, dstBuf, pitch, pixelFormat);
2037
2038
0
bailout:
2039
0
  if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
2040
0
  if (this->jerr.warning) retval = -1;
2041
0
  return retval;
2042
0
}
2043
2044
/* TurboJPEG 1.0+ */
2045
DLLEXPORT int tjDecompress(tjhandle handle, unsigned char *jpegBuf,
2046
                           unsigned long jpegSize, unsigned char *dstBuf,
2047
                           int width, int pitch, int height, int pixelSize,
2048
                           int flags)
2049
0
{
2050
0
  if (flags & TJ_YUV)
2051
0
    return tjDecompressToYUV(handle, jpegBuf, jpegSize, dstBuf, flags);
2052
0
  else
2053
0
    return tjDecompress2(handle, jpegBuf, jpegSize, dstBuf, width, pitch,
2054
0
                         height, getPixelFormat(pixelSize, flags), flags);
2055
0
}
2056
2057
2058
/* TurboJPEG 3+ */
2059
DLLEXPORT int tj3DecompressToYUVPlanes8(tjhandle handle,
2060
                                        const unsigned char *jpegBuf,
2061
                                        size_t jpegSize,
2062
                                        unsigned char **dstPlanes,
2063
                                        int *strides)
2064
31.9k
{
2065
31.9k
  static const char FUNCTION_NAME[] = "tj3DecompressToYUVPlanes8";
2066
31.9k
  int i, row, retval = 0;
2067
31.9k
  int pw[MAX_COMPONENTS], ph[MAX_COMPONENTS], iw[MAX_COMPONENTS],
2068
31.9k
    tmpbufsize = 0, usetmpbuf = 0, th[MAX_COMPONENTS];
2069
31.9k
  JSAMPLE *_tmpbuf = NULL, *ptr;
2070
31.9k
  JSAMPROW *outbuf[MAX_COMPONENTS], *tmpbuf[MAX_COMPONENTS];
2071
31.9k
  int dctsize;
2072
31.9k
  struct my_progress_mgr progress;
2073
2074
31.9k
  GET_DINSTANCE(handle);
2075
2076
351k
  for (i = 0; i < MAX_COMPONENTS; i++) {
2077
319k
    tmpbuf[i] = NULL;  outbuf[i] = NULL;
2078
319k
  }
2079
2080
31.9k
  if ((this->init & DECOMPRESS) == 0)
2081
31.9k
    THROW("Instance has not been initialized for decompression");
2082
2083
31.9k
  if (jpegBuf == NULL || jpegSize <= 0 || !dstPlanes || !dstPlanes[0])
2084
31.9k
    THROW("Invalid argument");
2085
2086
31.9k
  if (this->scanLimit) {
2087
31.9k
    memset(&progress, 0, sizeof(struct my_progress_mgr));
2088
31.9k
    progress.pub.progress_monitor = my_progress_monitor;
2089
31.9k
    progress.this = this;
2090
31.9k
    dinfo->progress = &progress.pub;
2091
31.9k
  } else
2092
0
    dinfo->progress = NULL;
2093
2094
31.9k
  dinfo->mem->max_memory_to_use = (long)this->maxMemory * 1048576L;
2095
2096
31.9k
  CATCH_LIBJPEG(this);
2097
2098
31.9k
  if (dinfo->global_state <= DSTATE_INHEADER) {
2099
0
    jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
2100
0
    jpeg_read_header(dinfo, TRUE);
2101
0
  }
2102
31.9k
  setDecompParameters(this);
2103
31.9k
  if (this->maxPixels &&
2104
0
      (unsigned long long)this->jpegWidth * this->jpegHeight >
2105
0
      (unsigned long long)this->maxPixels)
2106
31.9k
    THROW("Image is too large");
2107
31.9k
  if (this->subsamp == TJSAMP_UNKNOWN)
2108
31.9k
    THROW("Could not determine subsampling level of JPEG image");
2109
2110
31.9k
  if (this->subsamp != TJSAMP_GRAY && (!dstPlanes[1] || !dstPlanes[2]))
2111
31.9k
    THROW("Invalid argument");
2112
2113
31.9k
  if (dinfo->num_components > 3)
2114
31.8k
    THROW("JPEG image must have 3 or fewer components");
2115
2116
31.8k
  dinfo->scale_num = this->scalingFactor.num;
2117
31.8k
  dinfo->scale_denom = this->scalingFactor.denom;
2118
31.8k
  jpeg_calc_output_dimensions(dinfo);
2119
2120
31.8k
  dctsize = DCTSIZE * this->scalingFactor.num / this->scalingFactor.denom;
2121
2122
102k
  for (i = 0; i < dinfo->num_components; i++) {
2123
70.4k
    jpeg_component_info *compptr = &dinfo->comp_info[i];
2124
70.4k
    int ih;
2125
2126
70.4k
    iw[i] = compptr->width_in_blocks * dctsize;
2127
70.4k
    ih = compptr->height_in_blocks * dctsize;
2128
70.4k
    pw[i] = tj3YUVPlaneWidth(i, dinfo->output_width, this->subsamp);
2129
70.4k
    if (strides && strides[i] != 0 && strides[i] < pw[i])
2130
70.4k
      THROW("Invalid argument");
2131
70.4k
    ph[i] = tj3YUVPlaneHeight(i, dinfo->output_height, this->subsamp);
2132
70.4k
    if (iw[i] != pw[i] || ih != ph[i]) usetmpbuf = 1;
2133
70.4k
    th[i] = compptr->v_samp_factor * dctsize;
2134
70.4k
    tmpbufsize += iw[i] * th[i];
2135
70.4k
    if ((outbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i])) == NULL)
2136
70.4k
      THROW("Memory allocation failure");
2137
70.4k
    ptr = dstPlanes[i];
2138
375M
    for (row = 0; row < ph[i]; row++) {
2139
375M
      outbuf[i][row] = ptr;
2140
375M
      ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
2141
375M
    }
2142
70.4k
  }
2143
31.8k
  if (usetmpbuf) {
2144
28.3k
    if ((_tmpbuf = (JSAMPLE *)MALLOC(sizeof(JSAMPLE) * tmpbufsize)) == NULL)
2145
28.3k
      THROW("Memory allocation failure");
2146
28.3k
    ptr = _tmpbuf;
2147
91.7k
    for (i = 0; i < dinfo->num_components; i++) {
2148
63.4k
      if ((tmpbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * th[i])) == NULL)
2149
63.4k
        THROW("Memory allocation failure");
2150
762k
      for (row = 0; row < th[i]; row++) {
2151
699k
        tmpbuf[i][row] = ptr;
2152
699k
        ptr += iw[i];
2153
699k
      }
2154
63.4k
    }
2155
28.3k
  }
2156
2157
31.8k
  CATCH_LIBJPEG(this);
2158
2159
11.2k
  dinfo->do_fancy_upsampling = !this->fastUpsample;
2160
11.2k
  dinfo->dct_method = this->fastDCT ? JDCT_FASTEST : JDCT_ISLOW;
2161
11.2k
  dinfo->raw_data_out = TRUE;
2162
2163
11.2k
  dinfo->mem->max_memory_to_use = (long)this->maxMemory * 1048576L;
2164
2165
11.2k
  jpeg_start_decompress(dinfo);
2166
4.44M
  for (row = 0; row < (int)dinfo->output_height;
2167
4.43M
       row += dinfo->max_v_samp_factor * dinfo->_min_DCT_scaled_size) {
2168
4.43M
    JSAMPARRAY yuvptr[MAX_COMPONENTS];
2169
4.43M
    int crow[MAX_COMPONENTS];
2170
2171
12.1M
    for (i = 0; i < dinfo->num_components; i++) {
2172
7.69M
      jpeg_component_info *compptr = &dinfo->comp_info[i];
2173
2174
7.69M
      if (this->subsamp == TJSAMP_420) {
2175
        /* When 4:2:0 subsampling is used with IDCT scaling, libjpeg will try
2176
           to be clever and use the IDCT to perform upsampling on the U and V
2177
           planes.  For instance, if the output image is to be scaled by 1/2
2178
           relative to the JPEG image, then the scaling factor and upsampling
2179
           effectively cancel each other, so a normal 8x8 IDCT can be used.
2180
           However, this is not desirable when using the decompress-to-YUV
2181
           functionality in TurboJPEG, since we want to output the U and V
2182
           planes in their subsampled form.  Thus, we have to override some
2183
           internal libjpeg parameters to force it to use the "scaled" IDCT
2184
           functions on the U and V planes. */
2185
866k
        compptr->_DCT_scaled_size = dctsize;
2186
866k
        compptr->MCU_sample_width = tjMCUWidth[this->subsamp] *
2187
866k
          this->scalingFactor.num / this->scalingFactor.denom *
2188
866k
          compptr->h_samp_factor / dinfo->max_h_samp_factor;
2189
866k
        dinfo->idct->inverse_DCT[i] = dinfo->idct->inverse_DCT[0];
2190
866k
      }
2191
7.69M
      crow[i] = row * compptr->v_samp_factor / dinfo->max_v_samp_factor;
2192
7.69M
      if (usetmpbuf) yuvptr[i] = tmpbuf[i];
2193
975k
      else yuvptr[i] = &outbuf[i][crow[i]];
2194
7.69M
    }
2195
4.43M
    jpeg_read_raw_data(dinfo, yuvptr,
2196
4.43M
                       dinfo->max_v_samp_factor * dinfo->_min_DCT_scaled_size);
2197
4.43M
    if (usetmpbuf) {
2198
3.75M
      int j;
2199
2200
10.4M
      for (i = 0; i < dinfo->num_components; i++) {
2201
68.2M
        for (j = 0; j < MIN(th[i], ph[i] - crow[i]); j++) {
2202
61.5M
          memcpy(outbuf[i][crow[i] + j], tmpbuf[i][j], pw[i]);
2203
61.5M
        }
2204
6.69M
      }
2205
3.75M
    }
2206
4.43M
  }
2207
11.2k
  jpeg_finish_decompress(dinfo);
2208
2209
31.9k
bailout:
2210
31.9k
  if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
2211
351k
  for (i = 0; i < MAX_COMPONENTS; i++) {
2212
319k
    free(tmpbuf[i]);
2213
319k
    free(outbuf[i]);
2214
319k
  }
2215
31.9k
  free(_tmpbuf);
2216
31.9k
  if (this->jerr.warning) retval = -1;
2217
31.9k
  return retval;
2218
11.2k
}
2219
2220
/* TurboJPEG 1.4+ */
2221
DLLEXPORT int tjDecompressToYUVPlanes(tjhandle handle,
2222
                                      const unsigned char *jpegBuf,
2223
                                      unsigned long jpegSize,
2224
                                      unsigned char **dstPlanes, int width,
2225
                                      int *strides, int height, int flags)
2226
0
{
2227
0
  static const char FUNCTION_NAME[] = "tjDecompressToYUVPlanes";
2228
0
  int i, retval = 0, jpegwidth, jpegheight, scaledw, scaledh;
2229
2230
0
  GET_DINSTANCE(handle);
2231
0
  if ((this->init & DECOMPRESS) == 0)
2232
0
    THROW("Instance has not been initialized for decompression");
2233
2234
0
  if (jpegBuf == NULL || jpegSize <= 0 || width < 0 || height < 0)
2235
0
    THROW("Invalid argument");
2236
2237
0
  CATCH_LIBJPEG(this);
2238
2239
0
  jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
2240
0
  jpeg_read_header(dinfo, TRUE);
2241
0
  jpegwidth = dinfo->image_width;  jpegheight = dinfo->image_height;
2242
0
  if (width == 0) width = jpegwidth;
2243
0
  if (height == 0) height = jpegheight;
2244
0
  for (i = 0; i < NUMSF; i++) {
2245
0
    scaledw = TJSCALED(jpegwidth, sf[i]);
2246
0
    scaledh = TJSCALED(jpegheight, sf[i]);
2247
0
    if (scaledw <= width && scaledh <= height)
2248
0
      break;
2249
0
  }
2250
0
  if (i >= NUMSF)
2251
0
    THROW("Could not scale down to desired image dimensions");
2252
2253
0
  processFlags(handle, flags, DECOMPRESS);
2254
2255
0
  if (tj3SetScalingFactor(handle, sf[i]) == -1)
2256
0
    return -1;
2257
0
  return tj3DecompressToYUVPlanes8(handle, jpegBuf, jpegSize, dstPlanes,
2258
0
                                   strides);
2259
2260
0
bailout:
2261
0
  if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
2262
0
  if (this->jerr.warning) retval = -1;
2263
0
  return retval;
2264
0
}
2265
2266
2267
/* TurboJPEG 3+ */
2268
DLLEXPORT int tj3DecompressToYUV8(tjhandle handle,
2269
                                  const unsigned char *jpegBuf,
2270
                                  size_t jpegSize,
2271
                                  unsigned char *dstBuf, int align)
2272
49.9k
{
2273
49.9k
  static const char FUNCTION_NAME[] = "tj3DecompressToYUV8";
2274
49.9k
  unsigned char *dstPlanes[3];
2275
49.9k
  int pw0, ph0, strides[3], retval = -1;
2276
49.9k
  int width, height;
2277
2278
49.9k
  GET_DINSTANCE(handle);
2279
2280
49.9k
  if (jpegBuf == NULL || jpegSize <= 0 || dstBuf == NULL || align < 1 ||
2281
49.9k
      !IS_POW2(align))
2282
49.9k
    THROW("Invalid argument");
2283
2284
49.9k
  CATCH_LIBJPEG(this);
2285
2286
49.9k
  if (dinfo->global_state <= DSTATE_INHEADER) {
2287
49.9k
    jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
2288
49.9k
    jpeg_read_header(dinfo, TRUE);
2289
49.9k
  }
2290
49.9k
  setDecompParameters(this);
2291
49.9k
  if (this->subsamp == TJSAMP_UNKNOWN)
2292
48.8k
    THROW("Could not determine subsampling level of JPEG image");
2293
2294
48.8k
  width = TJSCALED(dinfo->image_width, this->scalingFactor);
2295
48.8k
  height = TJSCALED(dinfo->image_height, this->scalingFactor);
2296
2297
48.8k
  pw0 = tj3YUVPlaneWidth(0, width, this->subsamp);
2298
48.8k
  ph0 = tj3YUVPlaneHeight(0, height, this->subsamp);
2299
48.8k
  dstPlanes[0] = dstBuf;
2300
48.8k
  strides[0] = PAD(pw0, align);
2301
48.8k
  if (this->subsamp == TJSAMP_GRAY) {
2302
22.1k
    strides[1] = strides[2] = 0;
2303
22.1k
    dstPlanes[1] = dstPlanes[2] = NULL;
2304
26.7k
  } else {
2305
26.7k
    int pw1 = tj3YUVPlaneWidth(1, width, this->subsamp);
2306
26.7k
    int ph1 = tj3YUVPlaneHeight(1, height, this->subsamp);
2307
2308
26.7k
    strides[1] = strides[2] = PAD(pw1, align);
2309
26.7k
    if ((unsigned long long)strides[0] * (unsigned long long)ph0 >
2310
26.7k
        (unsigned long long)INT_MAX ||
2311
26.7k
        (unsigned long long)strides[1] * (unsigned long long)ph1 >
2312
26.7k
        (unsigned long long)INT_MAX)
2313
26.7k
      THROW("Image or row alignment is too large");
2314
26.7k
    dstPlanes[1] = dstPlanes[0] + strides[0] * ph0;
2315
26.7k
    dstPlanes[2] = dstPlanes[1] + strides[1] * ph1;
2316
26.7k
  }
2317
2318
48.8k
  return tj3DecompressToYUVPlanes8(handle, jpegBuf, jpegSize, dstPlanes,
2319
48.8k
                                   strides);
2320
2321
1.03k
bailout:
2322
1.03k
  if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
2323
1.03k
  if (this->jerr.warning) retval = -1;
2324
1.03k
  return retval;
2325
48.8k
}
2326
2327
/* TurboJPEG 1.4+ */
2328
DLLEXPORT int tjDecompressToYUV2(tjhandle handle, const unsigned char *jpegBuf,
2329
                                 unsigned long jpegSize, unsigned char *dstBuf,
2330
                                 int width, int align, int height, int flags)
2331
0
{
2332
0
  static const char FUNCTION_NAME[] = "tjDecompressToYUV2";
2333
0
  int i, retval = 0, jpegwidth, jpegheight, scaledw, scaledh;
2334
2335
0
  GET_DINSTANCE(handle);
2336
0
  if ((this->init & DECOMPRESS) == 0)
2337
0
    THROW("Instance has not been initialized for decompression");
2338
2339
0
  if (jpegBuf == NULL || jpegSize <= 0 || width < 0 || height < 0)
2340
0
    THROW("Invalid argument");
2341
2342
0
  CATCH_LIBJPEG(this);
2343
2344
0
  jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
2345
0
  jpeg_read_header(dinfo, TRUE);
2346
0
  jpegwidth = dinfo->image_width;  jpegheight = dinfo->image_height;
2347
0
  if (width == 0) width = jpegwidth;
2348
0
  if (height == 0) height = jpegheight;
2349
0
  for (i = 0; i < NUMSF; i++) {
2350
0
    scaledw = TJSCALED(jpegwidth, sf[i]);
2351
0
    scaledh = TJSCALED(jpegheight, sf[i]);
2352
0
    if (scaledw <= width && scaledh <= height)
2353
0
      break;
2354
0
  }
2355
0
  if (i >= NUMSF)
2356
0
    THROW("Could not scale down to desired image dimensions");
2357
2358
0
  width = scaledw;  height = scaledh;
2359
2360
0
  processFlags(handle, flags, DECOMPRESS);
2361
2362
0
  if (tj3SetScalingFactor(handle, sf[i]) == -1)
2363
0
    return -1;
2364
0
  return tj3DecompressToYUV8(handle, jpegBuf, (size_t)jpegSize, dstBuf, align);
2365
2366
0
bailout:
2367
0
  if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
2368
0
  if (this->jerr.warning) retval = -1;
2369
0
  return retval;
2370
0
}
2371
2372
/* TurboJPEG 1.1+ */
2373
DLLEXPORT int tjDecompressToYUV(tjhandle handle, unsigned char *jpegBuf,
2374
                                unsigned long jpegSize, unsigned char *dstBuf,
2375
                                int flags)
2376
0
{
2377
0
  return tjDecompressToYUV2(handle, jpegBuf, jpegSize, dstBuf, 0, 4, 0, flags);
2378
0
}
2379
2380
2381
static void setDecodeDefaults(tjinstance *this, int pixelFormat)
2382
2.10k
{
2383
2.10k
  int i;
2384
2385
2.10k
  this->dinfo.scale_num = this->dinfo.scale_denom = 1;
2386
2387
2.10k
  if (this->subsamp == TJSAMP_GRAY) {
2388
733
    this->dinfo.num_components = this->dinfo.comps_in_scan = 1;
2389
733
    this->dinfo.jpeg_color_space = JCS_GRAYSCALE;
2390
1.37k
  } else {
2391
1.37k
    this->dinfo.num_components = this->dinfo.comps_in_scan = 3;
2392
1.37k
    this->dinfo.jpeg_color_space = JCS_YCbCr;
2393
1.37k
  }
2394
2395
2.10k
  this->dinfo.comp_info = (jpeg_component_info *)
2396
2.10k
    (*this->dinfo.mem->alloc_small) ((j_common_ptr)&this->dinfo, JPOOL_IMAGE,
2397
2.10k
                                     this->dinfo.num_components *
2398
2.10k
                                     sizeof(jpeg_component_info));
2399
2400
6.96k
  for (i = 0; i < this->dinfo.num_components; i++) {
2401
4.85k
    jpeg_component_info *compptr = &this->dinfo.comp_info[i];
2402
2403
4.85k
    compptr->h_samp_factor = (i == 0) ? tjMCUWidth[this->subsamp] / 8 : 1;
2404
4.85k
    compptr->v_samp_factor = (i == 0) ? tjMCUHeight[this->subsamp] / 8 : 1;
2405
4.85k
    compptr->component_index = i;
2406
4.85k
    compptr->component_id = i + 1;
2407
4.85k
    compptr->quant_tbl_no = compptr->dc_tbl_no =
2408
4.85k
      compptr->ac_tbl_no = (i == 0) ? 0 : 1;
2409
4.85k
    this->dinfo.cur_comp_info[i] = compptr;
2410
4.85k
  }
2411
2.10k
  this->dinfo.data_precision = 8;
2412
6.32k
  for (i = 0; i < 2; i++) {
2413
4.21k
    if (this->dinfo.quant_tbl_ptrs[i] == NULL)
2414
579
      this->dinfo.quant_tbl_ptrs[i] =
2415
579
        jpeg_alloc_quant_table((j_common_ptr)&this->dinfo);
2416
4.21k
  }
2417
2418
2.10k
  this->dinfo.mem->max_memory_to_use = (long)this->maxMemory * 1048576L;
2419
2.10k
}
2420
2421
2422
static int my_read_markers(j_decompress_ptr dinfo)
2423
2.10k
{
2424
2.10k
  return JPEG_REACHED_SOS;
2425
2.10k
}
2426
2427
static void my_reset_marker_reader(j_decompress_ptr dinfo)
2428
2.10k
{
2429
2.10k
}
2430
2431
/* TurboJPEG 3+ */
2432
DLLEXPORT int tj3DecodeYUVPlanes8(tjhandle handle,
2433
                                  const unsigned char * const *srcPlanes,
2434
                                  const int *strides, unsigned char *dstBuf,
2435
                                  int width, int pitch, int height,
2436
                                  int pixelFormat)
2437
2.10k
{
2438
2.10k
  static const char FUNCTION_NAME[] = "tj3DecodeYUVPlanes8";
2439
2.10k
  JSAMPROW *row_pointer = NULL;
2440
2.10k
  JSAMPLE *_tmpbuf[MAX_COMPONENTS];
2441
2.10k
  JSAMPROW *tmpbuf[MAX_COMPONENTS], *inbuf[MAX_COMPONENTS];
2442
2.10k
  int i, retval = 0, row, pw0, ph0, pw[MAX_COMPONENTS], ph[MAX_COMPONENTS];
2443
2.10k
  JSAMPLE *ptr;
2444
2.10k
  jpeg_component_info *compptr;
2445
2.10k
  int (*old_read_markers) (j_decompress_ptr) = NULL;
2446
2.10k
  void (*old_reset_marker_reader) (j_decompress_ptr) = NULL;
2447
2448
2.10k
  GET_DINSTANCE(handle);
2449
2450
23.1k
  for (i = 0; i < MAX_COMPONENTS; i++) {
2451
21.0k
    tmpbuf[i] = NULL;  _tmpbuf[i] = NULL;  inbuf[i] = NULL;
2452
21.0k
  }
2453
2454
2.10k
  if ((this->init & DECOMPRESS) == 0)
2455
2.10k
    THROW("Instance has not been initialized for decompression");
2456
2457
2.10k
  if (!srcPlanes || !srcPlanes[0] || dstBuf == NULL || width <= 0 ||
2458
2.10k
      pitch < 0 || height <= 0 || pixelFormat < 0 || pixelFormat >= TJ_NUMPF)
2459
2.10k
    THROW("Invalid argument");
2460
2.10k
  if (this->subsamp != TJSAMP_GRAY && (!srcPlanes[1] || !srcPlanes[2]))
2461
2.10k
    THROW("Invalid argument");
2462
2463
2.10k
  if (this->subsamp == TJSAMP_UNKNOWN)
2464
2.10k
    THROW("TJPARAM_SUBSAMP must be specified");
2465
2.10k
  if (pixelFormat == TJPF_CMYK)
2466
2.10k
    THROW("Cannot decode YUV images into packed-pixel CMYK images.");
2467
2468
2.10k
  if (pitch == 0) pitch = width * tjPixelSize[pixelFormat];
2469
0
  else if (pitch < width * tjPixelSize[pixelFormat])
2470
2.10k
    THROW("Invalid argument");
2471
2.10k
  dinfo->image_width = width;
2472
2.10k
  dinfo->image_height = height;
2473
2474
2.10k
  dinfo->progressive_mode = dinfo->inputctl->has_multiple_scans = FALSE;
2475
2.10k
  dinfo->Ss = dinfo->Ah = dinfo->Al = 0;
2476
2.10k
  dinfo->Se = DCTSIZE2 - 1;
2477
2.10k
  setDecodeDefaults(this, pixelFormat);
2478
2.10k
  old_read_markers = dinfo->marker->read_markers;
2479
2.10k
  dinfo->marker->read_markers = my_read_markers;
2480
2.10k
  old_reset_marker_reader = dinfo->marker->reset_marker_reader;
2481
2.10k
  dinfo->marker->reset_marker_reader = my_reset_marker_reader;
2482
2.10k
  CATCH_LIBJPEG(this);
2483
2.07k
  jpeg_read_header(dinfo, TRUE);
2484
2.07k
  dinfo->marker->read_markers = old_read_markers;
2485
2.07k
  dinfo->marker->reset_marker_reader = old_reset_marker_reader;
2486
2487
2.07k
  this->dinfo.out_color_space = pf2cs[pixelFormat];
2488
2.07k
  this->dinfo.dct_method = this->fastDCT ? JDCT_FASTEST : JDCT_ISLOW;
2489
2.07k
  dinfo->do_fancy_upsampling = FALSE;
2490
2.07k
  dinfo->Se = DCTSIZE2 - 1;
2491
2.07k
  jinit_master_decompress(dinfo);
2492
2.07k
  (*dinfo->upsample->start_pass) (dinfo);
2493
2494
2.07k
  pw0 = PAD(width, dinfo->max_h_samp_factor);
2495
2.07k
  ph0 = PAD(height, dinfo->max_v_samp_factor);
2496
2497
2.07k
  if (pitch == 0) pitch = dinfo->output_width * tjPixelSize[pixelFormat];
2498
2499
2.07k
  if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph0)) == NULL)
2500
2.07k
    THROW("Memory allocation failure");
2501
13.2M
  for (i = 0; i < height; i++) {
2502
13.2M
    if (this->bottomUp)
2503
4.57M
      row_pointer[i] = &dstBuf[(height - i - 1) * (size_t)pitch];
2504
8.70M
    else
2505
8.70M
      row_pointer[i] = &dstBuf[i * (size_t)pitch];
2506
13.2M
  }
2507
2.07k
  if (height < ph0)
2508
1.15k
    for (i = height; i < ph0; i++) row_pointer[i] = row_pointer[height - 1];
2509
2510
6.84k
  for (i = 0; i < dinfo->num_components; i++) {
2511
4.76k
    compptr = &dinfo->comp_info[i];
2512
4.76k
    _tmpbuf[i] =
2513
4.76k
      (JSAMPLE *)malloc(PAD(compptr->width_in_blocks * DCTSIZE, 32) *
2514
4.76k
                        compptr->v_samp_factor + 32);
2515
4.76k
    if (!_tmpbuf[i])
2516
4.76k
      THROW("Memory allocation failure");
2517
4.76k
    tmpbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * compptr->v_samp_factor);
2518
4.76k
    if (!tmpbuf[i])
2519
4.76k
      THROW("Memory allocation failure");
2520
10.7k
    for (row = 0; row < compptr->v_samp_factor; row++) {
2521
5.94k
      unsigned char *_tmpbuf_aligned =
2522
5.94k
        (unsigned char *)PAD((JUINTPTR)_tmpbuf[i], 32);
2523
2524
5.94k
      tmpbuf[i][row] =
2525
5.94k
        &_tmpbuf_aligned[PAD(compptr->width_in_blocks * DCTSIZE, 32) * row];
2526
5.94k
    }
2527
4.76k
    pw[i] = pw0 * compptr->h_samp_factor / dinfo->max_h_samp_factor;
2528
4.76k
    if (strides && strides[i] != 0 && strides[i] < pw[i])
2529
4.76k
      THROW("Invalid argument");
2530
4.76k
    ph[i] = ph0 * compptr->v_samp_factor / dinfo->max_v_samp_factor;
2531
4.76k
    inbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i]);
2532
4.76k
    if (!inbuf[i])
2533
4.76k
      THROW("Memory allocation failure");
2534
4.76k
    ptr = (JSAMPLE *)srcPlanes[i];
2535
24.3M
    for (row = 0; row < ph[i]; row++) {
2536
24.3M
      inbuf[i][row] = ptr;
2537
24.3M
      ptr += (strides && strides[i] != 0) ? strides[i] : pw[i];
2538
24.3M
    }
2539
4.76k
  }
2540
2541
2.07k
  CATCH_LIBJPEG(this);
2542
2543
11.8M
  for (row = 0; row < ph0; row += dinfo->max_v_samp_factor) {
2544
11.8M
    JDIMENSION inrow = 0, outrow = 0;
2545
2546
34.6M
    for (i = 0, compptr = dinfo->comp_info; i < dinfo->num_components;
2547
22.8M
         i++, compptr++)
2548
22.8M
      jcopy_sample_rows(inbuf[i],
2549
22.8M
        row * compptr->v_samp_factor / dinfo->max_v_samp_factor, tmpbuf[i], 0,
2550
22.8M
        compptr->v_samp_factor, pw[i]);
2551
11.8M
    (dinfo->upsample->upsample) (dinfo, tmpbuf, &inrow,
2552
11.8M
                                 dinfo->max_v_samp_factor, &row_pointer[row],
2553
11.8M
                                 &outrow, dinfo->max_v_samp_factor);
2554
11.8M
  }
2555
2.07k
  jpeg_abort_decompress(dinfo);
2556
2557
2.10k
bailout:
2558
2.10k
  if (old_read_markers)
2559
2.10k
    dinfo->marker->read_markers = old_read_markers;
2560
2.10k
  if (old_reset_marker_reader)
2561
2.10k
    dinfo->marker->reset_marker_reader = old_reset_marker_reader;
2562
2.10k
  if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
2563
2.10k
  free(row_pointer);
2564
23.1k
  for (i = 0; i < MAX_COMPONENTS; i++) {
2565
21.0k
    free(tmpbuf[i]);
2566
21.0k
    free(_tmpbuf[i]);
2567
21.0k
    free(inbuf[i]);
2568
21.0k
  }
2569
2.10k
  if (this->jerr.warning) retval = -1;
2570
2.10k
  return retval;
2571
2.07k
}
2572
2573
/* TurboJPEG 1.4+ */
2574
DLLEXPORT int tjDecodeYUVPlanes(tjhandle handle,
2575
                                const unsigned char **srcPlanes,
2576
                                const int *strides, int subsamp,
2577
                                unsigned char *dstBuf, int width, int pitch,
2578
                                int height, int pixelFormat, int flags)
2579
0
{
2580
0
  static const char FUNCTION_NAME[] = "tjDecodeYUVPlanes";
2581
0
  int retval = 0;
2582
2583
0
  GET_TJINSTANCE(handle, -1);
2584
2585
0
  if (subsamp < 0 || subsamp >= TJ_NUMSAMP)
2586
0
    THROW("Invalid argument");
2587
2588
0
  this->subsamp = subsamp;
2589
0
  processFlags(handle, flags, DECOMPRESS);
2590
2591
0
  return tj3DecodeYUVPlanes8(handle, srcPlanes, strides, dstBuf, width, pitch,
2592
0
                             height, pixelFormat);
2593
2594
0
bailout:
2595
0
  return retval;
2596
0
}
2597
2598
2599
/* TurboJPEG 3+ */
2600
DLLEXPORT int tj3DecodeYUV8(tjhandle handle, const unsigned char *srcBuf,
2601
                            int align, unsigned char *dstBuf, int width,
2602
                            int pitch, int height, int pixelFormat)
2603
2.10k
{
2604
2.10k
  static const char FUNCTION_NAME[] = "tj3DecodeYUV8";
2605
2.10k
  const unsigned char *srcPlanes[3];
2606
2.10k
  int pw0, ph0, strides[3], retval = -1;
2607
2608
2.10k
  GET_TJINSTANCE(handle, -1);
2609
2610
2.10k
  if (srcBuf == NULL || align < 1 || !IS_POW2(align) || width <= 0 ||
2611
2.10k
      height <= 0)
2612
2.10k
    THROW("Invalid argument");
2613
2614
2.10k
  if (this->subsamp == TJSAMP_UNKNOWN)
2615
2.10k
    THROW("TJPARAM_SUBSAMP must be specified");
2616
2617
2.10k
  pw0 = tj3YUVPlaneWidth(0, width, this->subsamp);
2618
2.10k
  ph0 = tj3YUVPlaneHeight(0, height, this->subsamp);
2619
2.10k
  srcPlanes[0] = srcBuf;
2620
2.10k
  strides[0] = (int)PAD((unsigned long long)pw0, align);
2621
2.10k
  if (this->subsamp == TJSAMP_GRAY) {
2622
733
    strides[1] = strides[2] = 0;
2623
733
    srcPlanes[1] = srcPlanes[2] = NULL;
2624
1.37k
  } else {
2625
1.37k
    int pw1 = tj3YUVPlaneWidth(1, width, this->subsamp);
2626
1.37k
    int ph1 = tj3YUVPlaneHeight(1, height, this->subsamp);
2627
2628
1.37k
    strides[1] = strides[2] = (int)PAD((unsigned long long)pw1, align);
2629
1.37k
    if ((unsigned long long)strides[0] * (unsigned long long)ph0 >
2630
1.37k
        (unsigned long long)INT_MAX ||
2631
1.37k
        (unsigned long long)strides[1] * (unsigned long long)ph1 >
2632
1.37k
        (unsigned long long)INT_MAX)
2633
1.37k
      THROW("Image or row alignment is too large");
2634
1.37k
    srcPlanes[1] = srcPlanes[0] + strides[0] * ph0;
2635
1.37k
    srcPlanes[2] = srcPlanes[1] + strides[1] * ph1;
2636
1.37k
  }
2637
2638
2.10k
  return tj3DecodeYUVPlanes8(handle, srcPlanes, strides, dstBuf, width, pitch,
2639
2.10k
                             height, pixelFormat);
2640
2641
0
bailout:
2642
0
  return retval;
2643
2.10k
}
2644
2645
/* TurboJPEG 1.4+ */
2646
DLLEXPORT int tjDecodeYUV(tjhandle handle, const unsigned char *srcBuf,
2647
                          int align, int subsamp, unsigned char *dstBuf,
2648
                          int width, int pitch, int height, int pixelFormat,
2649
                          int flags)
2650
0
{
2651
0
  static const char FUNCTION_NAME[] = "tjDecodeYUV";
2652
0
  int retval = -1;
2653
2654
0
  GET_TJINSTANCE(handle, -1);
2655
2656
0
  if (subsamp < 0 || subsamp >= TJ_NUMSAMP)
2657
0
    THROW("Invalid argument");
2658
2659
0
  this->subsamp = subsamp;
2660
0
  processFlags(handle, flags, DECOMPRESS);
2661
2662
0
  return tj3DecodeYUV8(handle, srcBuf, align, dstBuf, width, pitch, height,
2663
0
                       pixelFormat);
2664
2665
0
bailout:
2666
0
  return retval;
2667
0
}
2668
2669
2670
/******************************** Transformer ********************************/
2671
2672
/* TurboJPEG 1.2+ */
2673
DLLEXPORT tjhandle tjInitTransform(void)
2674
0
{
2675
0
  return tj3Init(TJINIT_TRANSFORM);
2676
0
}
2677
2678
2679
/* TurboJPEG 3+ */
2680
DLLEXPORT int tj3Transform(tjhandle handle, const unsigned char *jpegBuf,
2681
                           size_t jpegSize, int n, unsigned char **dstBufs,
2682
                           size_t *dstSizes, const tjtransform *t)
2683
0
{
2684
0
  static const char FUNCTION_NAME[] = "tj3Transform";
2685
0
  int retval = 0;
2686
2687
0
#if TRANSFORMS_SUPPORTED
2688
2689
0
  jpeg_transform_info *xinfo = NULL;
2690
0
  jvirt_barray_ptr *srccoefs, *dstcoefs;
2691
0
  int i, saveMarkers = 0, srcSubsamp;
2692
0
  boolean alloc = TRUE;
2693
0
  struct my_progress_mgr progress;
2694
2695
0
  GET_INSTANCE(handle);
2696
0
  if ((this->init & COMPRESS) == 0 || (this->init & DECOMPRESS) == 0)
2697
0
    THROW("Instance has not been initialized for transformation");
2698
2699
0
  if (jpegBuf == NULL || jpegSize <= 0 || n < 1 || dstBufs == NULL ||
2700
0
      dstSizes == NULL || t == NULL)
2701
0
    THROW("Invalid argument");
2702
2703
0
  if (this->scanLimit) {
2704
0
    memset(&progress, 0, sizeof(struct my_progress_mgr));
2705
0
    progress.pub.progress_monitor = my_progress_monitor;
2706
0
    progress.this = this;
2707
0
    dinfo->progress = &progress.pub;
2708
0
  } else
2709
0
    dinfo->progress = NULL;
2710
2711
0
  dinfo->mem->max_memory_to_use = (long)this->maxMemory * 1048576L;
2712
2713
0
  if ((xinfo =
2714
0
       (jpeg_transform_info *)malloc(sizeof(jpeg_transform_info) * n)) == NULL)
2715
0
    THROW("Memory allocation failure");
2716
0
  memset(xinfo, 0, sizeof(jpeg_transform_info) * n);
2717
2718
0
  CATCH_LIBJPEG(this);
2719
2720
0
  if (dinfo->global_state <= DSTATE_INHEADER)
2721
0
    jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);
2722
2723
0
  for (i = 0; i < n; i++) {
2724
0
    if (t[i].op < 0 || t[i].op >= TJ_NUMXOP)
2725
0
      THROW("Invalid transform operation");
2726
0
    xinfo[i].transform = xformtypes[t[i].op];
2727
0
    xinfo[i].perfect = (t[i].options & TJXOPT_PERFECT) ? 1 : 0;
2728
0
    xinfo[i].trim = (t[i].options & TJXOPT_TRIM) ? 1 : 0;
2729
0
    xinfo[i].force_grayscale = (t[i].options & TJXOPT_GRAY) ? 1 : 0;
2730
0
    xinfo[i].crop = (t[i].options & TJXOPT_CROP) ? 1 : 0;
2731
0
    if (n != 1 && t[i].op == TJXOP_HFLIP) xinfo[i].slow_hflip = 1;
2732
0
    else xinfo[i].slow_hflip = 0;
2733
2734
0
    if (xinfo[i].crop) {
2735
0
      if (t[i].r.x < 0 || t[i].r.y < 0 || t[i].r.w < 0 || t[i].r.h < 0)
2736
0
        THROW("Invalid cropping region");
2737
0
      xinfo[i].crop_xoffset = t[i].r.x;  xinfo[i].crop_xoffset_set = JCROP_POS;
2738
0
      xinfo[i].crop_yoffset = t[i].r.y;  xinfo[i].crop_yoffset_set = JCROP_POS;
2739
0
      if (t[i].r.w != 0) {
2740
0
        xinfo[i].crop_width = t[i].r.w;  xinfo[i].crop_width_set = JCROP_POS;
2741
0
      } else
2742
0
        xinfo[i].crop_width = JCROP_UNSET;
2743
0
      if (t[i].r.h != 0) {
2744
0
        xinfo[i].crop_height = t[i].r.h;  xinfo[i].crop_height_set = JCROP_POS;
2745
0
      } else
2746
0
        xinfo[i].crop_height = JCROP_UNSET;
2747
0
    }
2748
0
    if (!(t[i].options & TJXOPT_COPYNONE)) saveMarkers = 1;
2749
0
  }
2750
2751
0
  jcopy_markers_setup(dinfo, saveMarkers ? JCOPYOPT_ALL : JCOPYOPT_NONE);
2752
0
  if (dinfo->global_state <= DSTATE_INHEADER)
2753
0
    jpeg_read_header(dinfo, TRUE);
2754
0
  if (this->maxPixels &&
2755
0
      (unsigned long long)dinfo->image_width * dinfo->image_height >
2756
0
      (unsigned long long)this->maxPixels)
2757
0
    THROW("Image is too large");
2758
0
  srcSubsamp = getSubsamp(&this->dinfo);
2759
2760
0
  for (i = 0; i < n; i++) {
2761
0
    if (!jtransform_request_workspace(dinfo, &xinfo[i]))
2762
0
      THROW("Transform is not perfect");
2763
2764
0
    if (xinfo[i].crop) {
2765
0
      int dstSubsamp = (t[i].options & TJXOPT_GRAY) ? TJSAMP_GRAY : srcSubsamp;
2766
2767
0
      if (t[i].op == TJXOP_TRANSPOSE || t[i].op == TJXOP_TRANSVERSE ||
2768
0
          t[i].op == TJXOP_ROT90 || t[i].op == TJXOP_ROT270) {
2769
0
        if (dstSubsamp == TJSAMP_422) dstSubsamp = TJSAMP_440;
2770
0
        else if (dstSubsamp == TJSAMP_440) dstSubsamp = TJSAMP_422;
2771
0
        else if (dstSubsamp == TJSAMP_411) dstSubsamp = TJSAMP_441;
2772
0
        else if (dstSubsamp == TJSAMP_441) dstSubsamp = TJSAMP_411;
2773
0
      }
2774
0
      if (dstSubsamp == TJSAMP_UNKNOWN)
2775
0
        THROW("Could not determine subsampling level of destination image");
2776
0
      if ((t[i].r.x % tjMCUWidth[dstSubsamp]) != 0 ||
2777
0
          (t[i].r.y % tjMCUHeight[dstSubsamp]) != 0)
2778
0
        THROWI("To crop this JPEG image, x must be a multiple of %d\n"
2779
0
               "and y must be a multiple of %d.", tjMCUWidth[dstSubsamp],
2780
0
               tjMCUHeight[dstSubsamp]);
2781
0
    }
2782
0
  }
2783
2784
0
  srccoefs = jpeg_read_coefficients(dinfo);
2785
2786
0
  for (i = 0; i < n; i++) {
2787
0
    JDIMENSION dstWidth = dinfo->image_width, dstHeight = dinfo->image_height;
2788
2789
0
    if (t[i].op == TJXOP_TRANSPOSE || t[i].op == TJXOP_TRANSVERSE ||
2790
0
        t[i].op == TJXOP_ROT90 || t[i].op == TJXOP_ROT270) {
2791
0
      dstWidth = dinfo->image_height;  dstHeight = dinfo->image_width;
2792
0
    }
2793
2794
0
    if (xinfo[i].crop) {
2795
0
      if ((JDIMENSION)t[i].r.x >= dstWidth ||
2796
0
          t[i].r.x + xinfo[i].crop_width > dstWidth ||
2797
0
          (JDIMENSION)t[i].r.y >= dstHeight ||
2798
0
          t[i].r.y + xinfo[i].crop_height > dstHeight)
2799
0
        THROW("The cropping region exceeds the destination image dimensions");
2800
0
      dstWidth = xinfo[i].crop_width;  dstHeight = xinfo[i].crop_height;
2801
0
    }
2802
0
    if (this->noRealloc) {
2803
0
      int dstSubsamp = (t[i].options & TJXOPT_GRAY) ? TJSAMP_GRAY : srcSubsamp;
2804
2805
0
      if (t[i].op == TJXOP_TRANSPOSE || t[i].op == TJXOP_TRANSVERSE ||
2806
0
          t[i].op == TJXOP_ROT90 || t[i].op == TJXOP_ROT270) {
2807
0
        if (dstSubsamp == TJSAMP_422) dstSubsamp = TJSAMP_440;
2808
0
        else if (dstSubsamp == TJSAMP_440) dstSubsamp = TJSAMP_422;
2809
0
        else if (dstSubsamp == TJSAMP_411) dstSubsamp = TJSAMP_441;
2810
0
        else if (dstSubsamp == TJSAMP_441) dstSubsamp = TJSAMP_411;
2811
0
      }
2812
0
      if (dstSubsamp == TJSAMP_UNKNOWN)
2813
0
        THROW("Could not determine subsampling level of destination image");
2814
0
      alloc = FALSE;
2815
0
      dstSizes[i] = tj3JPEGBufSize(dstWidth, dstHeight, dstSubsamp);
2816
0
    }
2817
0
    if (!(t[i].options & TJXOPT_NOOUTPUT))
2818
0
      jpeg_mem_dest_tj(cinfo, &dstBufs[i], &dstSizes[i], alloc);
2819
0
    jpeg_copy_critical_parameters(dinfo, cinfo);
2820
0
    dstcoefs = jtransform_adjust_parameters(dinfo, cinfo, srccoefs, &xinfo[i]);
2821
0
    if (this->optimize || t[i].options & TJXOPT_OPTIMIZE)
2822
0
      cinfo->optimize_coding = TRUE;
2823
0
#ifdef C_PROGRESSIVE_SUPPORTED
2824
0
    if (this->progressive || t[i].options & TJXOPT_PROGRESSIVE)
2825
0
      jpeg_simple_progression(cinfo);
2826
0
#endif
2827
0
    if (this->arithmetic || t[i].options & TJXOPT_ARITHMETIC) {
2828
0
      cinfo->arith_code = TRUE;
2829
0
      cinfo->optimize_coding = FALSE;
2830
0
    }
2831
0
    if (!(t[i].options & TJXOPT_NOOUTPUT)) {
2832
0
      jpeg_write_coefficients(cinfo, dstcoefs);
2833
0
      jcopy_markers_execute(dinfo, cinfo, t[i].options & TJXOPT_COPYNONE ?
2834
0
                                          JCOPYOPT_NONE : JCOPYOPT_ALL);
2835
0
    } else
2836
0
      jinit_c_master_control(cinfo, TRUE);
2837
0
    jtransform_execute_transformation(dinfo, cinfo, srccoefs, &xinfo[i]);
2838
0
    if (t[i].customFilter) {
2839
0
      int ci, y;
2840
0
      JDIMENSION by;
2841
2842
0
      for (ci = 0; ci < cinfo->num_components; ci++) {
2843
0
        jpeg_component_info *compptr = &cinfo->comp_info[ci];
2844
0
        tjregion arrayRegion = { 0, 0, 0, 0 };
2845
0
        tjregion planeRegion = { 0, 0, 0, 0 };
2846
2847
0
        arrayRegion.w = compptr->width_in_blocks * DCTSIZE;
2848
0
        arrayRegion.h = DCTSIZE;
2849
0
        planeRegion.w = compptr->width_in_blocks * DCTSIZE;
2850
0
        planeRegion.h = compptr->height_in_blocks * DCTSIZE;
2851
2852
0
        for (by = 0; by < compptr->height_in_blocks;
2853
0
             by += compptr->v_samp_factor) {
2854
0
          JBLOCKARRAY barray = (dinfo->mem->access_virt_barray)
2855
0
            ((j_common_ptr)dinfo, dstcoefs[ci], by, compptr->v_samp_factor,
2856
0
             TRUE);
2857
2858
0
          for (y = 0; y < compptr->v_samp_factor; y++) {
2859
0
            if (t[i].customFilter(barray[y][0], arrayRegion, planeRegion, ci,
2860
0
                                  i, (tjtransform *)&t[i]) == -1)
2861
0
              THROW("Error in custom filter");
2862
0
            arrayRegion.y += DCTSIZE;
2863
0
          }
2864
0
        }
2865
0
      }
2866
0
    }
2867
0
    if (!(t[i].options & TJXOPT_NOOUTPUT)) jpeg_finish_compress(cinfo);
2868
0
  }
2869
2870
0
  jpeg_finish_decompress(dinfo);
2871
2872
0
bailout:
2873
0
  if (cinfo->global_state > CSTATE_START) {
2874
0
    if (alloc) (*cinfo->dest->term_destination) (cinfo);
2875
0
    jpeg_abort_compress(cinfo);
2876
0
  }
2877
0
  if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo);
2878
0
  free(xinfo);
2879
0
  if (this->jerr.warning) retval = -1;
2880
0
  return retval;
2881
2882
#else /* TRANSFORMS_SUPPORTED */
2883
2884
  GET_TJINSTANCE(handle, -1)
2885
  THROW("Lossless transformations were disabled at build time")
2886
bailout:
2887
  return retval;
2888
2889
#endif
2890
0
}
2891
2892
/* TurboJPEG 1.2+ */
2893
DLLEXPORT int tjTransform(tjhandle handle, const unsigned char *jpegBuf,
2894
                          unsigned long jpegSize, int n,
2895
                          unsigned char **dstBufs, unsigned long *dstSizes,
2896
                          tjtransform *t, int flags)
2897
0
{
2898
0
  static const char FUNCTION_NAME[] = "tjTransform";
2899
0
  int i, retval = 0;
2900
0
  size_t *sizes = NULL;
2901
2902
0
  GET_TJINSTANCE(handle, -1);
2903
0
  if ((this->init & DECOMPRESS) == 0)
2904
0
    THROW("Instance has not been initialized for decompression");
2905
2906
0
  if (n < 1 || dstSizes == NULL)
2907
0
    THROW("Invalid argument");
2908
2909
0
  if ((sizes = (size_t *)malloc(n * sizeof(size_t))) == NULL)
2910
0
    THROW("Memory allocation failure");
2911
0
  for (i = 0; i < n; i++)
2912
0
    sizes[i] = (size_t)dstSizes[i];
2913
0
  retval = tj3Transform(handle, jpegBuf, (size_t)jpegSize, n, dstBufs, sizes,
2914
0
                        t);
2915
0
  for (i = 0; i < n; i++)
2916
0
    dstSizes[i] = (unsigned long)sizes[i];
2917
2918
0
bailout:
2919
0
  free(sizes);
2920
0
  return retval;
2921
0
}
2922
2923
2924
/*************************** Packed-Pixel Image I/O **************************/
2925
2926
/* tj3LoadImage*() is implemented in turbojpeg-mp.c */
2927
2928
/* TurboJPEG 2.0+ */
2929
DLLEXPORT unsigned char *tjLoadImage(const char *filename, int *width,
2930
                                     int align, int *height,
2931
                                     int *pixelFormat, int flags)
2932
0
{
2933
0
  tjhandle handle = NULL;
2934
0
  unsigned char *dstBuf = NULL;
2935
2936
0
  if ((handle = tj3Init(TJINIT_COMPRESS)) == NULL) return NULL;
2937
2938
0
  processFlags(handle, flags, COMPRESS);
2939
2940
0
  dstBuf = tj3LoadImage8(handle, filename, width, align, height, pixelFormat);
2941
2942
0
  tj3Destroy(handle);
2943
0
  return dstBuf;
2944
0
}
2945
2946
2947
/* tj3SaveImage*() is implemented in turbojpeg-mp.c */
2948
2949
/* TurboJPEG 2.0+ */
2950
DLLEXPORT int tjSaveImage(const char *filename, unsigned char *buffer,
2951
                          int width, int pitch, int height, int pixelFormat,
2952
                          int flags)
2953
0
{
2954
0
  tjhandle handle = NULL;
2955
0
  int retval = -1;
2956
2957
0
  if ((handle = tj3Init(TJINIT_DECOMPRESS)) == NULL) return -1;
2958
2959
0
  processFlags(handle, flags, DECOMPRESS);
2960
2961
0
  retval = tj3SaveImage8(handle, filename, buffer, width, pitch, height,
2962
0
                         pixelFormat);
2963
2964
0
  tj3Destroy(handle);
2965
0
  return retval;
2966
0
}