blob: dd753f1de8bc7fb5cd07ea38d4e926e7b168cca6 [file] [log] [blame]
Adam Lesinski98aa3ad2015-04-06 11:46:52 -07001/*
2 * Copyright (C) 2015 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 "Logger.h"
18#include "Png.h"
19#include "Source.h"
20#include "Util.h"
21
22#include <androidfw/ResourceTypes.h>
23#include <iostream>
24#include <png.h>
25#include <sstream>
26#include <string>
27#include <vector>
28#include <zlib.h>
29
30namespace aapt {
31
32constexpr bool kDebug = false;
33constexpr size_t kPngSignatureSize = 8u;
34
35struct PngInfo {
36 ~PngInfo() {
37 for (png_bytep row : rows) {
38 if (row != nullptr) {
39 delete[] row;
40 }
41 }
42
43 delete[] xDivs;
44 delete[] yDivs;
45 }
46
47 void* serialize9Patch() {
48 void* serialized = android::Res_png_9patch::serialize(info9Patch, xDivs, yDivs,
49 colors.data());
50 reinterpret_cast<android::Res_png_9patch*>(serialized)->deviceToFile();
51 return serialized;
52 }
53
54 uint32_t width = 0;
55 uint32_t height = 0;
56 std::vector<png_bytep> rows;
57
58 bool is9Patch = false;
59 android::Res_png_9patch info9Patch;
60 int32_t* xDivs = nullptr;
61 int32_t* yDivs = nullptr;
62 std::vector<uint32_t> colors;
63
64 // Layout padding.
65 bool haveLayoutBounds = false;
66 int32_t layoutBoundsLeft;
67 int32_t layoutBoundsTop;
68 int32_t layoutBoundsRight;
69 int32_t layoutBoundsBottom;
70
71 // Round rect outline description.
72 int32_t outlineInsetsLeft;
73 int32_t outlineInsetsTop;
74 int32_t outlineInsetsRight;
75 int32_t outlineInsetsBottom;
76 float outlineRadius;
77 uint8_t outlineAlpha;
78};
79
80static void readDataFromStream(png_structp readPtr, png_bytep data, png_size_t length) {
81 std::istream* input = reinterpret_cast<std::istream*>(png_get_io_ptr(readPtr));
82 if (!input->read(reinterpret_cast<char*>(data), length)) {
83 png_error(readPtr, strerror(errno));
84 }
85}
86
87static void writeDataToStream(png_structp writePtr, png_bytep data, png_size_t length) {
88 std::ostream* output = reinterpret_cast<std::ostream*>(png_get_io_ptr(writePtr));
89 if (!output->write(reinterpret_cast<const char*>(data), length)) {
90 png_error(writePtr, strerror(errno));
91 }
92}
93
94static void flushDataToStream(png_structp writePtr) {
95 std::ostream* output = reinterpret_cast<std::ostream*>(png_get_io_ptr(writePtr));
96 if (!output->flush()) {
97 png_error(writePtr, strerror(errno));
98 }
99}
100
101static void logWarning(png_structp readPtr, png_const_charp warningMessage) {
102 SourceLogger* logger = reinterpret_cast<SourceLogger*>(png_get_error_ptr(readPtr));
103 logger->warn() << warningMessage << "." << std::endl;
104}
105
106
107static bool readPng(png_structp readPtr, png_infop infoPtr, PngInfo* outInfo,
108 std::string* outError) {
109 if (setjmp(png_jmpbuf(readPtr))) {
110 *outError = "failed reading png";
111 return false;
112 }
113
114 png_set_sig_bytes(readPtr, kPngSignatureSize);
115 png_read_info(readPtr, infoPtr);
116
117 int colorType, bitDepth, interlaceType, compressionType;
118 png_get_IHDR(readPtr, infoPtr, &outInfo->width, &outInfo->height, &bitDepth, &colorType,
119 &interlaceType, &compressionType, nullptr);
120
121 if (colorType == PNG_COLOR_TYPE_PALETTE) {
122 png_set_palette_to_rgb(readPtr);
123 }
124
125 if (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) {
126 png_set_expand_gray_1_2_4_to_8(readPtr);
127 }
128
129 if (png_get_valid(readPtr, infoPtr, PNG_INFO_tRNS)) {
130 png_set_tRNS_to_alpha(readPtr);
131 }
132
133 if (bitDepth == 16) {
134 png_set_strip_16(readPtr);
135 }
136
137 if (!(colorType & PNG_COLOR_MASK_ALPHA)) {
138 png_set_add_alpha(readPtr, 0xFF, PNG_FILLER_AFTER);
139 }
140
141 if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
142 png_set_gray_to_rgb(readPtr);
143 }
144
145 png_set_interlace_handling(readPtr);
146 png_read_update_info(readPtr, infoPtr);
147
148 const uint32_t rowBytes = png_get_rowbytes(readPtr, infoPtr);
149 outInfo->rows.resize(outInfo->height);
150 for (size_t i = 0; i < outInfo->height; i++) {
151 outInfo->rows[i] = new png_byte[rowBytes];
152 }
153
154 png_read_image(readPtr, outInfo->rows.data());
155 png_read_end(readPtr, infoPtr);
156 return true;
157}
158
159static void checkNinePatchSerialization(android::Res_png_9patch* inPatch, void* data) {
160 size_t patchSize = inPatch->serializedSize();
161 void* newData = malloc(patchSize);
162 memcpy(newData, data, patchSize);
163 android::Res_png_9patch* outPatch = inPatch->deserialize(newData);
164 outPatch->fileToDevice();
165 // deserialization is done in place, so outPatch == newData
166 assert(outPatch == newData);
167 assert(outPatch->numXDivs == inPatch->numXDivs);
168 assert(outPatch->numYDivs == inPatch->numYDivs);
169 assert(outPatch->paddingLeft == inPatch->paddingLeft);
170 assert(outPatch->paddingRight == inPatch->paddingRight);
171 assert(outPatch->paddingTop == inPatch->paddingTop);
172 assert(outPatch->paddingBottom == inPatch->paddingBottom);
173/* for (int i = 0; i < outPatch->numXDivs; i++) {
174 assert(outPatch->getXDivs()[i] == inPatch->getXDivs()[i]);
175 }
176 for (int i = 0; i < outPatch->numYDivs; i++) {
177 assert(outPatch->getYDivs()[i] == inPatch->getYDivs()[i]);
178 }
179 for (int i = 0; i < outPatch->numColors; i++) {
180 assert(outPatch->getColors()[i] == inPatch->getColors()[i]);
181 }*/
182 free(newData);
183}
184
185/*static void dump_image(int w, int h, const png_byte* const* rows, int color_type) {
186 int i, j, rr, gg, bb, aa;
187
188 int bpp;
189 if (color_type == PNG_COLOR_TYPE_PALETTE || color_type == PNG_COLOR_TYPE_GRAY) {
190 bpp = 1;
191 } else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
192 bpp = 2;
193 } else if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
194 // We use a padding byte even when there is no alpha
195 bpp = 4;
196 } else {
197 printf("Unknown color type %d.\n", color_type);
198 }
199
200 for (j = 0; j < h; j++) {
201 const png_byte* row = rows[j];
202 for (i = 0; i < w; i++) {
203 rr = row[0];
204 gg = row[1];
205 bb = row[2];
206 aa = row[3];
207 row += bpp;
208
209 if (i == 0) {
210 printf("Row %d:", j);
211 }
212 switch (bpp) {
213 case 1:
214 printf(" (%d)", rr);
215 break;
216 case 2:
217 printf(" (%d %d", rr, gg);
218 break;
219 case 3:
220 printf(" (%d %d %d)", rr, gg, bb);
221 break;
222 case 4:
223 printf(" (%d %d %d %d)", rr, gg, bb, aa);
224 break;
225 }
226 if (i == (w - 1)) {
227 printf("\n");
228 }
229 }
230 }
231}*/
232
233#define MAX(a,b) ((a)>(b)?(a):(b))
234#define ABS(a) ((a)<0?-(a):(a))
235
236static void analyze_image(SourceLogger* logger, const PngInfo& imageInfo, int grayscaleTolerance,
237 png_colorp rgbPalette, png_bytep alphaPalette,
238 int *paletteEntries, bool *hasTransparency, int *colorType,
239 png_bytepp outRows) {
240 int w = imageInfo.width;
241 int h = imageInfo.height;
242 int i, j, rr, gg, bb, aa, idx;
243 uint32_t colors[256], col;
244 int num_colors = 0;
245 int maxGrayDeviation = 0;
246
247 bool isOpaque = true;
248 bool isPalette = true;
249 bool isGrayscale = true;
250
251 // Scan the entire image and determine if:
252 // 1. Every pixel has R == G == B (grayscale)
253 // 2. Every pixel has A == 255 (opaque)
254 // 3. There are no more than 256 distinct RGBA colors
255
256 if (kDebug) {
257 printf("Initial image data:\n");
258 //dump_image(w, h, imageInfo.rows.data(), PNG_COLOR_TYPE_RGB_ALPHA);
259 }
260
261 for (j = 0; j < h; j++) {
262 const png_byte* row = imageInfo.rows[j];
263 png_bytep out = outRows[j];
264 for (i = 0; i < w; i++) {
265 rr = *row++;
266 gg = *row++;
267 bb = *row++;
268 aa = *row++;
269
270 int odev = maxGrayDeviation;
271 maxGrayDeviation = MAX(ABS(rr - gg), maxGrayDeviation);
272 maxGrayDeviation = MAX(ABS(gg - bb), maxGrayDeviation);
273 maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation);
274 if (maxGrayDeviation > odev) {
275 if (kDebug) {
276 printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
277 maxGrayDeviation, i, j, rr, gg, bb, aa);
278 }
279 }
280
281 // Check if image is really grayscale
282 if (isGrayscale) {
283 if (rr != gg || rr != bb) {
284 if (kDebug) {
285 printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n",
286 i, j, rr, gg, bb, aa);
287 }
288 isGrayscale = false;
289 }
290 }
291
292 // Check if image is really opaque
293 if (isOpaque) {
294 if (aa != 0xff) {
295 if (kDebug) {
296 printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n",
297 i, j, rr, gg, bb, aa);
298 }
299 isOpaque = false;
300 }
301 }
302
303 // Check if image is really <= 256 colors
304 if (isPalette) {
305 col = (uint32_t) ((rr << 24) | (gg << 16) | (bb << 8) | aa);
306 bool match = false;
307 for (idx = 0; idx < num_colors; idx++) {
308 if (colors[idx] == col) {
309 match = true;
310 break;
311 }
312 }
313
314 // Write the palette index for the pixel to outRows optimistically
315 // We might overwrite it later if we decide to encode as gray or
316 // gray + alpha
317 *out++ = idx;
318 if (!match) {
319 if (num_colors == 256) {
320 if (kDebug) {
321 printf("Found 257th color at %d, %d\n", i, j);
322 }
323 isPalette = false;
324 } else {
325 colors[num_colors++] = col;
326 }
327 }
328 }
329 }
330 }
331
332 *paletteEntries = 0;
333 *hasTransparency = !isOpaque;
334 int bpp = isOpaque ? 3 : 4;
335 int paletteSize = w * h + bpp * num_colors;
336
337 if (kDebug) {
338 printf("isGrayscale = %s\n", isGrayscale ? "true" : "false");
339 printf("isOpaque = %s\n", isOpaque ? "true" : "false");
340 printf("isPalette = %s\n", isPalette ? "true" : "false");
341 printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n",
342 paletteSize, 2 * w * h, bpp * w * h);
343 printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance);
344 }
345
346 // Choose the best color type for the image.
347 // 1. Opaque gray - use COLOR_TYPE_GRAY at 1 byte/pixel
348 // 2. Gray + alpha - use COLOR_TYPE_PALETTE if the number of distinct combinations
349 // is sufficiently small, otherwise use COLOR_TYPE_GRAY_ALPHA
350 // 3. RGB(A) - use COLOR_TYPE_PALETTE if the number of distinct colors is sufficiently
351 // small, otherwise use COLOR_TYPE_RGB{_ALPHA}
352 if (isGrayscale) {
353 if (isOpaque) {
354 *colorType = PNG_COLOR_TYPE_GRAY; // 1 byte/pixel
355 } else {
356 // Use a simple heuristic to determine whether using a palette will
357 // save space versus using gray + alpha for each pixel.
358 // This doesn't take into account chunk overhead, filtering, LZ
359 // compression, etc.
360 if (isPalette && (paletteSize < 2 * w * h)) {
361 *colorType = PNG_COLOR_TYPE_PALETTE; // 1 byte/pixel + 4 bytes/color
362 } else {
363 *colorType = PNG_COLOR_TYPE_GRAY_ALPHA; // 2 bytes per pixel
364 }
365 }
366 } else if (isPalette && (paletteSize < bpp * w * h)) {
367 *colorType = PNG_COLOR_TYPE_PALETTE;
368 } else {
369 if (maxGrayDeviation <= grayscaleTolerance) {
370 logger->note() << "forcing image to gray (max deviation = " << maxGrayDeviation
371 << ")."
372 << std::endl;
373 *colorType = isOpaque ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA;
374 } else {
375 *colorType = isOpaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA;
376 }
377 }
378
379 // Perform postprocessing of the image or palette data based on the final
380 // color type chosen
381
382 if (*colorType == PNG_COLOR_TYPE_PALETTE) {
383 // Create separate RGB and Alpha palettes and set the number of colors
384 *paletteEntries = num_colors;
385
386 // Create the RGB and alpha palettes
387 for (int idx = 0; idx < num_colors; idx++) {
388 col = colors[idx];
389 rgbPalette[idx].red = (png_byte) ((col >> 24) & 0xff);
390 rgbPalette[idx].green = (png_byte) ((col >> 16) & 0xff);
391 rgbPalette[idx].blue = (png_byte) ((col >> 8) & 0xff);
392 alphaPalette[idx] = (png_byte) (col & 0xff);
393 }
394 } else if (*colorType == PNG_COLOR_TYPE_GRAY || *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
395 // If the image is gray or gray + alpha, compact the pixels into outRows
396 for (j = 0; j < h; j++) {
397 const png_byte* row = imageInfo.rows[j];
398 png_bytep out = outRows[j];
399 for (i = 0; i < w; i++) {
400 rr = *row++;
401 gg = *row++;
402 bb = *row++;
403 aa = *row++;
404
405 if (isGrayscale) {
406 *out++ = rr;
407 } else {
408 *out++ = (png_byte) (rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
409 }
410 if (!isOpaque) {
411 *out++ = aa;
412 }
413 }
414 }
415 }
416}
417
418static bool writePng(png_structp writePtr, png_infop infoPtr, PngInfo* info,
419 int grayScaleTolerance, SourceLogger* logger, std::string* outError) {
420 if (setjmp(png_jmpbuf(writePtr))) {
421 *outError = "failed to write png";
422 return false;
423 }
424
425 uint32_t width, height;
426 int colorType, bitDepth, interlaceType, compressionType;
427
428 png_unknown_chunk unknowns[3];
429 unknowns[0].data = nullptr;
430 unknowns[1].data = nullptr;
431 unknowns[2].data = nullptr;
432
433 png_bytepp outRows = (png_bytepp) malloc((int) info->height * sizeof(png_bytep));
434 if (outRows == (png_bytepp) 0) {
435 printf("Can't allocate output buffer!\n");
436 exit(1);
437 }
438 for (uint32_t i = 0; i < info->height; i++) {
439 outRows[i] = (png_bytep) malloc(2 * (int) info->width);
440 if (outRows[i] == (png_bytep) 0) {
441 printf("Can't allocate output buffer!\n");
442 exit(1);
443 }
444 }
445
446 png_set_compression_level(writePtr, Z_BEST_COMPRESSION);
447
448 if (kDebug) {
449 logger->note() << "writing image: w = " << info->width
450 << ", h = " << info->height
451 << std::endl;
452 }
453
454 png_color rgbPalette[256];
455 png_byte alphaPalette[256];
456 bool hasTransparency;
457 int paletteEntries;
458
459 analyze_image(logger, *info, grayScaleTolerance, rgbPalette, alphaPalette,
460 &paletteEntries, &hasTransparency, &colorType, outRows);
461
462 // If the image is a 9-patch, we need to preserve it as a ARGB file to make
463 // sure the pixels will not be pre-dithered/clamped until we decide they are
464 if (info->is9Patch && (colorType == PNG_COLOR_TYPE_RGB ||
465 colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_PALETTE)) {
466 colorType = PNG_COLOR_TYPE_RGB_ALPHA;
467 }
468
469 if (kDebug) {
470 switch (colorType) {
471 case PNG_COLOR_TYPE_PALETTE:
472 logger->note() << "has " << paletteEntries
473 << " colors" << (hasTransparency ? " (with alpha)" : "")
474 << ", using PNG_COLOR_TYPE_PALLETTE."
475 << std::endl;
476 break;
477 case PNG_COLOR_TYPE_GRAY:
478 logger->note() << "is opaque gray, using PNG_COLOR_TYPE_GRAY." << std::endl;
479 break;
480 case PNG_COLOR_TYPE_GRAY_ALPHA:
481 logger->note() << "is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA." << std::endl;
482 break;
483 case PNG_COLOR_TYPE_RGB:
484 logger->note() << "is opaque RGB, using PNG_COLOR_TYPE_RGB." << std::endl;
485 break;
486 case PNG_COLOR_TYPE_RGB_ALPHA:
487 logger->note() << "is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA." << std::endl;
488 break;
489 }
490 }
491
492 png_set_IHDR(writePtr, infoPtr, info->width, info->height, 8, colorType,
493 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
494
495 if (colorType == PNG_COLOR_TYPE_PALETTE) {
496 png_set_PLTE(writePtr, infoPtr, rgbPalette, paletteEntries);
497 if (hasTransparency) {
498 png_set_tRNS(writePtr, infoPtr, alphaPalette, paletteEntries, (png_color_16p) 0);
499 }
500 png_set_filter(writePtr, 0, PNG_NO_FILTERS);
501 } else {
502 png_set_filter(writePtr, 0, PNG_ALL_FILTERS);
503 }
504
505 if (info->is9Patch) {
506 int chunkCount = 2 + (info->haveLayoutBounds ? 1 : 0);
507 int pIndex = info->haveLayoutBounds ? 2 : 1;
508 int bIndex = 1;
509 int oIndex = 0;
510
511 // Chunks ordered thusly because older platforms depend on the base 9 patch data being last
512 png_bytep chunkNames = info->haveLayoutBounds
513 ? (png_bytep)"npOl\0npLb\0npTc\0"
514 : (png_bytep)"npOl\0npTc";
515
516 // base 9 patch data
517 if (kDebug) {
518 logger->note() << "adding 9-patch info..." << std::endl;
519 }
520 strcpy((char*)unknowns[pIndex].name, "npTc");
521 unknowns[pIndex].data = (png_byte*) info->serialize9Patch();
522 unknowns[pIndex].size = info->info9Patch.serializedSize();
523 // TODO: remove the check below when everything works
524 checkNinePatchSerialization(&info->info9Patch, unknowns[pIndex].data);
525
526 // automatically generated 9 patch outline data
527 int chunkSize = sizeof(png_uint_32) * 6;
528 strcpy((char*)unknowns[oIndex].name, "npOl");
529 unknowns[oIndex].data = (png_byte*) calloc(chunkSize, 1);
530 png_byte outputData[chunkSize];
531 memcpy(&outputData, &info->outlineInsetsLeft, 4 * sizeof(png_uint_32));
532 ((float*) outputData)[4] = info->outlineRadius;
533 ((png_uint_32*) outputData)[5] = info->outlineAlpha;
534 memcpy(unknowns[oIndex].data, &outputData, chunkSize);
535 unknowns[oIndex].size = chunkSize;
536
537 // optional optical inset / layout bounds data
538 if (info->haveLayoutBounds) {
539 int chunkSize = sizeof(png_uint_32) * 4;
540 strcpy((char*)unknowns[bIndex].name, "npLb");
541 unknowns[bIndex].data = (png_byte*) calloc(chunkSize, 1);
542 memcpy(unknowns[bIndex].data, &info->layoutBoundsLeft, chunkSize);
543 unknowns[bIndex].size = chunkSize;
544 }
545
546 for (int i = 0; i < chunkCount; i++) {
547 unknowns[i].location = PNG_HAVE_PLTE;
548 }
549 png_set_keep_unknown_chunks(writePtr, PNG_HANDLE_CHUNK_ALWAYS,
550 chunkNames, chunkCount);
551 png_set_unknown_chunks(writePtr, infoPtr, unknowns, chunkCount);
552
553#if PNG_LIBPNG_VER < 10600
554 // Deal with unknown chunk location bug in 1.5.x and earlier.
555 png_set_unknown_chunk_location(writePtr, infoPtr, 0, PNG_HAVE_PLTE);
556 if (info->haveLayoutBounds) {
557 png_set_unknown_chunk_location(writePtr, infoPtr, 1, PNG_HAVE_PLTE);
558 }
559#endif
560 }
561
562 png_write_info(writePtr, infoPtr);
563
564 png_bytepp rows;
565 if (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_RGB_ALPHA) {
566 if (colorType == PNG_COLOR_TYPE_RGB) {
567 png_set_filler(writePtr, 0, PNG_FILLER_AFTER);
568 }
569 rows = info->rows.data();
570 } else {
571 rows = outRows;
572 }
573 png_write_image(writePtr, rows);
574
575 if (kDebug) {
576 printf("Final image data:\n");
577 //dump_image(info->width, info->height, rows, colorType);
578 }
579
580 png_write_end(writePtr, infoPtr);
581
582 for (uint32_t i = 0; i < info->height; i++) {
583 free(outRows[i]);
584 }
585 free(outRows);
586 free(unknowns[0].data);
587 free(unknowns[1].data);
588 free(unknowns[2].data);
589
590 png_get_IHDR(writePtr, infoPtr, &width, &height, &bitDepth, &colorType, &interlaceType,
591 &compressionType, nullptr);
592
593 if (kDebug) {
594 logger->note() << "image written: w = " << width << ", h = " << height
595 << ", d = " << bitDepth << ", colors = " << colorType
596 << ", inter = " << interlaceType << ", comp = " << compressionType
597 << std::endl;
598 }
599 return true;
600}
601
602constexpr uint32_t kColorWhite = 0xffffffffu;
603constexpr uint32_t kColorTick = 0xff000000u;
604constexpr uint32_t kColorLayoutBoundsTick = 0xff0000ffu;
605
606enum class TickType {
607 kNone,
608 kTick,
609 kLayoutBounds,
610 kBoth
611};
612
613static TickType tickType(png_bytep p, bool transparent, const char** outError) {
614 png_uint_32 color = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
615
616 if (transparent) {
617 if (p[3] == 0) {
618 return TickType::kNone;
619 }
620 if (color == kColorLayoutBoundsTick) {
621 return TickType::kLayoutBounds;
622 }
623 if (color == kColorTick) {
624 return TickType::kTick;
625 }
626
627 // Error cases
628 if (p[3] != 0xff) {
629 *outError = "Frame pixels must be either solid or transparent "
630 "(not intermediate alphas)";
631 return TickType::kNone;
632 }
633
634 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
635 *outError = "Ticks in transparent frame must be black or red";
636 }
637 return TickType::kTick;
638 }
639
640 if (p[3] != 0xFF) {
641 *outError = "White frame must be a solid color (no alpha)";
642 }
643 if (color == kColorWhite) {
644 return TickType::kNone;
645 }
646 if (color == kColorTick) {
647 return TickType::kTick;
648 }
649 if (color == kColorLayoutBoundsTick) {
650 return TickType::kLayoutBounds;
651 }
652
653 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
654 *outError = "Ticks in white frame must be black or red";
655 return TickType::kNone;
656 }
657 return TickType::kTick;
658}
659
660enum class TickState {
661 kStart,
662 kInside1,
663 kOutside1
664};
665
666static bool getHorizontalTicks(png_bytep row, int width, bool transparent, bool required,
667 int32_t* outLeft, int32_t* outRight, const char** outError,
668 uint8_t* outDivs, bool multipleAllowed) {
669 *outLeft = *outRight = -1;
670 TickState state = TickState::kStart;
671 bool found = false;
672
673 for (int i = 1; i < width - 1; i++) {
674 if (tickType(row+i*4, transparent, outError) == TickType::kTick) {
675 if (state == TickState::kStart ||
676 (state == TickState::kOutside1 && multipleAllowed)) {
677 *outLeft = i-1;
678 *outRight = width-2;
679 found = true;
680 if (outDivs != NULL) {
681 *outDivs += 2;
682 }
683 state = TickState::kInside1;
684 } else if (state == TickState::kOutside1) {
685 *outError = "Can't have more than one marked region along edge";
686 *outLeft = i;
687 return false;
688 }
689 } else if (!*outError) {
690 if (state == TickState::kInside1) {
691 // We're done with this div. Move on to the next.
692 *outRight = i-1;
693 outRight += 2;
694 outLeft += 2;
695 state = TickState::kOutside1;
696 }
697 } else {
698 *outLeft = i;
699 return false;
700 }
701 }
702
703 if (required && !found) {
704 *outError = "No marked region found along edge";
705 *outLeft = -1;
706 return false;
707 }
708 return true;
709}
710
711static bool getVerticalTicks(png_bytepp rows, int offset, int height, bool transparent,
712 bool required, int32_t* outTop, int32_t* outBottom,
713 const char** outError, uint8_t* outDivs, bool multipleAllowed) {
714 *outTop = *outBottom = -1;
715 TickState state = TickState::kStart;
716 bool found = false;
717
718 for (int i = 1; i < height - 1; i++) {
719 if (tickType(rows[i]+offset, transparent, outError) == TickType::kTick) {
720 if (state == TickState::kStart ||
721 (state == TickState::kOutside1 && multipleAllowed)) {
722 *outTop = i-1;
723 *outBottom = height-2;
724 found = true;
725 if (outDivs != NULL) {
726 *outDivs += 2;
727 }
728 state = TickState::kInside1;
729 } else if (state == TickState::kOutside1) {
730 *outError = "Can't have more than one marked region along edge";
731 *outTop = i;
732 return false;
733 }
734 } else if (!*outError) {
735 if (state == TickState::kInside1) {
736 // We're done with this div. Move on to the next.
737 *outBottom = i-1;
738 outTop += 2;
739 outBottom += 2;
740 state = TickState::kOutside1;
741 }
742 } else {
743 *outTop = i;
744 return false;
745 }
746 }
747
748 if (required && !found) {
749 *outError = "No marked region found along edge";
750 *outTop = -1;
751 return false;
752 }
753 return true;
754}
755
756static bool getHorizontalLayoutBoundsTicks(png_bytep row, int width, bool transparent,
757 bool /* required */, int32_t* outLeft,
758 int32_t* outRight, const char** outError) {
759 *outLeft = *outRight = 0;
760
761 // Look for left tick
762 if (tickType(row + 4, transparent, outError) == TickType::kLayoutBounds) {
763 // Starting with a layout padding tick
764 int i = 1;
765 while (i < width - 1) {
766 (*outLeft)++;
767 i++;
768 if (tickType(row + i * 4, transparent, outError) != TickType::kLayoutBounds) {
769 break;
770 }
771 }
772 }
773
774 // Look for right tick
775 if (tickType(row + (width - 2) * 4, transparent, outError) == TickType::kLayoutBounds) {
776 // Ending with a layout padding tick
777 int i = width - 2;
778 while (i > 1) {
779 (*outRight)++;
780 i--;
781 if (tickType(row+i*4, transparent, outError) != TickType::kLayoutBounds) {
782 break;
783 }
784 }
785 }
786 return true;
787}
788
789static bool getVerticalLayoutBoundsTicks(png_bytepp rows, int offset, int height, bool transparent,
790 bool /* required */, int32_t* outTop, int32_t* outBottom,
791 const char** outError) {
792 *outTop = *outBottom = 0;
793
794 // Look for top tick
795 if (tickType(rows[1] + offset, transparent, outError) == TickType::kLayoutBounds) {
796 // Starting with a layout padding tick
797 int i = 1;
798 while (i < height - 1) {
799 (*outTop)++;
800 i++;
801 if (tickType(rows[i] + offset, transparent, outError) != TickType::kLayoutBounds) {
802 break;
803 }
804 }
805 }
806
807 // Look for bottom tick
808 if (tickType(rows[height - 2] + offset, transparent, outError) == TickType::kLayoutBounds) {
809 // Ending with a layout padding tick
810 int i = height - 2;
811 while (i > 1) {
812 (*outBottom)++;
813 i--;
814 if (tickType(rows[i] + offset, transparent, outError) != TickType::kLayoutBounds) {
815 break;
816 }
817 }
818 }
819 return true;
820}
821
822static void findMaxOpacity(png_bytepp rows, int startX, int startY, int endX, int endY,
823 int dX, int dY, int* outInset) {
824 uint8_t maxOpacity = 0;
825 int inset = 0;
826 *outInset = 0;
827 for (int x = startX, y = startY; x != endX && y != endY; x += dX, y += dY, inset++) {
828 png_byte* color = rows[y] + x * 4;
829 uint8_t opacity = color[3];
830 if (opacity > maxOpacity) {
831 maxOpacity = opacity;
832 *outInset = inset;
833 }
834 if (opacity == 0xff) return;
835 }
836}
837
838static uint8_t maxAlphaOverRow(png_bytep row, int startX, int endX) {
839 uint8_t maxAlpha = 0;
840 for (int x = startX; x < endX; x++) {
841 uint8_t alpha = (row + x * 4)[3];
842 if (alpha > maxAlpha) maxAlpha = alpha;
843 }
844 return maxAlpha;
845}
846
847static uint8_t maxAlphaOverCol(png_bytepp rows, int offsetX, int startY, int endY) {
848 uint8_t maxAlpha = 0;
849 for (int y = startY; y < endY; y++) {
850 uint8_t alpha = (rows[y] + offsetX * 4)[3];
851 if (alpha > maxAlpha) maxAlpha = alpha;
852 }
853 return maxAlpha;
854}
855
856static void getOutline(PngInfo* image) {
857 int midX = image->width / 2;
858 int midY = image->height / 2;
859 int endX = image->width - 2;
860 int endY = image->height - 2;
861
862 // find left and right extent of nine patch content on center row
863 if (image->width > 4) {
864 findMaxOpacity(image->rows.data(), 1, midY, midX, -1, 1, 0, &image->outlineInsetsLeft);
865 findMaxOpacity(image->rows.data(), endX, midY, midX, -1, -1, 0,
866 &image->outlineInsetsRight);
867 } else {
868 image->outlineInsetsLeft = 0;
869 image->outlineInsetsRight = 0;
870 }
871
872 // find top and bottom extent of nine patch content on center column
873 if (image->height > 4) {
874 findMaxOpacity(image->rows.data(), midX, 1, -1, midY, 0, 1, &image->outlineInsetsTop);
875 findMaxOpacity(image->rows.data(), midX, endY, -1, midY, 0, -1,
876 &image->outlineInsetsBottom);
877 } else {
878 image->outlineInsetsTop = 0;
879 image->outlineInsetsBottom = 0;
880 }
881
882 int innerStartX = 1 + image->outlineInsetsLeft;
883 int innerStartY = 1 + image->outlineInsetsTop;
884 int innerEndX = endX - image->outlineInsetsRight;
885 int innerEndY = endY - image->outlineInsetsBottom;
886 int innerMidX = (innerEndX + innerStartX) / 2;
887 int innerMidY = (innerEndY + innerStartY) / 2;
888
889 // assuming the image is a round rect, compute the radius by marching
890 // diagonally from the top left corner towards the center
891 image->outlineAlpha = std::max(
892 maxAlphaOverRow(image->rows[innerMidY], innerStartX, innerEndX),
893 maxAlphaOverCol(image->rows.data(), innerMidX, innerStartY, innerStartY));
894
895 int diagonalInset = 0;
896 findMaxOpacity(image->rows.data(), innerStartX, innerStartY, innerMidX, innerMidY, 1, 1,
897 &diagonalInset);
898
899 /* Determine source radius based upon inset:
900 * sqrt(r^2 + r^2) = sqrt(i^2 + i^2) + r
901 * sqrt(2) * r = sqrt(2) * i + r
902 * (sqrt(2) - 1) * r = sqrt(2) * i
903 * r = sqrt(2) / (sqrt(2) - 1) * i
904 */
905 image->outlineRadius = 3.4142f * diagonalInset;
906
907 if (kDebug) {
908 printf("outline insets %d %d %d %d, rad %f, alpha %x\n",
909 image->outlineInsetsLeft,
910 image->outlineInsetsTop,
911 image->outlineInsetsRight,
912 image->outlineInsetsBottom,
913 image->outlineRadius,
914 image->outlineAlpha);
915 }
916}
917
918static uint32_t getColor(png_bytepp rows, int left, int top, int right, int bottom) {
919 png_bytep color = rows[top] + left*4;
920
921 if (left > right || top > bottom) {
922 return android::Res_png_9patch::TRANSPARENT_COLOR;
923 }
924
925 while (top <= bottom) {
926 for (int i = left; i <= right; i++) {
927 png_bytep p = rows[top]+i*4;
928 if (color[3] == 0) {
929 if (p[3] != 0) {
930 return android::Res_png_9patch::NO_COLOR;
931 }
932 } else if (p[0] != color[0] || p[1] != color[1] ||
933 p[2] != color[2] || p[3] != color[3]) {
934 return android::Res_png_9patch::NO_COLOR;
935 }
936 }
937 top++;
938 }
939
940 if (color[3] == 0) {
941 return android::Res_png_9patch::TRANSPARENT_COLOR;
942 }
943 return (color[3]<<24) | (color[0]<<16) | (color[1]<<8) | color[2];
944}
945
946static bool do9Patch(PngInfo* image, std::string* outError) {
947 image->is9Patch = true;
948
949 int W = image->width;
950 int H = image->height;
951 int i, j;
952
953 const int maxSizeXDivs = W * sizeof(int32_t);
954 const int maxSizeYDivs = H * sizeof(int32_t);
955 int32_t* xDivs = image->xDivs = new int32_t[W];
956 int32_t* yDivs = image->yDivs = new int32_t[H];
957 uint8_t numXDivs = 0;
958 uint8_t numYDivs = 0;
959
960 int8_t numColors;
961 int numRows;
962 int numCols;
963 int top;
964 int left;
965 int right;
966 int bottom;
967 memset(xDivs, -1, maxSizeXDivs);
968 memset(yDivs, -1, maxSizeYDivs);
969 image->info9Patch.paddingLeft = image->info9Patch.paddingRight = -1;
970 image->info9Patch.paddingTop = image->info9Patch.paddingBottom = -1;
971 image->layoutBoundsLeft = image->layoutBoundsRight = 0;
972 image->layoutBoundsTop = image->layoutBoundsBottom = 0;
973
974 png_bytep p = image->rows[0];
975 bool transparent = p[3] == 0;
976 bool hasColor = false;
977
978 const char* errorMsg = nullptr;
979 int errorPixel = -1;
980 const char* errorEdge = nullptr;
981
982 int colorIndex = 0;
983 std::vector<png_bytep> newRows;
984
985 // Validate size...
986 if (W < 3 || H < 3) {
987 errorMsg = "Image must be at least 3x3 (1x1 without frame) pixels";
988 goto getout;
989 }
990
991 // Validate frame...
992 if (!transparent &&
993 (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) {
994 errorMsg = "Must have one-pixel frame that is either transparent or white";
995 goto getout;
996 }
997
998 // Find left and right of sizing areas...
999 if (!getHorizontalTicks(p, W, transparent, true, &xDivs[0], &xDivs[1], &errorMsg, &numXDivs,
1000 true)) {
1001 errorPixel = xDivs[0];
1002 errorEdge = "top";
1003 goto getout;
1004 }
1005
1006 // Find top and bottom of sizing areas...
1007 if (!getVerticalTicks(image->rows.data(), 0, H, transparent, true, &yDivs[0], &yDivs[1],
1008 &errorMsg, &numYDivs, true)) {
1009 errorPixel = yDivs[0];
1010 errorEdge = "left";
1011 goto getout;
1012 }
1013
1014 // Copy patch size data into image...
1015 image->info9Patch.numXDivs = numXDivs;
1016 image->info9Patch.numYDivs = numYDivs;
1017
1018 // Find left and right of padding area...
1019 if (!getHorizontalTicks(image->rows[H-1], W, transparent, false,
1020 &image->info9Patch.paddingLeft, &image->info9Patch.paddingRight,
1021 &errorMsg, nullptr, false)) {
1022 errorPixel = image->info9Patch.paddingLeft;
1023 errorEdge = "bottom";
1024 goto getout;
1025 }
1026
1027 // Find top and bottom of padding area...
1028 if (!getVerticalTicks(image->rows.data(), (W-1)*4, H, transparent, false,
1029 &image->info9Patch.paddingTop, &image->info9Patch.paddingBottom,
1030 &errorMsg, nullptr, false)) {
1031 errorPixel = image->info9Patch.paddingTop;
1032 errorEdge = "right";
1033 goto getout;
1034 }
1035
1036 // Find left and right of layout padding...
1037 getHorizontalLayoutBoundsTicks(image->rows[H-1], W, transparent, false,
1038 &image->layoutBoundsLeft, &image->layoutBoundsRight, &errorMsg);
1039
1040 getVerticalLayoutBoundsTicks(image->rows.data(), (W-1)*4, H, transparent, false,
1041 &image->layoutBoundsTop, &image->layoutBoundsBottom, &errorMsg);
1042
1043 image->haveLayoutBounds = image->layoutBoundsLeft != 0
1044 || image->layoutBoundsRight != 0
1045 || image->layoutBoundsTop != 0
1046 || image->layoutBoundsBottom != 0;
1047
1048 if (image->haveLayoutBounds) {
1049 if (kDebug) {
1050 printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
1051 image->layoutBoundsRight, image->layoutBoundsBottom);
1052 }
1053 }
1054
1055 // use opacity of pixels to estimate the round rect outline
1056 getOutline(image);
1057
1058 // If padding is not yet specified, take values from size.
1059 if (image->info9Patch.paddingLeft < 0) {
1060 image->info9Patch.paddingLeft = xDivs[0];
1061 image->info9Patch.paddingRight = W - 2 - xDivs[1];
1062 } else {
1063 // Adjust value to be correct!
1064 image->info9Patch.paddingRight = W - 2 - image->info9Patch.paddingRight;
1065 }
1066 if (image->info9Patch.paddingTop < 0) {
1067 image->info9Patch.paddingTop = yDivs[0];
1068 image->info9Patch.paddingBottom = H - 2 - yDivs[1];
1069 } else {
1070 // Adjust value to be correct!
1071 image->info9Patch.paddingBottom = H - 2 - image->info9Patch.paddingBottom;
1072 }
1073
1074/* if (kDebug) {
1075 printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName,
1076 xDivs[0], xDivs[1],
1077 yDivs[0], yDivs[1]);
1078 printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName,
1079 image->info9Patch.paddingLeft, image->info9Patch.paddingRight,
1080 image->info9Patch.paddingTop, image->info9Patch.paddingBottom);
1081 }*/
1082
1083 // Remove frame from image.
1084 newRows.resize(H - 2);
1085 for (i = 0; i < H - 2; i++) {
1086 newRows[i] = image->rows[i + 1];
1087 memmove(newRows[i], newRows[i] + 4, (W - 2) * 4);
1088 }
1089 image->rows.swap(newRows);
1090
1091 image->width -= 2;
1092 W = image->width;
1093 image->height -= 2;
1094 H = image->height;
1095
1096 // Figure out the number of rows and columns in the N-patch
1097 numCols = numXDivs + 1;
1098 if (xDivs[0] == 0) { // Column 1 is strechable
1099 numCols--;
1100 }
1101 if (xDivs[numXDivs - 1] == W) {
1102 numCols--;
1103 }
1104 numRows = numYDivs + 1;
1105 if (yDivs[0] == 0) { // Row 1 is strechable
1106 numRows--;
1107 }
1108 if (yDivs[numYDivs - 1] == H) {
1109 numRows--;
1110 }
1111
1112 // Make sure the amount of rows and columns will fit in the number of
1113 // colors we can use in the 9-patch format.
1114 if (numRows * numCols > 0x7F) {
1115 errorMsg = "Too many rows and columns in 9-patch perimeter";
1116 goto getout;
1117 }
1118
1119 numColors = numRows * numCols;
1120 image->info9Patch.numColors = numColors;
1121 image->colors.resize(numColors);
1122
1123 // Fill in color information for each patch.
1124
1125 uint32_t c;
1126 top = 0;
1127
1128 // The first row always starts with the top being at y=0 and the bottom
1129 // being either yDivs[1] (if yDivs[0]=0) of yDivs[0]. In the former case
1130 // the first row is stretchable along the Y axis, otherwise it is fixed.
1131 // The last row always ends with the bottom being bitmap.height and the top
1132 // being either yDivs[numYDivs-2] (if yDivs[numYDivs-1]=bitmap.height) or
1133 // yDivs[numYDivs-1]. In the former case the last row is stretchable along
1134 // the Y axis, otherwise it is fixed.
1135 //
1136 // The first and last columns are similarly treated with respect to the X
1137 // axis.
1138 //
1139 // The above is to help explain some of the special casing that goes on the
1140 // code below.
1141
1142 // The initial yDiv and whether the first row is considered stretchable or
1143 // not depends on whether yDiv[0] was zero or not.
1144 for (j = (yDivs[0] == 0 ? 1 : 0); j <= numYDivs && top < H; j++) {
1145 if (j == numYDivs) {
1146 bottom = H;
1147 } else {
1148 bottom = yDivs[j];
1149 }
1150 left = 0;
1151 // The initial xDiv and whether the first column is considered
1152 // stretchable or not depends on whether xDiv[0] was zero or not.
1153 for (i = xDivs[0] == 0 ? 1 : 0; i <= numXDivs && left < W; i++) {
1154 if (i == numXDivs) {
1155 right = W;
1156 } else {
1157 right = xDivs[i];
1158 }
1159 c = getColor(image->rows.data(), left, top, right - 1, bottom - 1);
1160 image->colors[colorIndex++] = c;
1161 if (kDebug) {
1162 if (c != android::Res_png_9patch::NO_COLOR) {
1163 hasColor = true;
1164 }
1165 }
1166 left = right;
1167 }
1168 top = bottom;
1169 }
1170
1171 assert(colorIndex == numColors);
1172
1173 if (kDebug && hasColor) {
1174 for (i = 0; i < numColors; i++) {
1175 if (i == 0) printf("Colors:\n");
1176 printf(" #%08x", image->colors[i]);
1177 if (i == numColors - 1) printf("\n");
1178 }
1179 }
1180getout:
1181 if (errorMsg) {
1182 std::stringstream err;
1183 err << "9-patch malformed: " << errorMsg;
1184 if (!errorEdge) {
1185 err << "." << std::endl;
1186 if (errorPixel >= 0) {
1187 err << "Found at pixel #" << errorPixel << " along " << errorEdge << " edge";
1188 } else {
1189 err << "Found along " << errorEdge << " edge";
1190 }
1191 }
1192 *outError = err.str();
1193 return false;
1194 }
1195 return true;
1196}
1197
1198
1199bool Png::process(const Source& source, std::istream& input, std::ostream& output,
1200 const Options& options, std::string* outError) {
1201 png_byte signature[kPngSignatureSize];
1202
1203 // Read the PNG signature first.
1204 if (!input.read(reinterpret_cast<char*>(signature), kPngSignatureSize)) {
1205 *outError = strerror(errno);
1206 return false;
1207 }
1208
1209 // If the PNG signature doesn't match, bail early.
1210 if (png_sig_cmp(signature, 0, kPngSignatureSize) != 0) {
1211 *outError = "not a valid png file";
1212 return false;
1213 }
1214
1215 SourceLogger logger(source);
1216 bool result = false;
1217 png_structp readPtr = nullptr;
1218 png_infop infoPtr = nullptr;
1219 png_structp writePtr = nullptr;
1220 png_infop writeInfoPtr = nullptr;
1221 PngInfo pngInfo = {};
1222
1223 readPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr);
1224 if (!readPtr) {
1225 *outError = "failed to allocate read ptr";
1226 goto bail;
1227 }
1228
1229 infoPtr = png_create_info_struct(readPtr);
1230 if (!infoPtr) {
1231 *outError = "failed to allocate info ptr";
1232 goto bail;
1233 }
1234
1235 png_set_error_fn(readPtr, reinterpret_cast<png_voidp>(&logger), nullptr, logWarning);
1236
1237 // Set the read function to read from std::istream.
1238 png_set_read_fn(readPtr, (png_voidp)&input, readDataFromStream);
1239
1240 if (!readPng(readPtr, infoPtr, &pngInfo, outError)) {
1241 goto bail;
1242 }
1243
1244 if (util::stringEndsWith(source.path, ".9.png")) {
1245 if (!do9Patch(&pngInfo, outError)) {
1246 goto bail;
1247 }
1248 }
1249
1250 writePtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr);
1251 if (!writePtr) {
1252 *outError = "failed to allocate write ptr";
1253 goto bail;
1254 }
1255
1256 writeInfoPtr = png_create_info_struct(writePtr);
1257 if (!writeInfoPtr) {
1258 *outError = "failed to allocate write info ptr";
1259 goto bail;
1260 }
1261
1262 png_set_error_fn(writePtr, nullptr, nullptr, logWarning);
1263
1264 // Set the write function to write to std::ostream.
1265 png_set_write_fn(writePtr, (png_voidp)&output, writeDataToStream, flushDataToStream);
1266
1267 if (!writePng(writePtr, writeInfoPtr, &pngInfo, options.grayScaleTolerance, &logger,
1268 outError)) {
1269 goto bail;
1270 }
1271
1272 result = true;
1273bail:
1274 if (readPtr) {
1275 png_destroy_read_struct(&readPtr, &infoPtr, nullptr);
1276 }
1277
1278 if (writePtr) {
1279 png_destroy_write_struct(&writePtr, &writeInfoPtr);
1280 }
1281 return result;
1282}
1283
1284} // namespace aapt