Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qjpeghandler.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
6
7#include <qbuffer.h>
8#include <qcolorspace.h>
9#include <qcolortransform.h>
10#include <qdebug.h>
11#include <qimage.h>
12#include <qlist.h>
13#include <qloggingcategory.h>
14#include <qmath.h>
15#include <qvariant.h>
16#include <private/qicc_p.h>
17#include <private/qsimd_p.h>
18#include <private/qimage_p.h> // for qt_getImageText
19
20#include <stdio.h> // jpeglib needs this to be pre-included
21#include <setjmp.h>
22
23#ifdef FAR
24#undef FAR
25#endif
26
27// including jpeglib.h seems to be a little messy
28extern "C" {
29#define XMD_H // shut JPEGlib up
30#include <jpeglib.h>
31#ifdef const
32# undef const // remove crazy C hackery in jconfig.h
33#endif
34}
35
36QT_BEGIN_NAMESPACE
37
38Q_LOGGING_CATEGORY(lcJpeg, "qt.gui.imageio.jpeg")
39
40QT_WARNING_DISABLE_GCC("-Wclobbered")
41
42Q_GUI_EXPORT void QT_FASTCALL qt_convert_rgb888_to_rgb32(quint32 *dst, const uchar *src, int len);
43typedef void (QT_FASTCALL *Rgb888ToRgb32Converter)(quint32 *dst, const uchar *src, int len);
44
45struct my_error_mgr : public jpeg_error_mgr {
47};
48
49extern "C" {
50
51static void my_error_exit (j_common_ptr cinfo)
52{
53 (*cinfo->err->output_message)(cinfo);
54 my_error_mgr* myerr = (my_error_mgr*) cinfo->err;
55 longjmp(myerr->setjmp_buffer, 1);
56}
57
58static void my_output_message(j_common_ptr cinfo)
59{
60 char buffer[JMSG_LENGTH_MAX];
61 (*cinfo->err->format_message)(cinfo, buffer);
62 qCWarning(lcJpeg,"%s", buffer);
63}
64
65}
66
67
68static const int max_buf = 4096;
69
70struct my_jpeg_source_mgr : public jpeg_source_mgr {
71 // Nothing dynamic - cannot rely on destruction over longjump
72 QIODevice *device;
73 JOCTET buffer[max_buf];
75
76public:
77 my_jpeg_source_mgr(QIODevice *device);
78};
79
80extern "C" {
81
82static void qt_init_source(j_decompress_ptr)
83{
84}
85
86static boolean qt_fill_input_buffer(j_decompress_ptr cinfo)
87{
88 my_jpeg_source_mgr* src = (my_jpeg_source_mgr*)cinfo->src;
89 qint64 num_read = 0;
90 if (src->memDevice) {
91 src->next_input_byte = (const JOCTET *)(src->memDevice->data().constData() + src->memDevice->pos());
92 num_read = src->memDevice->data().size() - src->memDevice->pos();
93 src->device->seek(src->memDevice->data().size());
94 } else {
95 src->next_input_byte = src->buffer;
96 num_read = src->device->read((char*)src->buffer, max_buf);
97 }
98 if (num_read <= 0) {
99 // Insert a fake EOI marker - as per jpeglib recommendation
100 src->next_input_byte = src->buffer;
101 src->buffer[0] = (JOCTET) 0xFF;
102 src->buffer[1] = (JOCTET) JPEG_EOI;
103 src->bytes_in_buffer = 2;
104 } else {
105 src->bytes_in_buffer = num_read;
106 }
107 return TRUE;
108}
109
110static void qt_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
111{
112 my_jpeg_source_mgr* src = (my_jpeg_source_mgr*)cinfo->src;
113
114 // `dumb' implementation from jpeglib
115
116 /* Just a dumb implementation for now. Could use fseek() except
117 * it doesn't work on pipes. Not clear that being smart is worth
118 * any trouble anyway --- large skips are infrequent.
119 */
120 if (num_bytes > 0) {
121 while (num_bytes > (long) src->bytes_in_buffer) { // Should not happen in case of memDevice
122 num_bytes -= (long) src->bytes_in_buffer;
123 (void) qt_fill_input_buffer(cinfo);
124 /* note we assume that qt_fill_input_buffer will never return false,
125 * so suspension need not be handled.
126 */
127 }
128 src->next_input_byte += (size_t) num_bytes;
129 src->bytes_in_buffer -= (size_t) num_bytes;
130 }
131}
132
133static void qt_term_source(j_decompress_ptr cinfo)
134{
135 my_jpeg_source_mgr* src = (my_jpeg_source_mgr*)cinfo->src;
136 if (!src->device->isSequential())
137 src->device->seek(src->device->pos() - src->bytes_in_buffer);
138}
139
140}
141
142inline my_jpeg_source_mgr::my_jpeg_source_mgr(QIODevice *device)
143{
144 jpeg_source_mgr::init_source = qt_init_source;
145 jpeg_source_mgr::fill_input_buffer = qt_fill_input_buffer;
146 jpeg_source_mgr::skip_input_data = qt_skip_input_data;
147 jpeg_source_mgr::resync_to_restart = jpeg_resync_to_restart;
148 jpeg_source_mgr::term_source = qt_term_source;
149 this->device = device;
150 memDevice = qobject_cast<QBuffer *>(device);
151 bytes_in_buffer = 0;
152 next_input_byte = buffer;
153}
154
155
156inline static bool read_jpeg_size(int &w, int &h, j_decompress_ptr cinfo)
157{
158 (void) jpeg_calc_output_dimensions(cinfo);
159
160 w = cinfo->output_width;
161 h = cinfo->output_height;
162 return true;
163}
164
165#define HIGH_QUALITY_THRESHOLD 50
166
167inline static bool read_jpeg_format(QImage::Format &format, j_decompress_ptr cinfo)
168{
169
170 bool result = true;
171 switch (cinfo->output_components) {
172 case 1:
173 format = QImage::Format_Grayscale8;
174 break;
175 case 3:
176 format = QImage::Format_RGB32;
177 break;
178 case 4:
179 if (cinfo->out_color_space == JCS_CMYK)
180 format = QImage::Format_CMYK8888;
181 else
182 format = QImage::Format_RGB32;
183 break;
184 default:
185 result = false;
186 break;
187 }
188 cinfo->output_scanline = cinfo->output_height;
189 return result;
190}
191
192static bool ensureValidImage(QImage *dest, struct jpeg_decompress_struct *info,
193 const QSize& size)
194{
195 QImage::Format format;
196 switch (info->output_components) {
197 case 1:
198 format = QImage::Format_Grayscale8;
199 break;
200 case 3:
201 format = QImage::Format_RGB32;
202 break;
203 case 4:
204 if (info->out_color_space == JCS_CMYK)
205 format = QImage::Format_CMYK8888;
206 else
207 format = QImage::Format_RGB32;
208 break;
209 default:
210 return false; // unsupported format
211 }
212
213 return QImageIOHandler::allocateImage(size, format, dest);
214}
215
216static bool read_jpeg_image(QImage *outImage,
217 QSize scaledSize, QRect scaledClipRect,
218 QRect clipRect, int quality,
219 Rgb888ToRgb32Converter converter,
220 j_decompress_ptr info, struct my_error_mgr* err, bool invertCMYK)
221{
222 if (!setjmp(err->setjmp_buffer)) {
223 // -1 means default quality.
224 if (quality < 0)
225 quality = 75;
226
227 // If possible, merge the scaledClipRect into either scaledSize
228 // or clipRect to avoid doing a separate scaled clipping pass.
229 // Best results are achieved by clipping before scaling, not after.
230 if (!scaledClipRect.isEmpty()) {
231 if (scaledSize.isEmpty() && clipRect.isEmpty()) {
232 // No clipping or scaling before final clip.
233 clipRect = scaledClipRect;
234 scaledClipRect = QRect();
235 } else if (scaledSize.isEmpty()) {
236 // Clipping, but no scaling: combine the clip regions.
237 scaledClipRect.translate(clipRect.topLeft());
238 clipRect = scaledClipRect.intersected(clipRect);
239 scaledClipRect = QRect();
240 } else if (clipRect.isEmpty()) {
241 // No clipping, but scaling: if we can map back to an
242 // integer pixel boundary, then clip before scaling.
243 if ((info->image_width % scaledSize.width()) == 0 &&
244 (info->image_height % scaledSize.height()) == 0) {
245 int x = scaledClipRect.x() * info->image_width /
246 scaledSize.width();
247 int y = scaledClipRect.y() * info->image_height /
248 scaledSize.height();
249 int width = (scaledClipRect.right() + 1) *
250 info->image_width / scaledSize.width() - x;
251 int height = (scaledClipRect.bottom() + 1) *
252 info->image_height / scaledSize.height() - y;
253 clipRect = QRect(x, y, width, height);
254 scaledSize = scaledClipRect.size();
255 scaledClipRect = QRect();
256 }
257 } else {
258 // Clipping and scaling: too difficult to figure out,
259 // and not a likely use case, so do it the long way.
260 }
261 }
262
263 // Determine the scale factor to pass to libjpeg for quick downscaling.
264 if (!scaledSize.isEmpty() && info->image_width && info->image_height) {
265 if (clipRect.isEmpty()) {
266 double f = qMin(double(info->image_width) / scaledSize.width(),
267 double(info->image_height) / scaledSize.height());
268
269 // libjpeg supports M/8 scaling with M=[1,16]. All downscaling factors
270 // are a speed improvement, but upscaling during decode is slower.
271 info->scale_num = qBound(1, qCeil(8/f), 8);
272 info->scale_denom = 8;
273 } else {
274 info->scale_denom = qMin(clipRect.width() / scaledSize.width(),
275 clipRect.height() / scaledSize.height());
276
277 // Only scale by powers of two when clipping so we can
278 // keep the exact pixel boundaries
279 if (info->scale_denom < 2)
280 info->scale_denom = 1;
281 else if (info->scale_denom < 4)
282 info->scale_denom = 2;
283 else if (info->scale_denom < 8)
284 info->scale_denom = 4;
285 else
286 info->scale_denom = 8;
287 info->scale_num = 1;
288
289 // Correct the scale factor so that we clip accurately.
290 // It is recommended that the clip rectangle be aligned
291 // on an 8-pixel boundary for best performance.
292 while (info->scale_denom > 1 &&
293 ((clipRect.x() % info->scale_denom) != 0 ||
294 (clipRect.y() % info->scale_denom) != 0 ||
295 (clipRect.width() % info->scale_denom) != 0 ||
296 (clipRect.height() % info->scale_denom) != 0)) {
297 info->scale_denom /= 2;
298 }
299 }
300 }
301
302 // If high quality not required, use fast decompression
303 if ( quality < HIGH_QUALITY_THRESHOLD ) {
304 info->dct_method = JDCT_IFAST;
305 info->do_fancy_upsampling = FALSE;
306 }
307
308 (void) jpeg_calc_output_dimensions(info);
309
310 // Determine the clip region to extract.
311 QRect imageRect(0, 0, info->output_width, info->output_height);
312 QRect clip;
313 if (clipRect.isEmpty()) {
314 clip = imageRect;
315 } else if (info->scale_denom == info->scale_num) {
316 clip = clipRect.intersected(imageRect);
317 } else {
318 // The scale factor was corrected above to ensure that
319 // we don't miss pixels when we scale the clip rectangle.
320 clip = QRect(clipRect.x() / int(info->scale_denom),
321 clipRect.y() / int(info->scale_denom),
322 clipRect.width() / int(info->scale_denom),
323 clipRect.height() / int(info->scale_denom));
324 clip = clip.intersected(imageRect);
325 }
326
327 // Allocate memory for the clipped QImage.
328 if (!ensureValidImage(outImage, info, clip.size()))
329 return false;
330
331 // Avoid memcpy() overhead if grayscale with no clipping.
332 bool quickGray = (info->output_components == 1 &&
333 clip == imageRect);
334 if (!quickGray) {
335 // Ask the jpeg library to allocate a temporary row.
336 // The library will automatically delete it for us later.
337 // The libjpeg docs say we should do this before calling
338 // jpeg_start_decompress(). We can't use "new" here
339 // because we are inside the setjmp() block and an error
340 // in the jpeg input stream would cause a memory leak.
341 JSAMPARRAY rows = (info->mem->alloc_sarray)
342 ((j_common_ptr)info, JPOOL_IMAGE,
343 info->output_width * info->output_components, 1);
344
345 (void) jpeg_start_decompress(info);
346
347 while (info->output_scanline < info->output_height) {
348 int y = int(info->output_scanline) - clip.y();
349 if (y >= clip.height())
350 break; // We've read the entire clip region, so abort.
351
352 (void) jpeg_read_scanlines(info, rows, 1);
353
354 if (y < 0)
355 continue; // Haven't reached the starting line yet.
356
357 if (info->output_components == 3) {
358 uchar *in = rows[0] + clip.x() * 3;
359 QRgb *out = (QRgb*)outImage->scanLine(y);
360 converter(out, in, clip.width());
361 } else if (info->out_color_space == JCS_CMYK) {
362 uchar *in = rows[0] + clip.x() * 4;
363 quint32 *out = (quint32*)outImage->scanLine(y);
364 if (invertCMYK) {
365 for (int i = 0; i < clip.width(); ++i) {
366 *out++ = 0xffffffffu - (in[0] | in[1] << 8 | in[2] << 16 | in[3] << 24);
367 in += 4;
368 }
369 } else {
370 memcpy(out, in, clip.width() * 4);
371 }
372 } else if (info->output_components == 1) {
373 // Grayscale.
374 memcpy(outImage->scanLine(y),
375 rows[0] + clip.x(), clip.width());
376 }
377 }
378 } else {
379 // Load unclipped grayscale data directly into the QImage.
380 (void) jpeg_start_decompress(info);
381 while (info->output_scanline < info->output_height) {
382 uchar *row = outImage->scanLine(info->output_scanline);
383 (void) jpeg_read_scanlines(info, &row, 1);
384 }
385 }
386
387 if (info->output_scanline == info->output_height)
388 (void) jpeg_finish_decompress(info);
389
390 if (info->density_unit == 1) {
391 outImage->setDotsPerMeterX(int(100. * info->X_density / 2.54));
392 outImage->setDotsPerMeterY(int(100. * info->Y_density / 2.54));
393 } else if (info->density_unit == 2) {
394 outImage->setDotsPerMeterX(int(100. * info->X_density));
395 outImage->setDotsPerMeterY(int(100. * info->Y_density));
396 }
397
398 if (scaledSize.isValid() && scaledSize != clip.size()) {
399 *outImage = outImage->scaled(scaledSize, Qt::IgnoreAspectRatio, quality >= HIGH_QUALITY_THRESHOLD ? Qt::SmoothTransformation : Qt::FastTransformation);
400 }
401
402 if (!scaledClipRect.isEmpty())
403 *outImage = outImage->copy(scaledClipRect);
404 return !outImage->isNull();
405 }
406 else {
407 my_output_message(j_common_ptr(info));
408 return false;
409 }
410}
411
412struct my_jpeg_destination_mgr : public jpeg_destination_mgr {
413 // Nothing dynamic - cannot rely on destruction over longjump
414 QIODevice *device;
416
417public:
419};
420
421
422extern "C" {
423
424static void qt_init_destination(j_compress_ptr)
425{
426}
427
428static boolean qt_empty_output_buffer(j_compress_ptr cinfo)
429{
431
432 int written = dest->device->write((char*)dest->buffer, max_buf);
433 if (written == -1)
434 (*cinfo->err->error_exit)((j_common_ptr)cinfo);
435
436 dest->next_output_byte = dest->buffer;
437 dest->free_in_buffer = max_buf;
438
439 return TRUE;
440}
441
442static void qt_term_destination(j_compress_ptr cinfo)
443{
445 qint64 n = max_buf - dest->free_in_buffer;
446
447 qint64 written = dest->device->write((char*)dest->buffer, n);
448 if (written == -1)
449 (*cinfo->err->error_exit)((j_common_ptr)cinfo);
450}
451
452}
453
455{
456 jpeg_destination_mgr::init_destination = qt_init_destination;
457 jpeg_destination_mgr::empty_output_buffer = qt_empty_output_buffer;
458 jpeg_destination_mgr::term_destination = qt_term_destination;
459 this->device = device;
460 next_output_byte = buffer;
461 free_in_buffer = max_buf;
462}
463
464static constexpr int maxMarkerSize = 65533;
465
466static inline void set_text(const QImage &image, j_compress_ptr cinfo, const QString &description)
467{
468 const QMap<QString, QString> text = qt_getImageText(image, description);
469 for (auto it = text.begin(), end = text.end(); it != end; ++it) {
470 QByteArray comment = it.key().toUtf8();
471 if (!comment.isEmpty())
472 comment += ": ";
473 comment += it.value().toUtf8();
474 if (comment.size() > maxMarkerSize)
475 comment.truncate(maxMarkerSize);
476 jpeg_write_marker(cinfo, JPEG_COM, (const JOCTET *)comment.constData(), comment.size());
477 }
478}
479
480static inline void write_icc_profile(const QImage &image, j_compress_ptr cinfo)
481{
482 const QByteArray iccProfile = image.colorSpace().iccProfile();
483 if (iccProfile.isEmpty())
484 return;
485
486 const QByteArray iccSignature("ICC_PROFILE", 12);
487 constexpr int maxIccMarkerSize = maxMarkerSize - (12 + 2);
488 int index = 0;
489 const int markers = (iccProfile.size() + (maxIccMarkerSize - 1)) / maxIccMarkerSize;
490 Q_ASSERT(markers < 256);
491 for (int marker = 1; marker <= markers; ++marker) {
492 const int len = qMin(iccProfile.size() - index, maxIccMarkerSize);
493 const QByteArray block = iccSignature
494 + QByteArray(1, char(marker)) + QByteArray(1, char(markers))
495 + iccProfile.mid(index, len);
496 jpeg_write_marker(cinfo, JPEG_APP0 + 2, reinterpret_cast<const JOCTET *>(block.constData()), block.size());
497 index += len;
498 }
499}
500
501static bool do_write_jpeg_image(struct jpeg_compress_struct &cinfo,
502 JSAMPROW *row_pointer,
503 const QImage &image,
504 QIODevice *device,
505 int sourceQuality,
506 const QString &description,
507 bool optimize,
508 bool progressive,
509 bool invertCMYK)
510{
511 bool success = false;
512 const QList<QRgb> cmap = image.colorTable();
513
514 if (image.format() == QImage::Format_Invalid || image.format() == QImage::Format_Alpha8)
515 return false;
516
517 struct my_jpeg_destination_mgr *iod_dest = new my_jpeg_destination_mgr(device);
518 struct my_error_mgr jerr;
519
520 cinfo.err = jpeg_std_error(&jerr);
521 jerr.error_exit = my_error_exit;
522 jerr.output_message = my_output_message;
523
524 if (!setjmp(jerr.setjmp_buffer)) {
525 // WARNING:
526 // this if loop is inside a setjmp/longjmp branch
527 // do not create C++ temporaries here because the destructor may never be called
528 // if you allocate memory, make sure that you can free it (row_pointer[0])
529 jpeg_create_compress(&cinfo);
530
531 cinfo.dest = iod_dest;
532
533 cinfo.image_width = image.width();
534 cinfo.image_height = image.height();
535
536 bool gray = false;
537 switch (image.format()) {
538 case QImage::Format_Mono:
539 case QImage::Format_MonoLSB:
540 case QImage::Format_Indexed8:
541 gray = true;
542 for (int i = image.colorCount(); gray && i; i--) {
543 gray = gray & qIsGray(cmap[i-1]);
544 }
545 cinfo.input_components = gray ? 1 : 3;
546 cinfo.in_color_space = gray ? JCS_GRAYSCALE : JCS_RGB;
547 break;
548 case QImage::Format_Grayscale8:
549 case QImage::Format_Grayscale16:
550 gray = true;
551 cinfo.input_components = 1;
552 cinfo.in_color_space = JCS_GRAYSCALE;
553 break;
554 case QImage::Format_CMYK8888:
555 cinfo.input_components = 4;
556 cinfo.in_color_space = JCS_CMYK;
557 break;
558 default:
559 cinfo.input_components = 3;
560 cinfo.in_color_space = JCS_RGB;
561 }
562
563 jpeg_set_defaults(&cinfo);
564
565 qreal diffInch = qAbs(image.dotsPerMeterX()*2.54/100. - qRound(image.dotsPerMeterX()*2.54/100.))
566 + qAbs(image.dotsPerMeterY()*2.54/100. - qRound(image.dotsPerMeterY()*2.54/100.));
567 qreal diffCm = (qAbs(image.dotsPerMeterX()/100. - qRound(image.dotsPerMeterX()/100.))
568 + qAbs(image.dotsPerMeterY()/100. - qRound(image.dotsPerMeterY()/100.)))*2.54;
569 if (diffInch < diffCm) {
570 cinfo.density_unit = 1; // dots/inch
571 cinfo.X_density = qRound(image.dotsPerMeterX()*2.54/100.);
572 cinfo.Y_density = qRound(image.dotsPerMeterY()*2.54/100.);
573 } else {
574 cinfo.density_unit = 2; // dots/cm
575 cinfo.X_density = (image.dotsPerMeterX()+50) / 100;
576 cinfo.Y_density = (image.dotsPerMeterY()+50) / 100;
577 }
578
579 if (optimize)
580 cinfo.optimize_coding = true;
581
582 if (progressive)
583 jpeg_simple_progression(&cinfo);
584
585 int quality = sourceQuality >= 0 ? qMin(int(sourceQuality),100) : 75;
586 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
587
588 // If the quality exceeds a certain threshold (such as 90), disable chroma subsampling
589 if (quality > 90) {
590 cinfo.comp_info[0].v_samp_factor = 1;
591 cinfo.comp_info[0].h_samp_factor = 1;
592 }
593
594 jpeg_start_compress(&cinfo, TRUE);
595
596 set_text(image, &cinfo, description);
597 if (cinfo.in_color_space == JCS_RGB || cinfo.in_color_space == JCS_CMYK)
598 write_icc_profile(image, &cinfo);
599
600 row_pointer[0] = new uchar[cinfo.image_width*cinfo.input_components];
601 int w = cinfo.image_width;
602 while (cinfo.next_scanline < cinfo.image_height) {
603 uchar *row = row_pointer[0];
604 switch (image.format()) {
605 case QImage::Format_Mono:
606 case QImage::Format_MonoLSB:
607 if (gray) {
608 const uchar* data = image.constScanLine(cinfo.next_scanline);
609 if (image.format() == QImage::Format_MonoLSB) {
610 for (int i=0; i<w; i++) {
611 bool bit = !!(*(data + (i >> 3)) & (1 << (i & 7)));
612 row[i] = qRed(cmap[bit]);
613 }
614 } else {
615 for (int i=0; i<w; i++) {
616 bool bit = !!(*(data + (i >> 3)) & (1 << (7 -(i & 7))));
617 row[i] = qRed(cmap[bit]);
618 }
619 }
620 } else {
621 const uchar* data = image.constScanLine(cinfo.next_scanline);
622 if (image.format() == QImage::Format_MonoLSB) {
623 for (int i=0; i<w; i++) {
624 bool bit = !!(*(data + (i >> 3)) & (1 << (i & 7)));
625 *row++ = qRed(cmap[bit]);
626 *row++ = qGreen(cmap[bit]);
627 *row++ = qBlue(cmap[bit]);
628 }
629 } else {
630 for (int i=0; i<w; i++) {
631 bool bit = !!(*(data + (i >> 3)) & (1 << (7 -(i & 7))));
632 *row++ = qRed(cmap[bit]);
633 *row++ = qGreen(cmap[bit]);
634 *row++ = qBlue(cmap[bit]);
635 }
636 }
637 }
638 break;
639 case QImage::Format_Indexed8:
640 if (gray) {
641 const uchar* pix = image.constScanLine(cinfo.next_scanline);
642 for (int i=0; i<w; i++) {
643 *row = qRed(cmap[*pix]);
644 ++row; ++pix;
645 }
646 } else {
647 const uchar* pix = image.constScanLine(cinfo.next_scanline);
648 for (int i=0; i<w; i++) {
649 *row++ = qRed(cmap[*pix]);
650 *row++ = qGreen(cmap[*pix]);
651 *row++ = qBlue(cmap[*pix]);
652 ++pix;
653 }
654 }
655 break;
656 case QImage::Format_Grayscale8:
657 memcpy(row, image.constScanLine(cinfo.next_scanline), w);
658 break;
659 case QImage::Format_Grayscale16:
660 {
661 QImage rowImg = image.copy(0, cinfo.next_scanline, w, 1).convertToFormat(QImage::Format_Grayscale8);
662 memcpy(row, rowImg.constScanLine(0), w);
663 }
664 break;
665 case QImage::Format_RGB888:
666 memcpy(row, image.constScanLine(cinfo.next_scanline), w * 3);
667 break;
668 case QImage::Format_RGB32:
669 case QImage::Format_ARGB32:
670 case QImage::Format_ARGB32_Premultiplied:
671 {
672 const QRgb* rgb = (const QRgb*)image.constScanLine(cinfo.next_scanline);
673 for (int i=0; i<w; i++) {
674 *row++ = qRed(*rgb);
675 *row++ = qGreen(*rgb);
676 *row++ = qBlue(*rgb);
677 ++rgb;
678 }
679 }
680 break;
681 case QImage::Format_CMYK8888: {
682 auto *cmykIn = reinterpret_cast<const quint32 *>(image.constScanLine(cinfo.next_scanline));
683 auto *cmykOut = reinterpret_cast<quint32 *>(row);
684 if (invertCMYK) {
685 for (int i = 0; i < w; ++i)
686 cmykOut[i] = 0xffffffffu - cmykIn[i];
687 } else {
688 memcpy(cmykOut, cmykIn, w * 4);
689 }
690 break;
691 }
692 default:
693 {
694 // (Testing shows that this way is actually faster than converting to RGB888 + memcpy)
695 QImage rowImg = image.copy(0, cinfo.next_scanline, w, 1).convertToFormat(QImage::Format_RGB32);
696 const QRgb* rgb = (const QRgb*)rowImg.constScanLine(0);
697 for (int i=0; i<w; i++) {
698 *row++ = qRed(*rgb);
699 *row++ = qGreen(*rgb);
700 *row++ = qBlue(*rgb);
701 ++rgb;
702 }
703 }
704 break;
705 }
706 jpeg_write_scanlines(&cinfo, row_pointer, 1);
707 }
708
709 jpeg_finish_compress(&cinfo);
710 jpeg_destroy_compress(&cinfo);
711 success = true;
712 } else {
713 my_output_message(j_common_ptr(&cinfo));
714 jpeg_destroy_compress(&cinfo);
715 success = false;
716 }
717
718 delete iod_dest;
719 return success;
720}
721
722static bool write_jpeg_image(const QImage &image,
723 QIODevice *device,
724 int sourceQuality,
725 const QString &description,
726 bool optimize,
727 bool progressive,
728 bool invertCMYK)
729{
730 // protect these objects from the setjmp/longjmp pair inside
731 // do_write_jpeg_image (by making them non-local).
732 struct jpeg_compress_struct cinfo;
733 JSAMPROW row_pointer[1];
734 row_pointer[0] = nullptr;
735
736 const bool success = do_write_jpeg_image(cinfo, row_pointer,
737 image, device,
738 sourceQuality, description,
739 optimize, progressive, invertCMYK);
740
741 delete [] row_pointer[0];
742 return success;
743}
744
746{
747public:
754
759
761 {
762 if (iod_src)
763 {
764 jpeg_destroy_decompress(&info);
765 delete iod_src;
766 iod_src = nullptr;
767 }
768 }
769
770 bool readJpegHeader(QIODevice*);
771 bool read(QImage *image);
772
775 QVariant size;
779 QRect clipRect;
783
784 // Photoshop historically invertes the quantities in CMYK JPEG files:
785 // 0 means 100% ink, 255 means no ink. Every reader does the same,
786 // for compatibility reasons.
787 // Use such an interpretation by default, but also offer the alternative
788 // of not inverting the channels.
789 // This is just a "fancy" API; it could be reduced to a boolean setting
790 // for CMYK files.
798
799 struct jpeg_decompress_struct info;
802
804
806
809
811};
812
813static const char SupportedJPEGSubtypes[][14] = {
814 "Automatic",
815 "Inverted_CMYK",
816 "CMYK"
817};
818
820
821static bool readExifHeader(QDataStream &stream)
822{
823 char prefix[6];
824 if (stream.readRawData(prefix, sizeof(prefix)) != sizeof(prefix))
825 return false;
826 static const char exifMagic[6] = {'E', 'x', 'i', 'f', 0, 0};
827 return memcmp(prefix, exifMagic, 6) == 0;
828}
829
830/*
831 * Returns -1 on error
832 * Returns 0 if no Exif orientation was found
833 * Returns 1 orientation is horizontal (normal)
834 * Returns 2 mirror horizontal
835 * Returns 3 rotate 180
836 * Returns 4 mirror vertical
837 * Returns 5 mirror horizontal and rotate 270 CCW
838 * Returns 6 rotate 90 CW
839 * Returns 7 mirror horizontal and rotate 90 CW
840 * Returns 8 rotate 270 CW
841 */
842static int getExifOrientation(QByteArray &exifData)
843{
844 // Current EXIF version (2.3) says there can be at most 5 IFDs,
845 // byte we allow for 10 so we're able to deal with future extensions.
846 const int maxIfdCount = 10;
847
848 QDataStream stream(&exifData, QIODevice::ReadOnly);
849
850 if (!readExifHeader(stream))
851 return -1;
852
853 quint16 val;
854 quint32 offset;
855 const qint64 headerStart = 6; // the EXIF header has a constant size
856 Q_ASSERT(headerStart == stream.device()->pos());
857
858 // read byte order marker
859 stream >> val;
860 if (val == 0x4949) // 'II' == Intel
861 stream.setByteOrder(QDataStream::LittleEndian);
862 else if (val == 0x4d4d) // 'MM' == Motorola
863 stream.setByteOrder(QDataStream::BigEndian);
864 else
865 return -1; // unknown byte order
866
867 // confirm byte order
868 stream >> val;
869 if (val != 0x2a)
870 return -1;
871
872 stream >> offset;
873
874 // read IFD
875 for (int n = 0; n < maxIfdCount; ++n) {
876 quint16 numEntries;
877
878 const qint64 bytesToSkip = offset - (stream.device()->pos() - headerStart);
879 if (bytesToSkip < 0 || (offset + headerStart >= exifData.size())) {
880 // disallow going backwards, though it's permitted in the spec
881 return -1;
882 } else if (bytesToSkip != 0) {
883 // seek to the IFD
884 if (!stream.device()->seek(offset + headerStart))
885 return -1;
886 }
887
888 stream >> numEntries;
889
890 for (; numEntries > 0 && stream.status() == QDataStream::Ok; --numEntries) {
891 quint16 tag;
892 quint16 type;
893 quint32 components;
894 quint16 value;
895 quint16 dummy;
896
897 stream >> tag >> type >> components >> value >> dummy;
898 if (tag == 0x0112) { // Tag Exif.Image.Orientation
899 if (components != 1)
900 return -1;
901 if (type != 3) // we are expecting it to be an unsigned short
902 return -1;
903 if (value < 1 || value > 8) // check for valid range
904 return -1;
905
906 // It is possible to include the orientation multiple times.
907 // Right now the first value is returned.
908 return value;
909 }
910 }
911
912 // read offset to next IFD
913 if (!(stream >> offset))
914 return -1;
915 if (offset == 0) // this is the last IFD
916 return 0; // No Exif orientation was found
917 }
918
919 // too many IFDs
920 return -1;
921}
922
923static QImageIOHandler::Transformations exif2Qt(int exifOrientation)
924{
925 switch (exifOrientation) {
926 case 1: // normal
927 return QImageIOHandler::TransformationNone;
928 case 2: // mirror horizontal
929 return QImageIOHandler::TransformationMirror;
930 case 3: // rotate 180
931 return QImageIOHandler::TransformationRotate180;
932 case 4: // mirror vertical
933 return QImageIOHandler::TransformationFlip;
934 case 5: // mirror horizontal and rotate 270 CW
935 return QImageIOHandler::TransformationFlipAndRotate90;
936 case 6: // rotate 90 CW
937 return QImageIOHandler::TransformationRotate90;
938 case 7: // mirror horizontal and rotate 90 CW
939 return QImageIOHandler::TransformationMirrorAndRotate90;
940 case 8: // rotate 270 CW
941 return QImageIOHandler::TransformationRotate270;
942 }
943 qCWarning(lcJpeg, "Invalid EXIF orientation");
944 return QImageIOHandler::TransformationNone;
945}
946
947/*!
948 \internal
949*/
950bool QJpegHandlerPrivate::readJpegHeader(QIODevice *device)
951{
952 if (state == Ready)
953 {
954 state = Error;
955 iod_src = new my_jpeg_source_mgr(device);
956
957 info.err = jpeg_std_error(&err);
958 err.error_exit = my_error_exit;
959 err.output_message = my_output_message;
960
961 jpeg_create_decompress(&info);
962 info.src = iod_src;
963
964 if (!setjmp(err.setjmp_buffer)) {
965 jpeg_save_markers(&info, JPEG_COM, 0xFFFF);
966 jpeg_save_markers(&info, JPEG_APP0 + 1, 0xFFFF); // Exif uses APP1 marker
967 jpeg_save_markers(&info, JPEG_APP0 + 2, 0xFFFF); // ICC uses APP2 marker
968
969 (void) jpeg_read_header(&info, TRUE);
970
971 int width = 0;
972 int height = 0;
973 read_jpeg_size(width, height, &info);
974 size = QSize(width, height);
975
976 format = QImage::Format_Invalid;
977 read_jpeg_format(format, &info);
978
979 QByteArray exifData;
980
981 for (jpeg_saved_marker_ptr marker = info.marker_list; marker != nullptr; marker = marker->next) {
982 if (marker->marker == JPEG_COM) {
983#ifndef QT_NO_IMAGEIO_TEXT_LOADING
984 QString key, value;
985 QString s = QString::fromUtf8((const char *)marker->data, marker->data_length);
986 int index = s.indexOf(QLatin1String(": "));
987 if (index == -1 || s.indexOf(QLatin1Char(' ')) < index) {
988 key = QLatin1String("Description");
989 value = s;
990 } else {
991 key = s.left(index);
992 value = s.mid(index + 2);
993 }
994 if (!description.isEmpty())
995 description += QLatin1String("\n\n");
996 description += key + QLatin1String(": ") + value.simplified();
997 readTexts.append(key);
998 readTexts.append(value);
999#endif
1000 } else if (marker->marker == JPEG_APP0 + 1) {
1001 exifData.append((const char*)marker->data, marker->data_length);
1002 } else if (marker->marker == JPEG_APP0 + 2) {
1003 if (marker->data_length > 128 + 4 + 14 && strcmp((const char *)marker->data, "ICC_PROFILE") == 0) {
1004 iccProfile.append((const char*)marker->data + 14, marker->data_length - 14);
1005 }
1006 }
1007 }
1008
1009 if (!exifData.isEmpty()) {
1010 // Exif data present
1011 int exifOrientation = getExifOrientation(exifData);
1012 if (exifOrientation > 0)
1013 transformation = exif2Qt(exifOrientation);
1014 }
1015
1016 state = ReadHeader;
1017 return true;
1018 }
1019 else {
1020 my_output_message(j_common_ptr(&info));
1021 return false;
1022 }
1023 }
1024 else if (state == Error)
1025 return false;
1026 return true;
1027}
1028
1029bool QJpegHandlerPrivate::read(QImage *image)
1030{
1031 if (state == Ready)
1032 readJpegHeader(q->device());
1033
1034 if (state == ReadHeader)
1035 {
1036 const bool invertCMYK = subType != QJpegHandlerPrivate::SubType::CMYK;
1037 bool success = read_jpeg_image(image, scaledSize, scaledClipRect, clipRect, quality, rgb888ToRgb32ConverterPtr, &info, &err, invertCMYK);
1038 if (success) {
1039 for (int i = 0; i < readTexts.size()-1; i+=2)
1040 image->setText(readTexts.at(i), readTexts.at(i+1));
1041
1042 if (!iccProfile.isEmpty())
1043 image->setColorSpace(QColorSpace::fromIccProfile(iccProfile));
1044
1045 state = ReadingEnd;
1046 return true;
1047 }
1048
1049 state = Error;
1050 }
1051
1052 return false;
1053}
1054
1055Q_GUI_EXPORT void QT_FASTCALL qt_convert_rgb888_to_rgb32_neon(quint32 *dst, const uchar *src, int len);
1056Q_GUI_EXPORT void QT_FASTCALL qt_convert_rgb888_to_rgb32_ssse3(quint32 *dst, const uchar *src, int len);
1057extern "C" void qt_convert_rgb888_to_rgb32_mips_dspr2_asm(quint32 *dst, const uchar *src, int len);
1058
1060 : d(new QJpegHandlerPrivate(this))
1061{
1062#if defined(__ARM_NEON__)
1063 // from qimage_neon.cpp
1064 if (qCpuHasFeature(NEON))
1065 d->rgb888ToRgb32ConverterPtr = qt_convert_rgb888_to_rgb32_neon;
1066#endif
1067
1068#if defined(QT_COMPILER_SUPPORTS_SSSE3)
1069 // from qimage_ssse3.cpps
1070 if (qCpuHasFeature(SSSE3)) {
1071 d->rgb888ToRgb32ConverterPtr = qt_convert_rgb888_to_rgb32_ssse3;
1072 }
1073#endif // QT_COMPILER_SUPPORTS_SSSE3
1074#if defined(QT_COMPILER_SUPPORTS_MIPS_DSPR2)
1075 if (qCpuHasFeature(DSPR2)) {
1076 d->rgb888ToRgb32ConverterPtr = qt_convert_rgb888_to_rgb32_mips_dspr2_asm;
1077 }
1078#endif // QT_COMPILER_SUPPORTS_DSPR2
1079}
1080
1082{
1083 delete d;
1084}
1085
1087{
1088 if (d->state == QJpegHandlerPrivate::Ready && !canRead(device()))
1089 return false;
1090
1092 setFormat("jpeg");
1093 return true;
1094 }
1095
1096 return false;
1097}
1098
1099bool QJpegHandler::canRead(QIODevice *device)
1100{
1101 if (!device) {
1102 qCWarning(lcJpeg, "QJpegHandler::canRead() called with no device");
1103 return false;
1104 }
1105
1106 char buffer[2];
1107 if (device->peek(buffer, 2) != 2)
1108 return false;
1109 return uchar(buffer[0]) == 0xff && uchar(buffer[1]) == 0xd8;
1110}
1111
1112bool QJpegHandler::read(QImage *image)
1113{
1114 if (!canRead())
1115 return false;
1116 return d->read(image);
1117}
1118
1119extern void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orient);
1120
1121bool QJpegHandler::write(const QImage &image)
1122{
1123 const bool invertCMYK = d->subType != QJpegHandlerPrivate::SubType::CMYK;
1124 if (d->transformation != QImageIOHandler::TransformationNone) {
1125 // We don't support writing EXIF headers so apply the transform to the data.
1126 QImage img = image;
1127 qt_imageTransform(img, d->transformation);
1128 return write_jpeg_image(img, device(), d->quality, d->description, d->optimize, d->progressive, invertCMYK);
1129 }
1130 return write_jpeg_image(image, device(), d->quality, d->description, d->optimize, d->progressive, invertCMYK);
1131}
1132
1133bool QJpegHandler::supportsOption(ImageOption option) const
1134{
1135 return option == Quality
1136 || option == ScaledSize
1137 || option == ScaledClipRect
1138 || option == ClipRect
1139 || option == Description
1140 || option == Size
1141 || option == SubType
1142 || option == SupportedSubTypes
1143 || option == ImageFormat
1144 || option == OptimizedWrite
1145 || option == ProgressiveScanWrite
1146 || option == ImageTransformation;
1147}
1148
1149QVariant QJpegHandler::option(ImageOption option) const
1150{
1151 switch(option) {
1152 case Quality:
1153 return d->quality;
1154 case ScaledSize:
1155 return d->scaledSize;
1156 case ScaledClipRect:
1157 return d->scaledClipRect;
1158 case ClipRect:
1159 return d->clipRect;
1160 case Description:
1161 d->readJpegHeader(device());
1162 return d->description;
1163 case Size:
1164 d->readJpegHeader(device());
1165 return d->size;
1166 case SubType:
1167 return QByteArray(SupportedJPEGSubtypes[int(d->subType)]);
1168 case SupportedSubTypes: {
1169 QByteArrayList list(std::begin(SupportedJPEGSubtypes),
1171 return QVariant::fromValue(list);
1172 }
1173 case ImageFormat:
1174 d->readJpegHeader(device());
1175 return d->format;
1176 case OptimizedWrite:
1177 return d->optimize;
1178 case ProgressiveScanWrite:
1179 return d->progressive;
1180 case ImageTransformation:
1181 d->readJpegHeader(device());
1182 return int(d->transformation);
1183 default:
1184 break;
1185 }
1186
1187 return QVariant();
1188}
1189
1190void QJpegHandler::setOption(ImageOption option, const QVariant &value)
1191{
1192 switch(option) {
1193 case Quality:
1194 d->quality = value.toInt();
1195 break;
1196 case ScaledSize:
1197 d->scaledSize = value.toSize();
1198 break;
1199 case ScaledClipRect:
1200 d->scaledClipRect = value.toRect();
1201 break;
1202 case ClipRect:
1203 d->clipRect = value.toRect();
1204 break;
1205 case Description:
1206 d->description = value.toString();
1207 break;
1208 case SubType: {
1209 const QByteArray subType = value.toByteArray();
1210 for (size_t i = 0; i < std::size(SupportedJPEGSubtypes); ++i) {
1211 if (subType == SupportedJPEGSubtypes[i]) {
1213 break;
1214 }
1215 }
1216 break;
1217 }
1218 case OptimizedWrite:
1219 d->optimize = value.toBool();
1220 break;
1221 case ProgressiveScanWrite:
1222 d->progressive = value.toBool();
1223 break;
1224 case ImageTransformation: {
1225 int transformation = value.toInt();
1226 if (transformation > 0 && transformation < 8)
1227 d->transformation = QImageIOHandler::Transformations(transformation);
1228 break;
1229 }
1230 default:
1231 break;
1232 }
1233}
1234
1235QT_END_NAMESPACE
\inmodule QtGui
Definition qimage.h:37
bool readJpegHeader(QIODevice *)
struct my_error_mgr err
struct jpeg_decompress_struct info
Rgb888ToRgb32Converter rgb888ToRgb32ConverterPtr
struct my_jpeg_source_mgr * iod_src
bool read(QImage *image)
QJpegHandlerPrivate(QJpegHandler *qq)
QImageIOHandler::Transformations transformation
bool canRead() const override
Returns true if an image can be read from the device (i.e., the image format is supported,...
uint QT_FASTCALL fetch1Pixel< QPixelLayout::BPP1LSB >(const uchar *src, int index)
void qt_convert_rgb888_to_rgb32_mips_dspr2_asm(uint *dst, const uchar *src, int len)
static void my_error_exit(j_common_ptr cinfo)
#define HIGH_QUALITY_THRESHOLD
static void qt_init_source(j_decompress_ptr)
static void my_output_message(j_common_ptr cinfo)
static void qt_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
static void set_text(const QImage &image, j_compress_ptr cinfo, const QString &description)
static void write_icc_profile(const QImage &image, j_compress_ptr cinfo)
static bool read_jpeg_image(QImage *outImage, QSize scaledSize, QRect scaledClipRect, QRect clipRect, int quality, Rgb888ToRgb32Converter converter, j_decompress_ptr info, struct my_error_mgr *err, bool invertCMYK)
static bool do_write_jpeg_image(struct jpeg_compress_struct &cinfo, JSAMPROW *row_pointer, const QImage &image, QIODevice *device, int sourceQuality, const QString &description, bool optimize, bool progressive, bool invertCMYK)
static bool readExifHeader(QDataStream &stream)
void(QT_FASTCALL * Rgb888ToRgb32Converter)(quint32 *dst, const uchar *src, int len)
static bool ensureValidImage(QImage *dest, struct jpeg_decompress_struct *info, const QSize &size)
static bool read_jpeg_format(QImage::Format &format, j_decompress_ptr cinfo)
static constexpr int maxMarkerSize
static void qt_init_destination(j_compress_ptr)
static void qt_term_destination(j_compress_ptr cinfo)
void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orient)
Definition qimage.cpp:6516
static void qt_term_source(j_decompress_ptr cinfo)
static const char SupportedJPEGSubtypes[][14]
static bool read_jpeg_size(int &w, int &h, j_decompress_ptr cinfo)
static int getExifOrientation(QByteArray &exifData)
static boolean qt_empty_output_buffer(j_compress_ptr cinfo)
static boolean qt_fill_input_buffer(j_decompress_ptr cinfo)
static QImageIOHandler::Transformations exif2Qt(int exifOrientation)
static const int max_buf
static bool write_jpeg_image(const QImage &image, QIODevice *device, int sourceQuality, const QString &description, bool optimize, bool progressive, bool invertCMYK)
#define Q_LOGGING_CATEGORY(name,...)
#define qCWarning(category,...)
jmp_buf setjmp_buffer
my_jpeg_destination_mgr(QIODevice *)
const QBuffer * memDevice
my_jpeg_source_mgr(QIODevice *device)
JOCTET buffer[max_buf]