Debian Codegraph @

java/org/libjpegturbo/turbojpeg/TJDecompressor.java

raw
1 /*
2 * Copyright (C)2011-2015, 2018, 2022-2024 D. R. Commander.
3 * All Rights Reserved.
4 * Copyright (C)2015 Viktor Szathmáry. All Rights Reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * - Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 * - Neither the name of the libjpeg-turbo Project nor the names of its
15 * contributors may be used to endorse or promote products derived from this
16 * software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 package org.libjpegturbo.turbojpeg;
32
33 import java.awt.Rectangle;
34 import java.awt.image.*;
35 import java.nio.*;
36 import java.io.*;
37
38 /**
39 * TurboJPEG decompressor
40 */
41 public class TJDecompressor implements Closeable {
42
43 private static final String NO_ASSOC_ERROR =
44 "No JPEG image is associated with this instance";
45
46 /**
47 * Create a TurboJPEG decompresssor instance.
48 */
49 public TJDecompressor() throws TJException {
50 init();
51 }
52
53 /**
54 * Create a TurboJPEG decompressor instance and associate the JPEG source
55 * image or "abbreviated table specification" (AKA "tables-only") datastream
56 * stored in <code>jpegImage</code> with the newly created instance. Refer
57 * to {@link #setSourceImage(byte[], int)} for more details.
58 *
59 * @param jpegImage buffer containing a JPEG source image or tables-only
60 * datastream. (The size of the JPEG image or datastream is assumed to be
61 * the length of the array.) This buffer is not modified.
62 */
63 public TJDecompressor(byte[] jpegImage) throws TJException {
64 init();
65 setSourceImage(jpegImage, jpegImage.length);
66 }
67
68 /**
69 * Create a TurboJPEG decompressor instance and associate the JPEG source
70 * image or "abbreviated table specification" (AKA "tables-only") datastream
71 * of length <code>imageSize</code> bytes stored in <code>jpegImage</code>
72 * with the newly created instance. Refer to
73 * {@link #setSourceImage(byte[], int)} for more details.
74 *
75 * @param jpegImage buffer containing a JPEG source image or tables-only
76 * datastream. This buffer is not modified.
77 *
78 * @param imageSize size of the JPEG source image or tables-only datastream
79 * (in bytes)
80 */
81 public TJDecompressor(byte[] jpegImage, int imageSize) throws TJException {
82 init();
83 setSourceImage(jpegImage, imageSize);
84 }
85
86 /**
87 * Create a TurboJPEG decompressor instance and associate the
88 * 8-bit-per-sample planar YUV source image stored in <code>yuvImage</code>
89 * with the newly created instance. Refer to
90 * {@link #setSourceImage(YUVImage)} for more details.
91 *
92 * @param yuvImage {@link YUVImage} instance containing a planar YUV source
93 * image to be decoded. This image is not modified.
94 */
95 @SuppressWarnings("checkstyle:HiddenField")
96 public TJDecompressor(YUVImage yuvImage) throws TJException {
97 init();
98 setSourceImage(yuvImage);
99 }
100
101 /**
102 * Associate the JPEG image or "abbreviated table specification" (AKA
103 * "tables-only") datastream of length <code>imageSize</code> bytes stored in
104 * <code>jpegImage</code> with this decompressor instance. If
105 * <code>jpegImage</code> contains a JPEG image, then this image will be used
106 * as the source image for subsequent decompression operations. Passing a
107 * tables-only datastream to this method primes the decompressor with
108 * quantization and Huffman tables that can be used when decompressing
109 * subsequent "abbreviated image" datastreams. This is useful, for instance,
110 * when decompressing video streams in which all frames share the same
111 * quantization and Huffman tables. If a JPEG image is passed to this
112 * method, then the {@link TJ#PARAM_STOPONWARNING parameters} that describe
113 * the JPEG image will be set when the method returns. If a JPEG image is
114 * passed to this method and {@link TJ#PARAM_SAVEMARKERS} is set to
115 * <code>2</code> or <code>4</code>, then the ICC profile (if any) will be
116 * extracted from the JPEG image. ({@link #getICCProfile()} can then be used
117 * to retrieve the profile.)
118 *
119 * @param jpegImage buffer containing a JPEG source image or tables-only
120 * datastream. This buffer is not modified.
121 *
122 * @param imageSize size of the JPEG source image or tables-only datastream
123 * (in bytes)
124 */
125 public void setSourceImage(byte[] jpegImage, int imageSize)
126 throws TJException {
127 if (jpegImage == null || imageSize < 1)
128 throw new IllegalArgumentException("Invalid argument in setSourceImage()");
129 jpegBuf = jpegImage;
130 jpegBufSize = imageSize;
131 decompressHeader(jpegBuf, jpegBufSize);
132 yuvImage = null;
133 }
134
135 /**
136 * Associate the specified planar YUV source image with this decompressor
137 * instance. Subsequent decompression operations will decode this image into
138 * a packed-pixel RGB or grayscale destination image. This method sets
139 * {@link TJ#PARAM_SUBSAMP} to the chrominance subsampling level of the
140 * source image.
141 *
142 * @param srcImage {@link YUVImage} instance containing a planar YUV source
143 * image to be decoded. This image is not modified.
144 */
145 public void setSourceImage(YUVImage srcImage) {
146 if (srcImage == null)
147 throw new IllegalArgumentException("Invalid argument in setSourceImage()");
148 yuvImage = srcImage;
149 set(TJ.PARAM_SUBSAMP, srcImage.getSubsamp());
150 jpegBuf = null;
151 jpegBufSize = 0;
152 }
153
154
155 /**
156 * Returns the width of the source image (JPEG or YUV) associated with this
157 * decompressor instance.
158 *
159 * @return the width of the source image (JPEG or YUV) associated with this
160 * decompressor instance.
161 */
162 public int getWidth() {
163 if (yuvImage != null)
164 return yuvImage.getWidth();
165 return getJPEGWidth();
166 }
167
168 private int getJPEGWidth() {
169 int jpegWidth = get(TJ.PARAM_JPEGWIDTH);
170 if (jpegWidth < 1)
171 throw new IllegalStateException(NO_ASSOC_ERROR);
172 return jpegWidth;
173 }
174
175 /**
176 * Returns the height of the source image (JPEG or YUV) associated with this
177 * decompressor instance.
178 *
179 * @return the height of the source image (JPEG or YUV) associated with this
180 * decompressor instance.
181 */
182 public int getHeight() {
183 if (yuvImage != null)
184 return yuvImage.getHeight();
185 return getJPEGHeight();
186 }
187
188 private int getJPEGHeight() {
189 int jpegHeight = get(TJ.PARAM_JPEGHEIGHT);
190 if (jpegHeight < 1)
191 throw new IllegalStateException(NO_ASSOC_ERROR);
192 return jpegHeight;
193 }
194
195 /**
196 * Set the value of a decompression parameter.
197 *
198 * @param param one of {@link TJ#PARAM_STOPONWARNING TJ.PARAM_*}
199 *
200 * @param value value of the decompression parameter (refer to
201 * {@link TJ#PARAM_STOPONWARNING parameter documentation})
202 */
203 public native void set(int param, int value);
204
205 /**
206 * Get the value of a decompression parameter.
207 *
208 * @param param one of {@link TJ#PARAM_STOPONWARNING TJ.PARAM_*}
209 *
210 * @return the value of the specified decompression parameter, or -1 if the
211 * value is unknown.
212 */
213 public native int get(int param);
214
215 /**
216 * Retrieve the ICC (International Color Consortium) color management profile
217 * (if any) that was previously extracted from the JPEG image associated with
218 * this decompressor instance (see {@link #setSourceImage(byte[], int)}), and
219 * return a buffer containing the ICC profile. Once the ICC profile is
220 * retrieved, it must be re-extracted before it can be retrieved again.
221 *
222 * @return a buffer containing the ICC profile
223 */
224 public native byte[] getICCProfile() throws TJException;
225
226 /**
227 * Returns the size of the ICC profile (if any) that was previously extracted
228 * from the JPEG image associated with this decompressor instance
229 * (see {@link #setSourceImage(byte[], int)}), or 0 if there is no ICC
230 * profile to retrieve.
231 *
232 * @return the size of the ICC profile (if any) that was previously extracted
233 * from the JPEG image associated with this decompressor instance
234 * (see {@link #setSourceImage(byte[], int)}), or 0 if there is no ICC
235 * profile to retrieve.
236 */
237 public native int getICCSize();
238
239 /**
240 * Set the scaling factor for subsequent lossy decompression operations.
241 *
242 * @param scalingFactor {@link TJScalingFactor} instance that specifies a
243 * fractional scaling factor that the decompressor supports (see
244 * {@link TJ#getScalingFactors}), or {@link TJ#UNSCALED} for no scaling.
245 * Decompression scaling is a function of the IDCT algorithm, so scaling
246 * factors are generally limited to multiples of 1/8. If the entire JPEG
247 * image will be decompressed, then the width and height of the scaled
248 * destination image can be determined by calling
249 * <code>scalingFactor.</code>{@link TJScalingFactor#getScaled getScaled()}
250 * with the JPEG image width and height (see {@link #getWidth} and
251 * {@link #getHeight}.) When decompressing into a planar YUV image, an
252 * intermediate buffer copy will be performed if the width or height of the
253 * scaled destination image is not an even multiple of the iMCU size (see
254 * {@link TJ#getMCUWidth TJ.getMCUWidth()} and {@link TJ#getMCUHeight
255 * TJ.getMCUHeight()}.) Note that decompression scaling is not available
256 * (and the specified scaling factor is ignored) when decompressing lossless
257 * JPEG images (see {@link TJ#PARAM_LOSSLESS}), since the IDCT algorithm is
258 * not used with those images. Note also that {@link TJ#PARAM_FASTDCT} is
259 * ignored when decompression scaling is enabled.
260 */
261 @SuppressWarnings("checkstyle:HiddenField")
262 public void setScalingFactor(TJScalingFactor scalingFactor) {
263 if (scalingFactor == null)
264 throw new IllegalArgumentException("Invalid argument in setScalingFactor()");
265
266 TJScalingFactor[] sf = TJ.getScalingFactors();
267 int i;
268 for (i = 0; i < sf.length; i++) {
269 if (scalingFactor.getNum() == sf[i].getNum() &&
270 scalingFactor.getDenom() == sf[i].getDenom())
271 break;
272 }
273 if (i >= sf.length)
274 throw new IllegalArgumentException("Unsupported scaling factor");
275
276 this.scalingFactor = scalingFactor;
277 }
278
279 /**
280 * Set the cropping region for partially decompressing a lossy JPEG image
281 * into a packed-pixel image.
282 *
283 * @param croppingRegion <code>java.awt.Rectangle</code> instance that
284 * specifies a subregion of the JPEG image to decompress, or
285 * {@link TJ#UNCROPPED} for no cropping. The left boundary of the cropping
286 * region must be evenly divisible by the scaled iMCU width, which can be
287 * determined by calling {@link TJScalingFactor#getScaled
288 * TJScalingFactor.getScaled()} with the specified scaling factor (see
289 * {@link #setScalingFactor setScalingFactor()}) and the iMCU width (see
290 * {@link TJ#getMCUWidth TJ.getMCUWidth()}) for the level of chrominance
291 * subsampling in the JPEG image (see {@link TJ#PARAM_SUBSAMP}.) The
292 * cropping region should be specified relative to the scaled image
293 * dimensions. Unless <code>croppingRegion</code> is {@link TJ#UNCROPPED},
294 * the JPEG header must be read (see {@link #setSourceImage(byte[], int)})
295 * prior to calling this method.
296 */
297 @SuppressWarnings("checkstyle:HiddenField")
298 public void setCroppingRegion(Rectangle croppingRegion) throws TJException {
299 this.croppingRegion = croppingRegion;
300 setCroppingRegion();
301 }
302
303 /**
304 * Returns the JPEG buffer associated with this decompressor instance.
305 *
306 * @return the JPEG buffer associated with this decompressor instance.
307 */
308 public byte[] getJPEGBuf() {
309 if (jpegBuf == null)
310 throw new IllegalStateException(NO_ASSOC_ERROR);
311 return jpegBuf;
312 }
313
314 /**
315 * Returns the size of the JPEG image (in bytes) associated with this
316 * decompressor instance.
317 *
318 * @return the size of the JPEG image (in bytes) associated with this
319 * decompressor instance.
320 */
321 public int getJPEGSize() {
322 if (jpegBufSize < 1)
323 throw new IllegalStateException(NO_ASSOC_ERROR);
324 return jpegBufSize;
325 }
326
327 private TJScalingFactor getScalingFactor(int desiredWidth,
328 int desiredHeight) {
329 int jpegWidth = getJPEGWidth();
330 int jpegHeight = getJPEGHeight();
331 if (desiredWidth < 0 || desiredHeight < 0)
332 throw new IllegalArgumentException("Invalid argument");
333
334 TJScalingFactor[] sf = TJ.getScalingFactors();
335
336 if (desiredWidth == 0)
337 desiredWidth = jpegWidth;
338 if (desiredHeight == 0)
339 desiredHeight = jpegHeight;
340 int i;
341 for (i = 0; i < sf.length; i++) {
342 if (sf[i].getScaled(jpegWidth) <= desiredWidth &&
343 sf[i].getScaled(jpegHeight) <= desiredHeight)
344 break;
345 }
346 if (i >= sf.length)
347 throw new IllegalArgumentException("Could not scale down to desired image dimensions");
348
349 return sf[i];
350 }
351
352 /**
353 * Decompress the JPEG source image with 2 to 8 bits per sample, or decode
354 * the 8-bit-per-sample planar YUV source image, associated with this
355 * decompressor instance and output a packed-pixel grayscale, RGB, or CMYK
356 * image with the same data precision to the given destination buffer.
357 *
358 * <p>NOTE: The destination image is fully recoverable if this method throws
359 * a non-fatal {@link TJException} (unless {@link TJ#PARAM_STOPONWARNING} is
360 * set.)
361 *
362 * @param dstBuf buffer that will receive the packed-pixel
363 * decompressed/decoded image. This buffer should normally be
364 * <code>pitch * destinationHeight</code> bytes in size. However, the buffer
365 * may also be larger, in which case the <code>x</code>, <code>y</code>, and
366 * <code>pitch</code> parameters can be used to specify the region into which
367 * the source image should be decompressed/decoded. NOTE: If the source
368 * image is a lossy JPEG image, then <code>destinationHeight</code> is either
369 * the scaled JPEG height (see {@link #setScalingFactor setScalingFactor()},
370 * {@link TJScalingFactor#getScaled TJScalingFactor.getScaled()}, and
371 * {@link #getHeight}) or the height of the cropping region (see
372 * {@link #setCroppingRegion setCroppingRegion()}.) If the source image is a
373 * YUV image or a lossless JPEG image, then <code>destinationHeight</code> is
374 * the height of the source image.
375 *
376 * @param x x offset (in pixels) of the region in the destination image into
377 * which the source image should be decompressed/decoded
378 *
379 * @param y y offset (in pixels) of the region in the destination image into
380 * which the source image should be decompressed/decoded
381 *
382 * @param pitch bytes per row in the destination image. Normally this should
383 * be set to <code>destinationWidth *
384 * {@link TJ#getPixelSize TJ.getPixelSize}(pixelFormat)</code>, if the
385 * destination image will be unpadded. (Setting this parameter to 0 is the
386 * equivalent of setting it to <code>destinationWidth *
387 * {@link TJ#getPixelSize TJ.getPixelSize}(pixelFormat)</code>.) However,
388 * you can also use this parameter to specify the row alignment/padding of
389 * the destination image, to skip rows, or to decompress/decode into a
390 * specific region of a larger image. NOTE: If the source image is a lossy
391 * JPEG image, then <code>destinationWidth</code> is either the scaled JPEG
392 * width (see {@link #setScalingFactor setScalingFactor()},
393 * {@link TJScalingFactor#getScaled TJScalingFactor.getScaled()}, and
394 * {@link #getWidth}) or the width of the cropping region (see
395 * {@link #setCroppingRegion setCroppingRegion()}.) If the source image is a
396 * YUV image or a lossless JPEG image, then <code>destinationWidth</code> is
397 * the width of the source image.
398 *
399 * @param pixelFormat pixel format of the decompressed/decoded image (one of
400 * {@link TJ#PF_RGB TJ.PF_*})
401 */
402 public void decompress8(byte[] dstBuf, int x, int y, int pitch,
403 int pixelFormat) throws TJException {
404 if (jpegBuf == null && yuvImage == null)
405 throw new IllegalStateException("No source image is associated with this instance");
406 if (dstBuf == null || x < 0 || y < 0 || pitch < 0 || pixelFormat < 0 ||
407 pixelFormat >= TJ.NUMPF)
408 throw new IllegalArgumentException("Invalid argument in decompress8()");
409 if (yuvImage != null) {
410 checkSubsampling();
411 decodeYUV8(yuvImage.getPlanes(), yuvImage.getOffsets(),
412 yuvImage.getStrides(), dstBuf, x, y, yuvImage.getWidth(),
413 pitch, yuvImage.getHeight(), pixelFormat);
414 } else
415 decompress8(jpegBuf, jpegBufSize, dstBuf, x, y, pitch, pixelFormat);
416 }
417
418 /**
419 * Decompress the JPEG source image with 2 to 8 bits per sample, or decode
420 * the 8-bit-per-sample planar YUV source image, associated with this
421 * decompressor instance and return a buffer containing a packed-pixel
422 * decompressed image with the same data precision.
423 *
424 * @param pitch see
425 * {@link #decompress8(byte[], int, int, int, int)} for description
426 *
427 * @param pixelFormat pixel format of the decompressed image (one of
428 * {@link TJ#PF_RGB TJ.PF_*})
429 *
430 * @return a buffer containing a packed-pixel decompressed image with 2 to 8
431 * bits of data precision per sample.
432 */
433 public byte[] decompress8(int pitch, int pixelFormat) throws TJException {
434 if (pitch < 0 || pixelFormat < 0 || pixelFormat >= TJ.NUMPF)
435 throw new IllegalArgumentException("Invalid argument in decompress8()");
436 int pixelSize = TJ.getPixelSize(pixelFormat);
437 int scaledWidth = scalingFactor.getScaled(getJPEGWidth());
438 int scaledHeight = scalingFactor.getScaled(getJPEGHeight());
439 if (pitch == 0)
440 pitch = scaledWidth * pixelSize;
441 byte[] buf = new byte[pitch * scaledHeight];
442 decompress8(buf, 0, 0, pitch, pixelFormat);
443 return buf;
444 }
445
446 /**
447 * Decompress the JPEG source image with 9 to 12 bits per sample associated
448 * with this decompressor instance and output a packed-pixel grayscale, RGB,
449 * or CMYK image with the same data precision to the given destination
450 * buffer.
451 *
452 * <p>NOTE: The destination image is fully recoverable if this method throws
453 * a non-fatal {@link TJException} (unless {@link TJ#PARAM_STOPONWARNING} is
454 * set.)
455 *
456 * @param dstBuf buffer that will receive the packed-pixel
457 * decompressed image. This buffer should normally be
458 * <code>pitch * destinationHeight</code> samples in size. However, the
459 * buffer may also be larger, in which case the <code>x</code>,
460 * <code>y</code>, and <code>pitch</code> parameters can be used to specify
461 * the region into which the source image should be decompressed. NOTE: If
462 * the source image is a lossy JPEG image, then
463 * <code>destinationHeight</code> is either the scaled JPEG height (see
464 * {@link #setScalingFactor setScalingFactor()},
465 * {@link TJScalingFactor#getScaled TJScalingFactor.getScaled()}, and
466 * {@link #getHeight}) or the height of the cropping region (see
467 * {@link #setCroppingRegion setCroppingRegion()}.) If the source image is a
468 * lossless JPEG image, then <code>destinationHeight</code> is the height of
469 * the source image.
470 *
471 * @param x x offset (in pixels) of the region in the destination image into
472 * which the source image should be decompressed
473 *
474 * @param y y offset (in pixels) of the region in the destination image into
475 * which the source image should be decompressed
476 *
477 * @param pitch samples per row in the destination image. Normally this
478 * should be set to <code>destinationWidth *
479 * {@link TJ#getPixelSize TJ.getPixelSize}(pixelFormat)</code>, if the
480 * destination image will be unpadded. (Setting this parameter to 0 is the
481 * equivalent of setting it to <code>destinationWidth *
482 * {@link TJ#getPixelSize TJ.getPixelSize}(pixelFormat)</code>.) However,
483 * you can also use this parameter to specify the row alignment/padding of
484 * the destination image, to skip rows, or to decompress into a specific
485 * region of a larger image. NOTE: If the source image is a lossy JPEG
486 * image, then <code>destinationWidth</code> is either the scaled JPEG width
487 * (see {@link #setScalingFactor setScalingFactor()},
488 * {@link TJScalingFactor#getScaled TJScalingFactor.getScaled()}, and
489 * {@link #getWidth}) or the width of the cropping region (see
490 * {@link #setCroppingRegion setCroppingRegion()}.) If the source image is a
491 * YUV image or a lossless JPEG image, then <code>destinationWidth</code> is
492 * the width of the source image.
493 *
494 * @param pixelFormat pixel format of the decompressed image (one of
495 * {@link TJ#PF_RGB TJ.PF_*})
496 */
497 public void decompress12(short[] dstBuf, int x, int y, int pitch,
498 int pixelFormat) throws TJException {
499 if (jpegBuf == null)
500 throw new IllegalStateException(NO_ASSOC_ERROR);
501 if (dstBuf == null || x < 0 || y < 0 || pitch < 0 || pixelFormat < 0 ||
502 pixelFormat >= TJ.NUMPF)
503 throw new IllegalArgumentException("Invalid argument in decompress12()");
504 decompress12(jpegBuf, jpegBufSize, dstBuf, x, y, pitch, pixelFormat);
505 }
506
507 /**
508 * Decompress the JPEG source image with 9 to 12 bits per sample associated
509 * with this decompressor instance and return a buffer containing a
510 * packed-pixel decompressed image with the same data precision.
511 *
512 * @param pitch see
513 * {@link #decompress12(short[], int, int, int, int)} for description
514 *
515 * @param pixelFormat pixel format of the decompressed image (one of
516 * {@link TJ#PF_RGB TJ.PF_*})
517 *
518 * @return a buffer containing a packed-pixel decompressed image with 9 to 12
519 * bits of data precision per sample.
520 */
521 public short[] decompress12(int pitch, int pixelFormat) throws TJException {
522 if (pitch < 0 || pixelFormat < 0 || pixelFormat >= TJ.NUMPF)
523 throw new IllegalArgumentException("Invalid argument in decompress12()");
524 int pixelSize = TJ.getPixelSize(pixelFormat);
525 int scaledWidth = scalingFactor.getScaled(getJPEGWidth());
526 int scaledHeight = scalingFactor.getScaled(getJPEGHeight());
527 if (pitch == 0)
528 pitch = scaledWidth * pixelSize;
529 short[] buf = new short[pitch * scaledHeight];
530 decompress12(buf, 0, 0, pitch, pixelFormat);
531 return buf;
532 }
533
534 /**
535 * Decompress the JPEG source image with 13 to 16 bits per sample associated
536 * with this decompressor instance and output a packed-pixel grayscale, RGB,
537 * or CMYK image with the same data precision to the given destination
538 * buffer.
539 *
540 * <p>NOTE: The destination image is fully recoverable if this method throws
541 * a non-fatal {@link TJException} (unless {@link TJ#PARAM_STOPONWARNING} is
542 * set.)
543 *
544 * @param dstBuf buffer that will receive the packed-pixel
545 * decompressed image. This buffer should normally be
546 * <code>pitch * jpegHeight</code> samples in size. However, the buffer may
547 * also be larger, in which case the <code>x</code>,
548 * <code>y</code>, and <code>pitch</code> parameters can be used to specify
549 * the region into which the source image should be decompressed.
550 *
551 * @param x x offset (in pixels) of the region in the destination image into
552 * which the source image should be decompressed
553 *
554 * @param y y offset (in pixels) of the region in the destination image into
555 * which the source image should be decompressed
556 *
557 * @param pitch samples per row in the destination image. Normally this
558 * should be set to <code>jpegWidth *
559 * {@link TJ#getPixelSize TJ.getPixelSize}(pixelFormat)</code>, if the
560 * destination image will be unpadded. (Setting this parameter to 0 is the
561 * equivalent of setting it to <code>jpegWidth *
562 * {@link TJ#getPixelSize TJ.getPixelSize}(pixelFormat)</code>.) However,
563 * you can also use this parameter to specify the row alignment/padding of
564 * the destination image, to skip rows, or to decompress into a specific
565 * region of a larger image.
566 *
567 * @param pixelFormat pixel format of the decompressed image (one of
568 * {@link TJ#PF_RGB TJ.PF_*})
569 */
570 public void decompress16(short[] dstBuf, int x, int y, int pitch,
571 int pixelFormat) throws TJException {
572 if (jpegBuf == null)
573 throw new IllegalStateException(NO_ASSOC_ERROR);
574 if (dstBuf == null || x < 0 || y < 0 || pitch < 0 || pixelFormat < 0 ||
575 pixelFormat >= TJ.NUMPF)
576 throw new IllegalArgumentException("Invalid argument in decompress16()");
577 decompress16(jpegBuf, jpegBufSize, dstBuf, x, y, pitch, pixelFormat);
578 }
579
580 /**
581 * Decompress the JPEG source image with 13 to 16 bits per sample associated
582 * with this decompressor instance and return a buffer containing a
583 * packed-pixel decompressed image with the same data precision.
584 *
585 * @param pitch see
586 * {@link #decompress16(short[], int, int, int, int)} for description
587 *
588 * @param pixelFormat pixel format of the decompressed image (one of
589 * {@link TJ#PF_RGB TJ.PF_*})
590 *
591 * @return a buffer containing a packed-pixel decompressed image with 13 to
592 * 16 bits of data precision per sample.
593 */
594 public short[] decompress16(int pitch, int pixelFormat) throws TJException {
595 if (pitch < 0 || pixelFormat < 0 || pixelFormat >= TJ.NUMPF)
596 throw new IllegalArgumentException("Invalid argument in decompress16()");
597 int pixelSize = TJ.getPixelSize(pixelFormat);
598 int scaledWidth = scalingFactor.getScaled(getJPEGWidth());
599 int scaledHeight = scalingFactor.getScaled(getJPEGHeight());
600 if (pitch == 0)
601 pitch = scaledWidth * pixelSize;
602 short[] buf = new short[pitch * scaledHeight];
603 decompress16(buf, 0, 0, pitch, pixelFormat);
604 return buf;
605 }
606
607 /**
608 * Decompress the 8-bit-per-sample JPEG source image associated with this
609 * decompressor instance into an 8-bit-per-sample planar YUV image and store
610 * it in the given {@link YUVImage} instance. This method performs JPEG
611 * decompression but leaves out the color conversion step, so a planar YUV
612 * image is generated instead of a packed-pixel image. This method cannot be
613 * used to decompress JPEG source images with the CMYK or YCCK colorspace.
614 *
615 * <p>NOTE: The planar YUV destination image is fully recoverable if this
616 * method throws a non-fatal {@link TJException} (unless
617 * {@link TJ#PARAM_STOPONWARNING} is set.)
618 *
619 * @param dstImage {@link YUVImage} instance that will receive the planar YUV
620 * decompressed image. The level of subsampling specified in this
621 * {@link YUVImage} instance must match that of the JPEG image, and the width
622 * and height specified in the {@link YUVImage} instance must match the
623 * scaled JPEG width and height (see {@link #setScalingFactor
624 * setScalingFactor()}, {@link TJScalingFactor#getScaled
625 * TJScalingFactor.getScaled()}, {@link #getWidth}, and {@link #getHeight}.)
626 */
627 public void decompressToYUV(YUVImage dstImage) throws TJException {
628 if (jpegBuf == null)
629 throw new IllegalStateException(NO_ASSOC_ERROR);
630 if (dstImage == null)
631 throw new IllegalArgumentException("Invalid argument in decompressToYUV()");
632 checkSubsampling();
633 if (get(TJ.PARAM_SUBSAMP) != dstImage.getSubsamp())
634 throw new IllegalArgumentException("YUVImage subsampling level does not match that of the JPEG image");
635 if (scalingFactor.getScaled(getJPEGWidth()) != dstImage.getWidth() ||
636 scalingFactor.getScaled(getJPEGHeight()) != dstImage.getHeight())
637 throw new IllegalArgumentException("YUVImage dimensions do not match the scaled JPEG dimensions");
638
639 decompressToYUV8(jpegBuf, jpegBufSize, dstImage.getPlanes(),
640 dstImage.getOffsets(), dstImage.getStrides());
641 }
642
643 /**
644 * Decompress the 8-bit-per-sample JPEG source image associated with this
645 * decompressor instance into a set of 8-bit-per-sample Y, U (Cb), and V (Cr)
646 * image planes and return a {@link YUVImage} instance containing the
647 * decompressed image planes. This method performs JPEG decompression but
648 * leaves out the color conversion step, so a planar YUV image is generated
649 * instead of a packed-pixel image. This method cannot be used to decompress
650 * JPEG source images with the CMYK or YCCK colorspace.
651 *
652 * @param strides an array of integers, each specifying the number of bytes
653 * per row in the corresponding plane of the YUV image. Setting the stride
654 * for any plane to 0 is the same as setting it to the scaled plane width
655 * (see {@link YUVImage}.) If <code>strides</code> is null, then the strides
656 * for all planes will be set to their respective scaled plane widths. You
657 * can adjust the strides in order to add an arbitrary amount of row padding
658 * to each plane.
659 *
660 * @return a {@link YUVImage} instance containing the decompressed image
661 * planes
662 */
663 public YUVImage decompressToYUV(int[] strides) throws TJException {
664 int jpegWidth = getJPEGWidth();
665 int jpegHeight = getJPEGHeight();
666 checkSubsampling();
667 if (yuvImage != null)
668 throw new IllegalStateException("Source image is the wrong type");
669
670 YUVImage dstYUVImage = new YUVImage(scalingFactor.getScaled(jpegWidth),
671 null,
672 scalingFactor.getScaled(jpegHeight),
673 get(TJ.PARAM_SUBSAMP));
674 decompressToYUV(dstYUVImage);
675 return dstYUVImage;
676 }
677
678 /**
679 * Decompress the 8-bit-per-sample JPEG source image associated with this
680 * decompressor instance into an 8-bit-per-sample unified planar YUV image
681 * and return a {@link YUVImage} instance containing the decompressed image.
682 * This method performs JPEG decompression but leaves out the color
683 * conversion step, so a planar YUV image is generated instead of a
684 * packed-pixel image. This method cannot be used to decompress JPEG source
685 * images with the CMYK or YCCK colorspace.
686 *
687 * @param align row alignment (in bytes) of the YUV image (must be a power of
688 * 2.) Setting this parameter to n will cause each row in each plane of the
689 * YUV image to be padded to the nearest multiple of n bytes (1 = unpadded.)
690 *
691 * @return a {@link YUVImage} instance containing the unified planar YUV
692 * decompressed image
693 */
694 public YUVImage decompressToYUV(int align) throws TJException {
695 int jpegWidth = getJPEGWidth();
696 int jpegHeight = getJPEGHeight();
697 checkSubsampling();
698 if (yuvImage != null)
699 throw new IllegalStateException("Source image is the wrong type");
700
701 YUVImage dstYUVImage = new YUVImage(scalingFactor.getScaled(jpegWidth),
702 align,
703 scalingFactor.getScaled(jpegHeight),
704 get(TJ.PARAM_SUBSAMP));
705 decompressToYUV(dstYUVImage);
706 return dstYUVImage;
707 }
708
709 /**
710 * Decompress the 8-bit-per-sample JPEG source image or decode the planar YUV
711 * source image associated with this decompressor instance and output an
712 * 8-bit-per-sample packed-pixel grayscale, RGB, or CMYK image to the given
713 * destination buffer.
714 *
715 * <p>NOTE: The destination image is fully recoverable if this method throws
716 * a non-fatal {@link TJException} (unless {@link TJ#PARAM_STOPONWARNING}
717 * is set.)
718 *
719 * @param dstBuf buffer that will receive the packed-pixel
720 * decompressed/decoded image. This buffer should normally be
721 * <code>stride * destinationHeight</code> pixels in size. However, the
722 * buffer may also be larger, in which case the <code>x</code>,
723 * <code>y</code>, and <code>pitch</code> parameters can be used to specify
724 * the region into which the source image should be decompressed/decoded.
725 * NOTE: If the source image is a lossy JPEG image, then
726 * <code>destinationHeight</code> is either the scaled JPEG height (see
727 * {@link #setScalingFactor setScalingFactor()},
728 * {@link TJScalingFactor#getScaled TJScalingFactor.getScaled()}, and
729 * {@link #getHeight}) or the height of the cropping region (see
730 * {@link #setCroppingRegion setCroppingRegion()}.) If the source image is a
731 * YUV image or a lossless JPEG image, then <code>destinationHeight</code> is
732 * the height of the source image.
733 *
734 * @param x x offset (in pixels) of the region in the destination image into
735 * which the source image should be decompressed/decoded
736 *
737 * @param y y offset (in pixels) of the region in the destination image into
738 * which the source image should be decompressed/decoded
739 *
740 * @param stride pixels per row in the destination image. Normally this
741 * should be set to <code>destinationWidth</code>. (Setting this parameter
742 * to 0 is the equivalent of setting it to <code>destinationWidth</code>.)
743 * However, you can also use this parameter to skip rows or to
744 * decompress/decode into a specific region of a larger image. NOTE: If the
745 * source image is a lossy JPEG image, then <code>destinationWidth</code> is
746 * either the scaled JPEG width (see {@link #setScalingFactor
747 * setScalingFactor()}, {@link TJScalingFactor#getScaled
748 * TJScalingFactor.getScaled()}, and {@link #getWidth}) or the width of the
749 * cropping region (see {@link #setCroppingRegion setCroppingRegion()}.) If
750 * the source image is a YUV image or a lossless JPEG image, then
751 * <code>destinationWidth</code> is the width of the source image.
752 *
753 * @param pixelFormat pixel format of the decompressed/decoded image (one of
754 * {@link TJ#PF_RGB TJ.PF_*})
755 */
756 public void decompress8(int[] dstBuf, int x, int y, int stride,
757 int pixelFormat) throws TJException {
758 if (jpegBuf == null && yuvImage == null)
759 throw new IllegalStateException("No source image is associated with this instance");
760 if (dstBuf == null || x < 0 || y < 0 || stride < 0 ||
761 pixelFormat < 0 || pixelFormat >= TJ.NUMPF)
762 throw new IllegalArgumentException("Invalid argument in decompress8()");
763 if (yuvImage != null) {
764 checkSubsampling();
765 decodeYUV8(yuvImage.getPlanes(), yuvImage.getOffsets(),
766 yuvImage.getStrides(), dstBuf, x, y, yuvImage.getWidth(),
767 stride, yuvImage.getHeight(), pixelFormat);
768 } else
769 decompress8(jpegBuf, jpegBufSize, dstBuf, x, y, stride, pixelFormat);
770 }
771
772 /**
773 * Decompress the 8-bit-per-sample JPEG source image or decode the planar YUV
774 * source image associated with this decompressor instance and output an
775 * 8-bit-per-sample packed-pixel decompressed/decoded image to the given
776 * <code>BufferedImage</code> instance.
777 *
778 * <p>NOTE: The destination image is fully recoverable if this method throws
779 * a non-fatal {@link TJException} (unless {@link TJ#PARAM_STOPONWARNING}
780 * is set.)
781 *
782 * @param dstImage a <code>BufferedImage</code> instance that will receive
783 * the packed-pixel decompressed/decoded image. If the source image is a
784 * lossy JPEG image, then the width and height of the
785 * <code>BufferedImage</code> instance must match the scaled JPEG width and
786 * height (see {@link #setScalingFactor setScalingFactor()},
787 * {@link TJScalingFactor#getScaled TJScalingFactor.getScaled()},
788 * {@link #getWidth}, and {@link #getHeight}) or the width and height of the
789 * cropping region (see {@link #setCroppingRegion setCroppingRegion()}.) If
790 * the source image is a YUV image or a lossless JPEG image, then the width
791 * and height of the <code>BufferedImage</code> instance must match the width
792 * and height of the source image.
793 */
794 public void decompress8(BufferedImage dstImage) throws TJException {
795 if (dstImage == null)
796 throw new IllegalArgumentException("Invalid argument in decompress8()");
797
798 if (yuvImage != null) {
799 if (dstImage.getWidth() != yuvImage.getWidth() ||
800 dstImage.getHeight() != yuvImage.getHeight())
801 throw new IllegalArgumentException("BufferedImage dimensions do not match the dimensions of the source image.");
802 } else {
803 if (scalingFactor.getScaled(getJPEGWidth()) != dstImage.getWidth() ||
804 scalingFactor.getScaled(getJPEGHeight()) != dstImage.getHeight())
805 throw new IllegalArgumentException("BufferedImage dimensions do not match the scaled JPEG dimensions.");
806 }
807 int pixelFormat; boolean intPixels = false;
808 if (byteOrder == null)
809 byteOrder = ByteOrder.nativeOrder();
810 switch (dstImage.getType()) {
811 case BufferedImage.TYPE_3BYTE_BGR:
812 pixelFormat = TJ.PF_BGR; break;
813 case BufferedImage.TYPE_4BYTE_ABGR:
814 case BufferedImage.TYPE_4BYTE_ABGR_PRE:
815 pixelFormat = TJ.PF_XBGR; break;
816 case BufferedImage.TYPE_BYTE_GRAY:
817 pixelFormat = TJ.PF_GRAY; break;
818 case BufferedImage.TYPE_INT_BGR:
819 if (byteOrder == ByteOrder.BIG_ENDIAN)
820 pixelFormat = TJ.PF_XBGR;
821 else
822 pixelFormat = TJ.PF_RGBX;
823 intPixels = true; break;
824 case BufferedImage.TYPE_INT_RGB:
825 if (byteOrder == ByteOrder.BIG_ENDIAN)
826 pixelFormat = TJ.PF_XRGB;
827 else
828 pixelFormat = TJ.PF_BGRX;
829 intPixels = true; break;
830 case BufferedImage.TYPE_INT_ARGB:
831 case BufferedImage.TYPE_INT_ARGB_PRE:
832 if (byteOrder == ByteOrder.BIG_ENDIAN)
833 pixelFormat = TJ.PF_ARGB;
834 else
835 pixelFormat = TJ.PF_BGRA;
836 intPixels = true; break;
837 default:
838 throw new IllegalArgumentException("Unsupported BufferedImage format");
839 }
840 WritableRaster wr = dstImage.getRaster();
841 if (intPixels) {
842 SinglePixelPackedSampleModel sm =
843 (SinglePixelPackedSampleModel)dstImage.getSampleModel();
844 int stride = sm.getScanlineStride();
845 DataBufferInt db = (DataBufferInt)wr.getDataBuffer();
846 int[] buf = db.getData();
847 if (yuvImage != null) {
848 checkSubsampling();
849 decodeYUV8(yuvImage.getPlanes(), yuvImage.getOffsets(),
850 yuvImage.getStrides(), buf, 0, 0, yuvImage.getWidth(),
851 stride, yuvImage.getHeight(), pixelFormat);
852 } else {
853 if (jpegBuf == null)
854 throw new IllegalStateException(NO_ASSOC_ERROR);
855 decompress8(jpegBuf, jpegBufSize, buf, 0, 0, stride, pixelFormat);
856 }
857 } else {
858 ComponentSampleModel sm =
859 (ComponentSampleModel)dstImage.getSampleModel();
860 int pixelSize = sm.getPixelStride();
861 if (pixelSize != TJ.getPixelSize(pixelFormat))
862 throw new IllegalArgumentException("Inconsistency between pixel format and pixel size in BufferedImage");
863 int pitch = sm.getScanlineStride();
864 DataBufferByte db = (DataBufferByte)wr.getDataBuffer();
865 byte[] buf = db.getData();
866 decompress8(buf, 0, 0, pitch, pixelFormat);
867 }
868 }
869
870 /**
871 * Decompress the 8-bit-per-sample JPEG source image or decode the planar YUV
872 * source image associated with this decompressor instance and return a
873 * <code>BufferedImage</code> instance containing the 8-bit-per-sample
874 * packed-pixel decompressed/decoded image.
875 *
876 * @param bufferedImageType the image type of the <code>BufferedImage</code>
877 * instance that will be created (for instance,
878 * <code>BufferedImage.TYPE_INT_RGB</code>)
879 *
880 * @return a <code>BufferedImage</code> instance containing the
881 * 8-bit-per-sample packed-pixel decompressed/decoded image.
882 */
883 public BufferedImage decompress8(int bufferedImageType) throws TJException {
884 BufferedImage img =
885 new BufferedImage(scalingFactor.getScaled(getJPEGWidth()),
886 scalingFactor.getScaled(getJPEGHeight()),
887 bufferedImageType);
888 decompress8(img);
889 return img;
890 }
891
892 /**
893 * Save a packed-pixel image with 2 to 16 bits of data precision per sample
894 * from memory to disk.
895 *
896 * @param fileName name of a file to which to save the packed-pixel image.
897 * The image will be stored in Windows BMP or PBMPLUS (PPM/PGM) format,
898 * depending on the file extension. Windows BMP files require
899 * 8-bit-per-sample data precision. When saving a PBMPLUS file, the source
900 * data precision (from 2 to 16 bits per sample) can be specified using
901 * {@link TJ#PARAM_PRECISION} and defaults to 8 if {@link TJ#PARAM_PRECISION}
902 * is unset.
903 *
904 * @param image buffer containing a packed-pixel RGB, grayscale, or CMYK
905 * image to be saved. The buffer is a <code>byte</code> array if the image
906 * has 2 to 8 bits of data precision per sample and a <code>short</code>
907 * array otherwise.
908 *
909 * @param x x offset (in pixels) of the region in the buffer from which to
910 * save the packed-pixel image
911 *
912 * @param y y offset (in pixels) of the region in the buffer from which to
913 * save the packed-pixel image
914 *
915 * @param width width (in pixels) of the region in the buffer from which to
916 * save the packed-pixel image
917 *
918 * @param pitch samples per row in the packed-pixel buffer. Setting this
919 * parameter to 0 is the equivalent of setting it to <code>width *
920 * {@link TJ#getPixelSize TJ.getPixelSize}(pixelFormat)</code>.
921 *
922 * @param height height (in pixels) of the region in the buffer from which to
923 * save the packed-pixel image
924 *
925 * @param pixelFormat pixel format of the packed-pixel image (one of
926 * {@link TJ#PF_RGB TJ.PF_*}). If this parameter is set to
927 * {@link TJ#PF_GRAY}, then the image will be stored in PGM or
928 * 8-bit-per-pixel (indexed color) BMP format. Otherwise, the image will be
929 * stored in PPM or 24-bit-per-pixel BMP format. If this parameter is set to
930 * {@link TJ#PF_CMYK}, then the CMYK pixels will be converted to RGB using a
931 * quick &amp; dirty algorithm that is suitable only for testing purposes.
932 * (Proper conversion between CMYK and other formats requires a color
933 * management system.)
934 */
935 public void saveImage(String fileName, Object image, int x, int y, int width,
936 int pitch, int height, int pixelFormat)
937 throws TJException {
938 int precision = get(TJ.PARAM_PRECISION);
939 if (precision < 2 || precision > 16)
940 precision = 8;
941 saveImage(precision, fileName, image, x, y, width, pitch, height,
942 pixelFormat);
943 }
944
945 /**
946 * Free the native structures associated with this decompressor instance.
947 */
948 @Override
949 public void close() throws TJException {
950 if (handle != 0)
951 destroy();
952 }
953
954 @SuppressWarnings("checkstyle:DesignForExtension")
955 @Override
956 protected void finalize() throws Throwable {
957 try {
958 close();
959 } catch (TJException e) {
960 } finally {
961 super.finalize();
962 }
963 };
964
965 final void checkSubsampling() {
966 if (get(TJ.PARAM_SUBSAMP) == TJ.SAMP_UNKNOWN)
967 throw new IllegalStateException("Unknown or unspecified subsampling level");
968 }
969
970 private native void init() throws TJException;
971
972 private native void destroy() throws TJException;
973
974 private native void decompressHeader(byte[] srcBuf, int size)
975 throws TJException;
976
977 private native void setCroppingRegion() throws TJException;
978
979 @SuppressWarnings("checkstyle:HiddenField")
980 private native void decompress8(byte[] srcBuf, int size, byte[] dstBuf,
981 int x, int y, int pitch, int pixelFormat) throws TJException;
982
983 @SuppressWarnings("checkstyle:HiddenField")
984 private native void decompress12(byte[] srcBuf, int size, short[] dstBuf,
985 int x, int y, int pitch, int pixelFormat) throws TJException;
986
987 @SuppressWarnings("checkstyle:HiddenField")
988 private native void decompress16(byte[] srcBuf, int size, short[] dstBuf,
989 int x, int y, int pitch, int pixelFormat) throws TJException;
990
991 @SuppressWarnings("checkstyle:HiddenField")
992 private native void decompress8(byte[] srcBuf, int size, int[] dstBuf, int x,
993 int y, int stride, int pixelFormat) throws TJException;
994
995 @SuppressWarnings("checkstyle:HiddenField")
996 private native void decompressToYUV8(byte[] srcBuf, int size,
997 byte[][] dstPlanes, int[] dstOffsets, int[] dstStrides) throws TJException;
998
999 private native void decodeYUV8(byte[][] srcPlanes, int[] srcOffsets,
1000 int[] srcStrides, byte[] dstBuf, int x, int y, int width, int pitch,
1001 int height, int pixelFormat) throws TJException;
1002
1003 private native void decodeYUV8(byte[][] srcPlanes, int[] srcOffsets,
1004 int[] srcStrides, int[] dstBuf, int x, int y, int width, int stride,
1005 int height, int pixelFormat) throws TJException;
1006
1007 private native void saveImage(int precision, String fileName, Object buffer,
1008 int x, int y, int width, int pitch, int height, int pixelFormat)
1009 throws TJException;
1010
1011 static {
1012 TJLoader.load();
1013 }
1014
1015 private long handle = 0;
1016 private byte[] jpegBuf = null;
1017 private int jpegBufSize = 0;
1018 private YUVImage yuvImage = null;
1019 private TJScalingFactor scalingFactor = TJ.UNSCALED;
1020 private Rectangle croppingRegion = TJ.UNCROPPED;
1021 private ByteOrder byteOrder = null;
1022 }