blob: 0346a1982d8a13950632a0f66544590cb124835b [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 Lesinskicc73e992017-05-12 18:16:44 -070076
77 // Causes libpng to longjmp to the spot where setjmp was set. This is how libpng does
78 // error handling. If this custom error handler method were to return, libpng would, by
79 // default, print the error message to stdout and call the same png_longjmp method.
80 png_longjmp(png_ptr, 1);
Adam Lesinski21efb682016-09-14 17:35:43 -070081}
82
Adam Lesinski06460ef2017-03-14 18:52:13 -070083static void ReadDataFromStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070084 io::InputStream* in = (io::InputStream*)png_get_io_ptr(png_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -070085
Adam Lesinskice5e56e2016-10-21 17:56:45 -070086 const void* in_buffer;
Adam Lesinski06460ef2017-03-14 18:52:13 -070087 size_t in_len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070088 if (!in->Next(&in_buffer, &in_len)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070089 if (in->HadError()) {
Adam Lesinskicc73e992017-05-12 18:16:44 -070090 std::stringstream error_msg_builder;
91 error_msg_builder << "failed reading from input";
92 if (!in->GetError().empty()) {
93 error_msg_builder << ": " << in->GetError();
94 }
95 std::string err = error_msg_builder.str();
Adam Lesinskice5e56e2016-10-21 17:56:45 -070096 png_error(png_ptr, err.c_str());
Adam Lesinski21efb682016-09-14 17:35:43 -070097 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -070098 return;
99 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700100
Adam Lesinski06460ef2017-03-14 18:52:13 -0700101 const size_t bytes_read = std::min(in_len, len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700102 memcpy(buffer, in_buffer, bytes_read);
Adam Lesinski06460ef2017-03-14 18:52:13 -0700103 if (bytes_read != in_len) {
104 in->BackUp(in_len - bytes_read);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700105 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700106}
107
Adam Lesinski06460ef2017-03-14 18:52:13 -0700108static void WriteDataToStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700109 io::OutputStream* out = (io::OutputStream*)png_get_io_ptr(png_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700110
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700111 void* out_buffer;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700112 size_t out_len;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700113 while (len > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700114 if (!out->Next(&out_buffer, &out_len)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700115 if (out->HadError()) {
Adam Lesinskicc73e992017-05-12 18:16:44 -0700116 std::stringstream err_msg_builder;
117 err_msg_builder << "failed writing to output";
118 if (!out->GetError().empty()) {
119 err_msg_builder << ": " << out->GetError();
120 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 std::string err = out->GetError();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700122 png_error(png_ptr, err.c_str());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123 }
124 return;
Adam Lesinski21efb682016-09-14 17:35:43 -0700125 }
126
Adam Lesinski06460ef2017-03-14 18:52:13 -0700127 const size_t bytes_written = std::min(out_len, len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700128 memcpy(out_buffer, buffer, bytes_written);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700129
130 // Advance the input buffer.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700131 buffer += bytes_written;
132 len -= bytes_written;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700133
134 // Advance the output buffer.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700135 out_len -= bytes_written;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700136 }
137
138 // If the entire output buffer wasn't used, backup.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700139 if (out_len > 0) {
140 out->BackUp(out_len);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700141 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700142}
143
Adam Lesinskicc73e992017-05-12 18:16:44 -0700144std::unique_ptr<Image> ReadPng(IAaptContext* context, const Source& source, io::InputStream* in) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700145 // Create a diagnostics that has the source information encoded.
146 SourcePathDiagnostics source_diag(source, context->GetDiagnostics());
147
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700148 // Read the first 8 bytes of the file looking for the PNG signature.
149 // Bail early if it does not match.
150 const png_byte* signature;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700151 size_t buffer_size;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700152 if (!in->Next((const void**)&signature, &buffer_size)) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700153 if (in->HadError()) {
154 source_diag.Error(DiagMessage() << "failed to read PNG signature: " << in->GetError());
155 } else {
156 source_diag.Error(DiagMessage() << "not enough data for PNG signature");
157 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700158 return {};
159 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700160
Adam Lesinski06460ef2017-03-14 18:52:13 -0700161 if (buffer_size < kPngSignatureSize || png_sig_cmp(signature, 0, kPngSignatureSize) != 0) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700162 source_diag.Error(DiagMessage() << "file signature does not match PNG signature");
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 // Start at the beginning of the first chunk.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700167 in->BackUp(buffer_size - kPngSignatureSize);
Adam Lesinski21efb682016-09-14 17:35:43 -0700168
Adam Lesinski06460ef2017-03-14 18:52:13 -0700169 // Create and initialize the png_struct with the default error and warning handlers.
170 // The header version is also passed in to ensure that this was built against the same
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700171 // version of libpng.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700172 png_structp read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700173 if (read_ptr == nullptr) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700174 source_diag.Error(DiagMessage() << "failed to create libpng read png_struct");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700175 return {};
176 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700177
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700178 // Create and initialize the memory for image header and data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700179 png_infop info_ptr = png_create_info_struct(read_ptr);
180 if (info_ptr == nullptr) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700181 source_diag.Error(DiagMessage() << "failed to create libpng read png_info");
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700182 png_destroy_read_struct(&read_ptr, nullptr, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700183 return {};
184 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700185
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700186 // Automatically release PNG resources at end of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700187 PngReadStructDeleter png_read_deleter(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700188
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700189 // libpng uses longjmp to jump to an error handling routine.
190 // setjmp will only return true if it was jumped to, aka there was
191 // an error.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700192 if (setjmp(png_jmpbuf(read_ptr))) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700193 return {};
194 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700195
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700196 // Handle warnings ourselves via IDiagnostics.
Adam Lesinskicc73e992017-05-12 18:16:44 -0700197 png_set_error_fn(read_ptr, (png_voidp)&source_diag, LogError, LogWarning);
Adam Lesinski21efb682016-09-14 17:35:43 -0700198
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700199 // Set up the read functions which read from our custom data sources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700200 png_set_read_fn(read_ptr, (png_voidp)in, ReadDataFromStream);
Adam Lesinski21efb682016-09-14 17:35:43 -0700201
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700202 // Skip the signature that we already read.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700203 png_set_sig_bytes(read_ptr, kPngSignatureSize);
Adam Lesinski21efb682016-09-14 17:35:43 -0700204
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700205 // Read the chunk headers.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700206 png_read_info(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700207
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700208 // Extract image meta-data from the various chunk headers.
209 uint32_t width, height;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700210 int bit_depth, color_type, interlace_method, compression_method, filter_method;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700211 png_get_IHDR(read_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
212 &interlace_method, &compression_method, &filter_method);
Adam Lesinski21efb682016-09-14 17:35:43 -0700213
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700214 // When the image is read, expand it so that it is in RGBA 8888 format
215 // so that image handling is uniform.
Adam Lesinski21efb682016-09-14 17:35:43 -0700216
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700217 if (color_type == PNG_COLOR_TYPE_PALETTE) {
218 png_set_palette_to_rgb(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700219 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700220
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700221 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
222 png_set_expand_gray_1_2_4_to_8(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700223 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700224
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700225 if (png_get_valid(read_ptr, info_ptr, PNG_INFO_tRNS)) {
226 png_set_tRNS_to_alpha(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700227 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700228
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700229 if (bit_depth == 16) {
230 png_set_strip_16(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700231 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700232
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700233 if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
234 png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700235 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700236
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700237 if (color_type == PNG_COLOR_TYPE_GRAY ||
238 color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
239 png_set_gray_to_rgb(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700240 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700241
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700242 if (interlace_method != PNG_INTERLACE_NONE) {
243 png_set_interlace_handling(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700244 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700245
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700246 // Once all the options for reading have been set, we need to flush
247 // them to libpng.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700248 png_read_update_info(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700249
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700250 // 9-patch uses int32_t to index images, so we cap the image dimensions to
251 // something
252 // that can always be represented by 9-patch.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700253 if (width > std::numeric_limits<int32_t>::max() || height > std::numeric_limits<int32_t>::max()) {
Adam Lesinskicc73e992017-05-12 18:16:44 -0700254 source_diag.Error(DiagMessage()
255 << "PNG image dimensions are too large: " << width << "x" << height);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700256 return {};
257 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700258
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700259 std::unique_ptr<Image> output_image = util::make_unique<Image>();
260 output_image->width = static_cast<int32_t>(width);
261 output_image->height = static_cast<int32_t>(height);
Adam Lesinski21efb682016-09-14 17:35:43 -0700262
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700263 const size_t row_bytes = png_get_rowbytes(read_ptr, info_ptr);
264 CHECK(row_bytes == 4 * width); // RGBA
Adam Lesinski21efb682016-09-14 17:35:43 -0700265
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700266 // Allocate one large block to hold the image.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700267 output_image->data = std::unique_ptr<uint8_t[]>(new uint8_t[height * row_bytes]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700268
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700269 // Create an array of rows that index into the data block.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700270 output_image->rows = std::unique_ptr<uint8_t* []>(new uint8_t*[height]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700271 for (uint32_t h = 0; h < height; h++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700272 output_image->rows[h] = output_image->data.get() + (h * row_bytes);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700273 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700274
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700275 // Actually read the image pixels.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700276 png_read_image(read_ptr, output_image->rows.get());
Adam Lesinski21efb682016-09-14 17:35:43 -0700277
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700278 // Finish reading. This will read any other chunks after the image data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700279 png_read_end(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700280
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700281 return output_image;
Adam Lesinski21efb682016-09-14 17:35:43 -0700282}
283
Adam Lesinski06460ef2017-03-14 18:52:13 -0700284// Experimentally chosen constant to be added to the overhead of using color type
285// PNG_COLOR_TYPE_PALETTE to account for the uncompressability of the palette chunk.
286// Without this, many small PNGs encoded with palettes are larger after compression than
287// the same PNGs encoded as RGBA.
Adam Lesinski21efb682016-09-14 17:35:43 -0700288constexpr static const size_t kPaletteOverheadConstant = 1024u * 10u;
289
Adam Lesinski06460ef2017-03-14 18:52:13 -0700290// Pick a color type by which to encode the image, based on which color type will take
Adam Lesinski21efb682016-09-14 17:35:43 -0700291// the least amount of disk space.
292//
293// 9-patch images traditionally have not been encoded with palettes.
294// The original rationale was to avoid dithering until after scaling,
295// but I don't think this would be an issue with palettes. Either way,
296// our naive size estimation tends to be wrong for small images like 9-patches
297// and using palettes balloons the size of the resulting 9-patch.
298// In order to not regress in size, restrict 9-patch to not use palettes.
299
300// The options are:
301//
302// - RGB
303// - RGBA
304// - RGB + cheap alpha
305// - Color palette
306// - Color palette + cheap alpha
307// - Color palette + alpha palette
308// - Grayscale
309// - Grayscale + cheap alpha
310// - Grayscale + alpha
311//
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700312static int PickColorType(int32_t width, int32_t height, bool grayscale,
313 bool convertible_to_grayscale, bool has_nine_patch,
314 size_t color_palette_size, size_t alpha_palette_size) {
315 const size_t palette_chunk_size = 16 + color_palette_size * 3;
316 const size_t alpha_chunk_size = 16 + alpha_palette_size;
317 const size_t color_alpha_data_chunk_size = 16 + 4 * width * height;
318 const size_t color_data_chunk_size = 16 + 3 * width * height;
319 const size_t grayscale_alpha_data_chunk_size = 16 + 2 * width * height;
320 const size_t palette_data_chunk_size = 16 + width * height;
Adam Lesinski21efb682016-09-14 17:35:43 -0700321
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700322 if (grayscale) {
323 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700324 // This is the smallest the data can be.
325 return PNG_COLOR_TYPE_GRAY;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700326 } else if (color_palette_size <= 256 && !has_nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700327 // This grayscale has alpha and can fit within a palette.
328 // See if it is worth fitting into a palette.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700329 const size_t palette_threshold = palette_chunk_size + alpha_chunk_size +
330 palette_data_chunk_size +
331 kPaletteOverheadConstant;
332 if (grayscale_alpha_data_chunk_size > palette_threshold) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700333 return PNG_COLOR_TYPE_PALETTE;
334 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700335 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700336 return PNG_COLOR_TYPE_GRAY_ALPHA;
337 }
338
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700339 if (color_palette_size <= 256 && !has_nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700340 // This image can fit inside a palette. Let's see if it is worth it.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700341 size_t total_size_with_palette =
342 palette_data_chunk_size + palette_chunk_size;
343 size_t total_size_without_palette = color_data_chunk_size;
344 if (alpha_palette_size > 0) {
345 total_size_with_palette += alpha_palette_size;
346 total_size_without_palette = color_alpha_data_chunk_size;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700347 }
348
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700349 if (total_size_without_palette >
350 total_size_with_palette + kPaletteOverheadConstant) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700351 return PNG_COLOR_TYPE_PALETTE;
352 }
353 }
354
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700355 if (convertible_to_grayscale) {
356 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700357 return PNG_COLOR_TYPE_GRAY;
358 } else {
359 return PNG_COLOR_TYPE_GRAY_ALPHA;
360 }
361 }
362
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700363 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 return PNG_COLOR_TYPE_RGB;
365 }
366 return PNG_COLOR_TYPE_RGBA;
Adam Lesinski21efb682016-09-14 17:35:43 -0700367}
368
Adam Lesinski06460ef2017-03-14 18:52:13 -0700369// Assigns indices to the color and alpha palettes, encodes them, and then invokes
Adam Lesinski21efb682016-09-14 17:35:43 -0700370// png_set_PLTE/png_set_tRNS.
371// This must be done before writing image data.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700372// Image data must be transformed to use the indices assigned within the palette.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700373static void WritePalette(png_structp write_ptr, png_infop write_info_ptr,
374 std::unordered_map<uint32_t, int>* color_palette,
375 std::unordered_set<uint32_t>* alpha_palette) {
376 CHECK(color_palette->size() <= 256);
377 CHECK(alpha_palette->size() <= 256);
Adam Lesinski21efb682016-09-14 17:35:43 -0700378
Adam Lesinski06460ef2017-03-14 18:52:13 -0700379 // Populate the PNG palette struct and assign indices to the color palette.
Adam Lesinski21efb682016-09-14 17:35:43 -0700380
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700381 // Colors in the alpha palette should have smaller indices.
382 // This will ensure that we can truncate the alpha palette if it is
383 // smaller than the color palette.
384 int index = 0;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700385 for (uint32_t color : *alpha_palette) {
386 (*color_palette)[color] = index++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700387 }
388
389 // Assign the rest of the entries.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700390 for (auto& entry : *color_palette) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700391 if (entry.second == -1) {
392 entry.second = index++;
Adam Lesinski21efb682016-09-14 17:35:43 -0700393 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700394 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700395
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700396 // Create the PNG color palette struct.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700397 auto color_palette_bytes = std::unique_ptr<png_color[]>(new png_color[color_palette->size()]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700398
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700399 std::unique_ptr<png_byte[]> alpha_palette_bytes;
400 if (!alpha_palette->empty()) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700401 alpha_palette_bytes = std::unique_ptr<png_byte[]>(new png_byte[alpha_palette->size()]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700402 }
403
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700404 for (const auto& entry : *color_palette) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700405 const uint32_t color = entry.first;
406 const int index = entry.second;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700407 CHECK(index >= 0);
408 CHECK(static_cast<size_t>(index) < color_palette->size());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700409
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700410 png_colorp slot = color_palette_bytes.get() + index;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700411 slot->red = color >> 24;
412 slot->green = color >> 16;
413 slot->blue = color >> 8;
414
415 const png_byte alpha = color & 0x000000ff;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700416 if (alpha != 0xff && alpha_palette_bytes) {
417 CHECK(static_cast<size_t>(index) < alpha_palette->size());
418 alpha_palette_bytes[index] = alpha;
Adam Lesinski21efb682016-09-14 17:35:43 -0700419 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700420 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700421
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700422 // The bytes get copied here, so it is safe to release color_palette_bytes at
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700423 // the end of function
424 // scope.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700425 png_set_PLTE(write_ptr, write_info_ptr, color_palette_bytes.get(), color_palette->size());
Adam Lesinski21efb682016-09-14 17:35:43 -0700426
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700427 if (alpha_palette_bytes) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700428 png_set_tRNS(write_ptr, write_info_ptr, alpha_palette_bytes.get(), alpha_palette->size(),
429 nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700430 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700431}
432
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700433// Write the 9-patch custom PNG chunks to write_info_ptr. This must be done
Adam Lesinski06460ef2017-03-14 18:52:13 -0700434// before writing image data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700435static void WriteNinePatch(png_structp write_ptr, png_infop write_info_ptr,
436 const NinePatch* nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700437 // The order of the chunks is important.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700438 // 9-patch code in older platforms expects the 9-patch chunk to be last.
Adam Lesinski21efb682016-09-14 17:35:43 -0700439
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700440 png_unknown_chunk unknown_chunks[3];
441 memset(unknown_chunks, 0, sizeof(unknown_chunks));
Adam Lesinski21efb682016-09-14 17:35:43 -0700442
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700443 size_t index = 0;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700444 size_t chunk_len = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700445
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700446 std::unique_ptr<uint8_t[]> serialized_outline =
447 nine_patch->SerializeRoundedRectOutline(&chunk_len);
448 strcpy((char*)unknown_chunks[index].name, "npOl");
449 unknown_chunks[index].size = chunk_len;
450 unknown_chunks[index].data = (png_bytep)serialized_outline.get();
451 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700452 index++;
453
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700454 std::unique_ptr<uint8_t[]> serialized_layout_bounds;
455 if (nine_patch->layout_bounds.nonZero()) {
456 serialized_layout_bounds = nine_patch->SerializeLayoutBounds(&chunk_len);
457 strcpy((char*)unknown_chunks[index].name, "npLb");
458 unknown_chunks[index].size = chunk_len;
459 unknown_chunks[index].data = (png_bytep)serialized_layout_bounds.get();
460 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinski21efb682016-09-14 17:35:43 -0700461 index++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700462 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700463
Adam Lesinski06460ef2017-03-14 18:52:13 -0700464 std::unique_ptr<uint8_t[]> serialized_nine_patch = nine_patch->SerializeBase(&chunk_len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700465 strcpy((char*)unknown_chunks[index].name, "npTc");
466 unknown_chunks[index].size = chunk_len;
467 unknown_chunks[index].data = (png_bytep)serialized_nine_patch.get();
468 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700469 index++;
Adam Lesinski21efb682016-09-14 17:35:43 -0700470
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700471 // Handle all unknown chunks. We are manually setting the chunks here,
472 // so we will only ever handle our custom chunks.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700473 png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS, nullptr, 0);
Adam Lesinski21efb682016-09-14 17:35:43 -0700474
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700475 // Set the actual chunks here. The data gets copied, so our buffers can
476 // safely go out of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700477 png_set_unknown_chunks(write_ptr, write_info_ptr, unknown_chunks, index);
Adam Lesinski21efb682016-09-14 17:35:43 -0700478}
479
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700480bool WritePng(IAaptContext* context, const Image* image,
481 const NinePatch* nine_patch, io::OutputStream* out,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700482 const PngOptions& options) {
483 // Create and initialize the write png_struct with the default error and
484 // warning handlers.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700485 // The header version is also passed in to ensure that this was built against the same
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700486 // version of libpng.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700487 png_structp write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700488 if (write_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700489 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng write png_struct");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700490 return false;
491 }
492
493 // Allocate memory to store image header data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700494 png_infop write_info_ptr = png_create_info_struct(write_ptr);
495 if (write_info_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700496 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng write png_info");
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700497 png_destroy_write_struct(&write_ptr, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700498 return false;
499 }
500
501 // Automatically release PNG resources at end of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700502 PngWriteStructDeleter png_write_deleter(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700503
504 // libpng uses longjmp to jump to error handling routines.
505 // setjmp will return true only if it was jumped to, aka, there was an error.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700506 if (setjmp(png_jmpbuf(write_ptr))) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700507 return false;
508 }
509
510 // Handle warnings with our IDiagnostics.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700511 png_set_error_fn(write_ptr, (png_voidp)context->GetDiagnostics(), LogError, LogWarning);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700512
513 // Set up the write functions which write to our custom data sources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700514 png_set_write_fn(write_ptr, (png_voidp)out, WriteDataToStream, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700515
516 // We want small files and can take the performance hit to achieve this goal.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700517 png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700518
519 // Begin analysis of the image data.
520 // Scan the entire image and determine if:
521 // 1. Every pixel has R == G == B (grayscale)
522 // 2. Every pixel has A == 255 (opaque)
523 // 3. There are no more than 256 distinct RGBA colors (palette).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700524 std::unordered_map<uint32_t, int> color_palette;
525 std::unordered_set<uint32_t> alpha_palette;
526 bool needs_to_zero_rgb_channels_of_transparent_pixels = false;
527 bool grayscale = true;
528 int max_gray_deviation = 0;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529
530 for (int32_t y = 0; y < image->height; y++) {
531 const uint8_t* row = image->rows[y];
532 for (int32_t x = 0; x < image->width; x++) {
533 int red = *row++;
534 int green = *row++;
535 int blue = *row++;
536 int alpha = *row++;
537
538 if (alpha == 0) {
539 // The color is completely transparent.
540 // For purposes of palettes and grayscale optimization,
541 // treat all channels as 0x00.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700542 needs_to_zero_rgb_channels_of_transparent_pixels =
543 needs_to_zero_rgb_channels_of_transparent_pixels ||
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 (red != 0 || green != 0 || blue != 0);
545 red = green = blue = 0;
546 }
547
548 // Insert the color into the color palette.
549 const uint32_t color = red << 24 | green << 16 | blue << 8 | alpha;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700550 color_palette[color] = -1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551
552 // If the pixel has non-opaque alpha, insert it into the
553 // alpha palette.
554 if (alpha != 0xff) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700555 alpha_palette.insert(color);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700556 }
557
558 // Check if the image is indeed grayscale.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700559 if (grayscale) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560 if (red != green || red != blue) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700561 grayscale = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562 }
563 }
564
565 // Calculate the gray scale deviation so that it can be compared
566 // with the threshold.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700567 max_gray_deviation = std::max(std::abs(red - green), max_gray_deviation);
568 max_gray_deviation = std::max(std::abs(green - blue), max_gray_deviation);
569 max_gray_deviation = std::max(std::abs(blue - red), max_gray_deviation);
Adam Lesinski21efb682016-09-14 17:35:43 -0700570 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700571 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700572
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700573 if (context->IsVerbose()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574 DiagMessage msg;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700575 msg << " paletteSize=" << color_palette.size()
576 << " alphaPaletteSize=" << alpha_palette.size()
577 << " maxGrayDeviation=" << max_gray_deviation
578 << " grayScale=" << (grayscale ? "true" : "false");
579 context->GetDiagnostics()->Note(msg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700580 }
581
Adam Lesinski06460ef2017-03-14 18:52:13 -0700582 const bool convertible_to_grayscale = max_gray_deviation <= options.grayscale_tolerance;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700583
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700584 const int new_color_type = PickColorType(
585 image->width, image->height, grayscale, convertible_to_grayscale,
586 nine_patch != nullptr, color_palette.size(), alpha_palette.size());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700587
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700588 if (context->IsVerbose()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700589 DiagMessage msg;
590 msg << "encoding PNG ";
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700591 if (nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700592 msg << "(with 9-patch) as ";
Adam Lesinski21efb682016-09-14 17:35:43 -0700593 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700594 switch (new_color_type) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700595 case PNG_COLOR_TYPE_GRAY:
596 msg << "GRAY";
597 break;
598 case PNG_COLOR_TYPE_GRAY_ALPHA:
599 msg << "GRAY + ALPHA";
600 break;
601 case PNG_COLOR_TYPE_RGB:
602 msg << "RGB";
603 break;
604 case PNG_COLOR_TYPE_RGB_ALPHA:
605 msg << "RGBA";
606 break;
607 case PNG_COLOR_TYPE_PALETTE:
608 msg << "PALETTE";
609 break;
610 default:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700611 msg << "unknown type " << new_color_type;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700612 break;
Adam Lesinski21efb682016-09-14 17:35:43 -0700613 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700614 context->GetDiagnostics()->Note(msg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700615 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700616
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700617 png_set_IHDR(write_ptr, write_info_ptr, image->width, image->height, 8,
618 new_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619 PNG_FILTER_TYPE_DEFAULT);
Adam Lesinski21efb682016-09-14 17:35:43 -0700620
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700621 if (new_color_type & PNG_COLOR_MASK_PALETTE) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700622 // Assigns indices to the palette, and writes the encoded palette to the
623 // libpng writePtr.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700624 WritePalette(write_ptr, write_info_ptr, &color_palette, &alpha_palette);
625 png_set_filter(write_ptr, 0, PNG_NO_FILTERS);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700626 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700627 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700628 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700629
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700630 if (nine_patch) {
631 WriteNinePatch(write_ptr, write_info_ptr, nine_patch);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700633
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700634 // Flush our updates to the header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700635 png_write_info(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700636
637 // Write out each row of image data according to its encoding.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700638 if (new_color_type == PNG_COLOR_TYPE_PALETTE) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700639 // 1 byte/pixel.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700640 auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700641
642 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700643 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700644 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700645 int rr = *in_row++;
646 int gg = *in_row++;
647 int bb = *in_row++;
648 int aa = *in_row++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649 if (aa == 0) {
650 // Zero out color channels when transparent.
651 rr = gg = bb = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700652 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653
654 const uint32_t color = rr << 24 | gg << 16 | bb << 8 | aa;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700655 const int idx = color_palette[color];
656 CHECK(idx != -1);
657 out_row[x] = static_cast<png_byte>(idx);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700658 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700659 png_write_row(write_ptr, out_row.get());
Adam Lesinski21efb682016-09-14 17:35:43 -0700660 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700661 } else if (new_color_type == PNG_COLOR_TYPE_GRAY ||
662 new_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
663 const size_t bpp = new_color_type == PNG_COLOR_TYPE_GRAY ? 1 : 2;
664 auto out_row =
665 std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700666
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700668 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700669 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700670 int rr = in_row[x * 4];
671 int gg = in_row[x * 4 + 1];
672 int bb = in_row[x * 4 + 2];
673 int aa = in_row[x * 4 + 3];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700674 if (aa == 0) {
675 // Zero out the gray channel when transparent.
676 rr = gg = bb = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700677 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700678
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700679 if (grayscale) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 // The image was already grayscale, red == green == blue.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700681 out_row[x * bpp] = in_row[x * 4];
Adam Lesinski21efb682016-09-14 17:35:43 -0700682 } else {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683 // The image is convertible to grayscale, use linear-luminance of
684 // sRGB colorspace:
685 // https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700686 out_row[x * bpp] =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700687 (png_byte)(rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
Adam Lesinski21efb682016-09-14 17:35:43 -0700688 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700689
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700690 if (bpp == 2) {
691 // Write out alpha if we have it.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700692 out_row[x * bpp + 1] = aa;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 }
694 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 png_write_row(write_ptr, out_row.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696 }
Adam Lesinski06460ef2017-03-14 18:52:13 -0700697 } else if (new_color_type == PNG_COLOR_TYPE_RGB || new_color_type == PNG_COLOR_TYPE_RGBA) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700698 const size_t bpp = new_color_type == PNG_COLOR_TYPE_RGB ? 3 : 4;
699 if (needs_to_zero_rgb_channels_of_transparent_pixels) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 // The source RGBA data can't be used as-is, because we need to zero out
Adam Lesinski06460ef2017-03-14 18:52:13 -0700701 // the RGB values of transparent pixels.
702 auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703
704 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700705 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700707 int rr = *in_row++;
708 int gg = *in_row++;
709 int bb = *in_row++;
710 int aa = *in_row++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711 if (aa == 0) {
712 // Zero out the RGB channels when transparent.
713 rr = gg = bb = 0;
714 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700715 out_row[x * bpp] = rr;
716 out_row[x * bpp + 1] = gg;
717 out_row[x * bpp + 2] = bb;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700718 if (bpp == 4) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700719 out_row[x * bpp + 3] = aa;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700720 }
721 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700722 png_write_row(write_ptr, out_row.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700723 }
724 } else {
725 // The source image can be used as-is, just tell libpng whether or not to
Adam Lesinski06460ef2017-03-14 18:52:13 -0700726 // ignore the alpha channel.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700727 if (new_color_type == PNG_COLOR_TYPE_RGB) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700728 // Delete the extraneous alpha values that we appended to our buffer
729 // when reading the original values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700730 png_set_filler(write_ptr, 0, PNG_FILLER_AFTER);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700732 png_write_image(write_ptr, image->rows.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700733 }
734 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700735 LOG(FATAL) << "unreachable";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 }
737
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700738 png_write_end(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700739 return true;
Adam Lesinski21efb682016-09-14 17:35:43 -0700740}
741
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742} // namespace aapt