File: png_codec.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 (327 lines) | stat: -rw-r--r-- 11,243 bytes parent folder | download | duplicates (3)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/codec/png_codec.h"

#include <stdint.h>

#include <optional>

#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/strings/string_util.h"
#include "skia/buildflags.h"
#include "skia/rusty_png_feature.h"
#include "third_party/skia/include/codec/SkPngDecoder.h"
#include "third_party/skia/include/core/SkAlphaType.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColorType.h"
#include "third_party/skia/include/core/SkUnPreMultiply.h"
#include "third_party/skia/include/encode/SkPngEncoder.h"
#include "third_party/zlib/zlib.h"
#include "ui/gfx/codec/vector_wstream.h"
#include "ui/gfx/geometry/size.h"

#if BUILDFLAG(SKIA_BUILD_RUST_PNG)
#include "third_party/skia/experimental/rust_png/decoder/SkPngRustDecoder.h"
#endif

namespace gfx {

PNGCodec::DecodeOutput::DecodeOutput() = default;
PNGCodec::DecodeOutput::DecodeOutput(PNGCodec::DecodeOutput&& other) = default;
PNGCodec::DecodeOutput& PNGCodec::DecodeOutput::operator=(
    PNGCodec::DecodeOutput&& other) = default;
PNGCodec::DecodeOutput::~DecodeOutput() = default;

// Decoder --------------------------------------------------------------------

namespace {

std::unique_ptr<SkCodec> CreatePngDecoder(std::unique_ptr<SkStream> stream,
                                          SkCodec::Result* result) {
  if (skia::IsRustyPngEnabled()) {
#if BUILDFLAG(SKIA_BUILD_RUST_PNG)
    return SkPngRustDecoder::Decode(std::move(stream), result);
#else
    // The `if` condition guarantees `SKIA_BUILD_RUST_PNG`.
    NOTREACHED();
#endif
  }

  return SkPngDecoder::Decode(std::move(stream), result);
}

struct PreparationOutput {
  std::unique_ptr<SkCodec> codec;
  SkImageInfo image_info;
};

std::optional<PreparationOutput> PrepareForPNGDecode(
    base::span<const uint8_t> input,
    PNGCodec::ColorFormat format) {
  PreparationOutput output;

  // Parse the input stream with the PNG decoder, yielding a SkCodec.
  auto stream = std::make_unique<SkMemoryStream>(input.data(), input.size(),
                                                 /*copyData=*/false);
  SkCodec::Result result;
  output.codec = CreatePngDecoder(std::move(stream), &result);
  if (!output.codec || result != SkCodec::kSuccess) {
    return std::nullopt;
  }

  // Protect against large PNGs. See http://bugzil.la/251381 for more details.
  // The limit of `1000000` has been copied from `blink::PNGImageDecoder` and
  // originates all the way back in WebKit.
  SkISize size = output.codec->dimensions();
  const int32_t kMaxPNGSize = 1000000;
  if ((size.width() > kMaxPNGSize) || (size.height() > kMaxPNGSize)) {
    return std::nullopt;
  }
  constexpr int kBytesPerPixel = 4;
  if (size.area() >= (INT_MAX / kBytesPerPixel)) {
    return std::nullopt;
  }

  // Create an SkImageInfo matching the PNG's, but with our desired format.
  SkImageInfo codec_info = output.codec->getInfo();
  SkAlphaType alpha_type = codec_info.alphaType();
  SkColorType color_type;
  switch (format) {
    case PNGCodec::FORMAT_RGBA:
      color_type = kRGBA_8888_SkColorType;
      break;
    case PNGCodec::FORMAT_BGRA:
      color_type = kBGRA_8888_SkColorType;
      break;
    case PNGCodec::FORMAT_SkBitmap:
      color_type = kN32_SkColorType;
      if (alpha_type == kUnpremul_SkAlphaType) {
        alpha_type = kPremul_SkAlphaType;
      }
      break;
    default:
      NOTREACHED() << "Invalid color format " << format;
  }
  output.image_info =
      SkImageInfo::Make(codec_info.width(), codec_info.height(), color_type,
                        alpha_type, codec_info.refColorSpace());

  return output;
}

}  // namespace

// static
std::optional<PNGCodec::DecodeOutput> PNGCodec::Decode(
    base::span<const uint8_t> input,
    ColorFormat format) {
  SCOPED_UMA_HISTOGRAM_TIMER_MICROS("ImageDecoder.Png.UiGfxIntoVector");

  std::optional<PreparationOutput> preparation_output =
      PrepareForPNGDecode(input, format);
  if (!preparation_output) {
    return std::nullopt;
  }

  DecodeOutput output;
  output.width = preparation_output->image_info.width();
  output.height = preparation_output->image_info.height();

  // Always decode into vanilla sRGB, because the output array is a bag of RGBA
  // pixels and doesn't have an associated colorspace.
  SkImageInfo info_srgb =
      preparation_output->image_info.makeColorSpace(SkColorSpace::MakeSRGB());

  // Decode the pixels into the `output` vector.
  output.output.resize(info_srgb.computeMinByteSize());
  SkCodec::Result result = preparation_output->codec->getPixels(
      info_srgb, output.output.data(),
      preparation_output->image_info.minRowBytes());
  if (result != SkCodec::kSuccess) {
    return std::nullopt;
  }
  return output;
}

SkBitmap PNGCodec::Decode(base::span<const uint8_t> input) {
  SCOPED_UMA_HISTOGRAM_TIMER_MICROS("ImageDecoder.Png.UiGfxIntoSkBitmap");

  std::optional<PreparationOutput> preparation_output =
      PrepareForPNGDecode(input, FORMAT_SkBitmap);
  if (!preparation_output) {
    return SkBitmap();
  }

  // The image alpha type is likely to be "unpremultiplied," as this is set by
  // the PNG standard. However, Skia prefers premultiplied bitmaps. We update
  // the image-info struct to specify premultiplication; the SkCodec will
  // automatically fix up the pixels as it runs.
  SkAlphaType alpha = preparation_output->image_info.alphaType();
  if (alpha == kUnpremul_SkAlphaType) {
    preparation_output->image_info =
        preparation_output->image_info.makeAlphaType(kPremul_SkAlphaType);
  }

  // Decode the image pixels directly into the SkBitmap. Alpha premultiplication
  // will be performed by `getPixels`. No colorspace conversion will occur,
  // because the bitmap uses the same colorspace as the original PNG.
  SkBitmap bitmap;
  if (!bitmap.tryAllocPixels(preparation_output->image_info)) {
    return SkBitmap();
  }

  SkCodec::Result result =
      preparation_output->codec->getPixels(bitmap.pixmap());
  if (result == SkCodec::kSuccess) {
    return bitmap;
  } else {
    return SkBitmap();
  }
}

// Encoder --------------------------------------------------------------------

namespace {

void AddComments(SkPngEncoder::Options& options,
                 const std::vector<PNGCodec::Comment>& comments) {
  std::vector<const char*> comment_pointers;
  std::vector<size_t> comment_sizes;
  for (const auto& comment : comments) {
    comment_pointers.push_back(comment.key.c_str());
    comment_pointers.push_back(comment.text.c_str());
    comment_sizes.push_back(comment.key.length() + 1);
    comment_sizes.push_back(comment.text.length() + 1);
  }
  options.fComments = SkDataTable::MakeCopyArrays(
      (void const* const*)comment_pointers.data(), comment_sizes.data(),
      static_cast<int>(comment_pointers.size()));
}

std::optional<std::vector<uint8_t>> EncodeSkPixmap(
    const SkPixmap& src,
    const std::vector<PNGCodec::Comment>& comments,
    int zlib_level,
    bool disable_filters) {
  std::vector<uint8_t> output;
  VectorWStream dst(&output);

  SkPngEncoder::Options options;
  AddComments(options, comments);
  options.fZLibLevel = zlib_level;
  if (disable_filters) {
    options.fFilterFlags = SkPngEncoder::FilterFlag::kNone;
  }

  if (!skia::EncodePng(&dst, src, options)) {
    return std::nullopt;
  }

  return output;
}

std::optional<std::vector<uint8_t>> EncodeSkPixmap(
    const SkPixmap& src,
    bool discard_transparency,
    const std::vector<PNGCodec::Comment>& comments,
    int zlib_level,
    bool disable_filters) {
  if (discard_transparency) {
    SkImageInfo opaque_info = src.info().makeAlphaType(kOpaque_SkAlphaType);
    SkBitmap copy;
    if (!copy.tryAllocPixels(opaque_info)) {
      return std::nullopt;
    }
    SkPixmap opaque_pixmap;
    bool success = copy.peekPixels(&opaque_pixmap);
    DCHECK(success);
    // The following step does the unpremul as we set the dst alpha type to be
    // kUnpremul_SkAlphaType. Later, because opaque_pixmap has
    // kOpaque_SkAlphaType, we'll discard the transparency as required.
    success =
        src.readPixels(opaque_info.makeAlphaType(kUnpremul_SkAlphaType),
                       opaque_pixmap.writable_addr(), opaque_pixmap.rowBytes());
    DCHECK(success);
    return EncodeSkPixmap(opaque_pixmap, comments, zlib_level, disable_filters);
  }

  // If the image's pixels are all opaque, encode the PNG as opaque, regardless
  // of the pixmap's alphaType.
  if (src.info().alphaType() != kOpaque_SkAlphaType && src.computeIsOpaque()) {
    SkPixmap opaque_pixmap{src.info().makeAlphaType(kOpaque_SkAlphaType),
                           src.addr(), src.rowBytes()};
    return EncodeSkPixmap(opaque_pixmap, comments, zlib_level, disable_filters);
  }

  // Encode the PNG without any conversions.
  return EncodeSkPixmap(src, comments, zlib_level, disable_filters);
}

std::optional<std::vector<uint8_t>> EncodeSkBitmap(const SkBitmap& input,
                                                   bool discard_transparency,
                                                   int zlib_level,
                                                   bool disable_filters) {
  SkPixmap src;
  if (!input.peekPixels(&src)) {
    return std::nullopt;
  }
  return EncodeSkPixmap(src, discard_transparency,
                        std::vector<PNGCodec::Comment>(), zlib_level,
                        disable_filters);
}

}  // namespace

std::optional<std::vector<uint8_t>> PNGCodec::Encode(
    const unsigned char* input,
    ColorFormat format,
    const Size& size,
    int row_byte_width,
    bool discard_transparency,
    const std::vector<Comment>& comments) {
  // Initialization required for Windows although the switch covers all cases.
  SkColorType colorType = kN32_SkColorType;
  switch (format) {
    case FORMAT_RGBA:
      colorType = kRGBA_8888_SkColorType;
      break;
    case FORMAT_BGRA:
      colorType = kBGRA_8888_SkColorType;
      break;
    case FORMAT_SkBitmap:
      colorType = kN32_SkColorType;
      break;
  }
  auto alphaType =
      format == FORMAT_SkBitmap ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
  SkImageInfo info =
      SkImageInfo::Make(size.width(), size.height(), colorType, alphaType);
  SkPixmap src(info, input, row_byte_width);
  return EncodeSkPixmap(src, discard_transparency, comments,
                        DEFAULT_ZLIB_COMPRESSION, /*disable_filters=*/false);
}

std::optional<std::vector<uint8_t>> PNGCodec::EncodeBGRASkBitmap(
    const SkBitmap& input,
    bool discard_transparency) {
  return EncodeSkBitmap(input, discard_transparency, DEFAULT_ZLIB_COMPRESSION,
                        /*disable_filters=*/false);
}

std::optional<std::vector<uint8_t>> PNGCodec::FastEncodeBGRASkBitmap(
    const SkBitmap& input,
    bool discard_transparency) {
  return EncodeSkBitmap(input, discard_transparency, Z_BEST_SPEED,
                        /*disable_filters=*/true);
}

PNGCodec::Comment::Comment(const std::string& k, const std::string& t)
    : key(k), text(t) {}

PNGCodec::Comment::~Comment() = default;

}  // namespace gfx