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