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
qwebphandler.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 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#include "webp/mux.h"
7#include "webp/encode.h"
8#include <qcolor.h>
9#include <qimage.h>
10#include <qdebug.h>
11#include <qpainter.h>
12#include <qvariant.h>
13#include <QtEndian>
14
15static const int riffHeaderSize = 12; // RIFF_HEADER_SIZE from webp/format_constants.h
16
17QT_BEGIN_NAMESPACE
18
19QWebpHandler::QWebpHandler() :
20 m_quality(75),
21 m_scanState(ScanNotScanned),
22 m_features(),
23 m_formatFlags(0),
24 m_loop(0),
25 m_frameCount(0),
26 m_demuxer(NULL),
27 m_composited(NULL)
28{
29 memset(&m_iter, 0, sizeof(m_iter));
30}
31
32QWebpHandler::~QWebpHandler()
33{
34 WebPDemuxReleaseIterator(&m_iter);
35 WebPDemuxDelete(m_demuxer);
36 delete m_composited;
37}
38
39bool QWebpHandler::canRead() const
40{
41 if (m_scanState == ScanNotScanned && !canRead(device()))
42 return false;
43
44 if (m_scanState != ScanError) {
45 setFormat(QByteArrayLiteral("webp"));
46
47 if (m_features.has_animation && m_iter.frame_num >= m_frameCount)
48 return false;
49
50 return true;
51 }
52 return false;
53}
54
55bool QWebpHandler::canRead(QIODevice *device)
56{
57 if (!device) {
58 qWarning("QWebpHandler::canRead() called with no device");
59 return false;
60 }
61
62 QByteArray header = device->peek(riffHeaderSize);
63 return header.startsWith("RIFF") && header.endsWith("WEBP");
64}
65
66bool QWebpHandler::ensureScanned() const
67{
68 if (m_scanState != ScanNotScanned)
69 return m_scanState == ScanSuccess;
70
71 m_scanState = ScanError;
72
73 QWebpHandler *that = const_cast<QWebpHandler *>(this);
74 // A complete, small image may be shorter than this
75 const int headerBytesNeeded = sizeof(WebPBitstreamFeatures);
76 QByteArray header = device()->peek(headerBytesNeeded);
77 if (header.size() < riffHeaderSize)
78 return false;
79
80 // We do no random access during decoding, just a readAll() of the whole image file. So if
81 // if it is all available already, we can accept a sequential device. The riff header contains
82 // the file size minus 8 bytes header
83 qint64 byteSize = qFromLittleEndian<quint32>(header.constData() + 4);
84 if (device()->isSequential() && device()->bytesAvailable() < byteSize + 8) {
85 qWarning() << "QWebpHandler: Insufficient data available in sequential device";
86 return false;
87 }
88 if (WebPGetFeatures((const uint8_t*)header.constData(), header.size(), &(that->m_features)) == VP8_STATUS_OK) {
89 if (m_features.has_animation) {
90 // For animation, we have to read and scan whole file to determine loop count and images count
91 if (that->ensureDemuxer()) {
92 that->m_loop = WebPDemuxGetI(m_demuxer, WEBP_FF_LOOP_COUNT);
93 that->m_frameCount = WebPDemuxGetI(m_demuxer, WEBP_FF_FRAME_COUNT);
94 that->m_bgColor = QColor::fromRgba(QRgb(WebPDemuxGetI(m_demuxer, WEBP_FF_BACKGROUND_COLOR)));
95
96 QSize sz(that->m_features.width, that->m_features.height);
97 that->m_composited = new QImage;
98 if (!QImageIOHandler::allocateImage(sz, QImage::Format_ARGB32, that->m_composited))
99 return false;
100 // Ensure whole image is initialized; anim frames may cover only partially
101 that->m_composited->fill(m_features.has_alpha ? QColor(Qt::transparent) : m_bgColor);
102
103 m_scanState = ScanSuccess;
104 }
105 } else {
106 m_scanState = ScanSuccess;
107 }
108 }
109
110 return m_scanState == ScanSuccess;
111}
112
113bool QWebpHandler::ensureDemuxer()
114{
115 if (m_demuxer)
116 return true;
117
118 m_rawData = device()->readAll();
119
120 m_demuxer = [&] {
121 WebPData data = {};
122 data.bytes = reinterpret_cast<const uint8_t *>(m_rawData.constData());
123 data.size = m_rawData.size();
124 return WebPDemux(&data); // reads `*data`, doesn't store `data`
125 }();
126
127 if (m_demuxer == NULL)
128 return false;
129
130 m_formatFlags = WebPDemuxGetI(m_demuxer, WEBP_FF_FORMAT_FLAGS);
131 return true;
132}
133
134bool QWebpHandler::read(QImage *image)
135{
136 if (!ensureScanned() || !ensureDemuxer())
137 return false;
138
139 QRect prevFrameRect;
140 if (m_iter.frame_num == 0) {
141 // Read global meta-data chunks first
142 WebPChunkIterator metaDataIter;
143 if ((m_formatFlags & ICCP_FLAG) && WebPDemuxGetChunk(m_demuxer, "ICCP", 1, &metaDataIter)) {
144 QByteArray iccProfile = QByteArray::fromRawData(reinterpret_cast<const char *>(metaDataIter.chunk.bytes),
145 metaDataIter.chunk.size);
146 // Ensure the profile is 4-byte aligned.
147 if (reinterpret_cast<qintptr>(iccProfile.constData()) & 0x3)
148 iccProfile.detach();
149 m_colorSpace = QColorSpace::fromIccProfile(iccProfile);
150 // ### consider parsing EXIF and/or XMP metadata too.
151 WebPDemuxReleaseChunkIterator(&metaDataIter);
152 }
153
154 // Go to first frame
155 if (!WebPDemuxGetFrame(m_demuxer, 1, &m_iter))
156 return false;
157 } else {
158 if (m_iter.has_alpha && m_iter.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND)
159 prevFrameRect = currentImageRect();
160
161 // Go to next frame
162 if (!WebPDemuxNextFrame(&m_iter))
163 return false;
164 }
165
166 WebPBitstreamFeatures features;
167 VP8StatusCode status = WebPGetFeatures(m_iter.fragment.bytes, m_iter.fragment.size, &features);
168 if (status != VP8_STATUS_OK)
169 return false;
170
171 QImage::Format format = m_features.has_alpha ? QImage::Format_ARGB32 : QImage::Format_RGB32;
172 QImage frame;
173 if (!QImageIOHandler::allocateImage(QSize(m_iter.width, m_iter.height), format, &frame))
174 return false;
175 uint8_t *output = frame.bits();
176 size_t output_size = frame.sizeInBytes();
177#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
178 if (!WebPDecodeBGRAInto(
179 reinterpret_cast<const uint8_t*>(m_iter.fragment.bytes), m_iter.fragment.size,
180 output, output_size, frame.bytesPerLine()))
181#else
182 if (!WebPDecodeARGBInto(
183 reinterpret_cast<const uint8_t*>(m_iter.fragment.bytes), m_iter.fragment.size,
184 output, output_size, frame.bytesPerLine()))
185#endif
186 return false;
187
188 if (m_features.has_animation) {
189 // Animation
190 QPainter painter(m_composited);
191 if (!prevFrameRect.isEmpty()) {
192 painter.setCompositionMode(QPainter::CompositionMode_Clear);
193 painter.fillRect(prevFrameRect, Qt::black);
194 }
195 if (m_features.has_alpha) {
196 if (m_iter.blend_method == WEBP_MUX_NO_BLEND)
197 painter.setCompositionMode(QPainter::CompositionMode_Source);
198 else
199 painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
200 }
201 painter.drawImage(currentImageRect(), frame);
202
203 *image = *m_composited;
204 } else {
205 // Single image
206 *image = std::move(frame);
207 }
208 image->setColorSpace(m_colorSpace);
209
210 return true;
211}
212
213bool QWebpHandler::write(const QImage &image)
214{
215 if (image.isNull()) {
216 qWarning() << "source image is null.";
217 return false;
218 }
219 if (std::max(image.width(), image.height()) > WEBP_MAX_DIMENSION) {
220 qWarning() << "QWebpHandler::write() source image too large for WebP: " << image.size();
221 return false;
222 }
223
224 const bool alpha = image.hasAlphaChannel();
225 QImage::Format newFormat = alpha ? QImage::Format_RGBA8888 : QImage::Format_RGB888;
226 const QImage srcImage = (image.format() == newFormat) ? image : image.convertedTo(newFormat);
227
228 WebPPicture picture;
229 WebPConfig config;
230
231 if (!WebPPictureInit(&picture) || !WebPConfigInit(&config)) {
232 qWarning() << "failed to init webp picture and config";
233 return false;
234 }
235
236 picture.width = srcImage.width();
237 picture.height = srcImage.height();
238 picture.use_argb = 1;
239 bool failed = false;
240 if (alpha)
241 failed = !WebPPictureImportRGBA(&picture, srcImage.constBits(), srcImage.bytesPerLine());
242 else
243 failed = !WebPPictureImportRGB(&picture, srcImage.constBits(), srcImage.bytesPerLine());
244
245 if (failed) {
246 qWarning() << "failed to import image data to webp picture.";
247 WebPPictureFree(&picture);
248 return false;
249 }
250
251 int reqQuality = m_quality < 0 ? 75 : qMin(m_quality, 100);
252 if (reqQuality < 100) {
253 config.lossless = 0;
254 config.quality = reqQuality;
255 } else {
256 config.lossless = 1;
257 config.quality = 70; // For lossless, specifies compression effort; 70 is libwebp default
258 }
259 config.alpha_quality = config.quality;
260 WebPMemoryWriter writer;
261 WebPMemoryWriterInit(&writer);
262 picture.writer = WebPMemoryWrite;
263 picture.custom_ptr = &writer;
264
265 if (!WebPEncode(&config, &picture)) {
266 qWarning() << "failed to encode webp picture, error code: " << picture.error_code;
267 WebPPictureFree(&picture);
268 WebPMemoryWriterClear(&writer);
269 return false;
270 }
271
272 bool res = false;
273 if (image.colorSpace().isValid()) {
274 int copy_data = 0;
275 WebPMux *mux = WebPMuxNew();
276 WebPData image_data = { writer.mem, writer.size };
277 WebPMuxSetImage(mux, &image_data, copy_data);
278 uint8_t vp8xChunk[10];
279 uint8_t flags = 0x20; // Has ICCP chunk, no XMP, EXIF or animation.
280 if (image.hasAlphaChannel())
281 flags |= 0x10;
282 vp8xChunk[0] = flags;
283 vp8xChunk[1] = 0;
284 vp8xChunk[2] = 0;
285 vp8xChunk[3] = 0;
286 const unsigned width = image.width() - 1;
287 const unsigned height = image.height() - 1;
288 vp8xChunk[4] = width & 0xff;
289 vp8xChunk[5] = (width >> 8) & 0xff;
290 vp8xChunk[6] = (width >> 16) & 0xff;
291 vp8xChunk[7] = height & 0xff;
292 vp8xChunk[8] = (height >> 8) & 0xff;
293 vp8xChunk[9] = (height >> 16) & 0xff;
294 WebPData vp8x_data = { vp8xChunk, 10 };
295 if (WebPMuxSetChunk(mux, "VP8X", &vp8x_data, copy_data) == WEBP_MUX_OK) {
296 QByteArray iccProfile = image.colorSpace().iccProfile();
297 WebPData iccp_data = {
298 reinterpret_cast<const uint8_t *>(iccProfile.constData()),
299 static_cast<size_t>(iccProfile.size())
300 };
301 if (WebPMuxSetChunk(mux, "ICCP", &iccp_data, copy_data) == WEBP_MUX_OK) {
302 WebPData output_data;
303 if (WebPMuxAssemble(mux, &output_data) == WEBP_MUX_OK) {
304 res = (output_data.size ==
305 static_cast<size_t>(device()->write(reinterpret_cast<const char *>(output_data.bytes), output_data.size)));
306 }
307 WebPDataClear(&output_data);
308 }
309 }
310 WebPMuxDelete(mux);
311 }
312 if (!res) {
313 res = (writer.size ==
314 static_cast<size_t>(device()->write(reinterpret_cast<const char *>(writer.mem), writer.size)));
315 }
316 WebPPictureFree(&picture);
317 WebPMemoryWriterClear(&writer);
318
319 return res;
320}
321
322QVariant QWebpHandler::option(ImageOption option) const
323{
324 if (!supportsOption(option) || !ensureScanned())
325 return QVariant();
326
327 switch (option) {
328 case Quality:
329 return m_quality;
330 case Size:
331 return QSize(m_features.width, m_features.height);
332 case Animation:
333 return m_features.has_animation;
334 case BackgroundColor:
335 return m_bgColor;
336 default:
337 return QVariant();
338 }
339}
340
341void QWebpHandler::setOption(ImageOption option, const QVariant &value)
342{
343 switch (option) {
344 case Quality:
345 m_quality = value.toInt();
346 return;
347 default:
348 break;
349 }
350 QImageIOHandler::setOption(option, value);
351}
352
353bool QWebpHandler::supportsOption(ImageOption option) const
354{
355 return option == Quality
356 || option == Size
357 || option == Animation
358 || option == BackgroundColor;
359}
360
361int QWebpHandler::imageCount() const
362{
363 if (!ensureScanned())
364 return 0;
365
366 if (!m_features.has_animation)
367 return 1;
368
369 return m_frameCount;
370}
371
372int QWebpHandler::currentImageNumber() const
373{
374 if (!ensureScanned() || !m_features.has_animation)
375 return 0;
376
377 // Frame number in WebP starts from 1
378 return m_iter.frame_num - 1;
379}
380
381QRect QWebpHandler::currentImageRect() const
382{
383 if (!ensureScanned())
384 return QRect();
385
386 return QRect(m_iter.x_offset, m_iter.y_offset, m_iter.width, m_iter.height);
387}
388
389int QWebpHandler::loopCount() const
390{
391 if (!ensureScanned() || !m_features.has_animation)
392 return 0;
393
394 // Loop count in WebP starts from 0
395 return m_loop - 1;
396}
397
398int QWebpHandler::nextImageDelay() const
399{
400 if (!ensureScanned() || !m_features.has_animation)
401 return 0;
402
403 return m_iter.duration;
404}
405
406QT_END_NAMESPACE
QIODevice * device() const
Returns the device currently assigned to QImageReader, or \nullptr if no device has been assigned.
static const int riffHeaderSize