blob: ae98afcd3cc3621545f2466b49c217f72582ce67 [file] [log] [blame]
Adam Lesinski21efb682016-09-14 17:35:43 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compile/Png.h"
18
Adam Lesinski21efb682016-09-14 17:35:43 -070019#include <png.h>
Adam Lesinskicacb28f2016-10-19 12:18:14 -070020#include <zlib.h>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021
Adam Lesinskicacb28f2016-10-19 12:18:14 -070022#include <algorithm>
Adam Lesinski21efb682016-09-14 17:35:43 -070023#include <unordered_map>
24#include <unordered_set>
Adam Lesinski21efb682016-09-14 17:35:43 -070025
Adam Lesinskice5e56e2016-10-21 17:56:45 -070026#include "android-base/errors.h"
27#include "android-base/logging.h"
28#include "android-base/macros.h"
29
Adam Lesinski21efb682016-09-14 17:35:43 -070030namespace aapt {
31
Adam Lesinski06460ef2017-03-14 18:52:13 -070032// Custom deleter that destroys libpng read and info structs.
Adam Lesinski21efb682016-09-14 17:35:43 -070033class PngReadStructDeleter {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070034 public:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070035 PngReadStructDeleter(png_structp read_ptr, png_infop info_ptr)
36 : read_ptr_(read_ptr), info_ptr_(info_ptr) {}
Adam Lesinski21efb682016-09-14 17:35:43 -070037
Adam Lesinskicacb28f2016-10-19 12:18:14 -070038 ~PngReadStructDeleter() {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070039 png_destroy_read_struct(&read_ptr_, &info_ptr_, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -070040 }
Adam Lesinski21efb682016-09-14 17:35:43 -070041
Adam Lesinskicacb28f2016-10-19 12:18:14 -070042 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070043 png_structp read_ptr_;
44 png_infop info_ptr_;
Adam Lesinski21efb682016-09-14 17:35:43 -070045
Adam Lesinskicacb28f2016-10-19 12:18:14 -070046 DISALLOW_COPY_AND_ASSIGN(PngReadStructDeleter);
Adam Lesinski21efb682016-09-14 17:35:43 -070047};
48
Adam Lesinski06460ef2017-03-14 18:52:13 -070049// Custom deleter that destroys libpng write and info structs.
Adam Lesinski21efb682016-09-14 17:35:43 -070050class PngWriteStructDeleter {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070051 public:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070052 PngWriteStructDeleter(png_structp write_ptr, png_infop info_ptr)
53 : write_ptr_(write_ptr), info_ptr_(info_ptr) {}
Adam Lesinski21efb682016-09-14 17:35:43 -070054
Adam Lesinskice5e56e2016-10-21 17:56:45 -070055 ~PngWriteStructDeleter() {
56 png_destroy_write_struct(&write_ptr_, &info_ptr_);
57 }
Adam Lesinski21efb682016-09-14 17:35:43 -070058
Adam Lesinskicacb28f2016-10-19 12:18:14 -070059 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070060 png_structp write_ptr_;
61 png_infop info_ptr_;
Adam Lesinski21efb682016-09-14 17:35:43 -070062
Adam Lesinskicacb28f2016-10-19 12:18:14 -070063 DISALLOW_COPY_AND_ASSIGN(PngWriteStructDeleter);
Adam Lesinski21efb682016-09-14 17:35:43 -070064};
65
66// Custom warning logging method that uses IDiagnostics.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070067static void LogWarning(png_structp png_ptr, png_const_charp warning_msg) {
68 IDiagnostics* diag = (IDiagnostics*)png_get_error_ptr(png_ptr);
69 diag->Warn(DiagMessage() << warning_msg);
Adam Lesinski21efb682016-09-14 17:35:43 -070070}
71
72// Custom error logging method that uses IDiagnostics.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070073static void LogError(png_structp png_ptr, png_const_charp error_msg) {
74 IDiagnostics* diag = (IDiagnostics*)png_get_error_ptr(png_ptr);
75 diag->Error(DiagMessage() << error_msg);
Adam Lesinski21efb682016-09-14 17:35:43 -070076}
77
Adam Lesinski06460ef2017-03-14 18:52:13 -070078static void ReadDataFromStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070079 io::InputStream* in = (io::InputStream*)png_get_io_ptr(png_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -070080
Adam Lesinskice5e56e2016-10-21 17:56:45 -070081 const void* in_buffer;
Adam Lesinski06460ef2017-03-14 18:52:13 -070082 size_t in_len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070083 if (!in->Next(&in_buffer, &in_len)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070084 if (in->HadError()) {
85 std::string err = in->GetError();
Adam Lesinskice5e56e2016-10-21 17:56:45 -070086 png_error(png_ptr, err.c_str());
Adam Lesinski21efb682016-09-14 17:35:43 -070087 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -070088 return;
89 }
Adam Lesinski21efb682016-09-14 17:35:43 -070090
Adam Lesinski06460ef2017-03-14 18:52:13 -070091 const size_t bytes_read = std::min(in_len, len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -070092 memcpy(buffer, in_buffer, bytes_read);
Adam Lesinski06460ef2017-03-14 18:52:13 -070093 if (bytes_read != in_len) {
94 in->BackUp(in_len - bytes_read);
Adam Lesinskicacb28f2016-10-19 12:18:14 -070095 }
Adam Lesinski21efb682016-09-14 17:35:43 -070096}
97
Adam Lesinski06460ef2017-03-14 18:52:13 -070098static void WriteDataToStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070099 io::OutputStream* out = (io::OutputStream*)png_get_io_ptr(png_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700100
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700101 void* out_buffer;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700102 size_t out_len;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700103 while (len > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 if (!out->Next(&out_buffer, &out_len)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700105 if (out->HadError()) {
106 std::string err = out->GetError();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700107 png_error(png_ptr, err.c_str());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700108 }
109 return;
Adam Lesinski21efb682016-09-14 17:35:43 -0700110 }
111
Adam Lesinski06460ef2017-03-14 18:52:13 -0700112 const size_t bytes_written = std::min(out_len, len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 memcpy(out_buffer, buffer, bytes_written);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700114
115 // Advance the input buffer.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700116 buffer += bytes_written;
117 len -= bytes_written;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700118
119 // Advance the output buffer.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700120 out_len -= bytes_written;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 }
122
123 // If the entire output buffer wasn't used, backup.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700124 if (out_len > 0) {
125 out->BackUp(out_len);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700127}
128
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700129std::unique_ptr<Image> ReadPng(IAaptContext* context, io::InputStream* in) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700130 // Read the first 8 bytes of the file looking for the PNG signature.
131 // Bail early if it does not match.
132 const png_byte* signature;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700133 size_t buffer_size;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700134 if (!in->Next((const void**)&signature, &buffer_size)) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700135 context->GetDiagnostics()->Error(DiagMessage()
136 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700137 return {};
138 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700139
Adam Lesinski06460ef2017-03-14 18:52:13 -0700140 if (buffer_size < kPngSignatureSize || png_sig_cmp(signature, 0, kPngSignatureSize) != 0) {
141 context->GetDiagnostics()->Error(DiagMessage()
142 << "file signature does not match PNG signature");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700143 return {};
144 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700145
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700146 // Start at the beginning of the first chunk.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700147 in->BackUp(buffer_size - kPngSignatureSize);
Adam Lesinski21efb682016-09-14 17:35:43 -0700148
Adam Lesinski06460ef2017-03-14 18:52:13 -0700149 // Create and initialize the png_struct with the default error and warning handlers.
150 // The header version is also passed in to ensure that this was built against the same
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700151 // version of libpng.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700152 png_structp read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700153 if (read_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700154 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng read png_struct");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700155 return {};
156 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700157
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700158 // Create and initialize the memory for image header and data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700159 png_infop info_ptr = png_create_info_struct(read_ptr);
160 if (info_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700161 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng read png_info");
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700162 png_destroy_read_struct(&read_ptr, nullptr, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700163 return {};
164 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700165
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700166 // Automatically release PNG resources at end of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700167 PngReadStructDeleter png_read_deleter(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700168
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700169 // libpng uses longjmp to jump to an error handling routine.
170 // setjmp will only return true if it was jumped to, aka there was
171 // an error.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700172 if (setjmp(png_jmpbuf(read_ptr))) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700173 return {};
174 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700175
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700176 // Handle warnings ourselves via IDiagnostics.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700177 png_set_error_fn(read_ptr, (png_voidp)context->GetDiagnostics(), LogError, LogWarning);
Adam Lesinski21efb682016-09-14 17:35:43 -0700178
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700179 // Set up the read functions which read from our custom data sources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700180 png_set_read_fn(read_ptr, (png_voidp)in, ReadDataFromStream);
Adam Lesinski21efb682016-09-14 17:35:43 -0700181
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700182 // Skip the signature that we already read.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700183 png_set_sig_bytes(read_ptr, kPngSignatureSize);
Adam Lesinski21efb682016-09-14 17:35:43 -0700184
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700185 // Read the chunk headers.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700186 png_read_info(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700187
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700188 // Extract image meta-data from the various chunk headers.
189 uint32_t width, height;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700190 int bit_depth, color_type, interlace_method, compression_method, filter_method;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700191 png_get_IHDR(read_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
192 &interlace_method, &compression_method, &filter_method);
Adam Lesinski21efb682016-09-14 17:35:43 -0700193
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700194 // When the image is read, expand it so that it is in RGBA 8888 format
195 // so that image handling is uniform.
Adam Lesinski21efb682016-09-14 17:35:43 -0700196
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700197 if (color_type == PNG_COLOR_TYPE_PALETTE) {
198 png_set_palette_to_rgb(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700199 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700200
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700201 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
202 png_set_expand_gray_1_2_4_to_8(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700203 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700204
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700205 if (png_get_valid(read_ptr, info_ptr, PNG_INFO_tRNS)) {
206 png_set_tRNS_to_alpha(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700207 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700208
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700209 if (bit_depth == 16) {
210 png_set_strip_16(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700211 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700212
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700213 if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
214 png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700215 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700216
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700217 if (color_type == PNG_COLOR_TYPE_GRAY ||
218 color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
219 png_set_gray_to_rgb(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700220 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700221
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700222 if (interlace_method != PNG_INTERLACE_NONE) {
223 png_set_interlace_handling(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700224 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700225
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700226 // Once all the options for reading have been set, we need to flush
227 // them to libpng.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700228 png_read_update_info(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700229
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700230 // 9-patch uses int32_t to index images, so we cap the image dimensions to
231 // something
232 // that can always be represented by 9-patch.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700233 if (width > std::numeric_limits<int32_t>::max() || height > std::numeric_limits<int32_t>::max()) {
234 context->GetDiagnostics()->Error(
235 DiagMessage() << "PNG image dimensions are too large: " << width << "x" << height);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700236 return {};
237 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700238
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700239 std::unique_ptr<Image> output_image = util::make_unique<Image>();
240 output_image->width = static_cast<int32_t>(width);
241 output_image->height = static_cast<int32_t>(height);
Adam Lesinski21efb682016-09-14 17:35:43 -0700242
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700243 const size_t row_bytes = png_get_rowbytes(read_ptr, info_ptr);
244 CHECK(row_bytes == 4 * width); // RGBA
Adam Lesinski21efb682016-09-14 17:35:43 -0700245
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700246 // Allocate one large block to hold the image.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700247 output_image->data = std::unique_ptr<uint8_t[]>(new uint8_t[height * row_bytes]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700248
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700249 // Create an array of rows that index into the data block.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700250 output_image->rows = std::unique_ptr<uint8_t* []>(new uint8_t*[height]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700251 for (uint32_t h = 0; h < height; h++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700252 output_image->rows[h] = output_image->data.get() + (h * row_bytes);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700253 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700254
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700255 // Actually read the image pixels.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700256 png_read_image(read_ptr, output_image->rows.get());
Adam Lesinski21efb682016-09-14 17:35:43 -0700257
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700258 // Finish reading. This will read any other chunks after the image data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700259 png_read_end(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700260
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700261 return output_image;
Adam Lesinski21efb682016-09-14 17:35:43 -0700262}
263
Adam Lesinski06460ef2017-03-14 18:52:13 -0700264// Experimentally chosen constant to be added to the overhead of using color type
265// PNG_COLOR_TYPE_PALETTE to account for the uncompressability of the palette chunk.
266// Without this, many small PNGs encoded with palettes are larger after compression than
267// the same PNGs encoded as RGBA.
Adam Lesinski21efb682016-09-14 17:35:43 -0700268constexpr static const size_t kPaletteOverheadConstant = 1024u * 10u;
269
Adam Lesinski06460ef2017-03-14 18:52:13 -0700270// Pick a color type by which to encode the image, based on which color type will take
Adam Lesinski21efb682016-09-14 17:35:43 -0700271// the least amount of disk space.
272//
273// 9-patch images traditionally have not been encoded with palettes.
274// The original rationale was to avoid dithering until after scaling,
275// but I don't think this would be an issue with palettes. Either way,
276// our naive size estimation tends to be wrong for small images like 9-patches
277// and using palettes balloons the size of the resulting 9-patch.
278// In order to not regress in size, restrict 9-patch to not use palettes.
279
280// The options are:
281//
282// - RGB
283// - RGBA
284// - RGB + cheap alpha
285// - Color palette
286// - Color palette + cheap alpha
287// - Color palette + alpha palette
288// - Grayscale
289// - Grayscale + cheap alpha
290// - Grayscale + alpha
291//
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700292static int PickColorType(int32_t width, int32_t height, bool grayscale,
293 bool convertible_to_grayscale, bool has_nine_patch,
294 size_t color_palette_size, size_t alpha_palette_size) {
295 const size_t palette_chunk_size = 16 + color_palette_size * 3;
296 const size_t alpha_chunk_size = 16 + alpha_palette_size;
297 const size_t color_alpha_data_chunk_size = 16 + 4 * width * height;
298 const size_t color_data_chunk_size = 16 + 3 * width * height;
299 const size_t grayscale_alpha_data_chunk_size = 16 + 2 * width * height;
300 const size_t palette_data_chunk_size = 16 + width * height;
Adam Lesinski21efb682016-09-14 17:35:43 -0700301
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700302 if (grayscale) {
303 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700304 // This is the smallest the data can be.
305 return PNG_COLOR_TYPE_GRAY;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700306 } else if (color_palette_size <= 256 && !has_nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700307 // This grayscale has alpha and can fit within a palette.
308 // See if it is worth fitting into a palette.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700309 const size_t palette_threshold = palette_chunk_size + alpha_chunk_size +
310 palette_data_chunk_size +
311 kPaletteOverheadConstant;
312 if (grayscale_alpha_data_chunk_size > palette_threshold) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700313 return PNG_COLOR_TYPE_PALETTE;
314 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700315 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700316 return PNG_COLOR_TYPE_GRAY_ALPHA;
317 }
318
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700319 if (color_palette_size <= 256 && !has_nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700320 // This image can fit inside a palette. Let's see if it is worth it.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700321 size_t total_size_with_palette =
322 palette_data_chunk_size + palette_chunk_size;
323 size_t total_size_without_palette = color_data_chunk_size;
324 if (alpha_palette_size > 0) {
325 total_size_with_palette += alpha_palette_size;
326 total_size_without_palette = color_alpha_data_chunk_size;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700327 }
328
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700329 if (total_size_without_palette >
330 total_size_with_palette + kPaletteOverheadConstant) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700331 return PNG_COLOR_TYPE_PALETTE;
332 }
333 }
334
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700335 if (convertible_to_grayscale) {
336 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700337 return PNG_COLOR_TYPE_GRAY;
338 } else {
339 return PNG_COLOR_TYPE_GRAY_ALPHA;
340 }
341 }
342
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700343 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700344 return PNG_COLOR_TYPE_RGB;
345 }
346 return PNG_COLOR_TYPE_RGBA;
Adam Lesinski21efb682016-09-14 17:35:43 -0700347}
348
Adam Lesinski06460ef2017-03-14 18:52:13 -0700349// Assigns indices to the color and alpha palettes, encodes them, and then invokes
Adam Lesinski21efb682016-09-14 17:35:43 -0700350// png_set_PLTE/png_set_tRNS.
351// This must be done before writing image data.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700352// Image data must be transformed to use the indices assigned within the palette.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700353static void WritePalette(png_structp write_ptr, png_infop write_info_ptr,
354 std::unordered_map<uint32_t, int>* color_palette,
355 std::unordered_set<uint32_t>* alpha_palette) {
356 CHECK(color_palette->size() <= 256);
357 CHECK(alpha_palette->size() <= 256);
Adam Lesinski21efb682016-09-14 17:35:43 -0700358
Adam Lesinski06460ef2017-03-14 18:52:13 -0700359 // Populate the PNG palette struct and assign indices to the color palette.
Adam Lesinski21efb682016-09-14 17:35:43 -0700360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 // Colors in the alpha palette should have smaller indices.
362 // This will ensure that we can truncate the alpha palette if it is
363 // smaller than the color palette.
364 int index = 0;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700365 for (uint32_t color : *alpha_palette) {
366 (*color_palette)[color] = index++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 }
368
369 // Assign the rest of the entries.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700370 for (auto& entry : *color_palette) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700371 if (entry.second == -1) {
372 entry.second = index++;
Adam Lesinski21efb682016-09-14 17:35:43 -0700373 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700374 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700375
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700376 // Create the PNG color palette struct.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700377 auto color_palette_bytes = std::unique_ptr<png_color[]>(new png_color[color_palette->size()]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700378
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700379 std::unique_ptr<png_byte[]> alpha_palette_bytes;
380 if (!alpha_palette->empty()) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700381 alpha_palette_bytes = std::unique_ptr<png_byte[]>(new png_byte[alpha_palette->size()]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700382 }
383
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700384 for (const auto& entry : *color_palette) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700385 const uint32_t color = entry.first;
386 const int index = entry.second;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700387 CHECK(index >= 0);
388 CHECK(static_cast<size_t>(index) < color_palette->size());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700389
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700390 png_colorp slot = color_palette_bytes.get() + index;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700391 slot->red = color >> 24;
392 slot->green = color >> 16;
393 slot->blue = color >> 8;
394
395 const png_byte alpha = color & 0x000000ff;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700396 if (alpha != 0xff && alpha_palette_bytes) {
397 CHECK(static_cast<size_t>(index) < alpha_palette->size());
398 alpha_palette_bytes[index] = alpha;
Adam Lesinski21efb682016-09-14 17:35:43 -0700399 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700400 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700401
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700402 // The bytes get copied here, so it is safe to release color_palette_bytes at
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700403 // the end of function
404 // scope.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700405 png_set_PLTE(write_ptr, write_info_ptr, color_palette_bytes.get(), color_palette->size());
Adam Lesinski21efb682016-09-14 17:35:43 -0700406
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700407 if (alpha_palette_bytes) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700408 png_set_tRNS(write_ptr, write_info_ptr, alpha_palette_bytes.get(), alpha_palette->size(),
409 nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700410 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700411}
412
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700413// Write the 9-patch custom PNG chunks to write_info_ptr. This must be done
Adam Lesinski06460ef2017-03-14 18:52:13 -0700414// before writing image data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700415static void WriteNinePatch(png_structp write_ptr, png_infop write_info_ptr,
416 const NinePatch* nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700417 // The order of the chunks is important.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700418 // 9-patch code in older platforms expects the 9-patch chunk to be last.
Adam Lesinski21efb682016-09-14 17:35:43 -0700419
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700420 png_unknown_chunk unknown_chunks[3];
421 memset(unknown_chunks, 0, sizeof(unknown_chunks));
Adam Lesinski21efb682016-09-14 17:35:43 -0700422
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700423 size_t index = 0;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700424 size_t chunk_len = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700425
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700426 std::unique_ptr<uint8_t[]> serialized_outline =
427 nine_patch->SerializeRoundedRectOutline(&chunk_len);
428 strcpy((char*)unknown_chunks[index].name, "npOl");
429 unknown_chunks[index].size = chunk_len;
430 unknown_chunks[index].data = (png_bytep)serialized_outline.get();
431 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700432 index++;
433
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700434 std::unique_ptr<uint8_t[]> serialized_layout_bounds;
435 if (nine_patch->layout_bounds.nonZero()) {
436 serialized_layout_bounds = nine_patch->SerializeLayoutBounds(&chunk_len);
437 strcpy((char*)unknown_chunks[index].name, "npLb");
438 unknown_chunks[index].size = chunk_len;
439 unknown_chunks[index].data = (png_bytep)serialized_layout_bounds.get();
440 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinski21efb682016-09-14 17:35:43 -0700441 index++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700442 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700443
Adam Lesinski06460ef2017-03-14 18:52:13 -0700444 std::unique_ptr<uint8_t[]> serialized_nine_patch = nine_patch->SerializeBase(&chunk_len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700445 strcpy((char*)unknown_chunks[index].name, "npTc");
446 unknown_chunks[index].size = chunk_len;
447 unknown_chunks[index].data = (png_bytep)serialized_nine_patch.get();
448 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700449 index++;
Adam Lesinski21efb682016-09-14 17:35:43 -0700450
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700451 // Handle all unknown chunks. We are manually setting the chunks here,
452 // so we will only ever handle our custom chunks.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700453 png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS, nullptr, 0);
Adam Lesinski21efb682016-09-14 17:35:43 -0700454
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700455 // Set the actual chunks here. The data gets copied, so our buffers can
456 // safely go out of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700457 png_set_unknown_chunks(write_ptr, write_info_ptr, unknown_chunks, index);
Adam Lesinski21efb682016-09-14 17:35:43 -0700458}
459
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700460bool WritePng(IAaptContext* context, const Image* image,
461 const NinePatch* nine_patch, io::OutputStream* out,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700462 const PngOptions& options) {
463 // Create and initialize the write png_struct with the default error and
464 // warning handlers.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700465 // The header version is also passed in to ensure that this was built against the same
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700466 // version of libpng.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700467 png_structp write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700468 if (write_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700469 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng write png_struct");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700470 return false;
471 }
472
473 // Allocate memory to store image header data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700474 png_infop write_info_ptr = png_create_info_struct(write_ptr);
475 if (write_info_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700476 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng write png_info");
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700477 png_destroy_write_struct(&write_ptr, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700478 return false;
479 }
480
481 // Automatically release PNG resources at end of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700482 PngWriteStructDeleter png_write_deleter(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700483
484 // libpng uses longjmp to jump to error handling routines.
485 // setjmp will return true only if it was jumped to, aka, there was an error.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700486 if (setjmp(png_jmpbuf(write_ptr))) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 return false;
488 }
489
490 // Handle warnings with our IDiagnostics.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700491 png_set_error_fn(write_ptr, (png_voidp)context->GetDiagnostics(), LogError, LogWarning);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492
493 // Set up the write functions which write to our custom data sources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700494 png_set_write_fn(write_ptr, (png_voidp)out, WriteDataToStream, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700495
496 // We want small files and can take the performance hit to achieve this goal.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700497 png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700498
499 // Begin analysis of the image data.
500 // Scan the entire image and determine if:
501 // 1. Every pixel has R == G == B (grayscale)
502 // 2. Every pixel has A == 255 (opaque)
503 // 3. There are no more than 256 distinct RGBA colors (palette).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700504 std::unordered_map<uint32_t, int> color_palette;
505 std::unordered_set<uint32_t> alpha_palette;
506 bool needs_to_zero_rgb_channels_of_transparent_pixels = false;
507 bool grayscale = true;
508 int max_gray_deviation = 0;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700509
510 for (int32_t y = 0; y < image->height; y++) {
511 const uint8_t* row = image->rows[y];
512 for (int32_t x = 0; x < image->width; x++) {
513 int red = *row++;
514 int green = *row++;
515 int blue = *row++;
516 int alpha = *row++;
517
518 if (alpha == 0) {
519 // The color is completely transparent.
520 // For purposes of palettes and grayscale optimization,
521 // treat all channels as 0x00.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700522 needs_to_zero_rgb_channels_of_transparent_pixels =
523 needs_to_zero_rgb_channels_of_transparent_pixels ||
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700524 (red != 0 || green != 0 || blue != 0);
525 red = green = blue = 0;
526 }
527
528 // Insert the color into the color palette.
529 const uint32_t color = red << 24 | green << 16 | blue << 8 | alpha;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700530 color_palette[color] = -1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700531
532 // If the pixel has non-opaque alpha, insert it into the
533 // alpha palette.
534 if (alpha != 0xff) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700535 alpha_palette.insert(color);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700536 }
537
538 // Check if the image is indeed grayscale.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700539 if (grayscale) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700540 if (red != green || red != blue) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700541 grayscale = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700542 }
543 }
544
545 // Calculate the gray scale deviation so that it can be compared
546 // with the threshold.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700547 max_gray_deviation = std::max(std::abs(red - green), max_gray_deviation);
548 max_gray_deviation = std::max(std::abs(green - blue), max_gray_deviation);
549 max_gray_deviation = std::max(std::abs(blue - red), max_gray_deviation);
Adam Lesinski21efb682016-09-14 17:35:43 -0700550 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700552
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700553 if (context->IsVerbose()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700554 DiagMessage msg;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700555 msg << " paletteSize=" << color_palette.size()
556 << " alphaPaletteSize=" << alpha_palette.size()
557 << " maxGrayDeviation=" << max_gray_deviation
558 << " grayScale=" << (grayscale ? "true" : "false");
559 context->GetDiagnostics()->Note(msg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560 }
561
Adam Lesinski06460ef2017-03-14 18:52:13 -0700562 const bool convertible_to_grayscale = max_gray_deviation <= options.grayscale_tolerance;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700564 const int new_color_type = PickColorType(
565 image->width, image->height, grayscale, convertible_to_grayscale,
566 nine_patch != nullptr, color_palette.size(), alpha_palette.size());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700567
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700568 if (context->IsVerbose()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569 DiagMessage msg;
570 msg << "encoding PNG ";
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700571 if (nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572 msg << "(with 9-patch) as ";
Adam Lesinski21efb682016-09-14 17:35:43 -0700573 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700574 switch (new_color_type) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575 case PNG_COLOR_TYPE_GRAY:
576 msg << "GRAY";
577 break;
578 case PNG_COLOR_TYPE_GRAY_ALPHA:
579 msg << "GRAY + ALPHA";
580 break;
581 case PNG_COLOR_TYPE_RGB:
582 msg << "RGB";
583 break;
584 case PNG_COLOR_TYPE_RGB_ALPHA:
585 msg << "RGBA";
586 break;
587 case PNG_COLOR_TYPE_PALETTE:
588 msg << "PALETTE";
589 break;
590 default:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700591 msg << "unknown type " << new_color_type;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700592 break;
Adam Lesinski21efb682016-09-14 17:35:43 -0700593 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700594 context->GetDiagnostics()->Note(msg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700595 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700596
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700597 png_set_IHDR(write_ptr, write_info_ptr, image->width, image->height, 8,
598 new_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700599 PNG_FILTER_TYPE_DEFAULT);
Adam Lesinski21efb682016-09-14 17:35:43 -0700600
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700601 if (new_color_type & PNG_COLOR_MASK_PALETTE) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700602 // Assigns indices to the palette, and writes the encoded palette to the
603 // libpng writePtr.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700604 WritePalette(write_ptr, write_info_ptr, &color_palette, &alpha_palette);
605 png_set_filter(write_ptr, 0, PNG_NO_FILTERS);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700606 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700607 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700609
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700610 if (nine_patch) {
611 WriteNinePatch(write_ptr, write_info_ptr, nine_patch);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700612 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700613
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700614 // Flush our updates to the header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700615 png_write_info(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616
617 // Write out each row of image data according to its encoding.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700618 if (new_color_type == PNG_COLOR_TYPE_PALETTE) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619 // 1 byte/pixel.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700620 auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700621
622 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700623 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700624 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700625 int rr = *in_row++;
626 int gg = *in_row++;
627 int bb = *in_row++;
628 int aa = *in_row++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700629 if (aa == 0) {
630 // Zero out color channels when transparent.
631 rr = gg = bb = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700632 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700633
634 const uint32_t color = rr << 24 | gg << 16 | bb << 8 | aa;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700635 const int idx = color_palette[color];
636 CHECK(idx != -1);
637 out_row[x] = static_cast<png_byte>(idx);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700638 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700639 png_write_row(write_ptr, out_row.get());
Adam Lesinski21efb682016-09-14 17:35:43 -0700640 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700641 } else if (new_color_type == PNG_COLOR_TYPE_GRAY ||
642 new_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
643 const size_t bpp = new_color_type == PNG_COLOR_TYPE_GRAY ? 1 : 2;
644 auto out_row =
645 std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700646
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700647 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700648 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700650 int rr = in_row[x * 4];
651 int gg = in_row[x * 4 + 1];
652 int bb = in_row[x * 4 + 2];
653 int aa = in_row[x * 4 + 3];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700654 if (aa == 0) {
655 // Zero out the gray channel when transparent.
656 rr = gg = bb = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700657 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700658
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700659 if (grayscale) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700660 // The image was already grayscale, red == green == blue.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700661 out_row[x * bpp] = in_row[x * 4];
Adam Lesinski21efb682016-09-14 17:35:43 -0700662 } else {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700663 // The image is convertible to grayscale, use linear-luminance of
664 // sRGB colorspace:
665 // https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700666 out_row[x * bpp] =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 (png_byte)(rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
Adam Lesinski21efb682016-09-14 17:35:43 -0700668 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700669
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 if (bpp == 2) {
671 // Write out alpha if we have it.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700672 out_row[x * bpp + 1] = aa;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673 }
674 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700675 png_write_row(write_ptr, out_row.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 }
Adam Lesinski06460ef2017-03-14 18:52:13 -0700677 } else if (new_color_type == PNG_COLOR_TYPE_RGB || new_color_type == PNG_COLOR_TYPE_RGBA) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700678 const size_t bpp = new_color_type == PNG_COLOR_TYPE_RGB ? 3 : 4;
679 if (needs_to_zero_rgb_channels_of_transparent_pixels) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 // The source RGBA data can't be used as-is, because we need to zero out
Adam Lesinski06460ef2017-03-14 18:52:13 -0700681 // the RGB values of transparent pixels.
682 auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683
684 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700685 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700686 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700687 int rr = *in_row++;
688 int gg = *in_row++;
689 int bb = *in_row++;
690 int aa = *in_row++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700691 if (aa == 0) {
692 // Zero out the RGB channels when transparent.
693 rr = gg = bb = 0;
694 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 out_row[x * bpp] = rr;
696 out_row[x * bpp + 1] = gg;
697 out_row[x * bpp + 2] = bb;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 if (bpp == 4) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 out_row[x * bpp + 3] = aa;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 }
701 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700702 png_write_row(write_ptr, out_row.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 }
704 } else {
705 // The source image can be used as-is, just tell libpng whether or not to
Adam Lesinski06460ef2017-03-14 18:52:13 -0700706 // ignore the alpha channel.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700707 if (new_color_type == PNG_COLOR_TYPE_RGB) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708 // Delete the extraneous alpha values that we appended to our buffer
709 // when reading the original values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700710 png_set_filler(write_ptr, 0, PNG_FILLER_AFTER);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700712 png_write_image(write_ptr, image->rows.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 }
714 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700715 LOG(FATAL) << "unreachable";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 }
717
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700718 png_write_end(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700719 return true;
Adam Lesinski21efb682016-09-14 17:35:43 -0700720}
721
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700722} // namespace aapt