Debian Codegraph @

src/encode/SkPngEncoderImpl.cpp

raw
1 /*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/encode/SkPngEncoderImpl.h"
9
10 #include <optional>
11
12 #include "include/core/SkBitmap.h"
13 #include "include/core/SkColorSpace.h"
14 #include "include/core/SkColorType.h"
15 #include "include/core/SkData.h"
16 #include "include/core/SkDataTable.h"
17 #include "include/core/SkImageInfo.h"
18 #include "include/core/SkPixmap.h"
19 #include "include/core/SkRefCnt.h"
20 #include "include/core/SkSpan.h"
21 #include "include/core/SkStream.h"
22 #include "include/core/SkString.h"
23 #include "include/encode/SkEncoder.h"
24 #include "include/encode/SkPngEncoder.h"
25 #include "include/private/SkEncodedInfo.h"
26 #include "include/private/SkGainmapInfo.h"
27 #include "include/private/base/SkAssert.h"
28 #include "include/private/base/SkDebug.h"
29 #include "include/private/base/SkNoncopyable.h"
30 #include "modules/skcms/skcms.h"
31 #include "src/codec/SkPngPriv.h"
32 #include "src/encode/SkImageEncoderFns.h"
33 #include "src/encode/SkImageEncoderPriv.h"
34 #include "src/encode/SkPngEncoderBase.h"
35 #include "src/image/SkImage_Base.h"
36
37 #include <algorithm>
38 #include <array>
39 #include <csetjmp>
40 #include <cstdint>
41 #include <cstring>
42 #include <memory>
43 #include <utility>
44 #include <vector>
45
46 #include <png.h>
47 #include <pngconf.h>
48
49 class GrDirectContext;
50 class SkImage;
51
52 static_assert(PNG_FILTER_NONE == (int)SkPngEncoder::FilterFlag::kNone, "Skia libpng filter err.");
53 static_assert(PNG_FILTER_SUB == (int)SkPngEncoder::FilterFlag::kSub, "Skia libpng filter err.");
54 static_assert(PNG_FILTER_UP == (int)SkPngEncoder::FilterFlag::kUp, "Skia libpng filter err.");
55 static_assert(PNG_FILTER_AVG == (int)SkPngEncoder::FilterFlag::kAvg, "Skia libpng filter err.");
56 static_assert(PNG_FILTER_PAETH == (int)SkPngEncoder::FilterFlag::kPaeth, "Skia libpng filter err.");
57 static_assert(PNG_ALL_FILTERS == (int)SkPngEncoder::FilterFlag::kAll, "Skia libpng filter err.");
58
59 static constexpr bool kSuppressPngEncodeWarnings = false;
60
61 static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
62 if (!kSuppressPngEncodeWarnings) {
63 SkDebugf("libpng encode error: %s\n", msg);
64 }
65
66 longjmp(png_jmpbuf(png_ptr), 1);
67 }
68
69 static void sk_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) {
70 SkWStream* stream = (SkWStream*)png_get_io_ptr(png_ptr);
71 if (!stream->write(data, len)) {
72 png_error(png_ptr, "sk_write_fn cannot write to stream");
73 }
74 }
75
76 class SkPngEncoderMgr final : SkNoncopyable {
77 public:
78 /*
79 * Create the decode manager
80 * Does not take ownership of stream
81 */
82 static std::unique_ptr<SkPngEncoderMgr> Make(SkWStream* stream);
83 bool setHeader(const SkPngEncoderBase::TargetInfo& targetInfo,
84 const SkImageInfo& srcInfo,
85 const SkPngEncoder::Options& options);
86 bool setColorSpace(const SkImageInfo& info, const SkPngEncoder::Options& options);
87 bool setHdrMetadata(const SkPngEncoder::Options& options);
88 bool writeInfo(const SkImageInfo& srcInfo,const SkPngEncoderBase::TargetInfo& targetInfo);
89
90 png_structp pngPtr() { return fPngPtr; }
91 png_infop infoPtr() { return fInfoPtr; }
92 transform_scanline_proc proc() const { return fProc; }
93
94 ~SkPngEncoderMgr() { png_destroy_write_struct(&fPngPtr, &fInfoPtr); }
95
96 private:
97 SkPngEncoderMgr(png_structp pngPtr, png_infop infoPtr) : fPngPtr(pngPtr), fInfoPtr(infoPtr) {}
98
99 png_structp fPngPtr;
100 png_infop fInfoPtr;
101 transform_scanline_proc fProc = nullptr;
102 };
103
104 std::unique_ptr<SkPngEncoderMgr> SkPngEncoderMgr::Make(SkWStream* stream) {
105 png_structp pngPtr =
106 png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, sk_error_fn, nullptr);
107 if (!pngPtr) {
108 return nullptr;
109 }
110
111 png_infop infoPtr = png_create_info_struct(pngPtr);
112 if (!infoPtr) {
113 png_destroy_write_struct(&pngPtr, nullptr);
114 return nullptr;
115 }
116
117 png_set_write_fn(pngPtr, (void*)stream, sk_write_fn, nullptr);
118 return std::unique_ptr<SkPngEncoderMgr>(new SkPngEncoderMgr(pngPtr, infoPtr));
119 }
120
121 bool SkPngEncoderMgr::setHeader(const SkPngEncoderBase::TargetInfo& targetInfo,
122 const SkImageInfo& srcInfo,
123 const SkPngEncoder::Options& options) {
124 if (setjmp(png_jmpbuf(fPngPtr))) {
125 return false;
126 }
127
128 const SkEncodedInfo& dstInfo = targetInfo.fDstInfo;
129 const std::optional<SkImageInfo>& dstRowInfo = targetInfo.fDstRowInfo;
130
131 int pngColorType;
132 switch (dstInfo.color()) {
133 case SkEncodedInfo::kRGB_Color:
134 pngColorType = PNG_COLOR_TYPE_RGB;
135 break;
136 case SkEncodedInfo::kRGBA_Color:
137 SkASSERT(dstRowInfo);
138 pngColorType = dstRowInfo->isOpaque() ? PNG_COLOR_TYPE_RGB
139 : PNG_COLOR_TYPE_RGB_ALPHA;
140 break;
141 case SkEncodedInfo::kGray_Color:
142 pngColorType = PNG_COLOR_TYPE_GRAY;
143 break;
144 case SkEncodedInfo::kGrayAlpha_Color:
145 pngColorType = PNG_COLOR_TYPE_GRAY_ALPHA;
146 break;
147 default:
148 SkDEBUGFAIL("`getTargetInfo` returned unexpected `SkEncodedInfo::Color`");
149 return false;
150 }
151
152 png_color_8 sigBit;
153 bool sigBitSet = true;
154 switch (srcInfo.colorType()) {
155 case kRGBA_F16Norm_SkColorType:
156 case kRGBA_F16_SkColorType:
157 case kRGBA_F32_SkColorType:
158 sigBit.red = 16;
159 sigBit.green = 16;
160 sigBit.blue = 16;
161 sigBit.alpha = 16;
162 break;
163 case kRGB_F16F16F16x_SkColorType:
164 sigBit.red = 16;
165 sigBit.green = 16;
166 sigBit.blue = 16;
167 break;
168 case kGray_8_SkColorType:
169 sigBit.gray = 8;
170 break;
171 case kRGB_888x_SkColorType:
172 sigBit.red = 8;
173 sigBit.green = 8;
174 sigBit.blue = 8;
175 break;
176 case kARGB_4444_SkColorType:
177 sigBit.red = 4;
178 sigBit.green = 4;
179 sigBit.blue = 4;
180 sigBit.alpha = 4;
181 break;
182 case kRGB_565_SkColorType:
183 sigBit.red = 5;
184 sigBit.green = 6;
185 sigBit.blue = 5;
186 break;
187 case kAlpha_8_SkColorType: // store as gray+alpha, but ignore gray
188 sigBit.gray = kGraySigBit_GrayAlphaIsJustAlpha;
189 sigBit.alpha = 8;
190 break;
191 case kRGBA_1010102_SkColorType:
192 case kBGRA_1010102_SkColorType:
193 sigBit.red = 10;
194 sigBit.green = 10;
195 sigBit.blue = 10;
196 sigBit.alpha = 2;
197 break;
198 case kBGR_101010x_XR_SkColorType:
199 case kRGB_101010x_SkColorType:
200 case kBGR_101010x_SkColorType:
201 sigBit.red = 10;
202 sigBit.green = 10;
203 sigBit.blue = 10;
204 break;
205 case kBGRA_10101010_XR_SkColorType:
206 sigBit.red = 10;
207 sigBit.green = 10;
208 sigBit.blue = 10;
209 sigBit.alpha = 10;
210 break;
211 case kRGBA_8888_SkColorType:
212 case kBGRA_8888_SkColorType:
213 sigBit.red = 8;
214 sigBit.green = 8;
215 sigBit.blue = 8;
216 sigBit.alpha = 8;
217 break;
218 default:
219 SkDEBUGFAIL("Unable to set sigBit for src colortype, unhandled value\n");
220 sigBitSet = false;
221 }
222
223 png_set_IHDR(fPngPtr,
224 fInfoPtr,
225 srcInfo.width(),
226 srcInfo.height(),
227 dstInfo.bitsPerComponent(),
228 pngColorType,
229 PNG_INTERLACE_NONE,
230 PNG_COMPRESSION_TYPE_BASE,
231 PNG_FILTER_TYPE_BASE);
232 if (sigBitSet) {
233 png_set_sBIT(fPngPtr, fInfoPtr, &sigBit);
234 }
235
236 int filters = (int)options.fFilterFlags & (int)SkPngEncoder::FilterFlag::kAll;
237 SkASSERT(filters == (int)options.fFilterFlags);
238 png_set_filter(fPngPtr, PNG_FILTER_TYPE_BASE, filters);
239
240 int zlibLevel = std::min(std::max(0, options.fZLibLevel), 9);
241 SkASSERT(zlibLevel == options.fZLibLevel);
242 png_set_compression_level(fPngPtr, zlibLevel);
243
244 // Set comments in tEXt chunk
245 const sk_sp<SkDataTable>& comments = options.fComments;
246 if (comments != nullptr) {
247 if (comments->count() % 2 != 0) {
248 return false;
249 }
250
251 std::vector<png_text> png_texts(comments->count());
252 std::vector<SkString> clippedKeys;
253 for (int i = 0; i < comments->count() / 2; ++i) {
254 const char* keyword;
255 const char* originalKeyword = comments->atStr(2 * i);
256 const char* text = comments->atStr(2 * i + 1);
257 if (strlen(originalKeyword) <= PNG_KEYWORD_MAX_LENGTH) {
258 keyword = originalKeyword;
259 } else {
260 SkDEBUGFAILF("PNG tEXt keyword should be no longer than %d.",
261 PNG_KEYWORD_MAX_LENGTH);
262 clippedKeys.emplace_back(originalKeyword, PNG_KEYWORD_MAX_LENGTH);
263 keyword = clippedKeys.back().c_str();
264 }
265 // It seems safe to convert png_const_charp to png_charp for key/text,
266 // and we don't have to provide text_length and other fields as we're providing
267 // 0-terminated c_str with PNG_TEXT_COMPRESSION_NONE (no compression, no itxt).
268 png_texts[i].compression = PNG_TEXT_COMPRESSION_NONE;
269 png_texts[i].key = const_cast<png_charp>(keyword);
270 png_texts[i].text = const_cast<png_charp>(text);
271 }
272 png_set_text(fPngPtr, fInfoPtr, png_texts.data(), png_texts.size());
273 }
274
275 return true;
276 }
277
278 static void set_icc(png_structp png_ptr, png_infop info_ptr, const SkImageInfo& info) {
279 sk_sp<SkData> icc = icc_from_color_space(info);
280 if (!icc) {
281 return;
282 }
283
284 #if PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 5)
285 const char* name = "Skia";
286 png_const_bytep iccPtr = icc->bytes();
287 #else
288 SkString str("Skia");
289 char* name = str.data();
290 png_charp iccPtr = (png_charp)icc->writable_data();
291 #endif
292 png_set_iCCP(png_ptr, info_ptr, name, 0, iccPtr, icc->size());
293 }
294
295 bool SkPngEncoderMgr::setColorSpace(const SkImageInfo& info, const SkPngEncoder::Options& options) {
296 if (setjmp(png_jmpbuf(fPngPtr))) {
297 return false;
298 }
299
300 if (info.colorSpace() && info.colorSpace()->isSRGB()) {
301 png_set_sRGB(fPngPtr, fInfoPtr, PNG_sRGB_INTENT_PERCEPTUAL);
302 } else {
303 set_icc(fPngPtr, fInfoPtr, info);
304 }
305
306 return true;
307 }
308
309 bool SkPngEncoderMgr::setHdrMetadata(const SkPngEncoder::Options& options) {
310 #ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
311 if (setjmp(png_jmpbuf(fPngPtr))) {
312 return false;
313 }
314
315 // List all chunks that might be included.
316 const char* hdrChunkNames = "gmAP\0"
317 "gdAT\0"
318 "mDCV\0"
319 "cLLI\0";
320 constexpr int numHdrChunkNames = 4;
321 png_set_keep_unknown_chunks(fPngPtr, PNG_HANDLE_CHUNK_ALWAYS,
322 (png_const_bytep)hdrChunkNames, numHdrChunkNames);
323
324 // In the below `png_unknown_chunk` structures, the `data` member is a non-const pointer,
325 // even though it will not be written to. In fact, `data` will be copied by the call to
326 // `png_set_unknown_chunks`, so it is safe for it to be deallocated immediately after
327 // the call.
328 skhdr::ContentLightLevelInformation clli;
329 if (options.fHdrMetadata.getContentLightLevelInformation(&clli)) {
330 auto data = clli.serializePngChunk();
331 png_unknown_chunk chunk = {
332 {'c', 'L', 'L', 'I', 0},
333 reinterpret_cast<png_byte*>(data->writable_data()),
334 data->size(),
335 PNG_HAVE_IHDR,
336 };
337 png_set_unknown_chunks(fPngPtr, fInfoPtr, &chunk, 1);
338 }
339
340 skhdr::MasteringDisplayColorVolume mdcv;
341 if (options.fHdrMetadata.getMasteringDisplayColorVolume(&mdcv)) {
342 auto data = mdcv.serialize();
343 png_unknown_chunk chunk = {
344 {'m', 'D', 'C', 'V', 0},
345 reinterpret_cast<png_byte*>(data->writable_data()),
346 data->size(),
347 PNG_HAVE_IHDR,
348 };
349 png_set_unknown_chunks(fPngPtr, fInfoPtr, &chunk, 1);
350 }
351
352 if (options.fGainmapInfo && options.fGainmap) {
353 sk_sp<SkData> gainmapVersion = SkGainmapInfo::SerializeVersion();
354
355 // When we encode the gainmap, we need to remove the gainmap from its
356 // own encoding options, so that we don't recurse.
357 auto modifiedOptions = options;
358 modifiedOptions.fGainmap = nullptr;
359
360 auto gainmapInfo = *(options.fGainmapInfo);
361 auto gainmapPixels = *(options.fGainmap);
362 auto targetInfo = SkPngEncoderBase::getTargetInfo(gainmapPixels.info());
363
364 if (targetInfo && targetInfo->fDstInfo.color() != SkEncodedInfo::kGray_Color &&
365 targetInfo->fDstInfo.color() != SkEncodedInfo::kGrayAlpha_Color) {
366 // Encode the alternate image colorspace directly in the gainmap profile,
367 // since the ISO gainmap payload does not contain the actual alternative
368 // image primaries.
369 const auto& gainmapColorSpace = options.fGainmapInfo->fGainmapMathColorSpace;
370 gainmapPixels.setColorSpace(gainmapColorSpace);
371 } else {
372 // Scrub the gainmap colorspace, since grayscale PNGs don't support
373 // RGB ICC profiles
374 gainmapInfo.fGainmapMathColorSpace = nullptr;
375 modifiedOptions.fGainmapInfo = &gainmapInfo;
376 }
377
378 sk_sp<SkData> gainmapData = SkPngEncoder::Encode(gainmapPixels, modifiedOptions);
379 if (!gainmapData) {
380 return false;
381 }
382
383 // The base image contains chunks for both the gainmap versioning (for possible
384 // forward-compat, and as a cheap way to check a gainmap might exist) as
385 // well as the gainmap data.
386 png_unknown_chunk gmapChunk = {
387 {'g', 'm', 'A', 'P', 0},
388 reinterpret_cast<png_byte*>(gainmapVersion->writable_data()),
389 gainmapVersion->size(),
390 PNG_HAVE_IHDR,
391 };
392 png_set_unknown_chunks(fPngPtr, fInfoPtr, &gmapChunk, 1);
393
394 png_unknown_chunk gdatChunk = {
395 {'g', 'd', 'A', 'T', 0},
396 reinterpret_cast<png_byte*>(gainmapData->writable_data()),
397 gainmapData->size(),
398 PNG_HAVE_IHDR,
399 };
400 png_set_unknown_chunks(fPngPtr, fInfoPtr, &gdatChunk, 1);
401 } else if (options.fGainmapInfo) {
402 // If there is no gainmap provided for encoding, but we have info, then
403 // we're currently encoding the gainmap pixels, so we need to encode the
404 // gainmap metadata to interpret those pixels.
405 sk_sp<SkData> data = options.fGainmapInfo->serialize();
406 png_unknown_chunk chunk = {
407 {'g', 'm', 'A', 'P', 0},
408 reinterpret_cast<png_byte*>(data->writable_data()),
409 data->size(),
410 PNG_HAVE_IHDR,
411 };
412 png_set_unknown_chunks(fPngPtr, fInfoPtr, &chunk, 1);
413 }
414 #endif
415 return true;
416 }
417
418 bool SkPngEncoderMgr::writeInfo(const SkImageInfo& srcInfo, const SkPngEncoderBase::TargetInfo& targetInfo) {
419 if (setjmp(png_jmpbuf(fPngPtr))) {
420 return false;
421 }
422 png_write_info(fPngPtr, fInfoPtr);
423
424 const SkEncodedInfo& dstInfo = targetInfo.fDstInfo;
425 const std::optional<SkImageInfo>& dstRowInfo = targetInfo.fDstRowInfo;
426
427 // Strip input data that has 4 or 8 bytes per pixel down to 3 or 6 bytes if we don't want alpha.
428 if (dstInfo.color() == SkEncodedInfo::kRGBA_Color) {
429 SkASSERT(dstRowInfo);
430 if (dstRowInfo->isOpaque()) {
431 png_set_filler(fPngPtr, 0, PNG_FILLER_AFTER);
432 }
433 }
434 return true;
435 }
436
437 SkPngEncoderImpl::SkPngEncoderImpl(TargetInfo targetInfo,
438 std::unique_ptr<SkPngEncoderMgr> encoderMgr,
439 const SkPixmap& src)
440 : SkPngEncoderBase(std::move(targetInfo), src), fEncoderMgr(std::move(encoderMgr)) {}
441
442 SkPngEncoderImpl::~SkPngEncoderImpl() {}
443
444 bool SkPngEncoderImpl::onEncodeRow(SkSpan<const uint8_t> row) {
445 if (setjmp(png_jmpbuf(fEncoderMgr->pngPtr()))) {
446 return false;
447 }
448
449 // `png_bytep` is `uint8_t*` rather than `const uint8_t*`.
450 png_bytep rowPtr = const_cast<png_bytep>(row.data());
451
452 // Swap to big endian if we are storing more than a byte per color channel
453 // (SkColorTypes are little endian by default).
454 // By this point our data will either be 8888 or 16161616, so we only check that case.
455 if (png_get_bit_depth(fEncoderMgr->pngPtr(), fEncoderMgr->infoPtr()) == 16) {
456 png_set_swap(fEncoderMgr->pngPtr());
457 }
458
459 png_write_rows(fEncoderMgr->pngPtr(), &rowPtr, 1);
460 return true;
461 }
462
463 bool SkPngEncoderImpl::onFinishEncoding() {
464 if (setjmp(png_jmpbuf(fEncoderMgr->pngPtr()))) {
465 return false;
466 }
467
468 png_write_end(fEncoderMgr->pngPtr(), fEncoderMgr->infoPtr());
469 return true;
470 }
471
472 namespace SkPngEncoder {
473 std::unique_ptr<SkEncoder> Make(SkWStream* dst, const SkPixmap& src, const Options& options) {
474 if (!SkPixmapIsValid(src)) {
475 return nullptr;
476 }
477
478 std::unique_ptr<SkPngEncoderMgr> encoderMgr = SkPngEncoderMgr::Make(dst);
479 if (!encoderMgr) {
480 return nullptr;
481 }
482
483 std::optional<SkPngEncoderBase::TargetInfo> targetInfo =
484 SkPngEncoderBase::getTargetInfo(src.info());
485 if (!targetInfo.has_value()) {
486 return nullptr;
487 }
488
489 if (!encoderMgr->setHeader(targetInfo.value(), src.info(), options)) {
490 return nullptr;
491 }
492
493 if (!encoderMgr->setColorSpace(src.info(), options)) {
494 return nullptr;
495 }
496
497 if (!encoderMgr->setHdrMetadata(options)) {
498 return nullptr;
499 }
500
501 if (!encoderMgr->writeInfo(src.info(), targetInfo.value())) {
502 return nullptr;
503 }
504 return std::make_unique<SkPngEncoderImpl>(std::move(*targetInfo), std::move(encoderMgr), src);
505 }
506
507 bool Encode(SkWStream* dst, const SkPixmap& src, const Options& options) {
508 auto encoder = Make(dst, src, options);
509 return encoder.get() && encoder->encodeRows(src.height());
510 }
511
512 sk_sp<SkData> Encode(const SkPixmap& src, const Options& options) {
513 SkDynamicMemoryWStream stream;
514 return Encode(&stream, src, options) ? stream.detachAsData() : nullptr;
515 }
516
517 sk_sp<SkData> Encode(GrDirectContext* ctx, const SkImage* img, const Options& options) {
518 if (!img) {
519 return nullptr;
520 }
521 SkBitmap bm;
522 if (!as_IB(img)->getROPixels(ctx, &bm)) {
523 return nullptr;
524 }
525 return Encode(bm.pixmap(), options);
526 }
527
528 } // namespace SkPngEncoder