2 * Copyright 2013 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
9 #include "SkBitmapSource.h"
11 #include "SkMallocPixelRef.h"
13 #include "SkPictureRecorder.h"
14 #include "SkTableColorFilter.h"
15 #include "SkTemplates.h"
16 #include "SkTypeface.h"
17 #include "SkWriteBuffer.h"
18 #include "SkValidatingReadBuffer.h"
19 #include "SkXfermodeImageFilter.h"
22 static const uint32_t kArraySize = 64;
23 static const int kBitmapSize = 256;
26 static void TestAlignment(T* testObj, skiatest::Reporter* reporter) {
27 // Test memory read/write functions directly
28 unsigned char dataWritten[1024];
29 size_t bytesWrittenToMemory = testObj->writeToMemory(dataWritten);
30 REPORTER_ASSERT(reporter, SkAlign4(bytesWrittenToMemory) == bytesWrittenToMemory);
31 size_t bytesReadFromMemory = testObj->readFromMemory(dataWritten, bytesWrittenToMemory);
32 REPORTER_ASSERT(reporter, SkAlign4(bytesReadFromMemory) == bytesReadFromMemory);
35 template<typename T> struct SerializationUtils {
36 // Generic case for flattenables
37 static void Write(SkWriteBuffer& writer, const T* flattenable) {
38 writer.writeFlattenable(flattenable);
40 static void Read(SkValidatingReadBuffer& reader, T** flattenable) {
41 *flattenable = (T*)reader.readFlattenable(T::GetFlattenableType());
45 template<> struct SerializationUtils<SkMatrix> {
46 static void Write(SkWriteBuffer& writer, const SkMatrix* matrix) {
47 writer.writeMatrix(*matrix);
49 static void Read(SkValidatingReadBuffer& reader, SkMatrix* matrix) {
50 reader.readMatrix(matrix);
54 template<> struct SerializationUtils<SkPath> {
55 static void Write(SkWriteBuffer& writer, const SkPath* path) {
56 writer.writePath(*path);
58 static void Read(SkValidatingReadBuffer& reader, SkPath* path) {
59 reader.readPath(path);
63 template<> struct SerializationUtils<SkRegion> {
64 static void Write(SkWriteBuffer& writer, const SkRegion* region) {
65 writer.writeRegion(*region);
67 static void Read(SkValidatingReadBuffer& reader, SkRegion* region) {
68 reader.readRegion(region);
72 template<> struct SerializationUtils<SkString> {
73 static void Write(SkWriteBuffer& writer, const SkString* string) {
74 writer.writeString(string->c_str());
76 static void Read(SkValidatingReadBuffer& reader, SkString* string) {
77 reader.readString(string);
81 template<> struct SerializationUtils<unsigned char> {
82 static void Write(SkWriteBuffer& writer, unsigned char* data, uint32_t arraySize) {
83 writer.writeByteArray(data, arraySize);
85 static bool Read(SkValidatingReadBuffer& reader, unsigned char* data, uint32_t arraySize) {
86 return reader.readByteArray(data, arraySize);
90 template<> struct SerializationUtils<SkColor> {
91 static void Write(SkWriteBuffer& writer, SkColor* data, uint32_t arraySize) {
92 writer.writeColorArray(data, arraySize);
94 static bool Read(SkValidatingReadBuffer& reader, SkColor* data, uint32_t arraySize) {
95 return reader.readColorArray(data, arraySize);
99 template<> struct SerializationUtils<int32_t> {
100 static void Write(SkWriteBuffer& writer, int32_t* data, uint32_t arraySize) {
101 writer.writeIntArray(data, arraySize);
103 static bool Read(SkValidatingReadBuffer& reader, int32_t* data, uint32_t arraySize) {
104 return reader.readIntArray(data, arraySize);
108 template<> struct SerializationUtils<SkPoint> {
109 static void Write(SkWriteBuffer& writer, SkPoint* data, uint32_t arraySize) {
110 writer.writePointArray(data, arraySize);
112 static bool Read(SkValidatingReadBuffer& reader, SkPoint* data, uint32_t arraySize) {
113 return reader.readPointArray(data, arraySize);
117 template<> struct SerializationUtils<SkScalar> {
118 static void Write(SkWriteBuffer& writer, SkScalar* data, uint32_t arraySize) {
119 writer.writeScalarArray(data, arraySize);
121 static bool Read(SkValidatingReadBuffer& reader, SkScalar* data, uint32_t arraySize) {
122 return reader.readScalarArray(data, arraySize);
126 template<typename T, bool testInvalid> struct SerializationTestUtils {
127 static void InvalidateData(unsigned char* data) {}
130 template<> struct SerializationTestUtils<SkString, true> {
131 static void InvalidateData(unsigned char* data) {
132 data[3] |= 0x80; // Reverse sign of 1st integer
136 template<typename T, bool testInvalid>
137 static void TestObjectSerializationNoAlign(T* testObj, skiatest::Reporter* reporter) {
138 SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
139 SerializationUtils<T>::Write(writer, testObj);
140 size_t bytesWritten = writer.bytesWritten();
141 REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
143 unsigned char dataWritten[1024];
144 writer.writeToMemory(dataWritten);
146 SerializationTestUtils<T, testInvalid>::InvalidateData(dataWritten);
148 // Make sure this fails when it should (test with smaller size, but still multiple of 4)
149 SkValidatingReadBuffer buffer(dataWritten, bytesWritten - 4);
151 SerializationUtils<T>::Read(buffer, &obj);
152 REPORTER_ASSERT(reporter, !buffer.isValid());
154 // Make sure this succeeds when it should
155 SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
156 const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
158 SerializationUtils<T>::Read(buffer2, &obj2);
159 const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
160 // This should have succeeded, since there are enough bytes to read this
161 REPORTER_ASSERT(reporter, buffer2.isValid() == !testInvalid);
162 // Note: This following test should always succeed, regardless of whether the buffer is valid,
163 // since if it is invalid, it will simply skip to the end, as if it had read the whole buffer.
164 REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
168 static void TestObjectSerialization(T* testObj, skiatest::Reporter* reporter) {
169 TestObjectSerializationNoAlign<T, false>(testObj, reporter);
170 TestAlignment(testObj, reporter);
174 static T* TestFlattenableSerialization(T* testObj, bool shouldSucceed,
175 skiatest::Reporter* reporter) {
176 SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
177 SerializationUtils<T>::Write(writer, testObj);
178 size_t bytesWritten = writer.bytesWritten();
179 REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
181 unsigned char dataWritten[4096];
182 SkASSERT(bytesWritten <= sizeof(dataWritten));
183 writer.writeToMemory(dataWritten);
185 // Make sure this fails when it should (test with smaller size, but still multiple of 4)
186 SkValidatingReadBuffer buffer(dataWritten, bytesWritten - 4);
188 SerializationUtils<T>::Read(buffer, &obj);
189 REPORTER_ASSERT(reporter, !buffer.isValid());
190 REPORTER_ASSERT(reporter, NULL == obj);
192 // Make sure this succeeds when it should
193 SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
194 const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
196 SerializationUtils<T>::Read(buffer2, &obj2);
197 const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
199 // This should have succeeded, since there are enough bytes to read this
200 REPORTER_ASSERT(reporter, buffer2.isValid());
201 REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
202 REPORTER_ASSERT(reporter, obj2);
204 // If the deserialization was supposed to fail, make sure it did
205 REPORTER_ASSERT(reporter, !buffer.isValid());
206 REPORTER_ASSERT(reporter, NULL == obj2);
209 return obj2; // Return object to perform further validity tests on it
213 static void TestArraySerialization(T* data, skiatest::Reporter* reporter) {
214 SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
215 SerializationUtils<T>::Write(writer, data, kArraySize);
216 size_t bytesWritten = writer.bytesWritten();
217 // This should write the length (in 4 bytes) and the array
218 REPORTER_ASSERT(reporter, (4 + kArraySize * sizeof(T)) == bytesWritten);
220 unsigned char dataWritten[1024];
221 writer.writeToMemory(dataWritten);
223 // Make sure this fails when it should
224 SkValidatingReadBuffer buffer(dataWritten, bytesWritten);
225 T dataRead[kArraySize];
226 bool success = SerializationUtils<T>::Read(buffer, dataRead, kArraySize / 2);
227 // This should have failed, since the provided size was too small
228 REPORTER_ASSERT(reporter, !success);
230 // Make sure this succeeds when it should
231 SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
232 success = SerializationUtils<T>::Read(buffer2, dataRead, kArraySize);
233 // This should have succeeded, since there are enough bytes to read this
234 REPORTER_ASSERT(reporter, success);
237 static void TestBitmapSerialization(const SkBitmap& validBitmap,
238 const SkBitmap& invalidBitmap,
240 skiatest::Reporter* reporter) {
241 SkAutoTUnref<SkBitmapSource> validBitmapSource(SkBitmapSource::Create(validBitmap));
242 SkAutoTUnref<SkBitmapSource> invalidBitmapSource(SkBitmapSource::Create(invalidBitmap));
243 SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(SkXfermode::kSrcOver_Mode));
244 SkAutoTUnref<SkXfermodeImageFilter> xfermodeImageFilter(
245 SkXfermodeImageFilter::Create(mode, invalidBitmapSource, validBitmapSource));
247 SkAutoTUnref<SkImageFilter> deserializedFilter(
248 TestFlattenableSerialization<SkImageFilter>(
249 xfermodeImageFilter, shouldSucceed, reporter));
251 // Try to render a small bitmap using the invalid deserialized filter
252 // to make sure we don't crash while trying to render it
255 bitmap.allocN32Pixels(24, 24);
256 SkCanvas canvas(bitmap);
257 canvas.clear(0x00000000);
259 paint.setImageFilter(deserializedFilter);
260 canvas.clipRect(SkRect::MakeXYWH(0, 0, SkIntToScalar(24), SkIntToScalar(24)));
261 canvas.drawBitmap(bitmap, 0, 0, &paint);
265 static void TestXfermodeSerialization(skiatest::Reporter* reporter) {
266 for (size_t i = 0; i <= SkXfermode::kLastMode; ++i) {
267 if (i == SkXfermode::kSrcOver_Mode) {
268 // skip SrcOver, as it is allowed to return NULL from Create()
271 SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(static_cast<SkXfermode::Mode>(i)));
272 REPORTER_ASSERT(reporter, mode.get());
273 SkAutoTUnref<SkXfermode> copy(
274 TestFlattenableSerialization<SkXfermode>(mode.get(), true, reporter));
278 static void TestColorFilterSerialization(skiatest::Reporter* reporter) {
280 for (int i = 0; i < 256; ++i) {
281 table[i] = (i * 41) % 256;
283 SkAutoTUnref<SkColorFilter> colorFilter(SkTableColorFilter::Create(table));
284 SkAutoTUnref<SkColorFilter> copy(
285 TestFlattenableSerialization<SkColorFilter>(colorFilter.get(), true, reporter));
288 static SkBitmap draw_picture(SkPicture& picture) {
290 bitmap.allocN32Pixels(SkScalarCeilToInt(picture.cullRect().width()),
291 SkScalarCeilToInt(picture.cullRect().height()));
292 SkCanvas canvas(bitmap);
293 picture.playback(&canvas);
297 static void compare_bitmaps(skiatest::Reporter* reporter,
298 const SkBitmap& b1, const SkBitmap& b2) {
299 REPORTER_ASSERT(reporter, b1.width() == b2.width());
300 REPORTER_ASSERT(reporter, b1.height() == b2.height());
301 SkAutoLockPixels autoLockPixels1(b1);
302 SkAutoLockPixels autoLockPixels2(b2);
304 if ((b1.width() != b2.width()) ||
305 (b1.height() != b2.height())) {
310 for (int y = 0; y < b2.height(); ++y) {
311 for (int x = 0; x < b2.width(); ++x) {
312 if (b1.getColor(x, y) != b2.getColor(x, y))
316 REPORTER_ASSERT(reporter, 0 == pixelErrors);
319 static void TestPictureTypefaceSerialization(skiatest::Reporter* reporter) {
320 // Load typeface form file.
321 // This test cannot run if there is no resource path.
322 SkString resourcePath = GetResourcePath();
323 if (resourcePath.isEmpty()) {
324 SkDebugf("Could not run fontstream test because resourcePath not specified.");
327 SkString filename = SkOSPath::Join(resourcePath.c_str(), "test.ttc");
328 SkTypeface* typeface = SkTypeface::CreateFromFile(filename.c_str(), 1);
330 SkDebugf("Could not run fontstream test because test.ttc not found.");
334 // Create a paint with the typeface we loaded.
336 paint.setColor(SK_ColorGRAY);
337 paint.setTextSize(SkIntToScalar(30));
338 SkSafeUnref(paint.setTypeface(typeface));
341 SkPictureRecorder recorder;
342 SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
343 SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
344 SkIntToScalar(canvasRect.height()),
346 canvas->drawColor(SK_ColorWHITE);
347 canvas->drawText("A!", 2, 24, 32, paint);
348 SkAutoTUnref<SkPicture> picture(recorder.endRecording());
350 // Serlialize picture and create its clone from stream.
351 SkDynamicMemoryWStream stream;
352 picture->serialize(&stream);
353 SkAutoTUnref<SkStream> inputStream(stream.detachAsStream());
354 SkAutoTUnref<SkPicture> loadedPicture(SkPicture::CreateFromStream(inputStream.get()));
356 // Draw both original and clone picture and compare bitmaps -- they should be identical.
357 SkBitmap origBitmap = draw_picture(*picture);
358 SkBitmap destBitmap = draw_picture(*loadedPicture);
359 compare_bitmaps(reporter, origBitmap, destBitmap);
362 static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
363 bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
366 static void make_checkerboard_bitmap(SkBitmap& bitmap) {
367 setup_bitmap_for_canvas(&bitmap);
369 SkCanvas canvas(bitmap);
370 canvas.clear(0x00000000);
372 darkPaint.setColor(0xFF804020);
374 lightPaint.setColor(0xFF244484);
375 const int i = kBitmapSize / 8;
376 const SkScalar f = SkIntToScalar(i);
377 for (int y = 0; y < kBitmapSize; y += i) {
378 for (int x = 0; x < kBitmapSize; x += i) {
380 canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
381 canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
382 canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
383 canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
384 canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
390 static void draw_something(SkCanvas* canvas) {
393 make_checkerboard_bitmap(bitmap);
396 canvas->scale(0.5f, 0.5f);
397 canvas->drawBitmap(bitmap, 0, 0, NULL);
400 const char beforeStr[] = "before circle";
401 const char afterStr[] = "after circle";
403 paint.setAntiAlias(true);
405 paint.setColor(SK_ColorRED);
406 canvas->drawData(beforeStr, sizeof(beforeStr));
407 canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
408 canvas->drawData(afterStr, sizeof(afterStr));
409 paint.setColor(SK_ColorBLACK);
410 paint.setTextSize(SkIntToScalar(kBitmapSize/3));
411 canvas->drawText("Picture", 7, SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), paint);
414 DEF_TEST(Serialization, reporter) {
415 // Test matrix serialization
417 SkMatrix matrix = SkMatrix::I();
418 TestObjectSerialization(&matrix, reporter);
421 // Test path serialization
424 TestObjectSerialization(&path, reporter);
427 // Test region serialization
430 TestObjectSerialization(®ion, reporter);
433 // Test xfermode serialization
435 TestXfermodeSerialization(reporter);
438 // Test color filter serialization
440 TestColorFilterSerialization(reporter);
443 // Test string serialization
445 SkString string("string");
446 TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
447 TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
450 // Test rrect serialization
452 // SkRRect does not initialize anything.
453 // An uninitialized SkRRect can be serialized,
454 // but will branch on uninitialized data when deserialized.
456 SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
457 SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
458 rrect.setRectRadii(rect, corners);
459 TestAlignment(&rrect, reporter);
462 // Test readByteArray
464 unsigned char data[kArraySize] = { 1, 2, 3 };
465 TestArraySerialization(data, reporter);
468 // Test readColorArray
470 SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
471 TestArraySerialization(data, reporter);
476 int32_t data[kArraySize] = { 1, 2, 4, 8 };
477 TestArraySerialization(data, reporter);
480 // Test readPointArray
482 SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
483 TestArraySerialization(data, reporter);
486 // Test readScalarArray
488 SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
489 TestArraySerialization(data, reporter);
492 // Test invalid deserializations
494 SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
496 SkBitmap validBitmap;
497 validBitmap.setInfo(info);
499 // Create a bitmap with a really large height
500 SkBitmap invalidBitmap;
501 invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
503 // The deserialization should succeed, and the rendering shouldn't crash,
504 // even when the device fails to initialize, due to its size
505 TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
508 // Test simple SkPicture serialization
510 SkPictureRecorder recorder;
511 draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
512 SkIntToScalar(kBitmapSize),
514 SkAutoTUnref<SkPicture> pict(recorder.endRecording());
517 SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
518 pict->flatten(writer);
519 size_t size = writer.bytesWritten();
520 SkAutoTMalloc<unsigned char> data(size);
521 writer.writeToMemory(static_cast<void*>(data.get()));
523 // Deserialize picture
524 SkValidatingReadBuffer reader(static_cast<void*>(data.get()), size);
525 SkAutoTUnref<SkPicture> readPict(
526 SkPicture::CreateFromBuffer(reader));
527 REPORTER_ASSERT(reporter, readPict.get());
530 TestPictureTypefaceSerialization(reporter);