blob: 1f4ea44d9f869308967b192752731ed76e2f79b0 [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
Fabien Sanglard2d34e762019-02-21 15:13:29 -080030#include "trace/TraceBuffer.h"
31
Adam Lesinski21efb682016-09-14 17:35:43 -070032namespace aapt {
33
Adam Lesinski06460ef2017-03-14 18:52:13 -070034// Custom deleter that destroys libpng read and info structs.
Adam Lesinski21efb682016-09-14 17:35:43 -070035class PngReadStructDeleter {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070036 public:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070037 PngReadStructDeleter(png_structp read_ptr, png_infop info_ptr)
38 : read_ptr_(read_ptr), info_ptr_(info_ptr) {}
Adam Lesinski21efb682016-09-14 17:35:43 -070039
Adam Lesinskicacb28f2016-10-19 12:18:14 -070040 ~PngReadStructDeleter() {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070041 png_destroy_read_struct(&read_ptr_, &info_ptr_, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -070042 }
Adam Lesinski21efb682016-09-14 17:35:43 -070043
Adam Lesinskicacb28f2016-10-19 12:18:14 -070044 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070045 png_structp read_ptr_;
46 png_infop info_ptr_;
Adam Lesinski21efb682016-09-14 17:35:43 -070047
Adam Lesinskicacb28f2016-10-19 12:18:14 -070048 DISALLOW_COPY_AND_ASSIGN(PngReadStructDeleter);
Adam Lesinski21efb682016-09-14 17:35:43 -070049};
50
Adam Lesinski06460ef2017-03-14 18:52:13 -070051// Custom deleter that destroys libpng write and info structs.
Adam Lesinski21efb682016-09-14 17:35:43 -070052class PngWriteStructDeleter {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070053 public:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070054 PngWriteStructDeleter(png_structp write_ptr, png_infop info_ptr)
55 : write_ptr_(write_ptr), info_ptr_(info_ptr) {}
Adam Lesinski21efb682016-09-14 17:35:43 -070056
Adam Lesinskice5e56e2016-10-21 17:56:45 -070057 ~PngWriteStructDeleter() {
58 png_destroy_write_struct(&write_ptr_, &info_ptr_);
59 }
Adam Lesinski21efb682016-09-14 17:35:43 -070060
Adam Lesinskicacb28f2016-10-19 12:18:14 -070061 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -070062 png_structp write_ptr_;
63 png_infop info_ptr_;
Adam Lesinski21efb682016-09-14 17:35:43 -070064
Adam Lesinskicacb28f2016-10-19 12:18:14 -070065 DISALLOW_COPY_AND_ASSIGN(PngWriteStructDeleter);
Adam Lesinski21efb682016-09-14 17:35:43 -070066};
67
68// Custom warning logging method that uses IDiagnostics.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070069static void LogWarning(png_structp png_ptr, png_const_charp warning_msg) {
70 IDiagnostics* diag = (IDiagnostics*)png_get_error_ptr(png_ptr);
71 diag->Warn(DiagMessage() << warning_msg);
Adam Lesinski21efb682016-09-14 17:35:43 -070072}
73
74// Custom error logging method that uses IDiagnostics.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070075static void LogError(png_structp png_ptr, png_const_charp error_msg) {
76 IDiagnostics* diag = (IDiagnostics*)png_get_error_ptr(png_ptr);
77 diag->Error(DiagMessage() << error_msg);
Adam Lesinskicc73e992017-05-12 18:16:44 -070078
79 // Causes libpng to longjmp to the spot where setjmp was set. This is how libpng does
80 // error handling. If this custom error handler method were to return, libpng would, by
81 // default, print the error message to stdout and call the same png_longjmp method.
82 png_longjmp(png_ptr, 1);
Adam Lesinski21efb682016-09-14 17:35:43 -070083}
84
Adam Lesinski06460ef2017-03-14 18:52:13 -070085static void ReadDataFromStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070086 io::InputStream* in = (io::InputStream*)png_get_io_ptr(png_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -070087
Adam Lesinskice5e56e2016-10-21 17:56:45 -070088 const void* in_buffer;
Adam Lesinski06460ef2017-03-14 18:52:13 -070089 size_t in_len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070090 if (!in->Next(&in_buffer, &in_len)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070091 if (in->HadError()) {
Adam Lesinskicc73e992017-05-12 18:16:44 -070092 std::stringstream error_msg_builder;
93 error_msg_builder << "failed reading from input";
94 if (!in->GetError().empty()) {
95 error_msg_builder << ": " << in->GetError();
96 }
97 std::string err = error_msg_builder.str();
Adam Lesinskice5e56e2016-10-21 17:56:45 -070098 png_error(png_ptr, err.c_str());
Adam Lesinski21efb682016-09-14 17:35:43 -070099 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700100 return;
101 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700102
Adam Lesinski06460ef2017-03-14 18:52:13 -0700103 const size_t bytes_read = std::min(in_len, len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 memcpy(buffer, in_buffer, bytes_read);
Adam Lesinski06460ef2017-03-14 18:52:13 -0700105 if (bytes_read != in_len) {
106 in->BackUp(in_len - bytes_read);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700107 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700108}
109
Adam Lesinski06460ef2017-03-14 18:52:13 -0700110static void WriteDataToStream(png_structp png_ptr, png_bytep buffer, png_size_t len) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700111 io::OutputStream* out = (io::OutputStream*)png_get_io_ptr(png_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700112
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 void* out_buffer;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700114 size_t out_len;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700115 while (len > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700116 if (!out->Next(&out_buffer, &out_len)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700117 if (out->HadError()) {
Adam Lesinskicc73e992017-05-12 18:16:44 -0700118 std::stringstream err_msg_builder;
119 err_msg_builder << "failed writing to output";
120 if (!out->GetError().empty()) {
121 err_msg_builder << ": " << out->GetError();
122 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123 std::string err = out->GetError();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700124 png_error(png_ptr, err.c_str());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700125 }
126 return;
Adam Lesinski21efb682016-09-14 17:35:43 -0700127 }
128
Adam Lesinski06460ef2017-03-14 18:52:13 -0700129 const size_t bytes_written = std::min(out_len, len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700130 memcpy(out_buffer, buffer, bytes_written);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700131
132 // Advance the input buffer.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700133 buffer += bytes_written;
134 len -= bytes_written;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700135
136 // Advance the output buffer.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700137 out_len -= bytes_written;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700138 }
139
140 // If the entire output buffer wasn't used, backup.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700141 if (out_len > 0) {
142 out->BackUp(out_len);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700143 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700144}
145
Adam Lesinskicc73e992017-05-12 18:16:44 -0700146std::unique_ptr<Image> ReadPng(IAaptContext* context, const Source& source, io::InputStream* in) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800147 TRACE_CALL();
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700148 // Create a diagnostics that has the source information encoded.
149 SourcePathDiagnostics source_diag(source, context->GetDiagnostics());
150
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700151 // Read the first 8 bytes of the file looking for the PNG signature.
152 // Bail early if it does not match.
153 const png_byte* signature;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700154 size_t buffer_size;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700155 if (!in->Next((const void**)&signature, &buffer_size)) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700156 if (in->HadError()) {
157 source_diag.Error(DiagMessage() << "failed to read PNG signature: " << in->GetError());
158 } else {
159 source_diag.Error(DiagMessage() << "not enough data for PNG signature");
160 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700161 return {};
162 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700163
Adam Lesinski06460ef2017-03-14 18:52:13 -0700164 if (buffer_size < kPngSignatureSize || png_sig_cmp(signature, 0, kPngSignatureSize) != 0) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700165 source_diag.Error(DiagMessage() << "file signature does not match PNG signature");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700166 return {};
167 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700168
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700169 // Start at the beginning of the first chunk.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700170 in->BackUp(buffer_size - kPngSignatureSize);
Adam Lesinski21efb682016-09-14 17:35:43 -0700171
Adam Lesinski06460ef2017-03-14 18:52:13 -0700172 // Create and initialize the png_struct with the default error and warning handlers.
173 // The header version is also passed in to ensure that this was built against the same
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700174 // version of libpng.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700175 png_structp read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700176 if (read_ptr == nullptr) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700177 source_diag.Error(DiagMessage() << "failed to create libpng read png_struct");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700178 return {};
179 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700180
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700181 // Create and initialize the memory for image header and data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700182 png_infop info_ptr = png_create_info_struct(read_ptr);
183 if (info_ptr == nullptr) {
Adam Lesinski60d9c2f2017-05-17 16:07:45 -0700184 source_diag.Error(DiagMessage() << "failed to create libpng read png_info");
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700185 png_destroy_read_struct(&read_ptr, nullptr, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700186 return {};
187 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700188
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700189 // Automatically release PNG resources at end of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700190 PngReadStructDeleter png_read_deleter(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700191
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700192 // libpng uses longjmp to jump to an error handling routine.
193 // setjmp will only return true if it was jumped to, aka there was
194 // an error.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700195 if (setjmp(png_jmpbuf(read_ptr))) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700196 return {};
197 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700198
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700199 // Handle warnings ourselves via IDiagnostics.
Adam Lesinskicc73e992017-05-12 18:16:44 -0700200 png_set_error_fn(read_ptr, (png_voidp)&source_diag, LogError, LogWarning);
Adam Lesinski21efb682016-09-14 17:35:43 -0700201
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700202 // Set up the read functions which read from our custom data sources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700203 png_set_read_fn(read_ptr, (png_voidp)in, ReadDataFromStream);
Adam Lesinski21efb682016-09-14 17:35:43 -0700204
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700205 // Skip the signature that we already read.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700206 png_set_sig_bytes(read_ptr, kPngSignatureSize);
Adam Lesinski21efb682016-09-14 17:35:43 -0700207
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700208 // Read the chunk headers.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700209 png_read_info(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700210
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700211 // Extract image meta-data from the various chunk headers.
212 uint32_t width, height;
Adam Lesinski06460ef2017-03-14 18:52:13 -0700213 int bit_depth, color_type, interlace_method, compression_method, filter_method;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700214 png_get_IHDR(read_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
215 &interlace_method, &compression_method, &filter_method);
Adam Lesinski21efb682016-09-14 17:35:43 -0700216
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700217 // When the image is read, expand it so that it is in RGBA 8888 format
218 // so that image handling is uniform.
Adam Lesinski21efb682016-09-14 17:35:43 -0700219
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700220 if (color_type == PNG_COLOR_TYPE_PALETTE) {
221 png_set_palette_to_rgb(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700222 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700223
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700224 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
225 png_set_expand_gray_1_2_4_to_8(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700226 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700227
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700228 if (png_get_valid(read_ptr, info_ptr, PNG_INFO_tRNS)) {
229 png_set_tRNS_to_alpha(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700230 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700231
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700232 if (bit_depth == 16) {
233 png_set_strip_16(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700234 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700235
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700236 if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
237 png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700238 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700239
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700240 if (color_type == PNG_COLOR_TYPE_GRAY ||
241 color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
242 png_set_gray_to_rgb(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700243 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700244
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700245 if (interlace_method != PNG_INTERLACE_NONE) {
246 png_set_interlace_handling(read_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700247 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700248
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700249 // Once all the options for reading have been set, we need to flush
250 // them to libpng.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700251 png_read_update_info(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700252
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700253 // 9-patch uses int32_t to index images, so we cap the image dimensions to
254 // something
255 // that can always be represented by 9-patch.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700256 if (width > std::numeric_limits<int32_t>::max() || height > std::numeric_limits<int32_t>::max()) {
Adam Lesinskicc73e992017-05-12 18:16:44 -0700257 source_diag.Error(DiagMessage()
258 << "PNG image dimensions are too large: " << width << "x" << height);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700259 return {};
260 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700261
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700262 std::unique_ptr<Image> output_image = util::make_unique<Image>();
263 output_image->width = static_cast<int32_t>(width);
264 output_image->height = static_cast<int32_t>(height);
Adam Lesinski21efb682016-09-14 17:35:43 -0700265
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700266 const size_t row_bytes = png_get_rowbytes(read_ptr, info_ptr);
267 CHECK(row_bytes == 4 * width); // RGBA
Adam Lesinski21efb682016-09-14 17:35:43 -0700268
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700269 // Allocate one large block to hold the image.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700270 output_image->data = std::unique_ptr<uint8_t[]>(new uint8_t[height * row_bytes]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700271
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700272 // Create an array of rows that index into the data block.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700273 output_image->rows = std::unique_ptr<uint8_t* []>(new uint8_t*[height]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700274 for (uint32_t h = 0; h < height; h++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700275 output_image->rows[h] = output_image->data.get() + (h * row_bytes);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700276 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700277
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700278 // Actually read the image pixels.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700279 png_read_image(read_ptr, output_image->rows.get());
Adam Lesinski21efb682016-09-14 17:35:43 -0700280
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700281 // Finish reading. This will read any other chunks after the image data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700282 png_read_end(read_ptr, info_ptr);
Adam Lesinski21efb682016-09-14 17:35:43 -0700283
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700284 return output_image;
Adam Lesinski21efb682016-09-14 17:35:43 -0700285}
286
Adam Lesinski06460ef2017-03-14 18:52:13 -0700287// Experimentally chosen constant to be added to the overhead of using color type
288// PNG_COLOR_TYPE_PALETTE to account for the uncompressability of the palette chunk.
289// Without this, many small PNGs encoded with palettes are larger after compression than
290// the same PNGs encoded as RGBA.
Adam Lesinski21efb682016-09-14 17:35:43 -0700291constexpr static const size_t kPaletteOverheadConstant = 1024u * 10u;
292
Adam Lesinski06460ef2017-03-14 18:52:13 -0700293// Pick a color type by which to encode the image, based on which color type will take
Adam Lesinski21efb682016-09-14 17:35:43 -0700294// the least amount of disk space.
295//
296// 9-patch images traditionally have not been encoded with palettes.
297// The original rationale was to avoid dithering until after scaling,
298// but I don't think this would be an issue with palettes. Either way,
299// our naive size estimation tends to be wrong for small images like 9-patches
300// and using palettes balloons the size of the resulting 9-patch.
301// In order to not regress in size, restrict 9-patch to not use palettes.
302
303// The options are:
304//
305// - RGB
306// - RGBA
307// - RGB + cheap alpha
308// - Color palette
309// - Color palette + cheap alpha
310// - Color palette + alpha palette
311// - Grayscale
312// - Grayscale + cheap alpha
313// - Grayscale + alpha
314//
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700315static int PickColorType(int32_t width, int32_t height, bool grayscale,
316 bool convertible_to_grayscale, bool has_nine_patch,
317 size_t color_palette_size, size_t alpha_palette_size) {
318 const size_t palette_chunk_size = 16 + color_palette_size * 3;
319 const size_t alpha_chunk_size = 16 + alpha_palette_size;
320 const size_t color_alpha_data_chunk_size = 16 + 4 * width * height;
321 const size_t color_data_chunk_size = 16 + 3 * width * height;
322 const size_t grayscale_alpha_data_chunk_size = 16 + 2 * width * height;
323 const size_t palette_data_chunk_size = 16 + width * height;
Adam Lesinski21efb682016-09-14 17:35:43 -0700324
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700325 if (grayscale) {
326 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700327 // This is the smallest the data can be.
328 return PNG_COLOR_TYPE_GRAY;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700329 } else if (color_palette_size <= 256 && !has_nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700330 // This grayscale has alpha and can fit within a palette.
331 // See if it is worth fitting into a palette.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700332 const size_t palette_threshold = palette_chunk_size + alpha_chunk_size +
333 palette_data_chunk_size +
334 kPaletteOverheadConstant;
335 if (grayscale_alpha_data_chunk_size > palette_threshold) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700336 return PNG_COLOR_TYPE_PALETTE;
337 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700338 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700339 return PNG_COLOR_TYPE_GRAY_ALPHA;
340 }
341
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700342 if (color_palette_size <= 256 && !has_nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700343 // This image can fit inside a palette. Let's see if it is worth it.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700344 size_t total_size_with_palette =
345 palette_data_chunk_size + palette_chunk_size;
346 size_t total_size_without_palette = color_data_chunk_size;
347 if (alpha_palette_size > 0) {
348 total_size_with_palette += alpha_palette_size;
349 total_size_without_palette = color_alpha_data_chunk_size;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700350 }
351
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700352 if (total_size_without_palette >
353 total_size_with_palette + kPaletteOverheadConstant) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 return PNG_COLOR_TYPE_PALETTE;
355 }
356 }
357
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700358 if (convertible_to_grayscale) {
359 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700360 return PNG_COLOR_TYPE_GRAY;
361 } else {
362 return PNG_COLOR_TYPE_GRAY_ALPHA;
363 }
364 }
365
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700366 if (alpha_palette_size == 0) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 return PNG_COLOR_TYPE_RGB;
368 }
369 return PNG_COLOR_TYPE_RGBA;
Adam Lesinski21efb682016-09-14 17:35:43 -0700370}
371
Adam Lesinski06460ef2017-03-14 18:52:13 -0700372// Assigns indices to the color and alpha palettes, encodes them, and then invokes
Adam Lesinski21efb682016-09-14 17:35:43 -0700373// png_set_PLTE/png_set_tRNS.
374// This must be done before writing image data.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700375// Image data must be transformed to use the indices assigned within the palette.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700376static void WritePalette(png_structp write_ptr, png_infop write_info_ptr,
377 std::unordered_map<uint32_t, int>* color_palette,
378 std::unordered_set<uint32_t>* alpha_palette) {
379 CHECK(color_palette->size() <= 256);
380 CHECK(alpha_palette->size() <= 256);
Adam Lesinski21efb682016-09-14 17:35:43 -0700381
Adam Lesinski06460ef2017-03-14 18:52:13 -0700382 // Populate the PNG palette struct and assign indices to the color palette.
Adam Lesinski21efb682016-09-14 17:35:43 -0700383
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700384 // Colors in the alpha palette should have smaller indices.
385 // This will ensure that we can truncate the alpha palette if it is
386 // smaller than the color palette.
387 int index = 0;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700388 for (uint32_t color : *alpha_palette) {
389 (*color_palette)[color] = index++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700390 }
391
392 // Assign the rest of the entries.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700393 for (auto& entry : *color_palette) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700394 if (entry.second == -1) {
395 entry.second = index++;
Adam Lesinski21efb682016-09-14 17:35:43 -0700396 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700397 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700398
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700399 // Create the PNG color palette struct.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700400 auto color_palette_bytes = std::unique_ptr<png_color[]>(new png_color[color_palette->size()]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700401
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700402 std::unique_ptr<png_byte[]> alpha_palette_bytes;
403 if (!alpha_palette->empty()) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700404 alpha_palette_bytes = std::unique_ptr<png_byte[]>(new png_byte[alpha_palette->size()]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700405 }
406
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700407 for (const auto& entry : *color_palette) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700408 const uint32_t color = entry.first;
409 const int index = entry.second;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700410 CHECK(index >= 0);
411 CHECK(static_cast<size_t>(index) < color_palette->size());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700412
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700413 png_colorp slot = color_palette_bytes.get() + index;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700414 slot->red = color >> 24;
415 slot->green = color >> 16;
416 slot->blue = color >> 8;
417
418 const png_byte alpha = color & 0x000000ff;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700419 if (alpha != 0xff && alpha_palette_bytes) {
420 CHECK(static_cast<size_t>(index) < alpha_palette->size());
421 alpha_palette_bytes[index] = alpha;
Adam Lesinski21efb682016-09-14 17:35:43 -0700422 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700423 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700424
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700425 // The bytes get copied here, so it is safe to release color_palette_bytes at
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700426 // the end of function
427 // scope.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700428 png_set_PLTE(write_ptr, write_info_ptr, color_palette_bytes.get(), color_palette->size());
Adam Lesinski21efb682016-09-14 17:35:43 -0700429
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700430 if (alpha_palette_bytes) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700431 png_set_tRNS(write_ptr, write_info_ptr, alpha_palette_bytes.get(), alpha_palette->size(),
432 nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700433 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700434}
435
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700436// Write the 9-patch custom PNG chunks to write_info_ptr. This must be done
Adam Lesinski06460ef2017-03-14 18:52:13 -0700437// before writing image data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700438static void WriteNinePatch(png_structp write_ptr, png_infop write_info_ptr,
439 const NinePatch* nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700440 // The order of the chunks is important.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700441 // 9-patch code in older platforms expects the 9-patch chunk to be last.
Adam Lesinski21efb682016-09-14 17:35:43 -0700442
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700443 png_unknown_chunk unknown_chunks[3];
444 memset(unknown_chunks, 0, sizeof(unknown_chunks));
Adam Lesinski21efb682016-09-14 17:35:43 -0700445
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700446 size_t index = 0;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700447 size_t chunk_len = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700448
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700449 std::unique_ptr<uint8_t[]> serialized_outline =
450 nine_patch->SerializeRoundedRectOutline(&chunk_len);
451 strcpy((char*)unknown_chunks[index].name, "npOl");
452 unknown_chunks[index].size = chunk_len;
453 unknown_chunks[index].data = (png_bytep)serialized_outline.get();
454 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700455 index++;
456
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700457 std::unique_ptr<uint8_t[]> serialized_layout_bounds;
458 if (nine_patch->layout_bounds.nonZero()) {
459 serialized_layout_bounds = nine_patch->SerializeLayoutBounds(&chunk_len);
460 strcpy((char*)unknown_chunks[index].name, "npLb");
461 unknown_chunks[index].size = chunk_len;
462 unknown_chunks[index].data = (png_bytep)serialized_layout_bounds.get();
463 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinski21efb682016-09-14 17:35:43 -0700464 index++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700465 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700466
Adam Lesinski06460ef2017-03-14 18:52:13 -0700467 std::unique_ptr<uint8_t[]> serialized_nine_patch = nine_patch->SerializeBase(&chunk_len);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700468 strcpy((char*)unknown_chunks[index].name, "npTc");
469 unknown_chunks[index].size = chunk_len;
470 unknown_chunks[index].data = (png_bytep)serialized_nine_patch.get();
471 unknown_chunks[index].location = PNG_HAVE_PLTE;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 index++;
Adam Lesinski21efb682016-09-14 17:35:43 -0700473
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700474 // Handle all unknown chunks. We are manually setting the chunks here,
475 // so we will only ever handle our custom chunks.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700476 png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS, nullptr, 0);
Adam Lesinski21efb682016-09-14 17:35:43 -0700477
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700478 // Set the actual chunks here. The data gets copied, so our buffers can
479 // safely go out of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700480 png_set_unknown_chunks(write_ptr, write_info_ptr, unknown_chunks, index);
Adam Lesinski21efb682016-09-14 17:35:43 -0700481}
482
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700483bool WritePng(IAaptContext* context, const Image* image,
484 const NinePatch* nine_patch, io::OutputStream* out,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700485 const PngOptions& options) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800486 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 // Create and initialize the write png_struct with the default error and
488 // warning handlers.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700489 // The header version is also passed in to ensure that this was built against the same
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700490 // version of libpng.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700491 png_structp write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700492 if (write_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700493 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng write png_struct");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700494 return false;
495 }
496
497 // Allocate memory to store image header data.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700498 png_infop write_info_ptr = png_create_info_struct(write_ptr);
499 if (write_info_ptr == nullptr) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700500 context->GetDiagnostics()->Error(DiagMessage() << "failed to create libpng write png_info");
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700501 png_destroy_write_struct(&write_ptr, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700502 return false;
503 }
504
505 // Automatically release PNG resources at end of scope.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700506 PngWriteStructDeleter png_write_deleter(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700507
508 // libpng uses longjmp to jump to error handling routines.
509 // setjmp will return true only if it was jumped to, aka, there was an error.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700510 if (setjmp(png_jmpbuf(write_ptr))) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700511 return false;
512 }
513
514 // Handle warnings with our IDiagnostics.
Adam Lesinski06460ef2017-03-14 18:52:13 -0700515 png_set_error_fn(write_ptr, (png_voidp)context->GetDiagnostics(), LogError, LogWarning);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700516
517 // Set up the write functions which write to our custom data sources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700518 png_set_write_fn(write_ptr, (png_voidp)out, WriteDataToStream, nullptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700519
520 // We want small files and can take the performance hit to achieve this goal.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700521 png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700522
523 // Begin analysis of the image data.
524 // Scan the entire image and determine if:
525 // 1. Every pixel has R == G == B (grayscale)
526 // 2. Every pixel has A == 255 (opaque)
527 // 3. There are no more than 256 distinct RGBA colors (palette).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700528 std::unordered_map<uint32_t, int> color_palette;
529 std::unordered_set<uint32_t> alpha_palette;
530 bool needs_to_zero_rgb_channels_of_transparent_pixels = false;
531 bool grayscale = true;
532 int max_gray_deviation = 0;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533
534 for (int32_t y = 0; y < image->height; y++) {
535 const uint8_t* row = image->rows[y];
536 for (int32_t x = 0; x < image->width; x++) {
537 int red = *row++;
538 int green = *row++;
539 int blue = *row++;
540 int alpha = *row++;
541
542 if (alpha == 0) {
543 // The color is completely transparent.
544 // For purposes of palettes and grayscale optimization,
545 // treat all channels as 0x00.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 needs_to_zero_rgb_channels_of_transparent_pixels =
547 needs_to_zero_rgb_channels_of_transparent_pixels ||
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700548 (red != 0 || green != 0 || blue != 0);
549 red = green = blue = 0;
550 }
551
552 // Insert the color into the color palette.
553 const uint32_t color = red << 24 | green << 16 | blue << 8 | alpha;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700554 color_palette[color] = -1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555
556 // If the pixel has non-opaque alpha, insert it into the
557 // alpha palette.
558 if (alpha != 0xff) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700559 alpha_palette.insert(color);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560 }
561
562 // Check if the image is indeed grayscale.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700563 if (grayscale) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700564 if (red != green || red != blue) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700565 grayscale = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566 }
567 }
568
569 // Calculate the gray scale deviation so that it can be compared
570 // with the threshold.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700571 max_gray_deviation = std::max(std::abs(red - green), max_gray_deviation);
572 max_gray_deviation = std::max(std::abs(green - blue), max_gray_deviation);
573 max_gray_deviation = std::max(std::abs(blue - red), max_gray_deviation);
Adam Lesinski21efb682016-09-14 17:35:43 -0700574 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700576
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700577 if (context->IsVerbose()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700578 DiagMessage msg;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700579 msg << " paletteSize=" << color_palette.size()
580 << " alphaPaletteSize=" << alpha_palette.size()
581 << " maxGrayDeviation=" << max_gray_deviation
582 << " grayScale=" << (grayscale ? "true" : "false");
583 context->GetDiagnostics()->Note(msg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700584 }
585
Adam Lesinski06460ef2017-03-14 18:52:13 -0700586 const bool convertible_to_grayscale = max_gray_deviation <= options.grayscale_tolerance;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700587
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700588 const int new_color_type = PickColorType(
589 image->width, image->height, grayscale, convertible_to_grayscale,
590 nine_patch != nullptr, color_palette.size(), alpha_palette.size());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700592 if (context->IsVerbose()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700593 DiagMessage msg;
594 msg << "encoding PNG ";
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700595 if (nine_patch) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700596 msg << "(with 9-patch) as ";
Adam Lesinski21efb682016-09-14 17:35:43 -0700597 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700598 switch (new_color_type) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700599 case PNG_COLOR_TYPE_GRAY:
600 msg << "GRAY";
601 break;
602 case PNG_COLOR_TYPE_GRAY_ALPHA:
603 msg << "GRAY + ALPHA";
604 break;
605 case PNG_COLOR_TYPE_RGB:
606 msg << "RGB";
607 break;
608 case PNG_COLOR_TYPE_RGB_ALPHA:
609 msg << "RGBA";
610 break;
611 case PNG_COLOR_TYPE_PALETTE:
612 msg << "PALETTE";
613 break;
614 default:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700615 msg << "unknown type " << new_color_type;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616 break;
Adam Lesinski21efb682016-09-14 17:35:43 -0700617 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700618 context->GetDiagnostics()->Note(msg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700620
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700621 png_set_IHDR(write_ptr, write_info_ptr, image->width, image->height, 8,
622 new_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623 PNG_FILTER_TYPE_DEFAULT);
Adam Lesinski21efb682016-09-14 17:35:43 -0700624
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700625 if (new_color_type & PNG_COLOR_MASK_PALETTE) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700626 // Assigns indices to the palette, and writes the encoded palette to the
627 // libpng writePtr.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700628 WritePalette(write_ptr, write_info_ptr, &color_palette, &alpha_palette);
629 png_set_filter(write_ptr, 0, PNG_NO_FILTERS);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700630 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700631 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700633
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700634 if (nine_patch) {
635 WriteNinePatch(write_ptr, write_info_ptr, nine_patch);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700636 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700637
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700638 // Flush our updates to the header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700639 png_write_info(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700640
641 // Write out each row of image data according to its encoding.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700642 if (new_color_type == PNG_COLOR_TYPE_PALETTE) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700643 // 1 byte/pixel.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700644 auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700645
646 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700647 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700649 int rr = *in_row++;
650 int gg = *in_row++;
651 int bb = *in_row++;
652 int aa = *in_row++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653 if (aa == 0) {
654 // Zero out color channels when transparent.
655 rr = gg = bb = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700656 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700657
658 const uint32_t color = rr << 24 | gg << 16 | bb << 8 | aa;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700659 const int idx = color_palette[color];
660 CHECK(idx != -1);
661 out_row[x] = static_cast<png_byte>(idx);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700662 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700663 png_write_row(write_ptr, out_row.get());
Adam Lesinski21efb682016-09-14 17:35:43 -0700664 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700665 } else if (new_color_type == PNG_COLOR_TYPE_GRAY ||
666 new_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
667 const size_t bpp = new_color_type == PNG_COLOR_TYPE_GRAY ? 1 : 2;
668 auto out_row =
669 std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
Adam Lesinski21efb682016-09-14 17:35:43 -0700670
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700671 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700672 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700674 int rr = in_row[x * 4];
675 int gg = in_row[x * 4 + 1];
676 int bb = in_row[x * 4 + 2];
677 int aa = in_row[x * 4 + 3];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700678 if (aa == 0) {
679 // Zero out the gray channel when transparent.
680 rr = gg = bb = 0;
Adam Lesinski21efb682016-09-14 17:35:43 -0700681 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700682
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700683 if (grayscale) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700684 // The image was already grayscale, red == green == blue.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700685 out_row[x * bpp] = in_row[x * 4];
Adam Lesinski21efb682016-09-14 17:35:43 -0700686 } else {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700687 // The image is convertible to grayscale, use linear-luminance of
688 // sRGB colorspace:
689 // https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700690 out_row[x * bpp] =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700691 (png_byte)(rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
Adam Lesinski21efb682016-09-14 17:35:43 -0700692 }
Adam Lesinski21efb682016-09-14 17:35:43 -0700693
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700694 if (bpp == 2) {
695 // Write out alpha if we have it.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700696 out_row[x * bpp + 1] = aa;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700697 }
698 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 png_write_row(write_ptr, out_row.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 }
Adam Lesinski06460ef2017-03-14 18:52:13 -0700701 } else if (new_color_type == PNG_COLOR_TYPE_RGB || new_color_type == PNG_COLOR_TYPE_RGBA) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700702 const size_t bpp = new_color_type == PNG_COLOR_TYPE_RGB ? 3 : 4;
703 if (needs_to_zero_rgb_channels_of_transparent_pixels) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700704 // The source RGBA data can't be used as-is, because we need to zero out
Adam Lesinski06460ef2017-03-14 18:52:13 -0700705 // the RGB values of transparent pixels.
706 auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707
708 for (int32_t y = 0; y < image->height; y++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700709 png_const_bytep in_row = image->rows[y];
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700710 for (int32_t x = 0; x < image->width; x++) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700711 int rr = *in_row++;
712 int gg = *in_row++;
713 int bb = *in_row++;
714 int aa = *in_row++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715 if (aa == 0) {
716 // Zero out the RGB channels when transparent.
717 rr = gg = bb = 0;
718 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700719 out_row[x * bpp] = rr;
720 out_row[x * bpp + 1] = gg;
721 out_row[x * bpp + 2] = bb;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700722 if (bpp == 4) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700723 out_row[x * bpp + 3] = aa;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700724 }
725 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700726 png_write_row(write_ptr, out_row.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700727 }
728 } else {
729 // The source image can be used as-is, just tell libpng whether or not to
Adam Lesinski06460ef2017-03-14 18:52:13 -0700730 // ignore the alpha channel.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700731 if (new_color_type == PNG_COLOR_TYPE_RGB) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700732 // Delete the extraneous alpha values that we appended to our buffer
733 // when reading the original values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 png_set_filler(write_ptr, 0, PNG_FILLER_AFTER);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700735 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700736 png_write_image(write_ptr, image->rows.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700737 }
738 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 LOG(FATAL) << "unreachable";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700740 }
741
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700742 png_write_end(write_ptr, write_info_ptr);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743 return true;
Adam Lesinski21efb682016-09-14 17:35:43 -0700744}
745
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700746} // namespace aapt