Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
SkPDFBitmap.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2015 Google Inc.
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
9
14#include "include/core/SkData.h"
23#include "src/pdf/SkDeflate.h"
25#include "src/pdf/SkPDFTypes.h"
26#include "src/pdf/SkPDFUnion.h"
27#include "src/pdf/SkPDFUtils.h"
28
29
31 return codec.getEncodedInfo();
32}
33
34namespace {
35
36// write a single byte to a stream n times.
37void fill_stream(SkWStream* out, char value, size_t n) {
38 char buffer[4096];
39 memset(buffer, value, sizeof(buffer));
40 for (size_t i = 0; i < n / sizeof(buffer); ++i) {
41 out->write(buffer, sizeof(buffer));
42 }
43 out->write(buffer, n % sizeof(buffer));
44}
45
46/* It is necessary to average the color component of transparent
47 pixels with their surrounding neighbors since the PDF renderer may
48 separately re-sample the alpha and color channels when the image is
49 not displayed at its native resolution. Since an alpha of zero
50 gives no information about the color component, the pathological
51 case is a white image with sharp transparency bounds - the color
52 channel goes to black, and the should-be-transparent pixels are
53 rendered as grey because of the separate soft mask and color
54 resizing. e.g.: gm/bitmappremul.cpp */
55SkColor get_neighbor_avg_color(const SkPixmap& bm, int xOrig, int yOrig) {
57 unsigned r = 0, g = 0, b = 0, n = 0;
58 // Clamp the range to the edge of the bitmap.
59 int ymin = std::max(0, yOrig - 1);
60 int ymax = std::min(yOrig + 1, bm.height() - 1);
61 int xmin = std::max(0, xOrig - 1);
62 int xmax = std::min(xOrig + 1, bm.width() - 1);
63 for (int y = ymin; y <= ymax; ++y) {
64 const SkColor* scanline = bm.addr32(0, y);
65 for (int x = xmin; x <= xmax; ++x) {
66 SkColor color = scanline[x];
68 r += SkColorGetR(color);
69 g += SkColorGetG(color);
71 n++;
72 }
73 }
74 }
75 return n > 0 ? SkColorSetRGB(SkToU8(r / n), SkToU8(g / n), SkToU8(b / n))
77}
78
79enum class SkPDFStreamFormat { DCT, Flate, Uncompressed };
80
81template <typename T>
82void emit_image_stream(SkPDFDocument* doc,
84 T writeStream,
85 SkISize size,
86 SkPDFUnion&& colorSpace,
88 int length,
89 SkPDFStreamFormat format) {
90 SkPDFDict pdfDict("XObject");
91 pdfDict.insertName("Subtype", "Image");
92 pdfDict.insertInt("Width", size.width());
93 pdfDict.insertInt("Height", size.height());
94 pdfDict.insertUnion("ColorSpace", std::move(colorSpace));
95 if (sMask) {
96 pdfDict.insertRef("SMask", sMask);
97 }
98 pdfDict.insertInt("BitsPerComponent", 8);
99 #ifdef SK_PDF_BASE85_BINARY
100 auto filters = SkPDFMakeArray();
101 filters->appendName("ASCII85Decode");
102 switch (format) {
103 case SkPDFStreamFormat::DCT: filters->appendName("DCTDecode"); break;
104 case SkPDFStreamFormat::Flate: filters->appendName("FlateDecode"); break;
105 case SkPDFStreamFormat::Uncompressed: break;
106 }
107 pdfDict.insertObject("Filter", std::move(filters));
108 #else
109 switch (format) {
110 case SkPDFStreamFormat::DCT: pdfDict.insertName("Filter", "DCTDecode"); break;
111 case SkPDFStreamFormat::Flate: pdfDict.insertName("Filter", "FlateDecode"); break;
112 case SkPDFStreamFormat::Uncompressed: break;
113 }
114 #endif
115 if (format == SkPDFStreamFormat::DCT) {
116 pdfDict.insertInt("ColorTransform", 0);
117 }
118 pdfDict.insertInt("Length", length);
119 doc->emitStream(pdfDict, std::move(writeStream), ref);
120}
121
122void do_deflated_alpha(const SkPixmap& pm, SkPDFDocument* doc, SkPDFIndirectReference ref) {
124 SkPDFStreamFormat format = compressionLevel == SkPDF::Metadata::CompressionLevel::None
125 ? SkPDFStreamFormat::Uncompressed
126 : SkPDFStreamFormat::Flate;
129 std::optional<SkDeflateWStream> deflateWStream;
130 if (format == SkPDFStreamFormat::Flate) {
131 deflateWStream.emplace(&buffer, SkToInt(compressionLevel));
132 stream = &*deflateWStream;
133 }
134 if (kAlpha_8_SkColorType == pm.colorType()) {
135 SkASSERT(pm.rowBytes() == (size_t)pm.width());
136 stream->write(pm.addr8(), pm.width() * pm.height());
137 } else {
140 SkASSERT(pm.rowBytes() == (size_t)pm.width() * 4);
141 const uint32_t* ptr = pm.addr32();
142 const uint32_t* stop = ptr + pm.height() * pm.width();
143
144 uint8_t byteBuffer[4092];
145 uint8_t* bufferStop = byteBuffer + std::size(byteBuffer);
146 uint8_t* dst = byteBuffer;
147 while (ptr != stop) {
148 *dst++ = 0xFF & ((*ptr++) >> SK_BGRA_A32_SHIFT);
149 if (dst == bufferStop) {
150 stream->write(byteBuffer, sizeof(byteBuffer));
151 dst = byteBuffer;
152 }
153 }
154 stream->write(byteBuffer, dst - byteBuffer);
155 }
156 if (deflateWStream) {
157 deflateWStream->finalize();
158 }
159
160 #ifdef SK_PDF_BASE85_BINARY
161 SkPDFUtils::Base85Encode(buffer.detachAsStream(), &buffer);
162 #endif
163 int length = SkToInt(buffer.bytesWritten());
164 emit_image_stream(doc, ref, [&buffer](SkWStream* stream) { buffer.writeToAndReset(stream); },
165 pm.info().dimensions(), SkPDFUnion::Name("DeviceGray"),
167}
168
169SkPDFUnion write_icc_profile(SkPDFDocument* doc, sk_sp<SkData>&& icc, int channels) {
170 SkPDFIndirectReference iccStreamRef;
171 {
172 static SkMutex iccProfileMapMutex;
173 SkAutoMutexExclusive lock(iccProfileMapMutex);
174
176 if (ref) {
177 iccStreamRef = *ref;
178 } else {
179 std::unique_ptr<SkPDFDict> iccStreamDict = SkPDFMakeDict();
180 iccStreamDict->insertInt("N", channels);
181 iccStreamRef = SkPDFStreamOut(std::move(iccStreamDict), SkMemoryStream::Make(icc), doc);
182 doc->fICCProfileMap.set(SkPDFIccProfileKey{icc, channels}, iccStreamRef);
183 }
184 }
185
186 std::unique_ptr<SkPDFArray> iccPDF = SkPDFMakeArray();
187 iccPDF->appendName("ICCBased");
188 iccPDF->appendRef(iccStreamRef);
189 return SkPDFUnion::Object(std::move(iccPDF));
190}
191
192void do_deflated_image(const SkPixmap& pm,
193 SkPDFDocument* doc,
194 bool isOpaque,
197 if (!isOpaque) {
198 sMask = doc->reserveRef();
199 }
201 SkPDFStreamFormat format = compressionLevel == SkPDF::Metadata::CompressionLevel::None
202 ? SkPDFStreamFormat::Uncompressed
203 : SkPDFStreamFormat::Flate;
206 std::optional<SkDeflateWStream> deflateWStream;
207 if (format == SkPDFStreamFormat::Flate) {
208 deflateWStream.emplace(&buffer, SkToInt(compressionLevel));
209 stream = &*deflateWStream;
210 }
211 SkPDFUnion colorSpace = SkPDFUnion::Name("DeviceGray");
212 int channels;
213 switch (pm.colorType()) {
215 channels = 1;
216 fill_stream(stream, '\x00', pm.width() * pm.height());
217 break;
219 channels = 1;
220 SkASSERT(sMask.fValue = -1);
221 SkASSERT(pm.rowBytes() == (size_t)pm.width());
222 stream->write(pm.addr8(), pm.width() * pm.height());
223 break;
224 default:
225 colorSpace = SkPDFUnion::Name("DeviceRGB");
226 channels = 3;
229 SkASSERT(pm.rowBytes() == (size_t)pm.width() * 4);
230 uint8_t byteBuffer[3072];
231 static_assert(std::size(byteBuffer) % 3 == 0, "");
232 uint8_t* bufferStop = byteBuffer + std::size(byteBuffer);
233 uint8_t* dst = byteBuffer;
234 for (int y = 0; y < pm.height(); ++y) {
235 const SkColor* src = pm.addr32(0, y);
236 for (int x = 0; x < pm.width(); ++x) {
237 SkColor color = *src++;
239 color = get_neighbor_avg_color(pm, x, y);
240 }
241 *dst++ = SkColorGetR(color);
242 *dst++ = SkColorGetG(color);
243 *dst++ = SkColorGetB(color);
244 if (dst == bufferStop) {
245 stream->write(byteBuffer, sizeof(byteBuffer));
246 dst = byteBuffer;
247 }
248 }
249 }
250 stream->write(byteBuffer, dst - byteBuffer);
251 }
252 if (deflateWStream) {
253 deflateWStream->finalize();
254 }
255
256 if (pm.colorSpace() && channels != 1) {
257 skcms_ICCProfile iccProfile;
258 pm.colorSpace()->toProfile(&iccProfile);
259 sk_sp<SkData> iccData = SkWriteICCProfile(&iccProfile, "");
260 colorSpace = write_icc_profile(doc, std::move(iccData), channels);
261 }
262
263 #ifdef SK_PDF_BASE85_BINARY
264 SkPDFUtils::Base85Encode(buffer.detachAsStream(), &buffer);
265 #endif
266 int length = SkToInt(buffer.bytesWritten());
267 emit_image_stream(doc, ref, [&buffer](SkWStream* stream) { buffer.writeToAndReset(stream); },
268 pm.info().dimensions(), std::move(colorSpace), sMask, length, format);
269 if (!isOpaque) {
270 do_deflated_alpha(pm, doc, sMask);
271 }
272}
273
274bool do_jpeg(sk_sp<SkData> data, SkColorSpace* imageColorSpace, SkPDFDocument* doc, SkISize size,
276 static constexpr const SkCodecs::Decoder decoders[] = {
278 };
279 std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(data, decoders);
280 if (!codec) {
281 return false;
282 }
283
284 SkISize jpegSize = codec->dimensions();
285 const SkEncodedInfo& encodedInfo = SkPDFBitmap::GetEncodedInfo(*codec);
286 SkEncodedInfo::Color jpegColorType = encodedInfo.color();
287 SkEncodedOrigin exifOrientation = codec->getOrigin();
288
289 bool yuv = jpegColorType == SkEncodedInfo::kYUV_Color;
290 bool goodColorType = yuv || jpegColorType == SkEncodedInfo::kGray_Color;
291 if (jpegSize != size // Safety check.
292 || !goodColorType
293 || kTopLeft_SkEncodedOrigin != exifOrientation) {
294 return false;
295 }
296 #ifdef SK_PDF_BASE85_BINARY
298 SkPDFUtils::Base85Encode(SkMemoryStream::MakeDirect(data->data(), data->size()), &buffer);
299 data = buffer.detachAsData();
300 #endif
301
302 int channels = yuv ? 3 : 1;
303 SkPDFUnion colorSpace = yuv ? SkPDFUnion::Name("DeviceRGB") : SkPDFUnion::Name("DeviceGray");
304 if (sk_sp<SkData> encodedIccProfileData = encodedInfo.profileData()) {
305 colorSpace = write_icc_profile(doc, std::move(encodedIccProfileData), channels);
306 } else if (const skcms_ICCProfile* codecIccProfile = codec->getICCProfile()) {
307 sk_sp<SkData> codecIccData = SkWriteICCProfile(codecIccProfile, "");
308 colorSpace = write_icc_profile(doc, std::move(codecIccData), channels);
309 } else if (imageColorSpace && channels != 1) {
310 skcms_ICCProfile imageIccProfile;
311 imageColorSpace->toProfile(&imageIccProfile);
312 sk_sp<SkData> imageIccData = SkWriteICCProfile(&imageIccProfile, "");
313 colorSpace = write_icc_profile(doc, std::move(imageIccData), channels);
314 }
315
316 emit_image_stream(doc, ref,
317 [&data](SkWStream* dst) { dst->write(data->data(), data->size()); },
318 jpegSize, std::move(colorSpace),
319 SkPDFIndirectReference(), SkToInt(data->size()), SkPDFStreamFormat::DCT);
320 return true;
321}
322
323SkBitmap to_pixels(const SkImage* image) {
324 SkBitmap bm;
325 int w = image->width(),
326 h = image->height();
327 switch (image->colorType()) {
330 break;
333 break;
334 default: {
335 // TODO: makeColorSpace(sRGB) or actually tag the images
337 bm.allocPixels(
339 }
340 }
341 // TODO: support GPU images in PDFs
342 if (!image->readPixels(nullptr, bm.pixmap(), 0, 0)) {
343 bm.eraseColor(SkColorSetARGB(0xFF, 0, 0, 0));
344 }
345 return bm;
346}
347
348void serialize_image(const SkImage* img,
349 int encodingQuality,
350 SkPDFDocument* doc,
352 SkASSERT(img);
353 SkASSERT(doc);
354 SkASSERT(encodingQuality >= 0);
355 SkISize dimensions = img->dimensions();
356
357 if (sk_sp<SkData> data = img->refEncodedData()) {
358 if (do_jpeg(std::move(data), img->colorSpace(), doc, dimensions, ref)) {
359 return;
360 }
361 }
362 SkBitmap bm = to_pixels(img);
363 const SkPixmap& pm = bm.pixmap();
364 bool isOpaque = pm.isOpaque() || pm.computeIsOpaque();
365 if (encodingQuality <= 100 && isOpaque) {
367 jOpts.fQuality = encodingQuality;
369 if (SkJpegEncoder::Encode(&stream, pm, jOpts)) {
370 if (do_jpeg(stream.detachAsData(), pm.colorSpace(), doc, dimensions, ref)) {
371 return;
372 }
373 }
374 }
375 do_deflated_image(pm, doc, isOpaque, ref);
376}
377
378} // namespace
379
381 SkPDFDocument* doc,
382 int encodingQuality) {
383 SkASSERT(img);
384 SkASSERT(doc);
386 if (SkExecutor* executor = doc->executor()) {
387 SkRef(img);
388 doc->incrementJobCount();
389 executor->add([img, encodingQuality, doc, ref]() {
390 serialize_image(img, encodingQuality, doc, ref);
391 SkSafeUnref(img);
392 doc->signalJobComplete();
393 });
394 return ref;
395 }
396 serialize_image(img, encodingQuality, doc, ref);
397 return ref;
398}
SkColor4f color
kUnpremul_SkAlphaType
SkAlphaType
Definition SkAlphaType.h:26
@ kOpaque_SkAlphaType
pixel is opaque
Definition SkAlphaType.h:28
#define SkASSERT(cond)
Definition SkAssert.h:116
#define SK_BGRA_A32_SHIFT
Definition SkColorPriv.h:70
@ kBGRA_8888_SkColorType
pixel with 8 bits for blue, green, red, alpha; in 32-bit word
Definition SkColorType.h:26
@ kAlpha_8_SkColorType
pixel with alpha in 8-bit byte
Definition SkColorType.h:21
@ kGray_8_SkColorType
pixel with grayscale level in 8-bit byte
Definition SkColorType.h:35
#define SkColorGetR(color)
Definition SkColor.h:65
#define SkColorGetG(color)
Definition SkColor.h:69
uint32_t SkColor
Definition SkColor.h:37
#define SkColorSetRGB(r, g, b)
Definition SkColor.h:57
constexpr SkColor SK_ColorTRANSPARENT
Definition SkColor.h:99
static constexpr SkColor SkColorSetARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b)
Definition SkColor.h:49
#define SkColorGetA(color)
Definition SkColor.h:61
#define SkColorGetB(color)
Definition SkColor.h:73
constexpr SkAlpha SK_AlphaTRANSPARENT
Definition SkColor.h:89
SkEncodedOrigin
@ kTopLeft_SkEncodedOrigin
SK_API sk_sp< SkData > SkWriteICCProfile(const skcms_TransferFunction &, const skcms_Matrix3x3 &toXYZD50)
Definition SkICC.cpp:679
SkPDFIndirectReference SkPDFSerializeImage(const SkImage *img, SkPDFDocument *doc, int encodingQuality)
SkPDFIndirectReference SkPDFStreamOut(std::unique_ptr< SkPDFDict > dict, std::unique_ptr< SkStreamAsset > content, SkPDFDocument *doc, SkPDFSteamCompressionEnabled compress)
static std::unique_ptr< SkPDFDict > SkPDFMakeDict(const char *type=nullptr)
Definition SkPDFTypes.h:195
static std::unique_ptr< SkPDFArray > SkPDFMakeArray(Args... args)
Definition SkPDFTypes.h:135
static void SkSafeUnref(T *obj)
Definition SkRefCnt.h:149
static T * SkRef(T *obj)
Definition SkRefCnt.h:132
constexpr int SkToInt(S x)
Definition SkTo.h:29
constexpr uint8_t SkToU8(S x)
Definition SkTo.h:22
static sk_sp< SkData > serialize_image(const SkImage *image, SkSerialProcs procs)
void allocPixels(const SkImageInfo &info, size_t rowBytes)
Definition SkBitmap.cpp:258
bool isOpaque() const
Definition SkBitmap.h:324
const SkPixmap & pixmap() const
Definition SkBitmap.h:133
void eraseColor(SkColor4f) const
Definition SkBitmap.cpp:442
static std::unique_ptr< SkCodec > MakeFromData(sk_sp< SkData >, SkSpan< const SkCodecs::Decoder > decoders, SkPngChunkReader *=nullptr)
Definition SkCodec.cpp:241
const SkEncodedInfo & getEncodedInfo() const
Definition SkCodec.h:788
void toProfile(skcms_ICCProfile *) const
SkColorSpace * colorSpace() const
Definition SkImage.cpp:156
SkISize dimensions() const
Definition SkImage.h:297
bool readPixels(GrDirectContext *context, const SkImageInfo &dstInfo, void *dstPixels, size_t dstRowBytes, int srcX, int srcY, CachingHint cachingHint=kAllow_CachingHint) const
Definition SkImage.cpp:42
int width() const
Definition SkImage.h:285
SkColorType colorType() const
Definition SkImage.cpp:152
int height() const
Definition SkImage.h:291
sk_sp< SkData > refEncodedData() const
Definition SkImage.cpp:214
sk_sp< SkColorSpace > refColorSpace() const
Definition SkImage.cpp:158
static std::unique_ptr< SkMemoryStream > Make(sk_sp< SkData > data)
Definition SkStream.cpp:314
static std::unique_ptr< SkMemoryStream > MakeDirect(const void *data, size_t length)
Definition SkStream.cpp:310
static const SkEncodedInfo & GetEncodedInfo(SkCodec &)
SkExecutor * executor() const
const SkPDF::Metadata & metadata() const
skia_private::THashMap< SkPDFIccProfileKey, SkPDFIndirectReference, SkPDFIccProfileKey::Hash > fICCProfileMap
void emitStream(const SkPDFDict &dict, T writeStream, SkPDFIndirectReference ref)
SkPDFIndirectReference reserveRef()
static SkPDFUnion Object(std::unique_ptr< SkPDFObject >)
static SkPDFUnion Name(const char *)
const uint8_t * addr8() const
Definition SkPixmap.h:326
bool computeIsOpaque() const
Definition SkPixmap.cpp:577
const uint32_t * addr32() const
Definition SkPixmap.h:352
size_t rowBytes() const
Definition SkPixmap.h:145
int width() const
Definition SkPixmap.h:160
SkColorType colorType() const
Definition SkPixmap.h:173
bool isOpaque() const
Definition SkPixmap.h:201
SkColorSpace * colorSpace() const
Definition SkPixmap.cpp:61
const SkImageInfo & info() const
Definition SkPixmap.h:135
int height() const
Definition SkPixmap.h:166
SkAlphaType alphaType() const
Definition SkPixmap.h:175
V * find(const K &key) const
Definition SkTHash.h:479
V * set(K key, V val)
Definition SkTHash.h:472
sk_sp< SkImage > image
Definition examples.cpp:29
static bool b
static const uint8_t buffer[]
uint32_t uint32_t * format
size_t length
double y
double x
ImplicitString Name
Definition DMSrcSink.h:38
constexpr SkCodecs::Decoder Decoder()
SK_API bool Encode(SkWStream *dst, const SkPixmap &src, const Options &options)
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot data
Definition switches.h:41
it will be possible to load the file into Perfetto s trace viewer disable asset Prevents usage of any non test fonts unless they were explicitly Loaded via prefetched default font Indicates whether the embedding started a prefetch of the default font manager before creating the engine run In non interactive keep the shell running after the Dart script has completed enable serial On low power devices with low core running concurrent GC tasks on threads can cause them to contend with the UI thread which could potentially lead to jank This option turns off all concurrent GC activities domain network JSON encoded network policy per domain This overrides the DisallowInsecureConnections switch Embedder can specify whether to allow or disallow insecure connections at a domain level old gen heap size
Definition switches.h:259
dst
Definition cp.py:12
SkScalar w
SkScalar h
#define T
sk_sp< SkData > profileData() const
Color color() const
static SkImageInfo Make(int width, int height, SkColorType ct, SkAlphaType at)
static SkImageInfo MakeA8(int width, int height)
enum SkPDF::Metadata::CompressionLevel fCompressionLevel