Debian Codegraph @

src/codec/SkPngCodecBase.cpp

raw
1 /*
2 * Copyright 2024 Google LLC.
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/codec/SkPngCodecBase.h"
9
10 #include <algorithm>
11 #include <cstddef>
12 #include <tuple>
13 #include <utility>
14
15 #include "include/codec/SkCodec.h"
16 #include "include/codec/SkEncodedImageFormat.h"
17 #include "include/core/SkAlphaType.h"
18 #include "include/core/SkColor.h"
19 #include "include/core/SkColorType.h"
20 #include "include/core/SkImageInfo.h"
21 #include "include/core/SkRect.h"
22 #include "include/core/SkStream.h"
23 #include "include/private/SkEncodedInfo.h"
24 #include "include/private/base/SkAssert.h"
25 #include "include/private/base/SkSpan_impl.h"
26 #include "modules/skcms/skcms.h"
27 #include "src/codec/SkCodecPriv.h"
28 #include "src/codec/SkColorPalette.h"
29 #include "src/codec/SkSwizzler.h"
30 #include "src/core/SkMemset.h"
31 #include "src/core/SkSwizzlePriv.h"
32
33 namespace {
34
35 constexpr SkColorType kXformSrcColorType = kRGBA_8888_SkColorType;
36
37 inline bool needs_premul(SkAlphaType dstAT, SkEncodedInfo::Alpha encodedAlpha) {
38 return kPremul_SkAlphaType == dstAT && SkEncodedInfo::kUnpremul_Alpha == encodedAlpha;
39 }
40
41 skcms_PixelFormat ToPixelFormat(const SkEncodedInfo& info) {
42 // We use kRGB and kRGBA formats because color PNGs are always RGB or RGBA.
43 if (16 == info.bitsPerComponent()) {
44 if (SkEncodedInfo::kRGBA_Color == info.color()) {
45 return skcms_PixelFormat_RGBA_16161616BE;
46 } else if (SkEncodedInfo::kRGB_Color == info.color()) {
47 return skcms_PixelFormat_RGB_161616BE;
48 }
49 } else if (SkEncodedInfo::kGray_Color == info.color()) {
50 return skcms_PixelFormat_G_8;
51 }
52
53 return skcms_PixelFormat_RGBA_8888;
54 }
55
56 } // namespace
57
58 SkPngCodecBase::~SkPngCodecBase() = default;
59
60 // static
61 bool SkPngCodecBase::isCompatibleColorProfileAndType(const SkCodecs::ColorProfile* profile,
62 SkEncodedInfo::Color color) {
63 if (profile) {
64 switch (profile->dataSpace()) {
65 case SkCodecs::ColorProfile::DataSpace::kCMYK:
66 return false;
67 case SkCodecs::ColorProfile::DataSpace::kGray:
68 if (SkEncodedInfo::kGray_Color != color &&
69 SkEncodedInfo::kGrayAlpha_Color != color) {
70 return false;
71 }
72 break;
73 default:
74 break;
75 }
76 }
77
78 return true;
79 }
80
81 SkPngCodecBase::SkPngCodecBase(SkEncodedInfo&& encodedInfo,
82 std::unique_ptr<SkStream> stream,
83 SkEncodedOrigin origin)
84 : SkCodec(std::move(encodedInfo), ToPixelFormat(encodedInfo), std::move(stream), origin) {}
85
86 SkEncodedImageFormat SkPngCodecBase::onGetEncodedFormat() const {
87 return SkEncodedImageFormat::kPNG;
88 }
89
90 SkCodec::Result SkPngCodecBase::initializeXforms(const SkImageInfo& dstInfo,
91 const Options& options,
92 int frameWidth) {
93 if (frameWidth != dstInfo.width() && options.fSubset) {
94 return kInvalidParameters;
95 }
96 fXformWidth = frameWidth;
97
98 {
99 size_t encodedBitsPerPixel = static_cast<size_t>(getEncodedInfo().bitsPerPixel());
100
101 // We assume that `frameWidth` and `bitsPerPixel` have been already sanitized
102 // earlier (and that the multiplication and addition below won't overflow).
103 SkASSERT_RELEASE(0 < frameWidth);
104 SkASSERT_RELEASE(frameWidth < 0xFFFFFF);
105 SkASSERT_RELEASE(encodedBitsPerPixel < 128);
106
107 size_t encodedBitsPerRow = static_cast<size_t>(frameWidth) * encodedBitsPerPixel;
108 fEncodedRowBytes = (encodedBitsPerRow + 7) / 8; // Round up to the next byte.
109
110 size_t dstBytesPerPixel = dstInfo.bytesPerPixel();
111 fDstRowBytes = static_cast<size_t>(frameWidth) * dstBytesPerPixel;
112 }
113
114 // Reset fSwizzler and this->colorXform(). We can't do this in onRewind() because the
115 // interlaced scanline decoder may need to rewind.
116 fSwizzler.reset(nullptr);
117
118 // If skcms directly supports the encoded PNG format, we should skip format
119 // conversion in the swizzler (or skip swizzling altogether).
120 bool skipFormatConversion = false;
121 switch (this->getEncodedInfo().color()) {
122 case SkEncodedInfo::kRGB_Color:
123 if (this->getEncodedInfo().bitsPerComponent() != 16) {
124 break;
125 }
126 [[fallthrough]];
127 case SkEncodedInfo::kRGBA_Color:
128 case SkEncodedInfo::kGray_Color:
129 skipFormatConversion = this->colorXform();
130 break;
131 default:
132 break;
133 }
134
135 if (skipFormatConversion && !options.fSubset) {
136 fXformMode = kColorOnly_XformMode;
137 } else {
138 if (SkEncodedInfo::kPalette_Color == this->getEncodedInfo().color()) {
139 if (!this->createColorTable(dstInfo)) {
140 return kInvalidInput;
141 }
142 }
143
144 Result result =
145 this->initializeSwizzler(dstInfo, options, skipFormatConversion, frameWidth);
146 if (result != kSuccess) {
147 return result;
148 }
149 }
150
151 this->allocateStorage(dstInfo);
152
153 // We can't call `initializeXformParams` here, because `swizzleWidth` may
154 // change *after* `onStartIncrementalDecode`
155 // (`SkSampledCodec::sampledDecode` first [transitively] calls
156 // `onStartIncrementalDecode` and *then* `SkSwizzler::onSetSampleX`).
157
158 return kSuccess;
159 }
160
161 void SkPngCodecBase::initializeXformParams() {
162 if (fXformMode == kSwizzleColor_XformMode) {
163 fXformWidth = this->swizzler()->swizzleWidth();
164 }
165 }
166
167 void SkPngCodecBase::allocateStorage(const SkImageInfo& dstInfo) {
168 switch (fXformMode) {
169 case kSwizzleOnly_XformMode:
170 break;
171 case kColorOnly_XformMode:
172 // Intentional fall through. A swizzler hasn't been created yet, but one will
173 // be created later if we are sampling. We'll go ahead and allocate
174 // enough memory to swizzle if necessary.
175 case kSwizzleColor_XformMode: {
176 const int bitsPerPixel = this->getEncodedInfo().bitsPerPixel();
177
178 // If we have more than 8-bits (per component) of precision, we will keep that
179 // extra precision. Otherwise, we will swizzle to RGBA_8888 before transforming.
180 const size_t bytesPerPixel = (bitsPerPixel > 32) ? bitsPerPixel / 8 : 4;
181 const size_t colorXformBytes = dstInfo.width() * bytesPerPixel;
182 fStorage.reset(colorXformBytes);
183 break;
184 }
185 }
186 }
187
188 SkCodec::Result SkPngCodecBase::initializeSwizzler(const SkImageInfo& dstInfo,
189 const Options& options,
190 bool skipFormatConversion,
191 int frameWidth) {
192 SkImageInfo swizzlerInfo = dstInfo;
193 Options swizzlerOptions = options;
194 fXformMode = kSwizzleOnly_XformMode;
195 if (this->colorXform() && this->xformOnDecode()) {
196 if (SkEncodedInfo::kGray_Color == this->getEncodedInfo().color()) {
197 swizzlerInfo = swizzlerInfo.makeColorType(kGray_8_SkColorType);
198 } else {
199 swizzlerInfo = swizzlerInfo.makeColorType(kXformSrcColorType);
200 }
201 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
202 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
203 }
204
205 fXformMode = kSwizzleColor_XformMode;
206
207 // Here, we swizzle into temporary memory, which is not zero initialized.
208 // FIXME (msarett):
209 // Is this a problem?
210 swizzlerOptions.fZeroInitialized = kNo_ZeroInitialized;
211 }
212
213 SkIRect frameRect = SkIRect::MakeWH(frameWidth, 1);
214 const SkIRect* frameRectPtr = nullptr;
215 if (options.fSubset) {
216 SkASSERT_RELEASE(frameWidth == dstInfo.width());
217 } else {
218 frameRectPtr = &frameRect;
219 }
220
221 if (skipFormatConversion) {
222 // We cannot skip format conversion when there is a color table.
223 SkASSERT_RELEASE(!fColorTable);
224 int srcBPP = 0;
225 switch (this->getEncodedInfo().color()) {
226 case SkEncodedInfo::kRGB_Color:
227 SkASSERT_RELEASE(this->getEncodedInfo().bitsPerComponent() == 16);
228 srcBPP = 6;
229 break;
230 case SkEncodedInfo::kRGBA_Color:
231 srcBPP = this->getEncodedInfo().bitsPerComponent() / 2;
232 break;
233 case SkEncodedInfo::kGray_Color:
234 srcBPP = 1;
235 break;
236 default:
237 SkASSERT_RELEASE(false);
238 break;
239 }
240 fSwizzler = SkSwizzler::MakeSimple(srcBPP, swizzlerInfo, swizzlerOptions, frameRectPtr);
241 } else {
242 const SkPMColor* colors = SkCodecPriv::GetColorPtr(fColorTable.get());
243 fSwizzler = SkSwizzler::Make(
244 this->getEncodedInfo(), colors, swizzlerInfo, swizzlerOptions, frameRectPtr);
245 }
246
247 return !!fSwizzler ? kSuccess : kUnimplemented;
248 }
249
250 SkSampler* SkPngCodecBase::getSampler(bool createIfNecessary) {
251 if (fSwizzler || !createIfNecessary) {
252 return fSwizzler.get();
253 }
254
255 // Ok to ignore `initializeSwizzler`'s result, because if it fails, then
256 // `fSwizzler` will be `nullptr` and we want to return `nullptr` upon
257 // failure.
258 std::ignore = this->initializeSwizzler(
259 this->dstInfo(), this->options(), true, this->dstInfo().width());
260
261 return fSwizzler.get();
262 }
263
264 void SkPngCodecBase::applyXformRow(SkSpan<uint8_t> dstRow, SkSpan<const uint8_t> srcRow) {
265 SkASSERT_RELEASE(dstRow.size() >= fDstRowBytes);
266 SkASSERT_RELEASE(srcRow.size() >= fEncodedRowBytes);
267 applyXformRow(dstRow.data(), srcRow.data());
268 }
269
270 void SkPngCodecBase::applyXformRow(void* dstRow, const uint8_t* srcRow) {
271 switch (fXformMode) {
272 case kSwizzleOnly_XformMode:
273 fSwizzler->swizzle(dstRow, srcRow);
274 break;
275 case kColorOnly_XformMode:
276 this->applyColorXform(dstRow, srcRow, fXformWidth);
277 break;
278 case kSwizzleColor_XformMode:
279 fSwizzler->swizzle(fStorage.get(), srcRow);
280 this->applyColorXform(dstRow, fStorage.get(), fXformWidth);
281 break;
282 }
283 }
284
285 // Note: SkColorPalette claims to store SkPMColors, which is not necessarily the case here.
286 bool SkPngCodecBase::createColorTable(const SkImageInfo& dstInfo) {
287 if (fDstInfoOfPreviousColorTableCreation.has_value() &&
288 *fDstInfoOfPreviousColorTableCreation == dstInfo) {
289 return !!fColorTable;
290 }
291 fColorTable.reset();
292 fDstInfoOfPreviousColorTableCreation = dstInfo;
293
294 std::optional<SkSpan<const PaletteColorEntry>> maybePlteChunk = this->onTryGetPlteChunk();
295 if (!maybePlteChunk.has_value()) {
296 return false;
297 }
298 const PaletteColorEntry* palette = maybePlteChunk->data();
299 constexpr size_t kMaxCountOfPaletteEntries = 256;
300 size_t numColors = maybePlteChunk->size();
301 numColors = std::min(numColors, kMaxCountOfPaletteEntries);
302
303 // Contents depend on tableColorType and our choice of if/when to premultiply:
304 // { kPremul, kUnpremul, kOpaque } x { RGBA, BGRA }
305 SkPMColor colorTable[kMaxCountOfPaletteEntries];
306 SkColorType tableColorType = this->colorXform() ? kXformSrcColorType : dstInfo.colorType();
307
308 std::optional<SkSpan<const uint8_t>> maybeTrnsChunk = this->onTryGetTrnsChunk();
309 const uint8_t* alphas = nullptr;
310 size_t numColorsWithAlpha = 0;
311 if (maybeTrnsChunk.has_value()) {
312 alphas = maybeTrnsChunk->data();
313 numColorsWithAlpha = maybeTrnsChunk->size();
314 numColorsWithAlpha = std::min(numColorsWithAlpha, numColors);
315 }
316
317 bool shouldApplyColorXformToColorTable = this->colorXform() && !this->xformOnDecode();
318 if (alphas) {
319 bool premultiply = !shouldApplyColorXformToColorTable &&
320 needs_premul(dstInfo.alphaType(), this->getEncodedInfo().alpha());
321
322 // Choose which function to use to create the color table. If the final destination's
323 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
324 SkCodecPriv::PackColorProc proc =
325 SkCodecPriv::ChoosePackColorProc(premultiply, tableColorType);
326
327 for (size_t i = 0; i < numColorsWithAlpha; i++) {
328 // We don't have a function in SkOpts that combines a set of alphas with a set
329 // of RGBs. We could write one, but it's hardly worth it, given that this
330 // is such a small fraction of the total decode time.
331 colorTable[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
332 palette++;
333 }
334 }
335
336 if (numColorsWithAlpha < numColors) {
337 // The optimized code depends on a 3-byte png_color struct with the colors
338 // in RGB order. These checks make sure it is safe to use.
339 static_assert(3 == sizeof(PaletteColorEntry));
340 static_assert(offsetof(PaletteColorEntry, red) == 0);
341 static_assert(offsetof(PaletteColorEntry, green) == 1);
342 static_assert(offsetof(PaletteColorEntry, blue) == 2);
343
344 if (SkCodecPriv::IsRGBA(tableColorType)) {
345 SkOpts::RGB_to_RGB1(colorTable + numColorsWithAlpha,
346 (const uint8_t*)palette,
347 numColors - numColorsWithAlpha);
348 } else {
349 SkOpts::RGB_to_BGR1(colorTable + numColorsWithAlpha,
350 (const uint8_t*)palette,
351 numColors - numColorsWithAlpha);
352 }
353 }
354
355 if (shouldApplyColorXformToColorTable) {
356 this->applyColorXform(colorTable, colorTable, numColors);
357 }
358
359 // Pad the color table with the last color in the table (or black) in the case that
360 // invalid pixel indices exceed the number of colors in the table.
361 const size_t maxColors = static_cast<size_t>(1) << this->getEncodedInfo().bitsPerComponent();
362 if (numColors < maxColors) {
363 SkPMColor lastColor = numColors > 0 ? colorTable[numColors - 1] : SK_ColorBLACK;
364 SkOpts::memset32(colorTable + numColors, lastColor, maxColors - numColors);
365 }
366
367 fColorTable.reset(new SkColorPalette(colorTable, maxColors));
368 return true;
369 }