blob: 78a1d6bb0c23fcd99cc003e4e34af3d38f136647 [file] [log] [blame]
Nathaniel Nifong0426c382019-06-21 11:09:19 -04001/*
2 * Copyright 2019 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 "tools/SkSharingProc.h"
9
Nathaniel Nifong82e0d522020-12-11 10:38:35 -050010#include "include/core/SkBitmap.h"
Nathaniel Nifong0426c382019-06-21 11:09:19 -040011#include "include/core/SkData.h"
12#include "include/core/SkImage.h"
13#include "include/core/SkSerialProcs.h"
14
15sk_sp<SkData> SkSharingSerialContext::serializeImage(SkImage* img, void* ctx) {
16 SkSharingSerialContext* context = reinterpret_cast<SkSharingSerialContext*>(ctx);
17 uint32_t id = img->uniqueID(); // get this process's id for the image. these are not hashes.
18 // find out if we have already serialized this, and if so, what its in-file id is.
19 auto iter = context->fImageMap.find(id);
20 if (iter == context->fImageMap.end()) {
21 // When not present, add its id to the map and return its usual serialized form.
22 context->fImageMap[id] = context->fImageMap.size();
23 return img->encodeToData();
24 }
25 uint32_t fid = context->fImageMap[id];
26 // if present, return only the in-file id we registered the first time we serialized it.
27 return SkData::MakeWithCopy(&fid, sizeof(fid));
28}
29
30sk_sp<SkImage> SkSharingDeserialContext::deserializeImage(
31 const void* data, size_t length, void* ctx) {
Nathaniel Nifong82e0d522020-12-11 10:38:35 -050032 if (!data || !length || !ctx) {
33 SkDebugf("SkSharingDeserialContext::deserializeImage arguments invalid %p %d %p.\n",
34 data, length, ctx);
35 // Return something so the rest of the debugger can proceeed.
36 SkBitmap bm;
37 bm.allocPixels(SkImageInfo::MakeN32Premul(1, 1));
38 return SkImage::MakeFromBitmap(bm);
39 }
Nathaniel Nifong0426c382019-06-21 11:09:19 -040040 SkSharingDeserialContext* context = reinterpret_cast<SkSharingDeserialContext*>(ctx);
41 uint32_t fid;
42 // If the data is an image fid, look up an already deserialized image from our map
43 if (length == sizeof(fid)) {
44 memcpy(&fid, data, sizeof(fid));
45 if (fid >= context->fImages.size()) {
46 SkDebugf("We do not have the data for image %d.\n", fid);
47 return nullptr;
48 }
49 return context->fImages[fid];
50 }
51 // Otherwise, the data is an image, deserialise it, store it in our map at its fid.
52 // TODO(nifong): make DeserialProcs accept sk_sp<SkData> so we don't have to copy this.
53 sk_sp<SkData> dataView = SkData::MakeWithCopy(data, length);
54 const sk_sp<SkImage> image = SkImage::MakeFromEncoded(std::move(dataView));
55 context->fImages.push_back(image);
56 return image;
57}