SkPipeCanvas.cpp revision 3ac64b427af596e4e8341857ce5f214bf0b49efb
1/*
2 * Copyright 2016 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 "SkPathEffect.h"
9#include "SkColorFilter.h"
10#include "SkDrawLooper.h"
11#include "SkImageFilter.h"
12#include "SkMaskFilter.h"
13#include "SkPipeCanvas.h"
14#include "SkPipeFormat.h"
15#include "SkRasterizer.h"
16#include "SkRSXform.h"
17#include "SkShader.h"
18#include "SkStream.h"
19#include "SkTextBlob.h"
20#include "SkTypeface.h"
21
22template <typename T> void write_rrect(T* writer, const SkRRect& rrect) {
23    char tmp[SkRRect::kSizeInMemory];
24    rrect.writeToMemory(tmp);
25    writer->write(tmp, SkRRect::kSizeInMemory);
26}
27
28template <typename T> void write_pad(T* writer, const void* buffer, size_t len) {
29    writer->write(buffer, len & ~3);
30    if (len & 3) {
31        const char* src = (const char*)buffer + (len & ~3);
32        len &= 3;
33        uint32_t tmp = 0;
34        memcpy(&tmp, src, len);
35        writer->write(&tmp, 4);
36    }
37}
38
39///////////////////////////////////////////////////////////////////////////////////////////////////
40
41static uint16_t compute_nondef(const SkPaint& paint, PaintUsage usage) {
42    // kRespectsStroke_PaintUsage is only valid if other bits are also set
43    SkASSERT(0 != (usage & ~kRespectsStroke_PaintUsage));
44
45    const SkScalar kTextSize_Default    = 12;
46    const SkScalar kTextScaleX_Default  = 1;
47    const SkScalar kTextSkewX_Default   = 0;
48    const SkScalar kStrokeWidth_Default = 0;
49    const SkScalar kStrokeMiter_Default = 4;
50    const SkColor  kColor_Default       = SK_ColorBLACK;
51
52    unsigned bits = (paint.getColor() != kColor_Default) ? kColor_NonDef : 0;
53
54    if (usage & kText_PaintUsage) {
55        bits |= (paint.getTextSize() != kTextSize_Default       ? kTextSize_NonDef : 0);
56        bits |= (paint.getTextScaleX() != kTextScaleX_Default   ? kTextScaleX_NonDef : 0);
57        bits |= (paint.getTextSkewX() != kTextSkewX_Default     ? kTextSkewX_NonDef : 0);
58        bits |= (paint.getTypeface()                            ? kTypeface_NonDef : 0);
59    }
60
61    // TODO: kImage_PaintUsage only needs the shader/maskfilter IF its colortype is kAlpha_8
62
63    if (usage & (kVertices_PaintUsage | kDrawPaint_PaintUsage | kImage_PaintUsage |
64                 kText_PaintUsage | kGeometry_PaintUsage | kTextBlob_PaintUsage)) {
65        bits |= (paint.getShader()      ? kShader_NonDef : 0);
66    }
67
68    if (usage & (kText_PaintUsage | kGeometry_PaintUsage | kTextBlob_PaintUsage)) {
69        bits |= (paint.getPathEffect()  ? kPathEffect_NonDef : 0);
70        bits |= (paint.getRasterizer()  ? kRasterizer_NonDef : 0);
71
72        if (paint.getStyle() != SkPaint::kFill_Style || (usage & kRespectsStroke_PaintUsage)) {
73            bits |= (paint.getStrokeWidth() != kStrokeWidth_Default ? kStrokeWidth_NonDef : 0);
74            bits |= (paint.getStrokeMiter() != kStrokeMiter_Default ? kStrokeMiter_NonDef : 0);
75        }
76    }
77
78    if (usage &
79        (kText_PaintUsage | kGeometry_PaintUsage | kImage_PaintUsage | kTextBlob_PaintUsage))
80    {
81        bits |= (paint.getMaskFilter()  ? kMaskFilter_NonDef : 0);
82    }
83
84    bits |= (paint.getColorFilter() ? kColorFilter_NonDef : 0);
85    bits |= (paint.getImageFilter() ? kImageFilter_NonDef : 0);
86    bits |= (paint.getDrawLooper()  ? kDrawLooper_NonDef : 0);
87
88    return SkToU16(bits);
89}
90
91static uint32_t pack_paint_flags(unsigned flags, unsigned hint, unsigned align,
92                                 unsigned filter, unsigned style, unsigned caps, unsigned joins,
93                                 unsigned encoding) {
94    SkASSERT(kFlags_BPF + kHint_BPF + kAlign_BPF + kFilter_BPF <= 32);
95
96    ASSERT_FITS_IN(flags, kFlags_BPF);
97    ASSERT_FITS_IN(filter, kFilter_BPF);
98    ASSERT_FITS_IN(style, kStyle_BPF);
99    ASSERT_FITS_IN(caps, kCaps_BPF);
100    ASSERT_FITS_IN(joins, kJoins_BPF);
101    ASSERT_FITS_IN(hint, kHint_BPF);
102    ASSERT_FITS_IN(align, kAlign_BPF);
103    ASSERT_FITS_IN(encoding, kEncoding_BPF);
104
105    // left-align the fields of "known" size, and right-align the last (flatFlags) so it can easly
106    // add more bits in the future.
107
108    uint32_t packed = 0;
109    int shift = 32;
110
111    shift -= kFlags_BPF;    packed |= (flags << shift);
112    shift -= kFilter_BPF;   packed |= (filter << shift);
113    shift -= kStyle_BPF;    packed |= (style << shift);
114    // these are only needed for stroking (geometry or text)
115    shift -= kCaps_BPF;     packed |= (caps << shift);
116    shift -= kJoins_BPF;    packed |= (joins << shift);
117    // these are only needed for text
118    shift -= kHint_BPF;     packed |= (hint << shift);
119    shift -= kAlign_BPF;    packed |= (align << shift);
120    shift -= kEncoding_BPF; packed |= (encoding << shift);
121
122    return packed;
123}
124
125#define CHECK_WRITE_SCALAR(writer, nondef, paint, Field)    \
126    do { if (nondef & (k##Field##_NonDef)) {                \
127        writer.writeScalar(paint.get##Field());             \
128    }} while (0)
129
130#define CHECK_WRITE_FLATTENABLE(writer, nondef, paint, Field)   \
131    do { if (nondef & (k##Field##_NonDef)) {                    \
132        SkFlattenable* f = paint.get##Field();                  \
133        SkASSERT(f != nullptr);                                 \
134        writer.writeFlattenable(f);                             \
135    } } while (0)
136
137/*
138 *  Header:
139 *      paint flags     : 32
140 *      non_def bits    : 16
141 *      xfermode enum   : 8
142 *      pad zeros       : 8
143 */
144static void write_paint(SkWriteBuffer& writer, const SkPaint& paint, unsigned usage) {
145    uint32_t packedFlags = pack_paint_flags(paint.getFlags(), paint.getHinting(),
146                                            paint.getTextAlign(), paint.getFilterQuality(),
147                                            paint.getStyle(), paint.getStrokeCap(),
148                                            paint.getStrokeJoin(), paint.getTextEncoding());
149    writer.write32(packedFlags);
150
151    unsigned nondef = compute_nondef(paint, (PaintUsage)usage);
152    const uint8_t pad = 0;
153    writer.write32((nondef << 16) | ((unsigned)paint.getBlendMode() << 8) | pad);
154
155    CHECK_WRITE_SCALAR(writer, nondef, paint, TextSize);
156    CHECK_WRITE_SCALAR(writer, nondef, paint, TextScaleX);
157    CHECK_WRITE_SCALAR(writer, nondef, paint, TextSkewX);
158    CHECK_WRITE_SCALAR(writer, nondef, paint, StrokeWidth);
159    CHECK_WRITE_SCALAR(writer, nondef, paint, StrokeMiter);
160
161    if (nondef & kColor_NonDef) {
162        writer.write32(paint.getColor());
163    }
164    if (nondef & kTypeface_NonDef) {
165        // TODO: explore idea of writing bits indicating "use the prev (or prev N) face"
166        // e.g. 1-N bits is an index into a ring buffer of typefaces
167        SkTypeface* tf = paint.getTypeface();
168        SkASSERT(tf);
169        writer.writeTypeface(tf);
170    }
171
172    CHECK_WRITE_FLATTENABLE(writer, nondef, paint, PathEffect);
173    CHECK_WRITE_FLATTENABLE(writer, nondef, paint, Shader);
174    CHECK_WRITE_FLATTENABLE(writer, nondef, paint, MaskFilter);
175    CHECK_WRITE_FLATTENABLE(writer, nondef, paint, ColorFilter);
176    CHECK_WRITE_FLATTENABLE(writer, nondef, paint, Rasterizer);
177    CHECK_WRITE_FLATTENABLE(writer, nondef, paint, ImageFilter);
178    CHECK_WRITE_FLATTENABLE(writer, nondef, paint, DrawLooper);
179}
180
181class SkPipeWriter : public SkBinaryWriteBuffer {
182    enum {
183        N = 1024/4,
184    };
185    uint32_t fStorage[N];
186    SkWStream* fStream;
187
188public:
189    SkPipeWriter(SkWStream* stream, SkDeduper* deduper)
190        : SkBinaryWriteBuffer(fStorage, sizeof(fStorage))
191        , fStream(stream)
192    {
193        this->setDeduper(deduper);
194    }
195
196    SkPipeWriter(SkPipeCanvas* pc) : SkPipeWriter(pc->fStream, pc->fDeduper) {}
197
198    ~SkPipeWriter() override {
199        SkASSERT(SkIsAlign4(fStream->bytesWritten()));
200        this->writeToStream(fStream);
201    }
202
203    void writePaint(const SkPaint& paint) override {
204        write_paint(*this, paint, kUnknown_PaintUsage);
205    }
206};
207
208///////////////////////////////////////////////////////////////////////////////////////////////////
209
210SkPipeCanvas::SkPipeCanvas(const SkRect& cull, SkPipeDeduper* deduper, SkWStream* stream)
211    : INHERITED(SkScalarCeilToInt(cull.width()), SkScalarCeilToInt(cull.height()))
212    , fDeduper(deduper)
213    , fStream(stream)
214{}
215
216SkPipeCanvas::~SkPipeCanvas() {}
217
218void SkPipeCanvas::willSave() {
219    fStream->write32(pack_verb(SkPipeVerb::kSave));
220    this->INHERITED::willSave();
221}
222
223SkCanvas::SaveLayerStrategy SkPipeCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {
224    SkPipeWriter writer(this);
225    uint32_t extra = rec.fSaveLayerFlags;
226
227    // remap this wacky flag
228    if (extra & (1 << 31)/*SkCanvas::kDontClipToLayer_PrivateSaveLayerFlag*/) {
229        extra &= ~(1 << 31);
230        extra |= kDontClipToLayer_SaveLayerMask;
231    }
232
233    if (rec.fBounds) {
234        extra |= kHasBounds_SaveLayerMask;
235    }
236    if (rec.fPaint) {
237        extra |= kHasPaint_SaveLayerMask;
238    }
239    if (rec.fBackdrop) {
240        extra |= kHasBackdrop_SaveLayerMask;
241    }
242
243    writer.write32(pack_verb(SkPipeVerb::kSaveLayer, extra));
244    if (rec.fBounds) {
245        writer.writeRect(*rec.fBounds);
246    }
247    if (rec.fPaint) {
248        write_paint(writer, *rec.fPaint, kSaveLayer_PaintUsage);
249    }
250    if (rec.fBackdrop) {
251        writer.writeFlattenable(rec.fBackdrop);
252    }
253    return kNoLayer_SaveLayerStrategy;
254}
255
256void SkPipeCanvas::willRestore() {
257    fStream->write32(pack_verb(SkPipeVerb::kRestore));
258    this->INHERITED::willRestore();
259}
260
261template <typename T> void write_sparse_matrix(T* writer, const SkMatrix& matrix) {
262    SkMatrix::TypeMask tm = matrix.getType();
263    SkScalar tmp[9];
264    if (tm & SkMatrix::kPerspective_Mask) {
265        matrix.get9(tmp);
266        writer->write(tmp, 9 * sizeof(SkScalar));
267    } else if (tm & SkMatrix::kAffine_Mask) {
268        tmp[0] = matrix[SkMatrix::kMScaleX];
269        tmp[1] = matrix[SkMatrix::kMSkewX];
270        tmp[2] = matrix[SkMatrix::kMTransX];
271        tmp[3] = matrix[SkMatrix::kMScaleY];
272        tmp[4] = matrix[SkMatrix::kMSkewY];
273        tmp[5] = matrix[SkMatrix::kMTransY];
274        writer->write(tmp, 6 * sizeof(SkScalar));
275    } else if (tm & SkMatrix::kScale_Mask) {
276        tmp[0] = matrix[SkMatrix::kMScaleX];
277        tmp[1] = matrix[SkMatrix::kMTransX];
278        tmp[2] = matrix[SkMatrix::kMScaleY];
279        tmp[3] = matrix[SkMatrix::kMTransY];
280        writer->write(tmp, 4 * sizeof(SkScalar));
281    } else if (tm & SkMatrix::kTranslate_Mask) {
282        tmp[0] = matrix[SkMatrix::kMTransX];
283        tmp[1] = matrix[SkMatrix::kMTransY];
284        writer->write(tmp, 2 * sizeof(SkScalar));
285    }
286    // else write nothing for Identity
287}
288
289static void do_concat(SkWStream* stream, const SkMatrix& matrix, bool isSetMatrix) {
290    unsigned mtype = matrix.getType();
291    SkASSERT(0 == (mtype & ~kTypeMask_ConcatMask));
292    unsigned extra = mtype;
293    if (isSetMatrix) {
294        extra |= kSetMatrix_ConcatMask;
295    }
296    if (mtype || isSetMatrix) {
297        stream->write32(pack_verb(SkPipeVerb::kConcat, extra));
298        write_sparse_matrix(stream, matrix);
299    }
300}
301
302void SkPipeCanvas::didConcat(const SkMatrix& matrix) {
303    do_concat(fStream, matrix, false);
304    this->INHERITED::didConcat(matrix);
305}
306
307void SkPipeCanvas::didSetMatrix(const SkMatrix& matrix) {
308    do_concat(fStream, matrix, true);
309    this->INHERITED::didSetMatrix(matrix);
310}
311
312void SkPipeCanvas::onClipRect(const SkRect& rect, ClipOp op, ClipEdgeStyle edgeStyle) {
313    fStream->write32(pack_verb(SkPipeVerb::kClipRect, ((unsigned)op << 1) | edgeStyle));
314    fStream->write(&rect, 4 * sizeof(SkScalar));
315
316    this->INHERITED::onClipRect(rect, op, edgeStyle);
317}
318
319void SkPipeCanvas::onClipRRect(const SkRRect& rrect, ClipOp op, ClipEdgeStyle edgeStyle) {
320    fStream->write32(pack_verb(SkPipeVerb::kClipRRect, ((unsigned)op << 1) | edgeStyle));
321    write_rrect(fStream, rrect);
322
323    this->INHERITED::onClipRRect(rrect, op, edgeStyle);
324}
325
326void SkPipeCanvas::onClipPath(const SkPath& path, ClipOp op, ClipEdgeStyle edgeStyle) {
327    SkPipeWriter writer(this);
328    writer.write32(pack_verb(SkPipeVerb::kClipPath, ((unsigned)op << 1) | edgeStyle));
329    writer.writePath(path);
330
331    this->INHERITED::onClipPath(path, op, edgeStyle);
332}
333
334void SkPipeCanvas::onClipRegion(const SkRegion& deviceRgn, ClipOp op) {
335    SkPipeWriter writer(this);
336    writer.write32(pack_verb(SkPipeVerb::kClipRegion, (unsigned)op << 1));
337    writer.writeRegion(deviceRgn);
338
339    this->INHERITED::onClipRegion(deviceRgn, op);
340}
341
342///////////////////////////////////////////////////////////////////////////////////////////////////
343
344void SkPipeCanvas::onDrawArc(const SkRect& bounds, SkScalar startAngle, SkScalar sweepAngle,
345                             bool useCenter, const SkPaint& paint) {
346    SkPipeWriter writer(this);
347    writer.write32(pack_verb(SkPipeVerb::kDrawArc, (int)useCenter));
348    writer.writeRect(bounds);
349    writer.writeScalar(startAngle);
350    writer.writeScalar(sweepAngle);
351    write_paint(writer, paint, kGeometry_PaintUsage);
352}
353
354void SkPipeCanvas::onDrawAtlas(const SkImage* image, const SkRSXform xform[], const SkRect rect[],
355                               const SkColor colors[], int count, SkXfermode::Mode mode,
356                               const SkRect* cull, const SkPaint* paint) {
357    unsigned extra = (unsigned)mode;
358    SkASSERT(0 == (extra & ~kMode_DrawAtlasMask));
359    if (colors) {
360        extra |= kHasColors_DrawAtlasMask;
361    }
362    if (cull) {
363        extra |= kHasCull_DrawAtlasMask;
364    }
365    if (paint) {
366        extra |= kHasPaint_DrawAtlasMask;
367    }
368
369    SkPipeWriter writer(this);
370    writer.write32(pack_verb(SkPipeVerb::kDrawAtlas, extra));
371    writer.writeImage(image);
372    writer.write32(count);
373    writer.write(xform, count * sizeof(SkRSXform));
374    writer.write(rect, count * sizeof(SkRect));
375    if (colors) {
376        writer.write(colors, count * sizeof(SkColor));
377    }
378    if (cull) {
379        writer.writeRect(*cull);
380    }
381    if (paint) {
382        write_paint(writer, *paint, kImage_PaintUsage);
383    }
384}
385
386void SkPipeCanvas::onDrawPaint(const SkPaint& paint) {
387    SkPipeWriter writer(this);
388    writer.write32(pack_verb(SkPipeVerb::kDrawPaint));
389    write_paint(writer, paint, kDrawPaint_PaintUsage);
390}
391
392void SkPipeCanvas::onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
393                                const SkPaint& paint) {
394    SkPipeWriter writer(this);
395    writer.write32(pack_verb(SkPipeVerb::kDrawPoints, mode));
396    writer.write32(SkToU32(count));
397    writer.write(pts, count * sizeof(SkPoint));
398    write_paint(writer, paint, kGeometry_PaintUsage | kRespectsStroke_PaintUsage);
399}
400
401void SkPipeCanvas::onDrawRect(const SkRect& rect, const SkPaint& paint) {
402    SkPipeWriter writer(this);
403    writer.write32(pack_verb(SkPipeVerb::kDrawRect));
404    writer.write(&rect, sizeof(SkRect));
405    write_paint(writer, paint, kGeometry_PaintUsage);
406}
407
408void SkPipeCanvas::onDrawOval(const SkRect& rect, const SkPaint& paint) {
409    SkPipeWriter writer(this);
410    writer.write32(pack_verb(SkPipeVerb::kDrawOval));
411    writer.write(&rect, sizeof(SkRect));
412    write_paint(writer, paint, kGeometry_PaintUsage);
413}
414
415void SkPipeCanvas::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) {
416    SkPipeWriter writer(this);
417    writer.write32(pack_verb(SkPipeVerb::kDrawRRect));
418    write_rrect(&writer, rrect);
419    write_paint(writer, paint, kGeometry_PaintUsage);
420}
421
422void SkPipeCanvas::onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) {
423    SkPipeWriter writer(this);
424    writer.write32(pack_verb(SkPipeVerb::kDrawDRRect));
425    write_rrect(&writer, outer);
426    write_rrect(&writer, inner);
427    write_paint(writer, paint, kGeometry_PaintUsage);
428}
429
430void SkPipeCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {
431    SkPipeWriter writer(this);
432    writer.write32(pack_verb(SkPipeVerb::kDrawPath));
433    writer.writePath(path);
434    write_paint(writer, paint, kGeometry_PaintUsage);
435}
436
437///////////////////////////////////////////////////////////////////////////////////////////////////
438
439static sk_sp<SkImage> make_from_bitmap(const SkBitmap& bitmap) {
440    // If we just "make" an image, it will force a CPU copy (if its mutable), only to have
441    // us then either find it in our cache, or compress and send it.
442    //
443    // Better could be to look it up in our cache first, and only create/compress it if we have to.
444    //
445    // But for now, just do the dumb thing...
446    return SkImage::MakeFromBitmap(bitmap);
447}
448
449void SkPipeCanvas::onDrawBitmap(const SkBitmap& bitmap, SkScalar x, SkScalar y,
450                                const SkPaint* paint) {
451    sk_sp<SkImage> image = make_from_bitmap(bitmap);
452    if (image) {
453        this->onDrawImage(image.get(), x, y, paint);
454    }
455}
456
457void SkPipeCanvas::onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
458                                    const SkPaint* paint, SrcRectConstraint constraint) {
459    sk_sp<SkImage> image = make_from_bitmap(bitmap);
460    if (image) {
461        this->onDrawImageRect(image.get(), src, dst, paint, constraint);
462    }
463}
464
465void SkPipeCanvas::onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
466                                    const SkRect& dst, const SkPaint* paint) {
467    sk_sp<SkImage> image = make_from_bitmap(bitmap);
468    if (image) {
469        this->onDrawImageNine(image.get(), center, dst, paint);
470    }
471}
472
473void SkPipeCanvas::onDrawBitmapLattice(const SkBitmap& bitmap, const Lattice& lattice,
474                                       const SkRect& dst, const SkPaint* paint) {
475    sk_sp<SkImage> image = make_from_bitmap(bitmap);
476    if (image) {
477        this->onDrawImageLattice(image.get(), lattice, dst, paint);
478    }
479}
480
481///////////////////////////////////////////////////////////////////////////////////////////////////
482
483void SkPipeCanvas::onDrawImage(const SkImage* image, SkScalar left, SkScalar top,
484                               const SkPaint* paint) {
485    unsigned extra = 0;
486    if (paint) {
487        extra |= kHasPaint_DrawImageMask;
488    }
489    SkPipeWriter writer(this);
490    writer.write32(pack_verb(SkPipeVerb::kDrawImage, extra));
491    writer.writeImage(image);
492    writer.writeScalar(left);
493    writer.writeScalar(top);
494    if (paint) {
495        write_paint(writer, *paint, kImage_PaintUsage);
496    }
497}
498
499void SkPipeCanvas::onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
500                                   const SkPaint* paint, SrcRectConstraint constraint) {
501    SkASSERT(0 == ((unsigned)constraint & ~1));
502    unsigned extra = (unsigned)constraint;
503    if (paint) {
504        extra |= kHasPaint_DrawImageRectMask;
505    }
506    if (src) {
507        extra |= kHasSrcRect_DrawImageRectMask;
508    }
509
510    SkPipeWriter writer(this);
511    writer.write32(pack_verb(SkPipeVerb::kDrawImageRect, extra));
512    writer.writeImage(image);
513    if (src) {
514        writer.write(src, sizeof(*src));
515    }
516    writer.write(&dst, sizeof(dst));
517    if (paint) {
518        write_paint(writer, *paint, kImage_PaintUsage);
519    }
520}
521
522void SkPipeCanvas::onDrawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
523                                   const SkPaint* paint) {
524    unsigned extra = 0;
525    if (paint) {
526        extra |= kHasPaint_DrawImageNineMask;
527    }
528    SkPipeWriter writer(this);
529    writer.write32(pack_verb(SkPipeVerb::kDrawImageNine, extra));
530    writer.writeImage(image);
531    writer.write(&center, sizeof(center));
532    writer.write(&dst, sizeof(dst));
533    if (paint) {
534        write_paint(writer, *paint, kImage_PaintUsage);
535    }
536}
537
538void SkPipeCanvas::onDrawImageLattice(const SkImage* image, const Lattice& lattice,
539                                      const SkRect& dst, const SkPaint* paint) {
540    unsigned extra = 0;
541    if (paint) {
542        extra |= kHasPaint_DrawImageLatticeMask;
543    }
544    if (lattice.fFlags) {
545        extra |= kHasFlags_DrawImageLatticeMask;
546    }
547    if (lattice.fXCount >= kCount_DrawImageLatticeMask) {
548        extra |= kCount_DrawImageLatticeMask << kXCount_DrawImageLatticeShift;
549    } else {
550        extra |= lattice.fXCount << kXCount_DrawImageLatticeShift;
551    }
552    if (lattice.fYCount >= kCount_DrawImageLatticeMask) {
553        extra |= kCount_DrawImageLatticeMask << kYCount_DrawImageLatticeShift;
554    } else {
555        extra |= lattice.fYCount << kYCount_DrawImageLatticeShift;
556    }
557
558    SkPipeWriter writer(this);
559    writer.write32(pack_verb(SkPipeVerb::kDrawImageLattice, extra));
560    writer.writeImage(image);
561    if (lattice.fXCount >= kCount_DrawImageLatticeMask) {
562        writer.write32(lattice.fXCount);
563    }
564    if (lattice.fYCount >= kCount_DrawImageLatticeMask) {
565        writer.write32(lattice.fYCount);
566    }
567    // Often these divs will be small (8 or 16 bits). Consider sniffing that and writing a flag
568    // so we can store them smaller.
569    writer.write(lattice.fXDivs, lattice.fXCount * sizeof(int32_t));
570    writer.write(lattice.fYDivs, lattice.fYCount * sizeof(int32_t));
571    if (lattice.fFlags) {
572        int32_t count = (lattice.fXCount + 1) * (lattice.fYCount + 1);
573        SkASSERT(count > 0);
574        write_pad(&writer, lattice.fFlags, count);
575    }
576    SkASSERT(lattice.fBounds);
577    writer.write(&lattice.fBounds, sizeof(*lattice.fBounds));
578    writer.write(&dst, sizeof(dst));
579    if (paint) {
580        write_paint(writer, *paint, kImage_PaintUsage);
581    }
582}
583
584///////////////////////////////////////////////////////////////////////////////////////////////////
585
586void SkPipeCanvas::onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
587                              const SkPaint& paint) {
588    SkASSERT(byteLength);
589
590    bool compact = fits_in(byteLength, 24);
591
592    SkPipeWriter writer(this);
593    writer.write32(pack_verb(SkPipeVerb::kDrawText, compact ? (unsigned)byteLength : 0));
594    if (!compact) {
595        writer.write32(SkToU32(byteLength));
596    }
597    write_pad(&writer, text, byteLength);
598    writer.writeScalar(x);
599    writer.writeScalar(y);
600    write_paint(writer, paint, kText_PaintUsage);
601}
602
603void SkPipeCanvas::onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[],
604                                 const SkPaint& paint) {
605    SkASSERT(byteLength);
606
607    bool compact = fits_in(byteLength, 24);
608
609    SkPipeWriter writer(this);
610    writer.write32(pack_verb(SkPipeVerb::kDrawPosText, compact ? (unsigned)byteLength : 0));
611    if (!compact) {
612        writer.write32(SkToU32(byteLength));
613    }
614    write_pad(&writer, text, byteLength);
615    writer.writePointArray(pos, paint.countText(text, byteLength));
616    write_paint(writer, paint, kText_PaintUsage);
617}
618
619void SkPipeCanvas::onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
620                                  SkScalar constY, const SkPaint& paint) {
621    SkASSERT(byteLength);
622
623    bool compact = fits_in(byteLength, 24);
624
625    SkPipeWriter writer(this);
626    writer.write32(pack_verb(SkPipeVerb::kDrawPosTextH, compact ? (unsigned)byteLength : 0));
627    if (!compact) {
628        writer.write32(SkToU32(byteLength));
629    }
630    write_pad(&writer, text, byteLength);
631    writer.writeScalarArray(xpos, paint.countText(text, byteLength));
632    writer.writeScalar(constY);
633    write_paint(writer, paint, kText_PaintUsage);
634}
635
636void SkPipeCanvas::onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
637                                    const SkMatrix* matrix, const SkPaint& paint) {
638    SkASSERT(byteLength > 0);
639
640    unsigned extra = 0;
641    if (byteLength <= kTextLength_DrawTextOnPathMask) {
642        extra |= byteLength;
643    } // else we will write the length after the packedverb
644    SkMatrix::TypeMask tm = matrix ? matrix->getType() : SkMatrix::kIdentity_Mask;
645    extra |= (unsigned)tm << kMatrixType_DrawTextOnPathShift;
646
647    SkPipeWriter writer(this);
648    writer.write32(pack_verb(SkPipeVerb::kDrawTextOnPath, extra));
649    if (byteLength > kTextLength_DrawTextOnPathMask) {
650        writer.write32(byteLength);
651    }
652    write_pad(&writer, text, byteLength);
653    writer.writePath(path);
654    if (matrix) {
655        write_sparse_matrix(&writer, *matrix);
656    }
657    write_paint(writer, paint, kText_PaintUsage);
658}
659
660void SkPipeCanvas::onDrawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
661                                     const SkRect* cull, const SkPaint& paint) {
662    SkASSERT(byteLength);
663
664    bool compact = fits_in(byteLength, 23);
665    unsigned extra = compact ? (byteLength << 1) : 0;
666    if (cull) {
667        extra |= 1;
668    }
669
670    SkPipeWriter writer(this);
671    writer.write32(pack_verb(SkPipeVerb::kDrawTextRSXform, extra));
672    if (!compact) {
673        writer.write32(SkToU32(byteLength));
674    }
675    write_pad(&writer, text, byteLength);
676
677    int count = paint.countText(text, byteLength);
678    writer.write32(count);  // maybe we can/should store this in extra as well?
679    writer.write(xform, count * sizeof(SkRSXform));
680    if (cull) {
681        writer.writeRect(*cull);
682    }
683    write_paint(writer, paint, kText_PaintUsage);
684}
685
686void SkPipeCanvas::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
687                                  const SkPaint &paint) {
688    SkPipeWriter writer(this);
689    writer.write32(pack_verb(SkPipeVerb::kDrawTextBlob, 0));
690    blob->flatten(writer);
691    writer.writeScalar(x);
692    writer.writeScalar(y);
693    write_paint(writer, paint, kTextBlob_PaintUsage);
694}
695
696void SkPipeCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
697                                 const SkPaint* paint) {
698    unsigned extra = fDeduper->findOrDefinePicture(const_cast<SkPicture*>(picture));
699    if (matrix) {
700        extra |= kHasMatrix_DrawPictureExtra;
701    }
702    if (paint) {
703        extra |= kHasPaint_DrawPictureExtra;
704    }
705    SkPipeWriter writer(this);
706    writer.write32(pack_verb(SkPipeVerb::kDrawPicture, extra));
707    if (matrix) {
708        writer.writeMatrix(*matrix);
709    }
710    if (paint) {
711        write_paint(writer, *paint, kSaveLayer_PaintUsage);
712    }
713}
714
715void SkPipeCanvas::onDrawRegion(const SkRegion& region, const SkPaint& paint) {
716    size_t size = region.writeToMemory(nullptr);
717    unsigned extra = 0;
718    if (fits_in(size, 24)) {
719        extra = SkToUInt(size);
720    }
721
722    SkPipeWriter writer(this);
723    writer.write32(pack_verb(SkPipeVerb::kDrawRegion, extra));
724    if (0 == extra) {
725        writer.write32(size);
726    }
727    SkAutoSMalloc<2048> storage(size);
728    region.writeToMemory(storage.get());
729    write_pad(&writer, storage.get(), size);
730    write_paint(writer, paint, kGeometry_PaintUsage);
731}
732
733void SkPipeCanvas::onDrawVertices(VertexMode vmode, int vertexCount,
734                                  const SkPoint vertices[], const SkPoint texs[],
735                                  const SkColor colors[], SkXfermode* xmode,
736                                  const uint16_t indices[], int indexCount,
737                                  const SkPaint& paint) {
738    SkASSERT(vertexCount > 0);
739
740    unsigned extra = 0;
741    if (vertexCount <= kVCount_DrawVerticesMask) {
742        extra |= vertexCount;
743    }
744    extra |= (unsigned)vmode << kVMode_DrawVerticesShift;
745
746    SkXfermode::Mode mode = SkXfermode::kModulate_Mode;
747    if (xmode && !SkXfermode::AsMode(xmode, &mode)) {
748        mode = (SkXfermode::Mode)0xFF;  // sentinel for read the xfer later
749    }
750    extra |= (unsigned)mode << kXMode_DrawVerticesShift;
751
752    if (texs) {
753        extra |= kHasTex_DrawVerticesMask;
754    }
755    if (colors) {
756        extra |= kHasColors_DrawVerticesMask;
757    }
758    if (indexCount > 0) {
759        extra |= kHasIndices_DrawVerticesMask;
760    }
761
762    SkPipeWriter writer(this);
763    writer.write32(pack_verb(SkPipeVerb::kDrawVertices, extra));
764    if (vertexCount > kVCount_DrawVerticesMask) {
765        writer.write32(vertexCount);
766    }
767    if (mode == (SkXfermode::Mode)0xFF) {
768        writer.writeFlattenable(xmode);
769    }
770    writer.write(vertices, vertexCount * sizeof(SkPoint));
771    if (texs) {
772        writer.write(texs, vertexCount * sizeof(SkPoint));
773    }
774    if (colors) {
775        writer.write(colors, vertexCount * sizeof(SkColor));
776    }
777    if (indexCount > 0) {
778        writer.write32(indexCount);
779        SkASSERT(SkIsAlign2(indexCount));
780        writer.write(indices, indexCount * sizeof(uint16_t));
781    }
782    write_paint(writer, paint, kVertices_PaintUsage);
783}
784
785void SkPipeCanvas::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
786                               const SkPoint texCoords[4], SkXfermode* xfer,
787                               const SkPaint& paint) {
788    SkPipeWriter writer(this);
789    unsigned extra = 0;
790    SkXfermode::Mode mode = SkXfermode::kModulate_Mode;
791    if (xfer && !xfer->asMode(&mode)) {
792        mode = (SkXfermode::Mode)kExplicitXfer_DrawPatchExtraValue;
793    } else {
794        xfer = nullptr;    // signal that we're using the mode enum
795    }
796    SkASSERT(0 == (mode & ~kModeEnum_DrawPatchExtraMask));
797    extra = (unsigned)mode;
798    if (colors) {
799        extra |= kHasColors_DrawPatchExtraMask;
800    }
801    if (texCoords) {
802        extra |= kHasTexture_DrawPatchExtraMask;
803    }
804    writer.write32(pack_verb(SkPipeVerb::kDrawPatch, extra));
805    writer.write(cubics, sizeof(SkPoint) * 12);
806    if (colors) {
807        writer.write(colors, sizeof(SkColor) * 4);
808    }
809    if (texCoords) {
810        writer.write(texCoords, sizeof(SkPoint) * 4);
811    }
812    if (xfer) {
813        xfer->flatten(writer);
814    }
815    write_paint(writer, paint, kGeometry_PaintUsage);
816}
817
818void SkPipeCanvas::onDrawAnnotation(const SkRect& rect, const char key[], SkData* data) {
819    const size_t len = strlen(key) + 1; // must write the trailing 0
820    bool compact = fits_in(len, 23);
821    uint32_t extra = compact ? (unsigned)len : 0;
822    extra <<= 1;   // make room for has_data_sentinel
823    if (data) {
824        extra |= 1;
825    }
826
827    fStream->write32(pack_verb(SkPipeVerb::kDrawAnnotation, extra));
828    fStream->write(&rect, sizeof(SkRect));
829    if (!compact) {
830        fStream->write32(SkToU32(len));
831    }
832    write_pad(fStream, key, len);
833    if (data) {
834        fStream->write32(SkToU32(data->size()));
835        write_pad(fStream, data->data(), data->size());
836    }
837}
838
839///////////////////////////////////////////////////////////////////////////////////////////////////
840
841class A8Serializer : public SkPixelSerializer {
842protected:
843    bool onUseEncodedData(const void* data, size_t len) {
844        return true;
845    }
846
847    SkData* onEncode(const SkPixmap& pmap) {
848        if (kAlpha_8_SkColorType == pmap.colorType()) {
849            SkDynamicMemoryWStream stream;
850            stream.write("skiaimgf", 8);
851            stream.write32(pmap.width());
852            stream.write32(pmap.height());
853            stream.write16(pmap.colorType());
854            stream.write16(pmap.alphaType());
855            stream.write32(0);  // no colorspace for now
856            for (int y = 0; y < pmap.height(); ++y) {
857                stream.write(pmap.addr8(0, y), pmap.width());
858            }
859            return stream.detachAsData().release();
860        }
861        return nullptr;
862    }
863};
864
865static sk_sp<SkData> default_image_serializer(SkImage* image) {
866    A8Serializer serial;
867    sk_sp<SkData> data(image->encode(&serial));
868    if (!data) {
869        data.reset(image->encode());
870    }
871    return data;
872}
873
874static bool show_deduper_traffic = false;
875
876int SkPipeDeduper::findOrDefineImage(SkImage* image) {
877    int index = fImages.find(image->uniqueID());
878    SkASSERT(index >= 0);
879    if (index) {
880        if (show_deduper_traffic) {
881            SkDebugf("  reuseImage(%d)\n", index - 1);
882        }
883        return index;
884    }
885
886    sk_sp<SkData> data = fIMSerializer ? fIMSerializer->serialize(image)
887                                       : default_image_serializer(image);
888    if (data) {
889        index = fImages.add(image->uniqueID());
890        SkASSERT(index > 0);
891        SkASSERT(fits_in(index, 24));
892        fStream->write32(pack_verb(SkPipeVerb::kDefineImage, index));
893
894        uint32_t len = SkToU32(data->size());
895        fStream->write32(SkAlign4(len));
896        write_pad(fStream, data->data(), len);
897
898        if (show_deduper_traffic) {
899            int size = image->width() * image->height() << 2;
900            SkDebugf("  defineImage(%d) %d -> %d\n", index - 1, size, len);
901        }
902        return index;
903    }
904    SkDebugf("+++ failed to encode image [%d %d]\n", image->width(), image->height());
905    return 0;   // failed to encode
906}
907
908int SkPipeDeduper::findOrDefinePicture(SkPicture* picture) {
909    int index = fPictures.find(picture->uniqueID());
910    SkASSERT(index >= 0);
911    if (index) {
912        if (show_deduper_traffic) {
913            SkDebugf("  reusePicture(%d)\n", index - 1);
914        }
915        return index;
916    }
917
918    size_t prevWritten = fStream->bytesWritten();
919    unsigned extra = 0; // 0 means we're defining a new picture, non-zero means undef_index + 1
920    fStream->write32(pack_verb(SkPipeVerb::kDefinePicture, extra));
921    const SkRect cull = picture->cullRect();
922    fStream->write(&cull, sizeof(cull));
923    picture->playback(fPipeCanvas);
924    // call fPictures.add *after* we're written the picture, so that any nested pictures will have
925    // already been defined, and we get the "last" index value.
926    index = fPictures.add(picture->uniqueID());
927    ASSERT_FITS_IN(index, kObjectDefinitionBits);
928    fStream->write32(pack_verb(SkPipeVerb::kEndPicture, index));
929
930    SkDebugf("  definePicture(%d) %d\n",
931             index - 1, SkToU32(fStream->bytesWritten() - prevWritten));
932    return index;
933}
934
935static sk_sp<SkData> encode(SkTypeface* tf) {
936    SkDynamicMemoryWStream stream;
937    tf->serialize(&stream);
938    return sk_sp<SkData>(stream.detachAsData());
939}
940
941int SkPipeDeduper::findOrDefineTypeface(SkTypeface* typeface) {
942    if (!typeface) {
943        return 0;   // default
944    }
945
946    int index = fTypefaces.find(typeface->uniqueID());
947    SkASSERT(index >= 0);
948    if (index) {
949        if (show_deduper_traffic) {
950            SkDebugf("  reuseTypeface(%d)\n", index - 1);
951        }
952        return index;
953    }
954
955    sk_sp<SkData> data = fTFSerializer ? fTFSerializer->serialize(typeface) : encode(typeface);
956    if (data) {
957        index = fTypefaces.add(typeface->uniqueID());
958        SkASSERT(index > 0);
959        SkASSERT(fits_in(index, 24));
960        fStream->write32(pack_verb(SkPipeVerb::kDefineTypeface, index));
961
962        uint32_t len = SkToU32(data->size());
963        fStream->write32(SkAlign4(len));
964        write_pad(fStream, data->data(), len);
965
966        if (show_deduper_traffic) {
967            SkDebugf("  defineTypeface(%d) %d\n", index - 1, len);
968        }
969        return index;
970    }
971    SkDebugf("+++ failed to encode typeface %d\n", typeface->uniqueID());
972    return 0;   // failed to encode
973}
974
975int SkPipeDeduper::findOrDefineFactory(SkFlattenable* flattenable) {
976    if (!flattenable) {
977        return 0;
978    }
979
980    int index = fFactories.find(flattenable->getFactory());
981    SkASSERT(index >= 0);
982    if (index) {
983        if (show_deduper_traffic) {
984            SkDebugf("  reuseFactory(%d)\n", index - 1);
985        }
986        return index;
987    }
988
989    index = fFactories.add(flattenable->getFactory());
990    ASSERT_FITS_IN(index, kIndex_DefineFactoryExtraBits);
991    const char* name = flattenable->getTypeName();
992    size_t len = strlen(name);
993    ASSERT_FITS_IN(len, kNameLength_DefineFactoryExtraBits);
994    unsigned extra = (index << kNameLength_DefineFactoryExtraBits) | len;
995    size_t prevWritten = fStream->bytesWritten();
996    fStream->write32(pack_verb(SkPipeVerb::kDefineFactory, extra));
997    write_pad(fStream, name, len + 1);
998    if (false) {
999        SkDebugf("  defineFactory(%d) %d %s\n",
1000             index - 1, SkToU32(fStream->bytesWritten() - prevWritten), name);
1001    }
1002    return index;
1003}
1004
1005///////////////////////////////////////////////////////////////////////////////////////////////////
1006#include "SkPipe.h"
1007
1008class SkPipeSerializer::Impl {
1009public:
1010    SkPipeDeduper   fDeduper;
1011    std::unique_ptr<SkPipeCanvas> fCanvas;
1012};
1013
1014SkPipeSerializer::SkPipeSerializer() : fImpl(new Impl) {}
1015
1016SkPipeSerializer::~SkPipeSerializer() {
1017    if (fImpl->fCanvas) {
1018        this->endWrite();
1019    }
1020}
1021
1022void SkPipeSerializer::setTypefaceSerializer(SkTypefaceSerializer* tfs) {
1023    fImpl->fDeduper.setTypefaceSerializer(tfs);
1024}
1025
1026void SkPipeSerializer::setImageSerializer(SkImageSerializer* ims) {
1027    fImpl->fDeduper.setImageSerializer(ims);
1028}
1029
1030void SkPipeSerializer::resetCache() {
1031    fImpl->fDeduper.resetCaches();
1032}
1033
1034sk_sp<SkData> SkPipeSerializer::writeImage(SkImage* image) {
1035    SkDynamicMemoryWStream stream;
1036    this->writeImage(image, &stream);
1037    return stream.detachAsData();
1038}
1039
1040sk_sp<SkData> SkPipeSerializer::writePicture(SkPicture* picture) {
1041    SkDynamicMemoryWStream stream;
1042    this->writePicture(picture, &stream);
1043    return stream.detachAsData();
1044}
1045
1046void SkPipeSerializer::writePicture(SkPicture* picture, SkWStream* stream) {
1047    int index = fImpl->fDeduper.findPicture(picture);
1048    if (0 == index) {
1049        // Try to define the picture
1050        this->beginWrite(picture->cullRect(), stream);
1051        index = fImpl->fDeduper.findOrDefinePicture(picture);
1052        this->endWrite();
1053    }
1054    stream->write32(pack_verb(SkPipeVerb::kWritePicture, index));
1055}
1056
1057void SkPipeSerializer::writeImage(SkImage* image, SkWStream* stream) {
1058    int index = fImpl->fDeduper.findImage(image);
1059    if (0 == index) {
1060        // Try to define the image
1061        fImpl->fDeduper.setStream(stream);
1062        index = fImpl->fDeduper.findOrDefineImage(image);
1063    }
1064    stream->write32(pack_verb(SkPipeVerb::kWriteImage, index));
1065}
1066
1067SkCanvas* SkPipeSerializer::beginWrite(const SkRect& cull, SkWStream* stream) {
1068    SkASSERT(nullptr == fImpl->fCanvas);
1069    fImpl->fCanvas.reset(new SkPipeCanvas(cull, &fImpl->fDeduper, stream));
1070    fImpl->fDeduper.setStream(stream);
1071    fImpl->fDeduper.setCanvas(fImpl->fCanvas.get());
1072    return fImpl->fCanvas.get();
1073}
1074
1075void SkPipeSerializer::endWrite() {
1076    fImpl->fCanvas->restoreToCount(1);
1077    fImpl->fCanvas.reset(nullptr);
1078    fImpl->fDeduper.setCanvas(nullptr);
1079}
1080