File: serial_utils.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (338 lines) | stat: -rw-r--r-- 13,471 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif

#include "components/paint_preview/common/serial_utils.h"

#include "base/trace_event/common/trace_event_common.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/paint_preview/common/subset_font.h"
#include "skia/ext/codec_utils.h"
#include "skia/ext/font_utils.h"
#include "third_party/skia/include/codec/SkBmpDecoder.h"
#include "third_party/skia/include/codec/SkCodec.h"
#include "third_party/skia/include/codec/SkGifDecoder.h"
#include "third_party/skia/include/codec/SkJpegDecoder.h"
#include "third_party/skia/include/codec/SkPngDecoder.h"
#include "third_party/skia/include/codec/SkWebpDecoder.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkFontMgr.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "third_party/skia/include/core/SkString.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "third_party/skia/include/private/chromium/Slug.h"

namespace paint_preview {

namespace {

// Supported by MSVC, g++, and clang++. Ensures no gaps in packing.
#pragma pack(push, 1)
struct SerializedRectData {
  uint32_t content_id;

  // The size of the subframe in the local coordinates when it was drawn.
  float subframe_width;
  float subframe_height;

  // The rect of the subframe in its parent frame's root coordinate system.
  float transformed_x;
  float transformed_y;
  float transformed_width;
  float transformed_height;
};
#pragma pack(pop)

// Serializes a SkPicture representing a subframe as a custom data placeholder.
sk_sp<SkData> SerializePictureAsRectData(SkPicture* picture, void* ctx) {
  const PictureSerializationContext* context =
      reinterpret_cast<PictureSerializationContext*>(ctx);

  auto it = context->content_id_to_transformed_clip.find(picture->uniqueID());
  // Defers picture serialization behavior to Skia.
  if (it == context->content_id_to_transformed_clip.end()) {
    return nullptr;
  }

  // This data originates from |PaintPreviewTracker|.
  const SkRect& transformed_cull_rect = it->second;
  SerializedRectData rect_data = {
      picture->uniqueID(),           picture->cullRect().width(),
      picture->cullRect().height(),  transformed_cull_rect.x(),
      transformed_cull_rect.y(),     transformed_cull_rect.width(),
      transformed_cull_rect.height()};
  return SkData::MakeWithCopy(&rect_data, sizeof(rect_data));
}

// De-duplicates and subsets used typefaces and discards any unused typefaces.
// If subsetting fails (or on Android) this returns data only for non-system
// fonts. This means the resulting SkPicture is not portable across devices.
sk_sp<SkData> SerializeTypeface(SkTypeface* typeface, void* ctx) {
  TRACE_EVENT0("paint_preview", "SerializeTypeface");
  TypefaceSerializationContext* context =
      reinterpret_cast<TypefaceSerializationContext*>(ctx);

  if (context->finished.count(typeface->uniqueID())) {
    return typeface->serialize(SkTypeface::SerializeBehavior::kDontIncludeData);
  }
  context->finished.insert(typeface->uniqueID());

  auto usage_it = context->usage->find(typeface->uniqueID());
  if (usage_it == context->usage->end()) {
    return typeface->serialize(SkTypeface::SerializeBehavior::kDontIncludeData);
  }

#if BUILDFLAG(IS_ANDROID)
  {
    SkString familyName;
    typeface->getFamilyName(&familyName);
    // On Android MakeFromName will return nullptr rather than falling back to
    // an alternative font if a system font doesn't match. As such, we can use
    // this to check if the SkTypeface is for a system font. If it is a system
    // font we don't need to subset/serialize it.
    if (skia::MakeTypefaceFromName(familyName.c_str(), typeface->fontStyle())) {
      return typeface->serialize(
          SkTypeface::SerializeBehavior::kIncludeDataIfLocal);
    }
  }
#endif

  auto subset_data = SubsetFont(typeface, *usage_it->second);
  if (!subset_data) {
    return typeface->serialize(
        SkTypeface::SerializeBehavior::kIncludeDataIfLocal);
  }
  return subset_data;
}

static sk_sp<SkTypeface> DeserializeTypeface(const void* data,
                                             size_t length,
                                             void* ctx) {
  // TODO(bungeman,kjlubick) This should not be how the Skia deserial proc
  // works.
  SkStream* stream = *(reinterpret_cast<SkStream**>(const_cast<void*>(data)));
  if (length < sizeof(stream)) {
    return nullptr;
  }
  // The default implementation of SkPicture deserialization of SkTypeface
  // does not use a fallback (system) font manager, but this is necessary
  // on Android due to the above behavior w/r to system fonts. Thus, we
  // call the underlying SkTypeface::MakeDeserialize and pass in the
  // system font manager ourselves.
  return SkTypeface::MakeDeserialize(stream, skia::DefaultFontMgr());
}

static bool is_supported_codec(sk_sp<SkData> data) {
  CHECK(data);
  return SkBmpDecoder::IsBmp(data->data(), data->size()) ||
         SkGifDecoder::IsGif(data->data(), data->size()) ||
         SkPngDecoder::IsPng(data->data(), data->size()) ||
         SkJpegDecoder::IsJpeg(data->data(), data->size()) ||
         SkWebpDecoder::IsWebp(data->data(), data->size());
}

sk_sp<SkData> SerializeImage(SkImage* image, void* ctx) {
  ImageSerializationContext* context =
      reinterpret_cast<ImageSerializationContext*>(ctx);
  // Ignore texture backed content if any slipped through. This shouldn't occur
  // now that ToSkPicture has a dedicated ImageProvider that forces software
  // SkImage inputs, but this is a safeguard.
  if (context->skip_texture_backed && image->isTextureBacked()) {
    return SkData::MakeEmpty();
  }

  // If the decoded form of the image would result in it exceeding the allowable
  // size then effectively delete it by providing no data.
  const SkImageInfo& image_info = image->imageInfo();
  if (context->max_decoded_image_size_bytes !=
          std::numeric_limits<uint64_t>::max() &&
      image_info.computeMinByteSize() > context->max_decoded_image_size_bytes) {
    return SkData::MakeEmpty();
  }

  // If there already exists encoded data use it directly.
  sk_sp<SkData> encoded_data = image->refEncodedData();
  if (!encoded_data || !is_supported_codec(encoded_data)) {
    // Use the default PNG at quality 100 as it is safe.
    // TODO(crbug.com/40177283): Investigate supporting JPEG at quality 100 for
    // opaque images.
    encoded_data = skia::EncodePngAsSkData(nullptr, image);
  }

  if (!encoded_data) {
    return SkData::MakeEmpty();
  }

  // Ensure the encoded data fits in the size restriction if present.
  // OOM Prevention: This avoids creating/keeping large serialized images
  // in-memory during serialization if the size budget is already exceeded due
  // to images.
  if (context->remaining_image_size != std::numeric_limits<uint64_t>::max()) {
    if (context->remaining_image_size < encoded_data->size()) {
      context->memory_budget_exceeded = true;
      return SkData::MakeEmpty();
    }
    context->remaining_image_size -= encoded_data->size();
  }

  return encoded_data;
}

sk_sp<SkImage> DeserializeImage(const void* bytes, size_t length, void*) {
  // Although we usually serialize images to the PNG format, if an image was
  // already encoded as a JPEG or WEBP, those bytes are written to the
  // SKP as-is, so we should try to decode those as well.
  sk_sp<SkData> data = SkData::MakeWithoutCopy(bytes, length);
  const auto get_image = [](std::unique_ptr<SkCodec> codec) -> sk_sp<SkImage> {
    if (!codec) {
      return nullptr;
    }
    // prefer premul over unpremul (this produces better filtering in general)
    SkImageInfo targetInfo =
        codec->getInfo().makeAlphaType(kPremul_SkAlphaType);
    return std::get<0>(codec->getImage(targetInfo));
  };
  if (SkPngDecoder::IsPng(bytes, length)) {
    return get_image(SkPngDecoder::Decode(data, nullptr));
  }
  if (SkBmpDecoder::IsBmp(bytes, length)) {
    return get_image(SkBmpDecoder::Decode(data, nullptr));
  }
  if (SkGifDecoder::IsGif(bytes, length)) {
    return get_image(SkGifDecoder::Decode(data, nullptr));
  }
  if (SkJpegDecoder::IsJpeg(bytes, length)) {
    return get_image(SkJpegDecoder::Decode(data, nullptr));
  }
  return get_image(SkWebpDecoder::Decode(data, nullptr));
}

// Deserializes a clip rect for a subframe within the main SkPicture. These
// represent subframes and require special decoding as they are custom data
// rather than a valid SkPicture.
// Precondition: the version of the SkPicture should be checked prior to
// invocation to ensure deserialization will succeed.
sk_sp<SkPicture> DeserializePictureAsRectData(const void* data,
                                              size_t length,
                                              void* ctx) {
  SerializedRectData rect_data;
  if (length < sizeof(rect_data)) {
    return MakeEmptyPicture();
  }
  memcpy(&rect_data, data, sizeof(rect_data));
  auto* context = reinterpret_cast<DeserializationContext*>(ctx);
  context->insert(
      {rect_data.content_id,
       gfx::RectF(rect_data.transformed_x, rect_data.transformed_y,
                  rect_data.transformed_width, rect_data.transformed_height)});
  return MakeEmptyPicture();
}

// Similar to |DeserializePictureAsRectData|, but instead of writing out the
// serialized rect data to |ctx|, |ctx| is instead a
// |LoadedFramesDeserialContext*| that is looked up to return the picture
// itself. This assumes that the picture was already previously deserialized
// and recorded into |ctx|. Returns an empty picture if |ctx| does not contain
// the content ID embedded in |data|.
sk_sp<SkPicture> GetPictureFromDeserialContext(const void* data,
                                               size_t length,
                                               void* ctx) {
  SerializedRectData rect_data;
  if (length < sizeof(rect_data)) {
    return MakeEmptyPicture();
  }
  memcpy(&rect_data, data, sizeof(rect_data));
  auto* context = reinterpret_cast<LoadedFramesDeserialContext*>(ctx);

  auto it = context->find(rect_data.content_id);
  if (it == context->end()) {
    return MakeEmptyPicture();
  }

  // Scroll and clip the subframe manually since the picture in |ctx| does not
  // encode this information.
  SkRect subframe_bounds =
      SkRect::MakeWH(rect_data.subframe_width, rect_data.subframe_height);
  SkPictureRecorder recorder;
  SkCanvas* canvas = recorder.beginRecording(subframe_bounds);
  canvas->clipRect(subframe_bounds);
  SkMatrix apply_scroll_offsets = SkMatrix::Translate(
      -it->second.scroll_offsets.width(), -it->second.scroll_offsets.height());
  canvas->drawPicture(it->second.picture, &apply_scroll_offsets, nullptr);
  return recorder.finishRecordingAsPicture();
}

}  // namespace

PictureSerializationContext::PictureSerializationContext() = default;
PictureSerializationContext::~PictureSerializationContext() = default;

PictureSerializationContext::PictureSerializationContext(
    PictureSerializationContext&&) noexcept = default;
PictureSerializationContext& PictureSerializationContext::operator=(
    PictureSerializationContext&&) noexcept = default;

TypefaceSerializationContext::TypefaceSerializationContext(
    TypefaceUsageMap* usage)
    : usage(usage) {}
TypefaceSerializationContext::~TypefaceSerializationContext() = default;

FrameAndScrollOffsets::FrameAndScrollOffsets() = default;
FrameAndScrollOffsets::~FrameAndScrollOffsets() = default;
FrameAndScrollOffsets::FrameAndScrollOffsets(const FrameAndScrollOffsets&) =
    default;
FrameAndScrollOffsets& FrameAndScrollOffsets::operator=(
    const FrameAndScrollOffsets&) = default;

sk_sp<SkPicture> MakeEmptyPicture() {
  // Effectively a no-op.
  SkPictureRecorder rec;
  rec.beginRecording(1, 1);
  return rec.finishRecordingAsPicture();
}

SkSerialProcs MakeSerialProcs(PictureSerializationContext* picture_ctx,
                              TypefaceSerializationContext* typeface_ctx,
                              ImageSerializationContext* image_ctx) {
  SkSerialProcs procs;
  procs.fPictureProc = SerializePictureAsRectData;
  procs.fPictureCtx = picture_ctx;
  procs.fTypefaceProc = SerializeTypeface;
  procs.fTypefaceCtx = typeface_ctx;

  image_ctx->memory_budget_exceeded = false;
  procs.fImageProc = SerializeImage;
  procs.fImageCtx = image_ctx;
  return procs;
}

SkDeserialProcs MakeDeserialProcs(DeserializationContext* ctx) {
  SkDeserialProcs procs;
  procs.fPictureProc = DeserializePictureAsRectData;
  procs.fPictureCtx = ctx;
  procs.fImageProc = DeserializeImage;
  procs.fTypefaceProc = DeserializeTypeface;
  sktext::gpu::Slug::AddDeserialProcs(&procs, nullptr);
  return procs;
}

SkDeserialProcs MakeDeserialProcs(LoadedFramesDeserialContext* ctx) {
  SkDeserialProcs procs;
  procs.fPictureProc = GetPictureFromDeserialContext;
  procs.fPictureCtx = ctx;
  procs.fImageProc = DeserializeImage;
  procs.fTypefaceProc = DeserializeTypeface;
  return procs;
}

}  // namespace paint_preview