1/*
2 Softimage PIC support for QImage.
3
4 SPDX-FileCopyrightText: 1998 Halfdan Ingvarsson
5 SPDX-FileCopyrightText: 2007 Ruben Lopez <r.lopez@bren.es>
6 SPDX-FileCopyrightText: 2014 Alex Merry <alex.merry@kde.org>
7
8 SPDX-License-Identifier: LGPL-2.0-or-later
9*/
10
11/* This code is based on the GIMP-PIC plugin by Halfdan Ingvarsson,
12 * and relicensed from GPL to LGPL to accommodate the KDE licensing policy
13 * with his permission.
14 */
15
16#include "pic_p.h"
17#include "rle_p.h"
18#include "scanlineconverter_p.h"
19#include "util_p.h"
20
21#include <QColorSpace>
22#include <QDataStream>
23#include <QImage>
24#include <QLoggingCategory>
25#include <QVariant>
26
27#include <algorithm>
28#include <functional>
29#include <qendian.h>
30#include <utility>
31
32#ifdef QT_DEBUG
33Q_LOGGING_CATEGORY(LOG_PICPLUGIN, "kf.imageformats.plugins.pic", QtDebugMsg)
34#else
35Q_LOGGING_CATEGORY(LOG_PICPLUGIN, "kf.imageformats.plugins.pic", QtWarningMsg)
36#endif
37
38/**
39 * Reads a PIC file header from a data stream.
40 *
41 * @param s The data stream to read from.
42 * @param channels Where the read header will be stored.
43 * @returns @p s
44 *
45 * @relates PicHeader
46 */
47static QDataStream &operator>>(QDataStream &s, PicHeader &header)
48{
49 s.setFloatingPointPrecision(QDataStream::SinglePrecision);
50 s >> header.magic;
51 s >> header.version;
52
53 // the comment should be truncated to the first null byte
54 char comment[81] = {};
55 s.readRawData(comment, len: 80);
56 header.comment = QByteArray(comment);
57
58 header.id.resize(size: 4);
59 const int bytesRead = s.readRawData(header.id.data(), len: 4);
60 if (bytesRead != 4) {
61 header.id.resize(size: bytesRead);
62 }
63
64 s >> header.width;
65 s >> header.height;
66 s >> header.ratio;
67 qint16 fields;
68 s >> fields;
69 header.fields = static_cast<PicFields>(fields);
70 qint16 pad;
71 s >> pad;
72 return s;
73}
74
75/**
76 * Writes a PIC file header to a data stream.
77 *
78 * @param s The data stream to write to.
79 * @param channels The header to write.
80 * @returns @p s
81 *
82 * @relates PicHeader
83 */
84static QDataStream &operator<<(QDataStream &s, const PicHeader &header)
85{
86 s.setFloatingPointPrecision(QDataStream::SinglePrecision);
87 s << header.magic;
88 s << header.version;
89
90 char comment[80] = {};
91 strncpy(dest: comment, src: header.comment.constData(), n: sizeof(comment));
92 s.writeRawData(comment, len: sizeof(comment));
93
94 char id[4] = {};
95 strncpy(dest: id, src: header.id.constData(), n: sizeof(id));
96 s.writeRawData(id, len: sizeof(id));
97
98 s << header.width;
99 s << header.height;
100 s << header.ratio;
101 s << quint16(header.fields);
102 s << quint16(0);
103 return s;
104}
105
106/**
107 * Reads a series of channel descriptions from a data stream.
108 *
109 * If the stream contains more than 8 channel descriptions, the status of @p s
110 * will be set to QDataStream::ReadCorruptData (note that more than 4 channels
111 * - one for each component - does not really make sense anyway).
112 *
113 * @param s The data stream to read from.
114 * @param channels The location to place the read channel descriptions; any
115 * existing entries will be cleared.
116 * @returns @p s
117 *
118 * @relates PicChannel
119 */
120static QDataStream &operator>>(QDataStream &s, QList<PicChannel> &channels)
121{
122 const unsigned maxChannels = 8;
123 unsigned count = 0;
124 quint8 chained = 1;
125 channels.clear();
126 while (chained && count < maxChannels && s.status() == QDataStream::Ok) {
127 PicChannel channel;
128 s >> chained;
129 s >> channel.size;
130 s >> channel.encoding;
131 s >> channel.code;
132 channels << channel;
133 ++count;
134 }
135 if (chained) {
136 // too many channels!
137 s.setStatus(QDataStream::ReadCorruptData);
138 }
139 return s;
140}
141
142/**
143 * Writes a series of channel descriptions to a data stream.
144 *
145 * Note that the corresponding read operation will not read more than 8 channel
146 * descriptions, although there should be no reason to have more than 4 channels
147 * anyway.
148 *
149 * @param s The data stream to write to.
150 * @param channels The channel descriptions to write.
151 * @returns @p s
152 *
153 * @relates PicChannel
154 */
155static QDataStream &operator<<(QDataStream &s, const QList<PicChannel> &channels)
156{
157 Q_ASSERT(channels.size() > 0);
158 for (int i = 0; i < channels.size() - 1; ++i) {
159 s << quint8(1); // chained
160 s << channels[i].size;
161 s << quint8(channels[i].encoding);
162 s << channels[i].code;
163 }
164 s << quint8(0); // chained
165 s << channels.last().size;
166 s << quint8(channels.last().encoding);
167 s << channels.last().code;
168 return s;
169}
170
171static bool readRow(QDataStream &stream, QRgb *row, quint16 width, const QList<PicChannel> &channels)
172{
173 for (const PicChannel &channel : channels) {
174 auto readPixel = [&](QDataStream &str) -> QRgb {
175 quint8 red = 0;
176 if (channel.code & RED) {
177 str >> red;
178 }
179 quint8 green = 0;
180 if (channel.code & GREEN) {
181 str >> green;
182 }
183 quint8 blue = 0;
184 if (channel.code & BLUE) {
185 str >> blue;
186 }
187 quint8 alpha = 0;
188 if (channel.code & ALPHA) {
189 str >> alpha;
190 }
191 return qRgba(r: red, g: green, b: blue, a: alpha);
192 };
193 auto updatePixel = [&](QRgb oldPixel, QRgb newPixel) -> QRgb {
194 return qRgba(r: qRed(rgb: (channel.code & RED) ? newPixel : oldPixel),
195 g: qGreen(rgb: (channel.code & GREEN) ? newPixel : oldPixel),
196 b: qBlue(rgb: (channel.code & BLUE) ? newPixel : oldPixel),
197 a: qAlpha(rgb: (channel.code & ALPHA) ? newPixel : oldPixel));
198 };
199 if (channel.encoding == MixedRLE) {
200 bool success = decodeRLEData(variant: RLEVariant::PIC, stream, dest: row, length: width, readData: readPixel, updateItem: updatePixel);
201 if (!success) {
202 qCDebug(LOG_PICPLUGIN) << "decodeRLEData failed";
203 return false;
204 }
205 } else if (channel.encoding == Uncompressed) {
206 for (quint16 i = 0; i < width; ++i) {
207 QRgb pixel = readPixel(stream);
208 row[i] = updatePixel(row[i], pixel);
209 }
210 } else {
211 // unknown encoding
212 qCDebug(LOG_PICPLUGIN) << "Unknown encoding";
213 return false;
214 }
215 }
216 if (stream.status() != QDataStream::Ok) {
217 qCDebug(LOG_PICPLUGIN) << "DataStream status was" << stream.status();
218 }
219 return stream.status() == QDataStream::Ok;
220}
221
222bool SoftimagePICHandler::canRead() const
223{
224 if (!SoftimagePICHandler::canRead(device: device())) {
225 return false;
226 }
227 setFormat("pic");
228 return true;
229}
230
231bool SoftimagePICHandler::read(QImage *image)
232{
233 if (!readChannels()) {
234 return false;
235 }
236
237 QImage::Format fmt = QImage::Format_RGB32;
238 for (const PicChannel &channel : std::as_const(t&: m_channels)) {
239 if (channel.size != 8) {
240 // we cannot read images that do not come in bytes
241 qCDebug(LOG_PICPLUGIN) << "Channel size was" << channel.size;
242 m_state = Error;
243 return false;
244 }
245 if (channel.code & ALPHA) {
246 fmt = QImage::Format_ARGB32;
247 }
248 }
249
250 QImage img = imageAlloc(width: m_header.width, height: m_header.height, format: fmt);
251 if (img.isNull()) {
252 qCDebug(LOG_PICPLUGIN) << "Failed to allocate image, invalid dimensions?" << QSize(m_header.width, m_header.height) << fmt;
253 return false;
254 }
255
256 img.fill(pixel: qRgb(r: 0, g: 0, b: 0));
257
258 for (int y = 0; y < m_header.height; y++) {
259 QRgb *row = reinterpret_cast<QRgb *>(img.scanLine(y));
260 if (!readRow(stream&: m_dataStream, row, width: m_header.width, channels: m_channels)) {
261 qCDebug(LOG_PICPLUGIN) << "readRow failed";
262 m_state = Error;
263 return false;
264 }
265 }
266
267 *image = img;
268 m_state = Ready;
269
270 return true;
271}
272
273bool SoftimagePICHandler::write(const QImage &image)
274{
275 bool alpha = image.hasAlphaChannel();
276 auto tcs = QColorSpace();
277 auto tfmt = image.format();
278 auto cs = image.colorSpace();
279 if (cs.isValid() && cs.colorModel() == QColorSpace::ColorModel::Cmyk && tfmt == QImage::Format_CMYK8888) {
280 tcs = QColorSpace(QColorSpace::SRgb);
281 tfmt = QImage::Format_RGB32;
282 }
283 if (tfmt != QImage::Format_ARGB32 && tfmt != QImage::Format_RGB32) {
284 tfmt = alpha ? QImage::Format_ARGB32 : QImage::Format_RGB32;
285 }
286
287 if (image.width() < 0 || image.height() < 0) {
288 qCDebug(LOG_PICPLUGIN) << "Image size invalid:" << image.width() << image.height();
289 return false;
290 }
291 if (image.width() > 65535 || image.height() > 65535) {
292 qCDebug(LOG_PICPLUGIN) << "Image too big:" << image.width() << image.height();
293 // there are only two bytes for each dimension
294 return false;
295 }
296
297 QDataStream stream(device());
298
299 stream << PicHeader(image.width(), image.height(), m_description);
300
301 PicChannelEncoding encoding = m_compression ? MixedRLE : Uncompressed;
302 QList<PicChannel> channels;
303 channels << PicChannel(encoding, RED | GREEN | BLUE);
304 if (alpha) {
305 channels << PicChannel(encoding, ALPHA);
306 }
307 stream << channels;
308
309 ScanLineConverter scl(tfmt);
310 scl.setTargetColorSpace(tcs);
311 for (int r = 0; r < image.height(); r++) {
312 const QRgb *row = reinterpret_cast<const QRgb *>(scl.convertedScanLine(image, y: r));
313
314 /* Write the RGB part of the scanline */
315 auto rgbEqual = [](QRgb p1, QRgb p2) -> bool {
316 return qRed(rgb: p1) == qRed(rgb: p2) && qGreen(rgb: p1) == qGreen(rgb: p2) && qBlue(rgb: p1) == qBlue(rgb: p2);
317 };
318 auto writeRgb = [](QDataStream &str, QRgb pixel) -> void {
319 str << quint8(qRed(rgb: pixel)) << quint8(qGreen(rgb: pixel)) << quint8(qBlue(rgb: pixel));
320 };
321 if (m_compression) {
322 encodeRLEData(variant: RLEVariant::PIC, stream, data: row, length: image.width(), itemsEqual: rgbEqual, writeItem: writeRgb);
323 } else {
324 for (int i = 0; i < image.width(); ++i) {
325 writeRgb(stream, row[i]);
326 }
327 }
328
329 /* Write the alpha channel */
330 if (alpha) {
331 auto alphaEqual = [](QRgb p1, QRgb p2) -> bool {
332 return qAlpha(rgb: p1) == qAlpha(rgb: p2);
333 };
334 auto writeAlpha = [](QDataStream &str, QRgb pixel) -> void {
335 str << quint8(qAlpha(rgb: pixel));
336 };
337 if (m_compression) {
338 encodeRLEData(variant: RLEVariant::PIC, stream, data: row, length: image.width(), itemsEqual: alphaEqual, writeItem: writeAlpha);
339 } else {
340 for (int i = 0; i < image.width(); ++i) {
341 writeAlpha(stream, row[i]);
342 }
343 }
344 }
345 }
346 return stream.status() == QDataStream::Ok;
347}
348
349bool SoftimagePICHandler::canRead(QIODevice *device)
350{
351 char data[4];
352 if (device->peek(data, maxlen: 4) != 4) {
353 return false;
354 }
355 return qFromBigEndian<qint32>(src: reinterpret_cast<uchar *>(data)) == PIC_MAGIC_NUMBER;
356}
357
358bool SoftimagePICHandler::readHeader()
359{
360 if (m_state == Ready) {
361 m_state = Error;
362 m_dataStream.setDevice(device());
363 m_dataStream >> m_header;
364 if (m_header.isValid() && m_dataStream.status() == QDataStream::Ok) {
365 m_state = ReadHeader;
366 }
367 }
368
369 return m_state != Error;
370}
371
372bool SoftimagePICHandler::readChannels()
373{
374 readHeader();
375 if (m_state == ReadHeader) {
376 m_state = Error;
377 m_dataStream >> m_channels;
378 if (m_dataStream.status() == QDataStream::Ok) {
379 m_state = ReadChannels;
380 }
381 }
382 return m_state != Error;
383}
384
385void SoftimagePICHandler::setOption(ImageOption option, const QVariant &value)
386{
387 switch (option) {
388 case CompressionRatio:
389 m_compression = value.toBool();
390 break;
391 case Description: {
392 m_description.clear();
393 const QStringList entries = value.toString().split(QStringLiteral("\n\n"));
394 for (const QString &entry : entries) {
395 if (entry.startsWith(QStringLiteral("Description: "))) {
396 m_description = entry.mid(position: 13).simplified().toUtf8();
397 }
398 }
399 break;
400 }
401 default:
402 break;
403 }
404}
405
406QVariant SoftimagePICHandler::option(ImageOption option) const
407{
408 const_cast<SoftimagePICHandler *>(this)->readHeader();
409 switch (option) {
410 case Size:
411 if (const_cast<SoftimagePICHandler *>(this)->readHeader()) {
412 return QSize(m_header.width, m_header.height);
413 } else {
414 return QVariant();
415 }
416 case CompressionRatio:
417 return m_compression;
418 case Description:
419 if (const_cast<SoftimagePICHandler *>(this)->readHeader()) {
420 QString descStr = QString::fromUtf8(ba: m_header.comment);
421 if (!descStr.isEmpty()) {
422 return QString(QStringLiteral("Description: ") + descStr + QStringLiteral("\n\n"));
423 }
424 }
425 return QString();
426 case ImageFormat:
427 if (const_cast<SoftimagePICHandler *>(this)->readChannels()) {
428 for (const PicChannel &channel : std::as_const(t: m_channels)) {
429 if (channel.code & ALPHA) {
430 return QImage::Format_ARGB32;
431 }
432 }
433 return QImage::Format_RGB32;
434 }
435 return QVariant();
436 default:
437 return QVariant();
438 }
439}
440
441bool SoftimagePICHandler::supportsOption(ImageOption option) const
442{
443 return (option == CompressionRatio || option == Description || option == ImageFormat || option == Size);
444}
445
446QImageIOPlugin::Capabilities SoftimagePICPlugin::capabilities(QIODevice *device, const QByteArray &format) const
447{
448 if (format == "pic") {
449 return Capabilities(CanRead | CanWrite);
450 }
451 if (!format.isEmpty()) {
452 return {};
453 }
454 if (!device->isOpen()) {
455 return {};
456 }
457
458 Capabilities cap;
459 if (device->isReadable() && SoftimagePICHandler::canRead(device)) {
460 cap |= CanRead;
461 }
462 if (device->isWritable()) {
463 cap |= CanWrite;
464 }
465 return cap;
466}
467
468QImageIOHandler *SoftimagePICPlugin::create(QIODevice *device, const QByteArray &format) const
469{
470 QImageIOHandler *handler = new SoftimagePICHandler();
471 handler->setDevice(device);
472 handler->setFormat(format);
473 return handler;
474}
475
476#include "moc_pic_p.cpp"
477

source code of kimageformats/src/imageformats/pic.cpp