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