Debian Codegraph @

src/core/SkPictureData.cpp

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * Copyright 2011 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
8 #include "src/core/SkPictureData.h"
9
10 #include "include/core/SkFlattenable.h"
11 #include "include/core/SkFontMgr.h"
12 #include "include/core/SkSerialProcs.h"
13 #include "include/core/SkStream.h"
14 #include "include/core/SkString.h"
15 #include "include/core/SkTypeface.h"
16 #include "include/private/base/SkDebug.h"
17 #include "include/private/base/SkTFitsIn.h"
18 #include "include/private/base/SkTemplates.h"
19 #include "include/private/base/SkTo.h"
20 #include "src/base/SkAutoMalloc.h"
•21 #include "src/core/SkDebugUtils.h"
22 #include "src/core/SkPicturePriv.h"
23 #include "src/core/SkPictureRecord.h"
24 #include "src/core/SkPtrRecorder.h"
25 #include "src/core/SkReadBuffer.h"
26 #include "src/core/SkStreamPriv.h"
27 #include "src/core/SkTHash.h"
28 #include "src/core/SkTextBlobPriv.h"
29 #include "src/core/SkVerticesPriv.h"
30 #include "src/core/SkWriteBuffer.h"
31
32 #include <cstring>
33 #include <utility>
34
35 using namespace skia_private;
36
37 template <typename T> int SafeCount(const T* obj) {
38 return obj ? obj->size() : 0;
39 }
40
41 SkPictureData::SkPictureData(const SkPictInfo& info)
42 : fInfo(info) {}
43
44 void SkPictureData::initForPlayback() const {
45 // ensure that the paths bounds are pre-computed
46 for (int i = 0; i < fPaths.size(); i++) {
47 fPaths[i].updateBoundsCache();
48 }
49 }
50
51 SkPictureData::SkPictureData(const SkPictureRecord& record,
52 const SkPictInfo& info)
53 : fPictures(record.getPictures())
54 , fDrawables(record.getDrawables())
55 , fTextBlobs(record.getTextBlobs())
56 , fVertices(record.getVertices())
57 , fImages(record.getImages())
58 , fSlugs(record.getSlugs())
59 , fInfo(info) {
60
61 fOpData = record.opData();
62
63 fPaints = record.fPaints;
64
65 fPaths.reset(record.fPaths.count());
66 record.fPaths.foreach([this](const SkPath& path, int n) {
67 // These indices are logically 1-based, but we need to serialize them
68 // 0-based to keep the deserializing SkPictureData::getPath() working.
69 fPaths[n-1] = path;
70 });
71
72 this->initForPlayback();
73 }
74
75 ///////////////////////////////////////////////////////////////////////////////
76 ///////////////////////////////////////////////////////////////////////////////
77
78 static size_t compute_chunk_size(SkFlattenable::Factory* array, int count) {
79 size_t size = 4; // for 'count'
80
81 for (int i = 0; i < count; i++) {
82 const char* name = SkFlattenable::FactoryToName(array[i]);
83 if (nullptr == name || 0 == *name) {
84 size += SkWStream::SizeOfPackedUInt(0);
85 } else {
86 size_t len = strlen(name);
87 size += SkWStream::SizeOfPackedUInt(len);
88 size += len;
89 }
90 }
91
92 return size;
93 }
94
95 static void write_tag_size(SkWriteBuffer& buffer, uint32_t tag, size_t size) {
96 buffer.writeUInt(tag);
97 buffer.writeUInt(SkToU32(size));
98 }
99
100 static void write_tag_size(SkWStream* stream, uint32_t tag, size_t size) {
101 stream->write32(tag);
102 stream->write32(SkToU32(size));
103 }
104
105 void SkPictureData::WriteFactories(SkWStream* stream, const SkFactorySet& rec) {
106 int count = rec.count();
107
108 AutoSTMalloc<16, SkFlattenable::Factory> storage(count);
109 SkFlattenable::Factory* array = (SkFlattenable::Factory*)storage.get();
110 rec.copyToArray(array);
111
112 size_t size = compute_chunk_size(array, count);
113
114 // TODO: write_tag_size should really take a size_t
115 write_tag_size(stream, SK_PICT_FACTORY_TAG, (uint32_t) size);
116 SkDEBUGCODE(size_t start = stream->bytesWritten());
117 stream->write32(count);
118
119 for (int i = 0; i < count; i++) {
120 const char* name = SkFlattenable::FactoryToName(array[i]);
121 if (nullptr == name || 0 == *name) {
122 stream->writePackedUInt(0);
123 } else {
124 size_t len = strlen(name);
125 stream->writePackedUInt(len);
126 stream->write(name, len);
127 }
128 }
129
130 SkASSERT(size == (stream->bytesWritten() - start));
131 }
132
133 void SkPictureData::WriteTypefaces(SkWStream* stream, const SkRefCntSet& rec,
134 const SkSerialProcs& procs) {
135 int count = rec.count();
136
137 write_tag_size(stream, SK_PICT_TYPEFACE_TAG, count);
138
139 AutoSTMalloc<16, SkTypeface*> storage(count);
140 SkTypeface** array = (SkTypeface**)storage.get();
141 rec.copyToArray((SkRefCnt**)array);
142
143 for (int i = 0; i < count; i++) {
144 SkTypeface* tf = array[i];
145 if (procs.fTypefaceProc) {
146 auto data = procs.fTypefaceProc(tf, procs.fTypefaceCtx);
147 if (data) {
148 stream->write(data->data(), data->size());
149 continue;
150 }
151 }
152 // With the default serialization and deserialization behavior,
153 // kIncludeDataIfLocal does not always work because there is no default
154 // fontmgr to pass into SkTypeface::MakeDeserialize, so there is no
155 // fontmgr to find a font given the descriptor only.
156 tf->serialize(stream, SkTypeface::SerializeBehavior::kDoIncludeData);
157 }
158 }
159
160 void SkPictureData::flattenToBuffer(SkWriteBuffer& buffer, bool textBlobsOnly) const {
161 if (!textBlobsOnly) {
162 int numPaints = fPaints.size();
163 if (numPaints > 0) {
164 write_tag_size(buffer, SK_PICT_PAINT_BUFFER_TAG, numPaints);
165 for (const SkPaint& paint : fPaints) {
166 buffer.writePaint(paint);
167 }
168 }
169
170 int numPaths = fPaths.size();
171 if (numPaths > 0) {
172 write_tag_size(buffer, SK_PICT_PATH_BUFFER_TAG, numPaths);
173 buffer.writeInt(numPaths);
174 for (const SkPath& path : fPaths) {
175 buffer.writePath(path);
176 }
177 }
178 }
179
180 if (!fTextBlobs.empty()) {
181 write_tag_size(buffer, SK_PICT_TEXTBLOB_BUFFER_TAG, fTextBlobs.size());
182 for (const auto& blob : fTextBlobs) {
183 SkTextBlobPriv::Flatten(*blob, buffer);
184 }
185 }
186
187 if (!textBlobsOnly) {
188 write_tag_size(buffer, SK_PICT_SLUG_BUFFER_TAG, fSlugs.size());
189 for (const auto& slug : fSlugs) {
190 slug->doFlatten(buffer);
191 }
192 }
193
194 if (!textBlobsOnly) {
195 if (!fVertices.empty()) {
196 write_tag_size(buffer, SK_PICT_VERTICES_BUFFER_TAG, fVertices.size());
197 for (const auto& vert : fVertices) {
198 vert->priv().encode(buffer);
199 }
200 }
201
202 if (!fImages.empty()) {
203 write_tag_size(buffer, SK_PICT_IMAGE_BUFFER_TAG, fImages.size());
204 for (const auto& img : fImages) {
205 buffer.writeImage(img.get());
206 }
207 }
208 }
209 }
210
211 // SkPictureData::serialize() will write out paints, and then write out an array of typefaces
212 // (unique set). However, paint's serializer will respect SerialProcs, which can cause us to
213 // call that custom typefaceproc on *every* typeface, not just on the unique ones. To avoid this,
214 // we ignore the custom proc (here) when we serialize the paints, and then do respect it when
215 // we serialize the typefaces.
216 static SkSerialProcs skip_typeface_proc(const SkSerialProcs& procs) {
217 SkSerialProcs newProcs = procs;
218 newProcs.fTypefaceProc = nullptr;
219 newProcs.fTypefaceCtx = nullptr;
220 return newProcs;
221 }
222
223 // topLevelTypeFaceSet is null only on the top level call.
224 // This method is called recursively on every subpicture in two passes.
225 // textBlobsOnly serves to indicate that we are on the first pass and skip as much work as
226 // possible that is not relevant to collecting text blobs in topLevelTypeFaceSet
227 // TODO(nifong): dedupe typefaces and all other shared resources in a faster and more readable way.
228 void SkPictureData::serialize(SkWStream* stream, const SkSerialProcs& procs,
229 SkRefCntSet* topLevelTypeFaceSet, bool textBlobsOnly) const {
230 // This can happen at pretty much any time, so might as well do it first.
231 write_tag_size(stream, SK_PICT_READER_TAG, fOpData->size());
232 stream->write(fOpData->bytes(), fOpData->size());
233
234 // We serialize all typefaces into the typeface section of the top-level picture.
235 SkRefCntSet localTypefaceSet;
236 SkRefCntSet* typefaceSet = topLevelTypeFaceSet ? topLevelTypeFaceSet : &localTypefaceSet;
237
238 // We delay serializing the bulk of our data until after we've serialized
239 // factories and typefaces by first serializing to an in-memory write buffer.
240 SkFactorySet factSet; // buffer refs factSet, so factSet must come first.
241 SkBinaryWriteBuffer buffer(skip_typeface_proc(procs));
242 buffer.setFactoryRecorder(sk_ref_sp(&factSet));
243 buffer.setTypefaceRecorder(sk_ref_sp(typefaceSet));
244 this->flattenToBuffer(buffer, textBlobsOnly);
245
246 // Pretend to serialize our sub-pictures for the side effect of filling typefaceSet
247 // with typefaces from sub-pictures.
248 struct DevNull: public SkWStream {
249 DevNull() : fBytesWritten(0) {}
250 size_t fBytesWritten;
251 bool write(const void*, size_t size) override { fBytesWritten += size; return true; }
252 size_t bytesWritten() const override { return fBytesWritten; }
253 } devnull;
254 for (const auto& pic : fPictures) {
255 pic->serialize(&devnull, nullptr, typefaceSet, /*textBlobsOnly=*/ true);
256 }
257 if (textBlobsOnly) { return; } // return early from fake serialize
258
259 // We need to write factories before we write the buffer.
260 // We need to write typefaces before we write the buffer or any sub-picture.
261 WriteFactories(stream, factSet);
262 // Pass the original typefaceproc (if any) now that we're ready to actually serialize the
263 // typefaces. We skipped this proc before, when we were serializing paints, so that the
264 // paints would just write indices into our typeface set.
265 WriteTypefaces(stream, *typefaceSet, procs);
266
267 // Write the buffer.
268 write_tag_size(stream, SK_PICT_BUFFER_SIZE_TAG, buffer.bytesWritten());
269 buffer.writeToStream(stream);
270
271 // Write sub-pictures by calling serialize again.
272 if (!fPictures.empty()) {
273 write_tag_size(stream, SK_PICT_PICTURE_TAG, fPictures.size());
274 for (const auto& pic : fPictures) {
275 pic->serialize(stream, &procs, typefaceSet, /*textBlobsOnly=*/ false);
276 }
277 }
278
279 stream->write32(SK_PICT_EOF_TAG);
280 }
281
282 void SkPictureData::flatten(SkWriteBuffer& buffer) const {
283 write_tag_size(buffer, SK_PICT_READER_TAG, fOpData->size());
284 buffer.writeByteArray(fOpData->bytes(), fOpData->size());
285
286 if (!fPictures.empty()) {
287 write_tag_size(buffer, SK_PICT_PICTURE_TAG, fPictures.size());
288 for (const auto& pic : fPictures) {
289 SkPicturePriv::Flatten(pic, buffer);
290 }
291 }
292
293 if (!fDrawables.empty()) {
294 write_tag_size(buffer, SK_PICT_DRAWABLE_TAG, fDrawables.size());
295 for (const auto& draw : fDrawables) {
296 buffer.writeFlattenable(draw.get());
297 }
298 }
299
300 // Write this picture playback's data into a writebuffer
301 this->flattenToBuffer(buffer, false);
302 buffer.write32(SK_PICT_EOF_TAG);
303 }
304
305 ///////////////////////////////////////////////////////////////////////////////
306
307 bool SkPictureData::parseStreamTag(SkStream* stream,
308 uint32_t tag,
309 uint32_t size,
310 const SkDeserialProcs& procs,
311 SkTypefacePlayback* topLevelTFPlayback,
312 int recursionLimit) {
•313 if (procs.fAllowTagsProc && !procs.fAllowTagsProc(tag, procs.fAllowTagsCtx)) {
314 // Typefaces are always set but if there's 0 of them, we won't mark the stream as invalid
315 // if the typeface tag is not allowed.
316 return size == 0;
317 }
318 switch (tag) {
319 case SK_PICT_READER_TAG:
320 SkASSERT(nullptr == fOpData);
321 fOpData = SkData::MakeFromStream(stream, size);
322 if (!fOpData) {
323 return false;
324 }
325 break;
326 case SK_PICT_FACTORY_TAG: {
327 if (!stream->readU32(&size)) { return false; }
328 if (SkStreamPriv::RemainingLengthIsBelow(stream, size)) {
329 return false;
330 }
331 fFactoryPlayback = std::make_unique<SkFactoryPlayback>(size);
332 for (size_t i = 0; i < size; i++) {
333 SkString str;
334 size_t len;
335 if (!stream->readPackedUInt(&len)) { return false; }
336 if (SkStreamPriv::RemainingLengthIsBelow(stream, len)) {
337 return false;
338 }
339 str.resize(len);
340 if (stream->read(str.data(), len) != len) {
341 return false;
342 }
343 fFactoryPlayback->base()[i] = SkFlattenable::NameToFactory(str.c_str());
344 }
345 } break;
346 case SK_PICT_TYPEFACE_TAG: {
347 if (SkStreamPriv::RemainingLengthIsBelow(stream, size)) {
348 return false;
349 }
350 fTFPlayback.setCount(size);
351 for (uint32_t i = 0; i < size; ++i) {
352 if (stream->isAtEnd()) {
353 return false;
354 }
355 sk_sp<SkTypeface> tf;
356 if (procs.fTypefaceStreamProc) {
357 tf = procs.fTypefaceStreamProc(*stream, procs.fTypefaceCtx);
358 } else {
359 tf = SkTypeface::MakeDeserialize(stream, nullptr);
360 }
361 if (!tf) { // failed to deserialize
362 // fTFPlayback asserts it never has a null, so we plop in
363 // a default here.
364 tf = SkTypeface::MakeEmpty();
365 }
366 fTFPlayback[i] = std::move(tf);
367 }
368 } break;
369 case SK_PICT_PICTURE_TAG: {
370 SkASSERT(fPictures.empty());
371 if (SkStreamPriv::RemainingLengthIsBelow(stream, size)) {
372 return false;
373 }
374 fPictures.reserve_exact(SkToInt(size));
375
376 for (uint32_t i = 0; i < size; i++) {
377 auto pic = SkPicture::MakeFromStreamPriv(stream, &procs,
378 topLevelTFPlayback, recursionLimit - 1);
379 if (!pic) {
380 return false;
381 }
382 fPictures.push_back(std::move(pic));
383 }
384 } break;
385 case SK_PICT_BUFFER_SIZE_TAG: {
386 if (SkStreamPriv::RemainingLengthIsBelow(stream, size)) {
387 return false;
388 }
389 SkAutoMalloc storage(size);
390 if (stream->read(storage.get(), size) != size) {
391 return false;
392 }
393
394 SkReadBuffer buffer(storage.get(), size);
395 buffer.setVersion(fInfo.getVersion());
396
397 if (!fFactoryPlayback) {
398 return false;
399 }
400 fFactoryPlayback->setupBuffer(buffer);
401 buffer.setDeserialProcs(procs);
402
403 if (fTFPlayback.count() > 0) {
404 // .skp files <= v43 have typefaces serialized with each sub picture.
405 fTFPlayback.setupBuffer(buffer);
406 } else {
407 // Newer .skp files serialize all typefaces with the top picture.
408 topLevelTFPlayback->setupBuffer(buffer);
409 }
410
411 while (!buffer.eof() && buffer.isValid()) {
412 tag = buffer.readUInt();
413 size = buffer.readUInt();
414 this->parseBufferTag(buffer, tag, size);
415 }
416 if (!buffer.isValid()) {
417 return false;
418 }
419 } break;
420 }
421 return true; // success
422 }
423
424 static sk_sp<SkImage> create_image_from_buffer(SkReadBuffer& buffer) {
425 return buffer.readImage();
426 }
427
428 static sk_sp<SkDrawable> create_drawable_from_buffer(SkReadBuffer& buffer) {
429 return sk_sp<SkDrawable>((SkDrawable*)buffer.readFlattenable(SkFlattenable::kSkDrawable_Type));
430 }
431
432 // We need two types 'cause SkDrawable is const-variant.
433 template <typename T, typename U>
434 bool new_array_from_buffer(SkReadBuffer& buffer, uint32_t inCount,
435 TArray<sk_sp<T>>& array, sk_sp<U> (*factory)(SkReadBuffer&)) {
436 if (!buffer.validate(array.empty() && SkTFitsIn<int>(inCount))) {
437 return false;
438 }
439 if (0 == inCount) {
440 return true;
441 }
442
443 for (uint32_t i = 0; i < inCount; ++i) {
444 auto obj = factory(buffer);
445
446 if (!buffer.validate(obj != nullptr)) {
447 array.clear();
448 return false;
449 }
450
451 array.push_back(std::move(obj));
452 }
453
454 return true;
455 }
456
457 void SkPictureData::parseBufferTag(SkReadBuffer& buffer, uint32_t tag, uint32_t size) {
•458 #if defined(SK_DUMP_TAGS)
459 SkDebugf("parseBufferTag ");
460 SkDumpTag(tag);
461 SkDebugf(" size %u\n", size);
462 #endif
463 if (!buffer.allowTags(tag)) {
464 buffer.validate(size == 0);
465 return;
466 }
467 switch (tag) {
468 case SK_PICT_PAINT_BUFFER_TAG: {
469 if (!buffer.validate(SkTFitsIn<int>(size))) {
470 return;
471 }
472 const int count = SkToInt(size);
473
474 for (int i = 0; i < count; ++i) {
475 fPaints.push_back(buffer.readPaint());
476 if (!buffer.isValid()) {
477 return;
478 }
479 }
480 } break;
481 case SK_PICT_PATH_BUFFER_TAG:
482 if (size > 0) {
483 const int count = buffer.readInt();
484 if (!buffer.validate(count >= 0)) {
485 return;
486 }
487 for (int i = 0; i < count; i++) {
488 if (auto path = buffer.readPath()) {
489 fPaths.push_back(std::move(*path));
490 } else {
491 // readPath should invalidate the buffer if we didn't get a path back.
492 SkASSERT(!buffer.isValid());
493 return;
494 }
495 }
496 } break;
497 case SK_PICT_TEXTBLOB_BUFFER_TAG:
498 new_array_from_buffer(buffer, size, fTextBlobs, SkTextBlobPriv::MakeFromBuffer);
499 break;
500 case SK_PICT_SLUG_BUFFER_TAG:
501 new_array_from_buffer(buffer, size, fSlugs, sktext::gpu::Slug::MakeFromBuffer);
502 break;
503 case SK_PICT_VERTICES_BUFFER_TAG:
504 new_array_from_buffer(buffer, size, fVertices, SkVerticesPriv::Decode);
505 break;
506 case SK_PICT_IMAGE_BUFFER_TAG:
507 new_array_from_buffer(buffer, size, fImages, create_image_from_buffer);
508 break;
509 case SK_PICT_READER_TAG: {
510 // Preflight check that we can initialize all data from the buffer
511 // before allocating it.
512 if (!buffer.validateCanReadN<uint8_t>(size)) {
513 return;
514 }
515 auto data(SkData::MakeUninitialized(size));
516 if (!buffer.readByteArray(data->writable_data(), size) ||
517 !buffer.validate(nullptr == fOpData)) {
518 return;
519 }
520 SkASSERT(nullptr == fOpData);
521 fOpData = std::move(data);
522 } break;
523 case SK_PICT_PICTURE_TAG:
524 new_array_from_buffer(buffer, size, fPictures, SkPicturePriv::MakeFromBuffer);
525 break;
526 case SK_PICT_DRAWABLE_TAG:
527 new_array_from_buffer(buffer, size, fDrawables, create_drawable_from_buffer);
528 break;
529 default:
530 buffer.validate(false); // The tag was invalid.
531 break;
532 }
533 }
534
535 SkPictureData* SkPictureData::CreateFromStream(SkStream* stream,
536 const SkPictInfo& info,
537 const SkDeserialProcs& procs,
538 SkTypefacePlayback* topLevelTFPlayback,
539 int recursionLimit) {
540 std::unique_ptr<SkPictureData> data(new SkPictureData(info));
541 if (!topLevelTFPlayback) {
542 topLevelTFPlayback = &data->fTFPlayback;
543 }
544
545 if (!data->parseStream(stream, procs, topLevelTFPlayback, recursionLimit)) {
546 return nullptr;
547 }
548 return data.release();
549 }
550
551 SkPictureData* SkPictureData::CreateFromBuffer(SkReadBuffer& buffer,
552 const SkPictInfo& info) {
553 std::unique_ptr<SkPictureData> data(new SkPictureData(info));
554 buffer.setVersion(info.getVersion());
555
556 if (!data->parseBuffer(buffer)) {
557 return nullptr;
558 }
559 return data.release();
560 }
561
562 bool SkPictureData::parseStream(SkStream* stream,
563 const SkDeserialProcs& procs,
564 SkTypefacePlayback* topLevelTFPlayback,
565 int recursionLimit) {
566 for (;;) {
567 uint32_t tag;
568 if (!stream->readU32(&tag)) { return false; }
569 if (SK_PICT_EOF_TAG == tag) {
570 break;
571 }
572
573 uint32_t size;
574 if (!stream->readU32(&size)) { return false; }
575 if (!this->parseStreamTag(stream, tag, size, procs, topLevelTFPlayback, recursionLimit)) {
576 return false; // we're invalid
577 }
578 }
579 return true;
580 }
581
582 bool SkPictureData::parseBuffer(SkReadBuffer& buffer) {
583 while (buffer.isValid()) {
584 uint32_t tag = buffer.readUInt();
585 if (SK_PICT_EOF_TAG == tag) {
586 break;
587 }
588 this->parseBufferTag(buffer, tag, buffer.readUInt());
589 }
590
591 // Check that we encountered required tags
592 if (!buffer.validate(this->opData() != nullptr)) {
593 // If we didn't build any opData, we are invalid. Even an EmptyPicture allocates the
594 // SkData for the ops (though its length may be zero).
595 return false;
596 }
597 return true;
598 }
599
600 const SkPaint* SkPictureData::optionalPaint(SkReadBuffer* reader) const {
601 int index = reader->readInt();
602 if (index == 0) {
603 return nullptr; // recorder wrote a zero for no paint (likely drawimage)
604 }
605 return reader->validate(index > 0 && index <= fPaints.size()) ?
606 &fPaints[index - 1] : nullptr;
607 }
608
609 const SkPaint& SkPictureData::requiredPaint(SkReadBuffer* reader) const {
610 const SkPaint* paint = this->optionalPaint(reader);
611 if (reader->validate(paint != nullptr)) {
612 return *paint;
613 }
614 static const SkPaint& stub = *(new SkPaint);
615 return stub;
616 }