blob: 627a231de5c8b48919d55797d12e27e4d2e247e9 [file] [log] [blame]
Adam Lesinski282e1812014-01-23 18:17:42 -08001//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
6
7#define PNG_INTERNAL
8
9#include "Images.h"
10
11#include <androidfw/ResourceTypes.h>
12#include <utils/ByteOrder.h>
13
14#include <png.h>
15#include <zlib.h>
16
Andreas Gampe2412f842014-09-30 20:55:57 -070017// Change this to true for noisy debug output.
18static const bool kIsDebug = false;
Adam Lesinski282e1812014-01-23 18:17:42 -080019
20static void
21png_write_aapt_file(png_structp png_ptr, png_bytep data, png_size_t length)
22{
23 AaptFile* aaptfile = (AaptFile*) png_get_io_ptr(png_ptr);
24 status_t err = aaptfile->writeData(data, length);
25 if (err != NO_ERROR) {
26 png_error(png_ptr, "Write Error");
27 }
28}
29
30
31static void
Andreas Gampe2412f842014-09-30 20:55:57 -070032png_flush_aapt_file(png_structp /* png_ptr */)
Adam Lesinski282e1812014-01-23 18:17:42 -080033{
34}
35
36// This holds an image as 8bpp RGBA.
37struct image_info
38{
Narayan Kamath6381dd42014-03-03 17:12:03 +000039 image_info() : rows(NULL), is9Patch(false),
40 xDivs(NULL), yDivs(NULL), colors(NULL), allocRows(NULL) { }
41
Adam Lesinski282e1812014-01-23 18:17:42 -080042 ~image_info() {
43 if (rows && rows != allocRows) {
44 free(rows);
45 }
46 if (allocRows) {
47 for (int i=0; i<(int)allocHeight; i++) {
48 free(allocRows[i]);
49 }
50 free(allocRows);
51 }
Narayan Kamath6381dd42014-03-03 17:12:03 +000052 free(xDivs);
53 free(yDivs);
54 free(colors);
55 }
56
57 void* serialize9patch() {
58 void* serialized = Res_png_9patch::serialize(info9Patch, xDivs, yDivs, colors);
59 reinterpret_cast<Res_png_9patch*>(serialized)->deviceToFile();
60 return serialized;
Adam Lesinski282e1812014-01-23 18:17:42 -080061 }
62
63 png_uint_32 width;
64 png_uint_32 height;
65 png_bytepp rows;
66
67 // 9-patch info.
68 bool is9Patch;
69 Res_png_9patch info9Patch;
Narayan Kamath6381dd42014-03-03 17:12:03 +000070 int32_t* xDivs;
71 int32_t* yDivs;
72 uint32_t* colors;
Adam Lesinski282e1812014-01-23 18:17:42 -080073
74 // Layout padding, if relevant
75 bool haveLayoutBounds;
76 int32_t layoutBoundsLeft;
77 int32_t layoutBoundsTop;
78 int32_t layoutBoundsRight;
79 int32_t layoutBoundsBottom;
80
Chris Craik47cd8e92014-07-08 17:13:08 -070081 // Round rect outline description
82 int32_t outlineInsetsLeft;
83 int32_t outlineInsetsTop;
84 int32_t outlineInsetsRight;
85 int32_t outlineInsetsBottom;
86 float outlineRadius;
Chris Craik77b5cad2014-07-30 18:23:07 -070087 uint8_t outlineAlpha;
Chris Craik47cd8e92014-07-08 17:13:08 -070088
Adam Lesinski282e1812014-01-23 18:17:42 -080089 png_uint_32 allocHeight;
90 png_bytepp allocRows;
91};
92
John Reck859e19f2013-09-05 16:26:04 -070093static void log_warning(png_structp png_ptr, png_const_charp warning_message)
94{
95 const char* imageName = (const char*) png_get_error_ptr(png_ptr);
96 fprintf(stderr, "%s: libpng warning: %s\n", imageName, warning_message);
97}
98
Adam Lesinski282e1812014-01-23 18:17:42 -080099static void read_png(const char* imageName,
100 png_structp read_ptr, png_infop read_info,
101 image_info* outImageInfo)
102{
103 int color_type;
104 int bit_depth, interlace_type, compression_type;
105 int i;
106
John Reck859e19f2013-09-05 16:26:04 -0700107 png_set_error_fn(read_ptr, const_cast<char*>(imageName),
108 NULL /* use default errorfn */, log_warning);
Adam Lesinski282e1812014-01-23 18:17:42 -0800109 png_read_info(read_ptr, read_info);
110
111 png_get_IHDR(read_ptr, read_info, &outImageInfo->width,
112 &outImageInfo->height, &bit_depth, &color_type,
113 &interlace_type, &compression_type, NULL);
114
115 //printf("Image %s:\n", imageName);
116 //printf("color_type=%d, bit_depth=%d, interlace_type=%d, compression_type=%d\n",
117 // color_type, bit_depth, interlace_type, compression_type);
118
119 if (color_type == PNG_COLOR_TYPE_PALETTE)
120 png_set_palette_to_rgb(read_ptr);
121
122 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
123 png_set_expand_gray_1_2_4_to_8(read_ptr);
124
125 if (png_get_valid(read_ptr, read_info, PNG_INFO_tRNS)) {
126 //printf("Has PNG_INFO_tRNS!\n");
127 png_set_tRNS_to_alpha(read_ptr);
128 }
129
130 if (bit_depth == 16)
131 png_set_strip_16(read_ptr);
132
133 if ((color_type&PNG_COLOR_MASK_ALPHA) == 0)
134 png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER);
135
136 if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
137 png_set_gray_to_rgb(read_ptr);
138
John Reck859e19f2013-09-05 16:26:04 -0700139 png_set_interlace_handling(read_ptr);
140
Adam Lesinski282e1812014-01-23 18:17:42 -0800141 png_read_update_info(read_ptr, read_info);
142
143 outImageInfo->rows = (png_bytepp)malloc(
144 outImageInfo->height * sizeof(png_bytep));
145 outImageInfo->allocHeight = outImageInfo->height;
146 outImageInfo->allocRows = outImageInfo->rows;
147
148 png_set_rows(read_ptr, read_info, outImageInfo->rows);
149
150 for (i = 0; i < (int)outImageInfo->height; i++)
151 {
152 outImageInfo->rows[i] = (png_bytep)
153 malloc(png_get_rowbytes(read_ptr, read_info));
154 }
155
156 png_read_image(read_ptr, outImageInfo->rows);
157
158 png_read_end(read_ptr, read_info);
159
Andreas Gampe2412f842014-09-30 20:55:57 -0700160 if (kIsDebug) {
161 printf("Image %s: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
162 imageName,
163 (int)outImageInfo->width, (int)outImageInfo->height,
164 bit_depth, color_type,
165 interlace_type, compression_type);
166 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800167
168 png_get_IHDR(read_ptr, read_info, &outImageInfo->width,
169 &outImageInfo->height, &bit_depth, &color_type,
170 &interlace_type, &compression_type, NULL);
171}
172
173#define COLOR_TRANSPARENT 0
174#define COLOR_WHITE 0xFFFFFFFF
175#define COLOR_TICK 0xFF000000
176#define COLOR_LAYOUT_BOUNDS_TICK 0xFF0000FF
177
178enum {
179 TICK_TYPE_NONE,
180 TICK_TYPE_TICK,
181 TICK_TYPE_LAYOUT_BOUNDS,
182 TICK_TYPE_BOTH
183};
184
185static int tick_type(png_bytep p, bool transparent, const char** outError)
186{
187 png_uint_32 color = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
188
189 if (transparent) {
190 if (p[3] == 0) {
191 return TICK_TYPE_NONE;
192 }
193 if (color == COLOR_LAYOUT_BOUNDS_TICK) {
194 return TICK_TYPE_LAYOUT_BOUNDS;
195 }
196 if (color == COLOR_TICK) {
197 return TICK_TYPE_TICK;
198 }
199
200 // Error cases
201 if (p[3] != 0xff) {
202 *outError = "Frame pixels must be either solid or transparent (not intermediate alphas)";
203 return TICK_TYPE_NONE;
204 }
205 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
206 *outError = "Ticks in transparent frame must be black or red";
207 }
208 return TICK_TYPE_TICK;
209 }
210
211 if (p[3] != 0xFF) {
212 *outError = "White frame must be a solid color (no alpha)";
213 }
214 if (color == COLOR_WHITE) {
215 return TICK_TYPE_NONE;
216 }
217 if (color == COLOR_TICK) {
218 return TICK_TYPE_TICK;
219 }
220 if (color == COLOR_LAYOUT_BOUNDS_TICK) {
221 return TICK_TYPE_LAYOUT_BOUNDS;
222 }
223
224 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
225 *outError = "Ticks in white frame must be black or red";
226 return TICK_TYPE_NONE;
227 }
228 return TICK_TYPE_TICK;
229}
230
231enum {
232 TICK_START,
233 TICK_INSIDE_1,
234 TICK_OUTSIDE_1
235};
236
237static status_t get_horizontal_ticks(
238 png_bytep row, int width, bool transparent, bool required,
239 int32_t* outLeft, int32_t* outRight, const char** outError,
240 uint8_t* outDivs, bool multipleAllowed)
241{
242 int i;
243 *outLeft = *outRight = -1;
244 int state = TICK_START;
245 bool found = false;
246
247 for (i=1; i<width-1; i++) {
248 if (TICK_TYPE_TICK == tick_type(row+i*4, transparent, outError)) {
249 if (state == TICK_START ||
250 (state == TICK_OUTSIDE_1 && multipleAllowed)) {
251 *outLeft = i-1;
252 *outRight = width-2;
253 found = true;
254 if (outDivs != NULL) {
255 *outDivs += 2;
256 }
257 state = TICK_INSIDE_1;
258 } else if (state == TICK_OUTSIDE_1) {
259 *outError = "Can't have more than one marked region along edge";
260 *outLeft = i;
261 return UNKNOWN_ERROR;
262 }
263 } else if (*outError == NULL) {
264 if (state == TICK_INSIDE_1) {
265 // We're done with this div. Move on to the next.
266 *outRight = i-1;
267 outRight += 2;
268 outLeft += 2;
269 state = TICK_OUTSIDE_1;
270 }
271 } else {
272 *outLeft = i;
273 return UNKNOWN_ERROR;
274 }
275 }
276
277 if (required && !found) {
278 *outError = "No marked region found along edge";
279 *outLeft = -1;
280 return UNKNOWN_ERROR;
281 }
282
283 return NO_ERROR;
284}
285
286static status_t get_vertical_ticks(
287 png_bytepp rows, int offset, int height, bool transparent, bool required,
288 int32_t* outTop, int32_t* outBottom, const char** outError,
289 uint8_t* outDivs, bool multipleAllowed)
290{
291 int i;
292 *outTop = *outBottom = -1;
293 int state = TICK_START;
294 bool found = false;
295
296 for (i=1; i<height-1; i++) {
297 if (TICK_TYPE_TICK == tick_type(rows[i]+offset, transparent, outError)) {
298 if (state == TICK_START ||
299 (state == TICK_OUTSIDE_1 && multipleAllowed)) {
300 *outTop = i-1;
301 *outBottom = height-2;
302 found = true;
303 if (outDivs != NULL) {
304 *outDivs += 2;
305 }
306 state = TICK_INSIDE_1;
307 } else if (state == TICK_OUTSIDE_1) {
308 *outError = "Can't have more than one marked region along edge";
309 *outTop = i;
310 return UNKNOWN_ERROR;
311 }
312 } else if (*outError == NULL) {
313 if (state == TICK_INSIDE_1) {
314 // We're done with this div. Move on to the next.
315 *outBottom = i-1;
316 outTop += 2;
317 outBottom += 2;
318 state = TICK_OUTSIDE_1;
319 }
320 } else {
321 *outTop = i;
322 return UNKNOWN_ERROR;
323 }
324 }
325
326 if (required && !found) {
327 *outError = "No marked region found along edge";
328 *outTop = -1;
329 return UNKNOWN_ERROR;
330 }
331
332 return NO_ERROR;
333}
334
335static status_t get_horizontal_layout_bounds_ticks(
Andreas Gampe2412f842014-09-30 20:55:57 -0700336 png_bytep row, int width, bool transparent, bool /* required */,
Adam Lesinski282e1812014-01-23 18:17:42 -0800337 int32_t* outLeft, int32_t* outRight, const char** outError)
338{
339 int i;
340 *outLeft = *outRight = 0;
341
342 // Look for left tick
343 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(row + 4, transparent, outError)) {
344 // Starting with a layout padding tick
345 i = 1;
346 while (i < width - 1) {
347 (*outLeft)++;
348 i++;
349 int tick = tick_type(row + i * 4, transparent, outError);
350 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
351 break;
352 }
353 }
354 }
355
356 // Look for right tick
357 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(row + (width - 2) * 4, transparent, outError)) {
358 // Ending with a layout padding tick
359 i = width - 2;
360 while (i > 1) {
361 (*outRight)++;
362 i--;
363 int tick = tick_type(row+i*4, transparent, outError);
364 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
365 break;
366 }
367 }
368 }
369
370 return NO_ERROR;
371}
372
373static status_t get_vertical_layout_bounds_ticks(
Andreas Gampe2412f842014-09-30 20:55:57 -0700374 png_bytepp rows, int offset, int height, bool transparent, bool /* required */,
Adam Lesinski282e1812014-01-23 18:17:42 -0800375 int32_t* outTop, int32_t* outBottom, const char** outError)
376{
377 int i;
378 *outTop = *outBottom = 0;
379
380 // Look for top tick
381 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(rows[1] + offset, transparent, outError)) {
382 // Starting with a layout padding tick
383 i = 1;
384 while (i < height - 1) {
385 (*outTop)++;
386 i++;
387 int tick = tick_type(rows[i] + offset, transparent, outError);
388 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
389 break;
390 }
391 }
392 }
393
394 // Look for bottom tick
395 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(rows[height - 2] + offset, transparent, outError)) {
396 // Ending with a layout padding tick
397 i = height - 2;
398 while (i > 1) {
399 (*outBottom)++;
400 i--;
401 int tick = tick_type(rows[i] + offset, transparent, outError);
402 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
403 break;
404 }
405 }
406 }
407
408 return NO_ERROR;
409}
410
Chris Craik47cd8e92014-07-08 17:13:08 -0700411static void find_max_opacity(png_byte** rows,
412 int startX, int startY, int endX, int endY, int dX, int dY,
413 int* out_inset)
414{
Chris Craik77b5cad2014-07-30 18:23:07 -0700415 uint8_t max_opacity = 0;
Chris Craik47cd8e92014-07-08 17:13:08 -0700416 int inset = 0;
417 *out_inset = 0;
418 for (int x = startX, y = startY; x != endX && y != endY; x += dX, y += dY, inset++) {
419 png_byte* color = rows[y] + x * 4;
Chris Craik77b5cad2014-07-30 18:23:07 -0700420 uint8_t opacity = color[3];
Chris Craik47cd8e92014-07-08 17:13:08 -0700421 if (opacity > max_opacity) {
422 max_opacity = opacity;
423 *out_inset = inset;
424 }
425 if (opacity == 0xff) return;
426 }
427}
428
Chris Craik77b5cad2014-07-30 18:23:07 -0700429static uint8_t max_alpha_over_row(png_byte* row, int startX, int endX)
Chris Craik47cd8e92014-07-08 17:13:08 -0700430{
Chris Craik77b5cad2014-07-30 18:23:07 -0700431 uint8_t max_alpha = 0;
Chris Craik47cd8e92014-07-08 17:13:08 -0700432 for (int x = startX; x < endX; x++) {
Chris Craik77b5cad2014-07-30 18:23:07 -0700433 uint8_t alpha = (row + x * 4)[3];
434 if (alpha > max_alpha) max_alpha = alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700435 }
Chris Craik77b5cad2014-07-30 18:23:07 -0700436 return max_alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700437}
438
Chris Craik77b5cad2014-07-30 18:23:07 -0700439static uint8_t max_alpha_over_col(png_byte** rows, int offsetX, int startY, int endY)
Chris Craik47cd8e92014-07-08 17:13:08 -0700440{
Chris Craik77b5cad2014-07-30 18:23:07 -0700441 uint8_t max_alpha = 0;
Chris Craik47cd8e92014-07-08 17:13:08 -0700442 for (int y = startY; y < endY; y++) {
Chris Craik77b5cad2014-07-30 18:23:07 -0700443 uint8_t alpha = (rows[y] + offsetX * 4)[3];
444 if (alpha > max_alpha) max_alpha = alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700445 }
Chris Craik77b5cad2014-07-30 18:23:07 -0700446 return max_alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700447}
448
449static void get_outline(image_info* image)
450{
451 int midX = image->width / 2;
452 int midY = image->height / 2;
453 int endX = image->width - 2;
454 int endY = image->height - 2;
455
456 // find left and right extent of nine patch content on center row
457 if (image->width > 4) {
458 find_max_opacity(image->rows, 1, midY, midX, -1, 1, 0, &image->outlineInsetsLeft);
459 find_max_opacity(image->rows, endX, midY, midX, -1, -1, 0, &image->outlineInsetsRight);
460 } else {
461 image->outlineInsetsLeft = 0;
462 image->outlineInsetsRight = 0;
463 }
464
465 // find top and bottom extent of nine patch content on center column
466 if (image->height > 4) {
467 find_max_opacity(image->rows, midX, 1, -1, midY, 0, 1, &image->outlineInsetsTop);
468 find_max_opacity(image->rows, midX, endY, -1, midY, 0, -1, &image->outlineInsetsBottom);
469 } else {
470 image->outlineInsetsTop = 0;
471 image->outlineInsetsBottom = 0;
472 }
473
474 int innerStartX = 1 + image->outlineInsetsLeft;
475 int innerStartY = 1 + image->outlineInsetsTop;
476 int innerEndX = endX - image->outlineInsetsRight;
477 int innerEndY = endY - image->outlineInsetsBottom;
478 int innerMidX = (innerEndX + innerStartX) / 2;
479 int innerMidY = (innerEndY + innerStartY) / 2;
480
481 // assuming the image is a round rect, compute the radius by marching
482 // diagonally from the top left corner towards the center
Dan Albert030f5362015-03-04 13:54:20 -0800483 image->outlineAlpha = std::max(
484 max_alpha_over_row(image->rows[innerMidY], innerStartX, innerEndX),
485 max_alpha_over_col(image->rows, innerMidX, innerStartY, innerStartY));
Chris Craik47cd8e92014-07-08 17:13:08 -0700486
487 int diagonalInset = 0;
488 find_max_opacity(image->rows, innerStartX, innerStartY, innerMidX, innerMidY, 1, 1,
489 &diagonalInset);
490
Chris Craik47d86232014-08-14 17:26:21 -0700491 /* Determine source radius based upon inset:
492 * sqrt(r^2 + r^2) = sqrt(i^2 + i^2) + r
493 * sqrt(2) * r = sqrt(2) * i + r
494 * (sqrt(2) - 1) * r = sqrt(2) * i
495 * r = sqrt(2) / (sqrt(2) - 1) * i
496 */
497 image->outlineRadius = 3.4142f * diagonalInset;
Chris Craik47cd8e92014-07-08 17:13:08 -0700498
Andreas Gampe8daabce2014-10-01 23:34:43 -0700499 if (kIsDebug) {
500 printf("outline insets %d %d %d %d, rad %f, alpha %x\n",
501 image->outlineInsetsLeft,
502 image->outlineInsetsTop,
503 image->outlineInsetsRight,
504 image->outlineInsetsBottom,
505 image->outlineRadius,
506 image->outlineAlpha);
507 }
Chris Craik47cd8e92014-07-08 17:13:08 -0700508}
509
Adam Lesinski282e1812014-01-23 18:17:42 -0800510
511static uint32_t get_color(
512 png_bytepp rows, int left, int top, int right, int bottom)
513{
514 png_bytep color = rows[top] + left*4;
515
516 if (left > right || top > bottom) {
517 return Res_png_9patch::TRANSPARENT_COLOR;
518 }
519
520 while (top <= bottom) {
521 for (int i = left; i <= right; i++) {
522 png_bytep p = rows[top]+i*4;
523 if (color[3] == 0) {
524 if (p[3] != 0) {
525 return Res_png_9patch::NO_COLOR;
526 }
527 } else if (p[0] != color[0] || p[1] != color[1]
528 || p[2] != color[2] || p[3] != color[3]) {
529 return Res_png_9patch::NO_COLOR;
530 }
531 }
532 top++;
533 }
534
535 if (color[3] == 0) {
536 return Res_png_9patch::TRANSPARENT_COLOR;
537 }
538 return (color[3]<<24) | (color[0]<<16) | (color[1]<<8) | color[2];
539}
540
Adam Lesinski282e1812014-01-23 18:17:42 -0800541static status_t do_9patch(const char* imageName, image_info* image)
542{
543 image->is9Patch = true;
544
545 int W = image->width;
546 int H = image->height;
547 int i, j;
548
549 int maxSizeXDivs = W * sizeof(int32_t);
550 int maxSizeYDivs = H * sizeof(int32_t);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000551 int32_t* xDivs = image->xDivs = (int32_t*) malloc(maxSizeXDivs);
552 int32_t* yDivs = image->yDivs = (int32_t*) malloc(maxSizeYDivs);
Elliott Hughesc367d482013-10-29 13:12:55 -0700553 uint8_t numXDivs = 0;
554 uint8_t numYDivs = 0;
555
Adam Lesinski282e1812014-01-23 18:17:42 -0800556 int8_t numColors;
557 int numRows;
558 int numCols;
559 int top;
560 int left;
561 int right;
562 int bottom;
563 memset(xDivs, -1, maxSizeXDivs);
564 memset(yDivs, -1, maxSizeYDivs);
565 image->info9Patch.paddingLeft = image->info9Patch.paddingRight =
566 image->info9Patch.paddingTop = image->info9Patch.paddingBottom = -1;
567
568 image->layoutBoundsLeft = image->layoutBoundsRight =
569 image->layoutBoundsTop = image->layoutBoundsBottom = 0;
570
571 png_bytep p = image->rows[0];
572 bool transparent = p[3] == 0;
573 bool hasColor = false;
574
575 const char* errorMsg = NULL;
576 int errorPixel = -1;
577 const char* errorEdge = NULL;
578
579 int colorIndex = 0;
580
581 // Validate size...
582 if (W < 3 || H < 3) {
583 errorMsg = "Image must be at least 3x3 (1x1 without frame) pixels";
584 goto getout;
585 }
586
587 // Validate frame...
588 if (!transparent &&
589 (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) {
590 errorMsg = "Must have one-pixel frame that is either transparent or white";
591 goto getout;
592 }
593
594 // Find left and right of sizing areas...
595 if (get_horizontal_ticks(p, W, transparent, true, &xDivs[0],
596 &xDivs[1], &errorMsg, &numXDivs, true) != NO_ERROR) {
597 errorPixel = xDivs[0];
598 errorEdge = "top";
599 goto getout;
600 }
601
602 // Find top and bottom of sizing areas...
603 if (get_vertical_ticks(image->rows, 0, H, transparent, true, &yDivs[0],
604 &yDivs[1], &errorMsg, &numYDivs, true) != NO_ERROR) {
605 errorPixel = yDivs[0];
606 errorEdge = "left";
607 goto getout;
608 }
609
Elliott Hughesb30296b2013-10-29 15:25:52 -0700610 // Copy patch size data into image...
611 image->info9Patch.numXDivs = numXDivs;
612 image->info9Patch.numYDivs = numYDivs;
613
Adam Lesinski282e1812014-01-23 18:17:42 -0800614 // Find left and right of padding area...
615 if (get_horizontal_ticks(image->rows[H-1], W, transparent, false, &image->info9Patch.paddingLeft,
616 &image->info9Patch.paddingRight, &errorMsg, NULL, false) != NO_ERROR) {
617 errorPixel = image->info9Patch.paddingLeft;
618 errorEdge = "bottom";
619 goto getout;
620 }
621
622 // Find top and bottom of padding area...
623 if (get_vertical_ticks(image->rows, (W-1)*4, H, transparent, false, &image->info9Patch.paddingTop,
624 &image->info9Patch.paddingBottom, &errorMsg, NULL, false) != NO_ERROR) {
625 errorPixel = image->info9Patch.paddingTop;
626 errorEdge = "right";
627 goto getout;
628 }
629
630 // Find left and right of layout padding...
631 get_horizontal_layout_bounds_ticks(image->rows[H-1], W, transparent, false,
632 &image->layoutBoundsLeft,
633 &image->layoutBoundsRight, &errorMsg);
634
635 get_vertical_layout_bounds_ticks(image->rows, (W-1)*4, H, transparent, false,
636 &image->layoutBoundsTop,
637 &image->layoutBoundsBottom, &errorMsg);
638
639 image->haveLayoutBounds = image->layoutBoundsLeft != 0
640 || image->layoutBoundsRight != 0
641 || image->layoutBoundsTop != 0
642 || image->layoutBoundsBottom != 0;
643
644 if (image->haveLayoutBounds) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700645 if (kIsDebug) {
646 printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
647 image->layoutBoundsRight, image->layoutBoundsBottom);
648 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800649 }
650
Chris Craik47cd8e92014-07-08 17:13:08 -0700651 // use opacity of pixels to estimate the round rect outline
652 get_outline(image);
653
Adam Lesinski282e1812014-01-23 18:17:42 -0800654 // If padding is not yet specified, take values from size.
655 if (image->info9Patch.paddingLeft < 0) {
656 image->info9Patch.paddingLeft = xDivs[0];
657 image->info9Patch.paddingRight = W - 2 - xDivs[1];
658 } else {
659 // Adjust value to be correct!
660 image->info9Patch.paddingRight = W - 2 - image->info9Patch.paddingRight;
661 }
662 if (image->info9Patch.paddingTop < 0) {
663 image->info9Patch.paddingTop = yDivs[0];
664 image->info9Patch.paddingBottom = H - 2 - yDivs[1];
665 } else {
666 // Adjust value to be correct!
667 image->info9Patch.paddingBottom = H - 2 - image->info9Patch.paddingBottom;
668 }
669
Andreas Gampe2412f842014-09-30 20:55:57 -0700670 if (kIsDebug) {
671 printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName,
Andreas Gampe8daabce2014-10-01 23:34:43 -0700672 xDivs[0], xDivs[1],
673 yDivs[0], yDivs[1]);
Andreas Gampe2412f842014-09-30 20:55:57 -0700674 printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName,
675 image->info9Patch.paddingLeft, image->info9Patch.paddingRight,
676 image->info9Patch.paddingTop, image->info9Patch.paddingBottom);
677 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800678
679 // Remove frame from image.
680 image->rows = (png_bytepp)malloc((H-2) * sizeof(png_bytep));
681 for (i=0; i<(H-2); i++) {
682 image->rows[i] = image->allocRows[i+1];
683 memmove(image->rows[i], image->rows[i]+4, (W-2)*4);
684 }
685 image->width -= 2;
686 W = image->width;
687 image->height -= 2;
688 H = image->height;
689
690 // Figure out the number of rows and columns in the N-patch
691 numCols = numXDivs + 1;
692 if (xDivs[0] == 0) { // Column 1 is strechable
693 numCols--;
694 }
695 if (xDivs[numXDivs - 1] == W) {
696 numCols--;
697 }
698 numRows = numYDivs + 1;
699 if (yDivs[0] == 0) { // Row 1 is strechable
700 numRows--;
701 }
702 if (yDivs[numYDivs - 1] == H) {
703 numRows--;
704 }
705
706 // Make sure the amount of rows and columns will fit in the number of
707 // colors we can use in the 9-patch format.
708 if (numRows * numCols > 0x7F) {
709 errorMsg = "Too many rows and columns in 9-patch perimeter";
710 goto getout;
711 }
712
713 numColors = numRows * numCols;
714 image->info9Patch.numColors = numColors;
Narayan Kamath6381dd42014-03-03 17:12:03 +0000715 image->colors = (uint32_t*)malloc(numColors * sizeof(uint32_t));
Adam Lesinski282e1812014-01-23 18:17:42 -0800716
717 // Fill in color information for each patch.
718
719 uint32_t c;
720 top = 0;
721
722 // The first row always starts with the top being at y=0 and the bottom
723 // being either yDivs[1] (if yDivs[0]=0) of yDivs[0]. In the former case
724 // the first row is stretchable along the Y axis, otherwise it is fixed.
725 // The last row always ends with the bottom being bitmap.height and the top
726 // being either yDivs[numYDivs-2] (if yDivs[numYDivs-1]=bitmap.height) or
727 // yDivs[numYDivs-1]. In the former case the last row is stretchable along
728 // the Y axis, otherwise it is fixed.
729 //
730 // The first and last columns are similarly treated with respect to the X
731 // axis.
732 //
733 // The above is to help explain some of the special casing that goes on the
734 // code below.
735
736 // The initial yDiv and whether the first row is considered stretchable or
737 // not depends on whether yDiv[0] was zero or not.
738 for (j = (yDivs[0] == 0 ? 1 : 0);
739 j <= numYDivs && top < H;
740 j++) {
741 if (j == numYDivs) {
742 bottom = H;
743 } else {
744 bottom = yDivs[j];
745 }
746 left = 0;
747 // The initial xDiv and whether the first column is considered
748 // stretchable or not depends on whether xDiv[0] was zero or not.
749 for (i = xDivs[0] == 0 ? 1 : 0;
750 i <= numXDivs && left < W;
751 i++) {
752 if (i == numXDivs) {
753 right = W;
754 } else {
755 right = xDivs[i];
756 }
757 c = get_color(image->rows, left, top, right - 1, bottom - 1);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000758 image->colors[colorIndex++] = c;
Andreas Gampe2412f842014-09-30 20:55:57 -0700759 if (kIsDebug) {
760 if (c != Res_png_9patch::NO_COLOR)
761 hasColor = true;
762 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800763 left = right;
764 }
765 top = bottom;
766 }
767
768 assert(colorIndex == numColors);
769
770 for (i=0; i<numColors; i++) {
771 if (hasColor) {
772 if (i == 0) printf("Colors in %s:\n ", imageName);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000773 printf(" #%08x", image->colors[i]);
Adam Lesinski282e1812014-01-23 18:17:42 -0800774 if (i == numColors - 1) printf("\n");
775 }
776 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800777getout:
778 if (errorMsg) {
779 fprintf(stderr,
780 "ERROR: 9-patch image %s malformed.\n"
781 " %s.\n", imageName, errorMsg);
782 if (errorEdge != NULL) {
783 if (errorPixel >= 0) {
784 fprintf(stderr,
785 " Found at pixel #%d along %s edge.\n", errorPixel, errorEdge);
786 } else {
787 fprintf(stderr,
788 " Found along %s edge.\n", errorEdge);
789 }
790 }
791 return UNKNOWN_ERROR;
792 }
793 return NO_ERROR;
794}
795
Narayan Kamath6381dd42014-03-03 17:12:03 +0000796static void checkNinePatchSerialization(Res_png_9patch* inPatch, void* data)
Adam Lesinski282e1812014-01-23 18:17:42 -0800797{
Adam Lesinski282e1812014-01-23 18:17:42 -0800798 size_t patchSize = inPatch->serializedSize();
Narayan Kamath6381dd42014-03-03 17:12:03 +0000799 void* newData = malloc(patchSize);
Adam Lesinski282e1812014-01-23 18:17:42 -0800800 memcpy(newData, data, patchSize);
801 Res_png_9patch* outPatch = inPatch->deserialize(newData);
802 // deserialization is done in place, so outPatch == newData
803 assert(outPatch == newData);
804 assert(outPatch->numXDivs == inPatch->numXDivs);
805 assert(outPatch->numYDivs == inPatch->numYDivs);
806 assert(outPatch->paddingLeft == inPatch->paddingLeft);
807 assert(outPatch->paddingRight == inPatch->paddingRight);
808 assert(outPatch->paddingTop == inPatch->paddingTop);
809 assert(outPatch->paddingBottom == inPatch->paddingBottom);
810 for (int i = 0; i < outPatch->numXDivs; i++) {
Adam Lesinski526d73b2016-07-18 17:01:14 -0700811 assert(outPatch->getXDivs()[i] == inPatch->getXDivs()[i]);
Adam Lesinski282e1812014-01-23 18:17:42 -0800812 }
813 for (int i = 0; i < outPatch->numYDivs; i++) {
Adam Lesinski526d73b2016-07-18 17:01:14 -0700814 assert(outPatch->getYDivs()[i] == inPatch->getYDivs()[i]);
Adam Lesinski282e1812014-01-23 18:17:42 -0800815 }
816 for (int i = 0; i < outPatch->numColors; i++) {
Adam Lesinski526d73b2016-07-18 17:01:14 -0700817 assert(outPatch->getColors()[i] == inPatch->getColors()[i]);
Adam Lesinski282e1812014-01-23 18:17:42 -0800818 }
819 free(newData);
820}
821
Adam Lesinski282e1812014-01-23 18:17:42 -0800822static void dump_image(int w, int h, png_bytepp rows, int color_type)
823{
824 int i, j, rr, gg, bb, aa;
825
826 int bpp;
827 if (color_type == PNG_COLOR_TYPE_PALETTE || color_type == PNG_COLOR_TYPE_GRAY) {
828 bpp = 1;
829 } else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
830 bpp = 2;
831 } else if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
832 // We use a padding byte even when there is no alpha
833 bpp = 4;
834 } else {
835 printf("Unknown color type %d.\n", color_type);
George Burgess IV0c2774b2016-10-11 17:51:10 -0700836 return;
Adam Lesinski282e1812014-01-23 18:17:42 -0800837 }
838
839 for (j = 0; j < h; j++) {
840 png_bytep row = rows[j];
841 for (i = 0; i < w; i++) {
842 rr = row[0];
843 gg = row[1];
844 bb = row[2];
845 aa = row[3];
846 row += bpp;
847
848 if (i == 0) {
849 printf("Row %d:", j);
850 }
851 switch (bpp) {
852 case 1:
853 printf(" (%d)", rr);
854 break;
855 case 2:
856 printf(" (%d %d", rr, gg);
857 break;
858 case 3:
859 printf(" (%d %d %d)", rr, gg, bb);
860 break;
861 case 4:
862 printf(" (%d %d %d %d)", rr, gg, bb, aa);
863 break;
864 }
865 if (i == (w - 1)) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700866 printf("\n");
Adam Lesinski282e1812014-01-23 18:17:42 -0800867 }
868 }
869 }
870}
871
872#define MAX(a,b) ((a)>(b)?(a):(b))
873#define ABS(a) ((a)<0?-(a):(a))
874
875static void analyze_image(const char *imageName, image_info &imageInfo, int grayscaleTolerance,
876 png_colorp rgbPalette, png_bytep alphaPalette,
Matt Sarett2a84e232016-01-28 18:38:38 -0500877 int *paletteEntries, int *alphaPaletteEntries, bool *hasTransparency,
878 int *colorType, png_bytepp outRows)
Adam Lesinski282e1812014-01-23 18:17:42 -0800879{
880 int w = imageInfo.width;
881 int h = imageInfo.height;
Matt Sarett2a84e232016-01-28 18:38:38 -0500882 int i, j, rr, gg, bb, aa, idx;;
883 uint32_t opaqueColors[256], alphaColors[256];
884 uint32_t col;
885 int numOpaqueColors = 0, numAlphaColors = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -0800886 int maxGrayDeviation = 0;
887
888 bool isOpaque = true;
889 bool isPalette = true;
890 bool isGrayscale = true;
891
892 // Scan the entire image and determine if:
893 // 1. Every pixel has R == G == B (grayscale)
894 // 2. Every pixel has A == 255 (opaque)
895 // 3. There are no more than 256 distinct RGBA colors
Matt Sarett2a84e232016-01-28 18:38:38 -0500896 // We will track opaque colors separately from colors with
897 // alpha. This allows us to reencode the color table more
898 // efficiently (color tables entries without a corresponding
899 // alpha value are assumed to be opaque).
Adam Lesinski282e1812014-01-23 18:17:42 -0800900
Andreas Gampe2412f842014-09-30 20:55:57 -0700901 if (kIsDebug) {
902 printf("Initial image data:\n");
903 dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA);
904 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800905
906 for (j = 0; j < h; j++) {
907 png_bytep row = imageInfo.rows[j];
908 png_bytep out = outRows[j];
909 for (i = 0; i < w; i++) {
Matt Sarett33fcd112016-01-29 18:02:41 -0500910
911 // Make sure any zero alpha pixels are fully zeroed. On average,
912 // each of our PNG assets seem to have about four distinct pixels
913 // with zero alpha.
914 // There are several advantages to setting these to zero:
915 // (1) Images are more likely able to be encodable with a palette.
916 // (2) Image palettes will be smaller.
917 // (3) Premultiplied and unpremultiplied PNG decodes can skip
918 // writing zeros to memory, often saving significant numbers
919 // of memory pages.
920 aa = *(row + 3);
921 if (aa == 0) {
922 rr = 0;
923 gg = 0;
924 bb = 0;
925
926 // Also set red, green, and blue to zero in "row". If we later
927 // decide to encode the PNG as RGB or RGBA, we will use the
928 // values stored there.
929 *(row) = 0;
930 *(row + 1) = 0;
931 *(row + 2) = 0;
932 } else {
933 rr = *(row);
934 gg = *(row + 1);
935 bb = *(row + 2);
936 }
937 row += 4;
Adam Lesinski282e1812014-01-23 18:17:42 -0800938
939 int odev = maxGrayDeviation;
940 maxGrayDeviation = MAX(ABS(rr - gg), maxGrayDeviation);
941 maxGrayDeviation = MAX(ABS(gg - bb), maxGrayDeviation);
942 maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation);
943 if (maxGrayDeviation > odev) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700944 if (kIsDebug) {
945 printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
946 maxGrayDeviation, i, j, rr, gg, bb, aa);
947 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800948 }
949
950 // Check if image is really grayscale
951 if (isGrayscale) {
952 if (rr != gg || rr != bb) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700953 if (kIsDebug) {
954 printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n",
955 i, j, rr, gg, bb, aa);
956 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800957 isGrayscale = false;
958 }
959 }
960
961 // Check if image is really opaque
962 if (isOpaque) {
963 if (aa != 0xff) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700964 if (kIsDebug) {
965 printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n",
966 i, j, rr, gg, bb, aa);
967 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800968 isOpaque = false;
969 }
970 }
971
972 // Check if image is really <= 256 colors
973 if (isPalette) {
974 col = (uint32_t) ((rr << 24) | (gg << 16) | (bb << 8) | aa);
975 bool match = false;
Matt Sarett2a84e232016-01-28 18:38:38 -0500976
977 if (aa == 0xff) {
978 for (idx = 0; idx < numOpaqueColors; idx++) {
979 if (opaqueColors[idx] == col) {
980 match = true;
981 break;
982 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800983 }
Matt Sarett2a84e232016-01-28 18:38:38 -0500984
985 if (!match) {
986 if (numOpaqueColors < 256) {
987 opaqueColors[numOpaqueColors] = col;
988 }
989 numOpaqueColors++;
990 }
991
992 // Write the palette index for the pixel to outRows optimistically.
993 // We might overwrite it later if we decide to encode as gray or
994 // gray + alpha. We may also need to overwrite it when we combine
995 // into a single palette.
996 *out++ = idx;
997 } else {
998 for (idx = 0; idx < numAlphaColors; idx++) {
999 if (alphaColors[idx] == col) {
1000 match = true;
1001 break;
1002 }
1003 }
1004
1005 if (!match) {
1006 if (numAlphaColors < 256) {
1007 alphaColors[numAlphaColors] = col;
1008 }
1009 numAlphaColors++;
1010 }
1011
1012 // Write the palette index for the pixel to outRows optimistically.
1013 // We might overwrite it later if we decide to encode as gray or
1014 // gray + alpha.
1015 *out++ = idx;
Adam Lesinski282e1812014-01-23 18:17:42 -08001016 }
1017
Matt Sarett2a84e232016-01-28 18:38:38 -05001018 if (numOpaqueColors + numAlphaColors > 256) {
1019 if (kIsDebug) {
1020 printf("Found 257th color at %d, %d\n", i, j);
Adam Lesinski282e1812014-01-23 18:17:42 -08001021 }
Matt Sarett2a84e232016-01-28 18:38:38 -05001022 isPalette = false;
Adam Lesinski282e1812014-01-23 18:17:42 -08001023 }
1024 }
1025 }
1026 }
1027
Matt Sarett2a84e232016-01-28 18:38:38 -05001028 // If we decide to encode the image using a palette, we will reset these counts
1029 // to the appropriate values later. Initializing them here avoids compiler
1030 // complaints about uses of possibly uninitialized variables.
Adam Lesinski282e1812014-01-23 18:17:42 -08001031 *paletteEntries = 0;
Matt Sarett2a84e232016-01-28 18:38:38 -05001032 *alphaPaletteEntries = 0;
Adam Lesinski282e1812014-01-23 18:17:42 -08001033
Matt Sarett2a84e232016-01-28 18:38:38 -05001034 *hasTransparency = !isOpaque;
1035 int paletteSize = w * h + 3 * numOpaqueColors + 4 * numAlphaColors;
1036
1037 int bpp = isOpaque ? 3 : 4;
Andreas Gampe2412f842014-09-30 20:55:57 -07001038 if (kIsDebug) {
1039 printf("isGrayscale = %s\n", isGrayscale ? "true" : "false");
1040 printf("isOpaque = %s\n", isOpaque ? "true" : "false");
1041 printf("isPalette = %s\n", isPalette ? "true" : "false");
1042 printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n",
1043 paletteSize, 2 * w * h, bpp * w * h);
1044 printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance);
1045 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001046
1047 // Choose the best color type for the image.
1048 // 1. Opaque gray - use COLOR_TYPE_GRAY at 1 byte/pixel
1049 // 2. Gray + alpha - use COLOR_TYPE_PALETTE if the number of distinct combinations
1050 // is sufficiently small, otherwise use COLOR_TYPE_GRAY_ALPHA
1051 // 3. RGB(A) - use COLOR_TYPE_PALETTE if the number of distinct colors is sufficiently
1052 // small, otherwise use COLOR_TYPE_RGB{_ALPHA}
1053 if (isGrayscale) {
1054 if (isOpaque) {
1055 *colorType = PNG_COLOR_TYPE_GRAY; // 1 byte/pixel
1056 } else {
1057 // Use a simple heuristic to determine whether using a palette will
1058 // save space versus using gray + alpha for each pixel.
1059 // This doesn't take into account chunk overhead, filtering, LZ
1060 // compression, etc.
1061 if (isPalette && (paletteSize < 2 * w * h)) {
1062 *colorType = PNG_COLOR_TYPE_PALETTE; // 1 byte/pixel + 4 bytes/color
1063 } else {
1064 *colorType = PNG_COLOR_TYPE_GRAY_ALPHA; // 2 bytes per pixel
1065 }
1066 }
1067 } else if (isPalette && (paletteSize < bpp * w * h)) {
1068 *colorType = PNG_COLOR_TYPE_PALETTE;
1069 } else {
1070 if (maxGrayDeviation <= grayscaleTolerance) {
1071 printf("%s: forcing image to gray (max deviation = %d)\n", imageName, maxGrayDeviation);
1072 *colorType = isOpaque ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA;
1073 } else {
1074 *colorType = isOpaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA;
1075 }
1076 }
1077
1078 // Perform postprocessing of the image or palette data based on the final
1079 // color type chosen
1080
1081 if (*colorType == PNG_COLOR_TYPE_PALETTE) {
Matt Sarett2a84e232016-01-28 18:38:38 -05001082 // Combine the alphaColors and the opaqueColors into a single palette.
1083 // The alphaColors must be at the start of the palette.
1084 uint32_t* colors = alphaColors;
1085 memcpy(colors + numAlphaColors, opaqueColors, 4 * numOpaqueColors);
1086
1087 // Fix the indices of the opaque colors in the image.
1088 for (j = 0; j < h; j++) {
1089 png_bytep row = imageInfo.rows[j];
1090 png_bytep out = outRows[j];
1091 for (i = 0; i < w; i++) {
1092 uint32_t pixel = ((uint32_t*) row)[i];
1093 if (pixel >> 24 == 0xFF) {
1094 out[i] += numAlphaColors;
1095 }
1096 }
1097 }
1098
Adam Lesinski282e1812014-01-23 18:17:42 -08001099 // Create separate RGB and Alpha palettes and set the number of colors
Matt Sarett2a84e232016-01-28 18:38:38 -05001100 int numColors = numOpaqueColors + numAlphaColors;
1101 *paletteEntries = numColors;
1102 *alphaPaletteEntries = numAlphaColors;
Adam Lesinski282e1812014-01-23 18:17:42 -08001103
1104 // Create the RGB and alpha palettes
Matt Sarett2a84e232016-01-28 18:38:38 -05001105 for (int idx = 0; idx < numColors; idx++) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001106 col = colors[idx];
1107 rgbPalette[idx].red = (png_byte) ((col >> 24) & 0xff);
1108 rgbPalette[idx].green = (png_byte) ((col >> 16) & 0xff);
1109 rgbPalette[idx].blue = (png_byte) ((col >> 8) & 0xff);
Matt Sarett2a84e232016-01-28 18:38:38 -05001110 if (idx < numAlphaColors) {
1111 alphaPalette[idx] = (png_byte) (col & 0xff);
1112 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001113 }
1114 } else if (*colorType == PNG_COLOR_TYPE_GRAY || *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
1115 // If the image is gray or gray + alpha, compact the pixels into outRows
1116 for (j = 0; j < h; j++) {
1117 png_bytep row = imageInfo.rows[j];
1118 png_bytep out = outRows[j];
1119 for (i = 0; i < w; i++) {
1120 rr = *row++;
1121 gg = *row++;
1122 bb = *row++;
1123 aa = *row++;
1124
1125 if (isGrayscale) {
1126 *out++ = rr;
1127 } else {
1128 *out++ = (png_byte) (rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
1129 }
1130 if (!isOpaque) {
1131 *out++ = aa;
1132 }
1133 }
1134 }
1135 }
1136}
1137
Adam Lesinski282e1812014-01-23 18:17:42 -08001138static void write_png(const char* imageName,
1139 png_structp write_ptr, png_infop write_info,
Matt Sarett48efde4f2016-03-16 18:22:59 -04001140 image_info& imageInfo, const Bundle* bundle)
Adam Lesinski282e1812014-01-23 18:17:42 -08001141{
Adam Lesinski282e1812014-01-23 18:17:42 -08001142 png_uint_32 width, height;
1143 int color_type;
1144 int bit_depth, interlace_type, compression_type;
1145 int i;
1146
Chris Craik47cd8e92014-07-08 17:13:08 -07001147 png_unknown_chunk unknowns[3];
Adam Lesinski282e1812014-01-23 18:17:42 -08001148 unknowns[0].data = NULL;
1149 unknowns[1].data = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -07001150 unknowns[2].data = NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08001151
1152 png_bytepp outRows = (png_bytepp) malloc((int) imageInfo.height * sizeof(png_bytep));
1153 if (outRows == (png_bytepp) 0) {
1154 printf("Can't allocate output buffer!\n");
1155 exit(1);
1156 }
1157 for (i = 0; i < (int) imageInfo.height; i++) {
1158 outRows[i] = (png_bytep) malloc(2 * (int) imageInfo.width);
1159 if (outRows[i] == (png_bytep) 0) {
1160 printf("Can't allocate output buffer!\n");
1161 exit(1);
1162 }
1163 }
1164
1165 png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
1166
Andreas Gampe2412f842014-09-30 20:55:57 -07001167 if (kIsDebug) {
1168 printf("Writing image %s: w = %d, h = %d\n", imageName,
1169 (int) imageInfo.width, (int) imageInfo.height);
1170 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001171
1172 png_color rgbPalette[256];
1173 png_byte alphaPalette[256];
1174 bool hasTransparency;
Matt Sarett2a84e232016-01-28 18:38:38 -05001175 int paletteEntries, alphaPaletteEntries;
Adam Lesinski282e1812014-01-23 18:17:42 -08001176
Matt Sarett48efde4f2016-03-16 18:22:59 -04001177 int grayscaleTolerance = bundle->getGrayscaleTolerance();
Adam Lesinski282e1812014-01-23 18:17:42 -08001178 analyze_image(imageName, imageInfo, grayscaleTolerance, rgbPalette, alphaPalette,
Matt Sarett2a84e232016-01-28 18:38:38 -05001179 &paletteEntries, &alphaPaletteEntries, &hasTransparency, &color_type, outRows);
Adam Lesinski282e1812014-01-23 18:17:42 -08001180
Matt Sarett48efde4f2016-03-16 18:22:59 -04001181 // Legacy versions of aapt would always encode 9patch PNGs as RGBA. This had the unintended
1182 // benefit of working around a bug decoding paletted images in Android 4.1.
1183 // https://code.google.com/p/android/issues/detail?id=34619
1184 //
1185 // If SDK_JELLY_BEAN is supported, we need to avoid a paletted encoding in order to not expose
1186 // this bug.
1187 if (!bundle->isMinSdkAtLeast(SDK_JELLY_BEAN_MR1)) {
1188 if (imageInfo.is9Patch && PNG_COLOR_TYPE_PALETTE == color_type) {
1189 if (hasTransparency) {
1190 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1191 } else {
1192 color_type = PNG_COLOR_TYPE_RGB;
1193 }
1194 }
1195 }
1196
Andreas Gampe2412f842014-09-30 20:55:57 -07001197 if (kIsDebug) {
1198 switch (color_type) {
1199 case PNG_COLOR_TYPE_PALETTE:
1200 printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n",
1201 imageName, paletteEntries,
1202 hasTransparency ? " (with alpha)" : "");
1203 break;
1204 case PNG_COLOR_TYPE_GRAY:
1205 printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName);
1206 break;
1207 case PNG_COLOR_TYPE_GRAY_ALPHA:
1208 printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName);
1209 break;
1210 case PNG_COLOR_TYPE_RGB:
1211 printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName);
1212 break;
1213 case PNG_COLOR_TYPE_RGB_ALPHA:
1214 printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName);
1215 break;
1216 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001217 }
1218
1219 png_set_IHDR(write_ptr, write_info, imageInfo.width, imageInfo.height,
1220 8, color_type, PNG_INTERLACE_NONE,
1221 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1222
1223 if (color_type == PNG_COLOR_TYPE_PALETTE) {
1224 png_set_PLTE(write_ptr, write_info, rgbPalette, paletteEntries);
1225 if (hasTransparency) {
Matt Sarett2a84e232016-01-28 18:38:38 -05001226 png_set_tRNS(write_ptr, write_info, alphaPalette, alphaPaletteEntries,
1227 (png_color_16p) 0);
Adam Lesinski282e1812014-01-23 18:17:42 -08001228 }
1229 png_set_filter(write_ptr, 0, PNG_NO_FILTERS);
1230 } else {
1231 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
1232 }
1233
1234 if (imageInfo.is9Patch) {
Chris Craik47cd8e92014-07-08 17:13:08 -07001235 int chunk_count = 2 + (imageInfo.haveLayoutBounds ? 1 : 0);
1236 int p_index = imageInfo.haveLayoutBounds ? 2 : 1;
1237 int b_index = 1;
1238 int o_index = 0;
1239
1240 // Chunks ordered thusly because older platforms depend on the base 9 patch data being last
Adam Lesinski282e1812014-01-23 18:17:42 -08001241 png_byte *chunk_names = imageInfo.haveLayoutBounds
Chris Craik47cd8e92014-07-08 17:13:08 -07001242 ? (png_byte*)"npOl\0npLb\0npTc\0"
1243 : (png_byte*)"npOl\0npTc";
1244
1245 // base 9 patch data
Andreas Gampe2412f842014-09-30 20:55:57 -07001246 if (kIsDebug) {
1247 printf("Adding 9-patch info...\n");
1248 }
Yunlian Jiangd32ae102017-09-13 12:01:15 -07001249 memcpy((char*)unknowns[p_index].name, "npTc", 5);
Narayan Kamath6381dd42014-03-03 17:12:03 +00001250 unknowns[p_index].data = (png_byte*)imageInfo.serialize9patch();
Adam Lesinski282e1812014-01-23 18:17:42 -08001251 unknowns[p_index].size = imageInfo.info9Patch.serializedSize();
1252 // TODO: remove the check below when everything works
1253 checkNinePatchSerialization(&imageInfo.info9Patch, unknowns[p_index].data);
1254
Chris Craik47cd8e92014-07-08 17:13:08 -07001255 // automatically generated 9 patch outline data
1256 int chunk_size = sizeof(png_uint_32) * 6;
Yunlian Jiangd32ae102017-09-13 12:01:15 -07001257 memcpy((char*)unknowns[o_index].name, "npOl", 5);
Chris Craik47cd8e92014-07-08 17:13:08 -07001258 unknowns[o_index].data = (png_byte*) calloc(chunk_size, 1);
1259 png_byte outputData[chunk_size];
1260 memcpy(&outputData, &imageInfo.outlineInsetsLeft, 4 * sizeof(png_uint_32));
1261 ((float*) outputData)[4] = imageInfo.outlineRadius;
Chris Craik77b5cad2014-07-30 18:23:07 -07001262 ((png_uint_32*) outputData)[5] = imageInfo.outlineAlpha;
Chris Craik47cd8e92014-07-08 17:13:08 -07001263 memcpy(unknowns[o_index].data, &outputData, chunk_size);
1264 unknowns[o_index].size = chunk_size;
1265
1266 // optional optical inset / layout bounds data
Adam Lesinski282e1812014-01-23 18:17:42 -08001267 if (imageInfo.haveLayoutBounds) {
1268 int chunk_size = sizeof(png_uint_32) * 4;
Yunlian Jiangd32ae102017-09-13 12:01:15 -07001269 memcpy((char*)unknowns[b_index].name, "npLb", 5);
Adam Lesinski282e1812014-01-23 18:17:42 -08001270 unknowns[b_index].data = (png_byte*) calloc(chunk_size, 1);
1271 memcpy(unknowns[b_index].data, &imageInfo.layoutBoundsLeft, chunk_size);
1272 unknowns[b_index].size = chunk_size;
1273 }
1274
1275 for (int i = 0; i < chunk_count; i++) {
Matt Sarett3b1b68d2015-12-14 13:08:33 -05001276 unknowns[i].location = PNG_HAVE_IHDR;
Adam Lesinski282e1812014-01-23 18:17:42 -08001277 }
1278 png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS,
1279 chunk_names, chunk_count);
1280 png_set_unknown_chunks(write_ptr, write_info, unknowns, chunk_count);
Adam Lesinski282e1812014-01-23 18:17:42 -08001281 }
1282
1283
1284 png_write_info(write_ptr, write_info);
1285
1286 png_bytepp rows;
1287 if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
1288 if (color_type == PNG_COLOR_TYPE_RGB) {
1289 png_set_filler(write_ptr, 0, PNG_FILLER_AFTER);
1290 }
1291 rows = imageInfo.rows;
1292 } else {
1293 rows = outRows;
1294 }
1295 png_write_image(write_ptr, rows);
1296
Andreas Gampe2412f842014-09-30 20:55:57 -07001297 if (kIsDebug) {
1298 printf("Final image data:\n");
1299 dump_image(imageInfo.width, imageInfo.height, rows, color_type);
1300 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001301
1302 png_write_end(write_ptr, write_info);
1303
1304 for (i = 0; i < (int) imageInfo.height; i++) {
1305 free(outRows[i]);
1306 }
1307 free(outRows);
1308 free(unknowns[0].data);
1309 free(unknowns[1].data);
Chris Craik47cd8e92014-07-08 17:13:08 -07001310 free(unknowns[2].data);
Adam Lesinski282e1812014-01-23 18:17:42 -08001311
1312 png_get_IHDR(write_ptr, write_info, &width, &height,
1313 &bit_depth, &color_type, &interlace_type,
1314 &compression_type, NULL);
1315
Andreas Gampe2412f842014-09-30 20:55:57 -07001316 if (kIsDebug) {
1317 printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
1318 (int)width, (int)height, bit_depth, color_type, interlace_type,
1319 compression_type);
1320 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001321}
1322
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -07001323static bool read_png_protected(png_structp read_ptr, String8& printableName, png_infop read_info,
1324 const sp<AaptFile>& file, FILE* fp, image_info* imageInfo) {
1325 if (setjmp(png_jmpbuf(read_ptr))) {
1326 return false;
1327 }
1328
1329 png_init_io(read_ptr, fp);
1330
1331 read_png(printableName.string(), read_ptr, read_info, imageInfo);
1332
1333 const size_t nameLen = file->getPath().length();
1334 if (nameLen > 6) {
1335 const char* name = file->getPath().string();
1336 if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
1337 if (do_9patch(printableName.string(), imageInfo) != NO_ERROR) {
1338 return false;
1339 }
1340 }
1341 }
1342
1343 return true;
1344}
1345
1346static bool write_png_protected(png_structp write_ptr, String8& printableName, png_infop write_info,
1347 image_info* imageInfo, const Bundle* bundle) {
1348 if (setjmp(png_jmpbuf(write_ptr))) {
1349 return false;
1350 }
1351
Matt Sarett48efde4f2016-03-16 18:22:59 -04001352 write_png(printableName.string(), write_ptr, write_info, *imageInfo, bundle);
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -07001353
1354 return true;
1355}
1356
Andreas Gampe2412f842014-09-30 20:55:57 -07001357status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& /* assets */,
1358 const sp<AaptFile>& file, String8* /* outNewLeafName */)
Adam Lesinski282e1812014-01-23 18:17:42 -08001359{
1360 String8 ext(file->getPath().getPathExtension());
1361
1362 // We currently only process PNG images.
1363 if (strcmp(ext.string(), ".png") != 0) {
1364 return NO_ERROR;
1365 }
1366
1367 // Example of renaming a file:
1368 //*outNewLeafName = file->getPath().getBasePath().getFileName();
1369 //outNewLeafName->append(".nupng");
1370
1371 String8 printableName(file->getPrintableSource());
1372
1373 if (bundle->getVerbose()) {
1374 printf("Processing image: %s\n", printableName.string());
1375 }
1376
1377 png_structp read_ptr = NULL;
1378 png_infop read_info = NULL;
1379 FILE* fp;
1380
1381 image_info imageInfo;
1382
1383 png_structp write_ptr = NULL;
1384 png_infop write_info = NULL;
1385
1386 status_t error = UNKNOWN_ERROR;
1387
Adam Lesinski282e1812014-01-23 18:17:42 -08001388 fp = fopen(file->getSourceFile().string(), "rb");
1389 if (fp == NULL) {
1390 fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string());
1391 goto bail;
1392 }
1393
1394 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1395 (png_error_ptr)NULL);
1396 if (!read_ptr) {
1397 goto bail;
1398 }
1399
1400 read_info = png_create_info_struct(read_ptr);
1401 if (!read_info) {
1402 goto bail;
1403 }
1404
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -07001405 if (!read_png_protected(read_ptr, printableName, read_info, file, fp, &imageInfo)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001406 goto bail;
1407 }
1408
Adam Lesinski282e1812014-01-23 18:17:42 -08001409 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1410 (png_error_ptr)NULL);
1411 if (!write_ptr)
1412 {
1413 goto bail;
1414 }
1415
1416 write_info = png_create_info_struct(write_ptr);
1417 if (!write_info)
1418 {
1419 goto bail;
1420 }
1421
1422 png_set_write_fn(write_ptr, (void*)file.get(),
1423 png_write_aapt_file, png_flush_aapt_file);
1424
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -07001425 if (!write_png_protected(write_ptr, printableName, write_info, &imageInfo, bundle)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001426 goto bail;
1427 }
1428
Adam Lesinski282e1812014-01-23 18:17:42 -08001429 error = NO_ERROR;
1430
1431 if (bundle->getVerbose()) {
1432 fseek(fp, 0, SEEK_END);
1433 size_t oldSize = (size_t)ftell(fp);
1434 size_t newSize = file->getSize();
1435 float factor = ((float)newSize)/oldSize;
1436 int percent = (int)(factor*100);
1437 printf(" (processed image %s: %d%% size of source)\n", printableName.string(), percent);
1438 }
1439
1440bail:
1441 if (read_ptr) {
1442 png_destroy_read_struct(&read_ptr, &read_info, (png_infopp)NULL);
1443 }
1444 if (fp) {
1445 fclose(fp);
1446 }
1447 if (write_ptr) {
1448 png_destroy_write_struct(&write_ptr, &write_info);
1449 }
1450
1451 if (error != NO_ERROR) {
1452 fprintf(stderr, "ERROR: Failure processing PNG image %s\n",
1453 file->getPrintableSource().string());
1454 }
1455 return error;
1456}
1457
1458status_t preProcessImageToCache(const Bundle* bundle, const String8& source, const String8& dest)
1459{
1460 png_structp read_ptr = NULL;
1461 png_infop read_info = NULL;
1462
1463 FILE* fp;
1464
1465 image_info imageInfo;
1466
1467 png_structp write_ptr = NULL;
1468 png_infop write_info = NULL;
1469
1470 status_t error = UNKNOWN_ERROR;
1471
1472 if (bundle->getVerbose()) {
1473 printf("Processing image to cache: %s => %s\n", source.string(), dest.string());
1474 }
1475
1476 // Get a file handler to read from
1477 fp = fopen(source.string(),"rb");
1478 if (fp == NULL) {
1479 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.string());
1480 return error;
1481 }
1482
1483 // Call libpng to get a struct to read image data into
1484 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1485 if (!read_ptr) {
1486 fclose(fp);
1487 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1488 return error;
1489 }
1490
1491 // Call libpng to get a struct to read image info into
1492 read_info = png_create_info_struct(read_ptr);
1493 if (!read_info) {
1494 fclose(fp);
1495 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1496 return error;
1497 }
1498
1499 // Set a jump point for libpng to long jump back to on error
1500 if (setjmp(png_jmpbuf(read_ptr))) {
1501 fclose(fp);
1502 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1503 return error;
1504 }
1505
1506 // Set up libpng to read from our file.
1507 png_init_io(read_ptr,fp);
1508
1509 // Actually read data from the file
1510 read_png(source.string(), read_ptr, read_info, &imageInfo);
1511
1512 // We're done reading so we can clean up
1513 // Find old file size before releasing handle
1514 fseek(fp, 0, SEEK_END);
1515 size_t oldSize = (size_t)ftell(fp);
1516 fclose(fp);
1517 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1518
1519 // Check to see if we're dealing with a 9-patch
1520 // If we are, process appropriately
1521 if (source.getBasePath().getPathExtension() == ".9") {
1522 if (do_9patch(source.string(), &imageInfo) != NO_ERROR) {
1523 return error;
1524 }
1525 }
1526
1527 // Call libpng to create a structure to hold the processed image data
1528 // that can be written to disk
1529 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1530 if (!write_ptr) {
1531 png_destroy_write_struct(&write_ptr, &write_info);
1532 return error;
1533 }
1534
1535 // Call libpng to create a structure to hold processed image info that can
1536 // be written to disk
1537 write_info = png_create_info_struct(write_ptr);
1538 if (!write_info) {
1539 png_destroy_write_struct(&write_ptr, &write_info);
1540 return error;
1541 }
1542
1543 // Open up our destination file for writing
1544 fp = fopen(dest.string(), "wb");
1545 if (!fp) {
1546 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.string());
1547 png_destroy_write_struct(&write_ptr, &write_info);
1548 return error;
1549 }
1550
1551 // Set up libpng to write to our file
1552 png_init_io(write_ptr, fp);
1553
1554 // Set up a jump for libpng to long jump back on on errors
1555 if (setjmp(png_jmpbuf(write_ptr))) {
1556 fclose(fp);
1557 png_destroy_write_struct(&write_ptr, &write_info);
1558 return error;
1559 }
1560
1561 // Actually write out to the new png
Matt Sarett48efde4f2016-03-16 18:22:59 -04001562 write_png(dest.string(), write_ptr, write_info, imageInfo, bundle);
Adam Lesinski282e1812014-01-23 18:17:42 -08001563
1564 if (bundle->getVerbose()) {
1565 // Find the size of our new file
1566 FILE* reader = fopen(dest.string(), "rb");
1567 fseek(reader, 0, SEEK_END);
1568 size_t newSize = (size_t)ftell(reader);
1569 fclose(reader);
1570
1571 float factor = ((float)newSize)/oldSize;
1572 int percent = (int)(factor*100);
1573 printf(" (processed image to cache entry %s: %d%% size of source)\n",
1574 dest.string(), percent);
1575 }
1576
1577 //Clean up
1578 fclose(fp);
1579 png_destroy_write_struct(&write_ptr, &write_info);
1580
1581 return NO_ERROR;
1582}
1583
Adam Lesinskie572c012014-09-19 15:10:04 -07001584status_t postProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski282e1812014-01-23 18:17:42 -08001585 ResourceTable* table, const sp<AaptFile>& file)
1586{
1587 String8 ext(file->getPath().getPathExtension());
1588
1589 // At this point, now that we have all the resource data, all we need to
1590 // do is compile XML files.
1591 if (strcmp(ext.string(), ".xml") == 0) {
Adam Lesinski9306a472014-10-17 14:40:17 -07001592 String16 resourceName(parseResourceName(file->getSourceFile().getPathLeaf()));
Adam Lesinskie572c012014-09-19 15:10:04 -07001593 return compileXmlFile(bundle, assets, resourceName, file, table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001594 }
1595
1596 return NO_ERROR;
1597}