blob: 063b4e6801a0e33df351a46c21be37d03227fa6d [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{
415 bool opaque_within_inset = true;
Chris Craik77b5cad2014-07-30 18:23:07 -0700416 uint8_t max_opacity = 0;
Chris Craik47cd8e92014-07-08 17:13:08 -0700417 int inset = 0;
418 *out_inset = 0;
419 for (int x = startX, y = startY; x != endX && y != endY; x += dX, y += dY, inset++) {
420 png_byte* color = rows[y] + x * 4;
Chris Craik77b5cad2014-07-30 18:23:07 -0700421 uint8_t opacity = color[3];
Chris Craik47cd8e92014-07-08 17:13:08 -0700422 if (opacity > max_opacity) {
423 max_opacity = opacity;
424 *out_inset = inset;
425 }
426 if (opacity == 0xff) return;
427 }
428}
429
Chris Craik77b5cad2014-07-30 18:23:07 -0700430static uint8_t max_alpha_over_row(png_byte* row, int startX, int endX)
Chris Craik47cd8e92014-07-08 17:13:08 -0700431{
Chris Craik77b5cad2014-07-30 18:23:07 -0700432 uint8_t max_alpha = 0;
Chris Craik47cd8e92014-07-08 17:13:08 -0700433 for (int x = startX; x < endX; x++) {
Chris Craik77b5cad2014-07-30 18:23:07 -0700434 uint8_t alpha = (row + x * 4)[3];
435 if (alpha > max_alpha) max_alpha = alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700436 }
Chris Craik77b5cad2014-07-30 18:23:07 -0700437 return max_alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700438}
439
Chris Craik77b5cad2014-07-30 18:23:07 -0700440static uint8_t max_alpha_over_col(png_byte** rows, int offsetX, int startY, int endY)
Chris Craik47cd8e92014-07-08 17:13:08 -0700441{
Chris Craik77b5cad2014-07-30 18:23:07 -0700442 uint8_t max_alpha = 0;
Chris Craik47cd8e92014-07-08 17:13:08 -0700443 for (int y = startY; y < endY; y++) {
Chris Craik77b5cad2014-07-30 18:23:07 -0700444 uint8_t alpha = (rows[y] + offsetX * 4)[3];
445 if (alpha > max_alpha) max_alpha = alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700446 }
Chris Craik77b5cad2014-07-30 18:23:07 -0700447 return max_alpha;
Chris Craik47cd8e92014-07-08 17:13:08 -0700448}
449
450static void get_outline(image_info* image)
451{
452 int midX = image->width / 2;
453 int midY = image->height / 2;
454 int endX = image->width - 2;
455 int endY = image->height - 2;
456
457 // find left and right extent of nine patch content on center row
458 if (image->width > 4) {
459 find_max_opacity(image->rows, 1, midY, midX, -1, 1, 0, &image->outlineInsetsLeft);
460 find_max_opacity(image->rows, endX, midY, midX, -1, -1, 0, &image->outlineInsetsRight);
461 } else {
462 image->outlineInsetsLeft = 0;
463 image->outlineInsetsRight = 0;
464 }
465
466 // find top and bottom extent of nine patch content on center column
467 if (image->height > 4) {
468 find_max_opacity(image->rows, midX, 1, -1, midY, 0, 1, &image->outlineInsetsTop);
469 find_max_opacity(image->rows, midX, endY, -1, midY, 0, -1, &image->outlineInsetsBottom);
470 } else {
471 image->outlineInsetsTop = 0;
472 image->outlineInsetsBottom = 0;
473 }
474
475 int innerStartX = 1 + image->outlineInsetsLeft;
476 int innerStartY = 1 + image->outlineInsetsTop;
477 int innerEndX = endX - image->outlineInsetsRight;
478 int innerEndY = endY - image->outlineInsetsBottom;
479 int innerMidX = (innerEndX + innerStartX) / 2;
480 int innerMidY = (innerEndY + innerStartY) / 2;
481
482 // assuming the image is a round rect, compute the radius by marching
483 // diagonally from the top left corner towards the center
Dan Albert030f5362015-03-04 13:54:20 -0800484 image->outlineAlpha = std::max(
485 max_alpha_over_row(image->rows[innerMidY], innerStartX, innerEndX),
486 max_alpha_over_col(image->rows, innerMidX, innerStartY, innerStartY));
Chris Craik47cd8e92014-07-08 17:13:08 -0700487
488 int diagonalInset = 0;
489 find_max_opacity(image->rows, innerStartX, innerStartY, innerMidX, innerMidY, 1, 1,
490 &diagonalInset);
491
Chris Craik47d86232014-08-14 17:26:21 -0700492 /* Determine source radius based upon inset:
493 * sqrt(r^2 + r^2) = sqrt(i^2 + i^2) + r
494 * sqrt(2) * r = sqrt(2) * i + r
495 * (sqrt(2) - 1) * r = sqrt(2) * i
496 * r = sqrt(2) / (sqrt(2) - 1) * i
497 */
498 image->outlineRadius = 3.4142f * diagonalInset;
Chris Craik47cd8e92014-07-08 17:13:08 -0700499
Andreas Gampe8daabce2014-10-01 23:34:43 -0700500 if (kIsDebug) {
501 printf("outline insets %d %d %d %d, rad %f, alpha %x\n",
502 image->outlineInsetsLeft,
503 image->outlineInsetsTop,
504 image->outlineInsetsRight,
505 image->outlineInsetsBottom,
506 image->outlineRadius,
507 image->outlineAlpha);
508 }
Chris Craik47cd8e92014-07-08 17:13:08 -0700509}
510
Adam Lesinski282e1812014-01-23 18:17:42 -0800511
512static uint32_t get_color(
513 png_bytepp rows, int left, int top, int right, int bottom)
514{
515 png_bytep color = rows[top] + left*4;
516
517 if (left > right || top > bottom) {
518 return Res_png_9patch::TRANSPARENT_COLOR;
519 }
520
521 while (top <= bottom) {
522 for (int i = left; i <= right; i++) {
523 png_bytep p = rows[top]+i*4;
524 if (color[3] == 0) {
525 if (p[3] != 0) {
526 return Res_png_9patch::NO_COLOR;
527 }
528 } else if (p[0] != color[0] || p[1] != color[1]
529 || p[2] != color[2] || p[3] != color[3]) {
530 return Res_png_9patch::NO_COLOR;
531 }
532 }
533 top++;
534 }
535
536 if (color[3] == 0) {
537 return Res_png_9patch::TRANSPARENT_COLOR;
538 }
539 return (color[3]<<24) | (color[0]<<16) | (color[1]<<8) | color[2];
540}
541
Adam Lesinski282e1812014-01-23 18:17:42 -0800542static status_t do_9patch(const char* imageName, image_info* image)
543{
544 image->is9Patch = true;
545
546 int W = image->width;
547 int H = image->height;
548 int i, j;
549
550 int maxSizeXDivs = W * sizeof(int32_t);
551 int maxSizeYDivs = H * sizeof(int32_t);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000552 int32_t* xDivs = image->xDivs = (int32_t*) malloc(maxSizeXDivs);
553 int32_t* yDivs = image->yDivs = (int32_t*) malloc(maxSizeYDivs);
Elliott Hughesc367d482013-10-29 13:12:55 -0700554 uint8_t numXDivs = 0;
555 uint8_t numYDivs = 0;
556
Adam Lesinski282e1812014-01-23 18:17:42 -0800557 int8_t numColors;
558 int numRows;
559 int numCols;
560 int top;
561 int left;
562 int right;
563 int bottom;
564 memset(xDivs, -1, maxSizeXDivs);
565 memset(yDivs, -1, maxSizeYDivs);
566 image->info9Patch.paddingLeft = image->info9Patch.paddingRight =
567 image->info9Patch.paddingTop = image->info9Patch.paddingBottom = -1;
568
569 image->layoutBoundsLeft = image->layoutBoundsRight =
570 image->layoutBoundsTop = image->layoutBoundsBottom = 0;
571
572 png_bytep p = image->rows[0];
573 bool transparent = p[3] == 0;
574 bool hasColor = false;
575
576 const char* errorMsg = NULL;
577 int errorPixel = -1;
578 const char* errorEdge = NULL;
579
580 int colorIndex = 0;
581
582 // Validate size...
583 if (W < 3 || H < 3) {
584 errorMsg = "Image must be at least 3x3 (1x1 without frame) pixels";
585 goto getout;
586 }
587
588 // Validate frame...
589 if (!transparent &&
590 (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) {
591 errorMsg = "Must have one-pixel frame that is either transparent or white";
592 goto getout;
593 }
594
595 // Find left and right of sizing areas...
596 if (get_horizontal_ticks(p, W, transparent, true, &xDivs[0],
597 &xDivs[1], &errorMsg, &numXDivs, true) != NO_ERROR) {
598 errorPixel = xDivs[0];
599 errorEdge = "top";
600 goto getout;
601 }
602
603 // Find top and bottom of sizing areas...
604 if (get_vertical_ticks(image->rows, 0, H, transparent, true, &yDivs[0],
605 &yDivs[1], &errorMsg, &numYDivs, true) != NO_ERROR) {
606 errorPixel = yDivs[0];
607 errorEdge = "left";
608 goto getout;
609 }
610
Elliott Hughesb30296b2013-10-29 15:25:52 -0700611 // Copy patch size data into image...
612 image->info9Patch.numXDivs = numXDivs;
613 image->info9Patch.numYDivs = numYDivs;
614
Adam Lesinski282e1812014-01-23 18:17:42 -0800615 // Find left and right of padding area...
616 if (get_horizontal_ticks(image->rows[H-1], W, transparent, false, &image->info9Patch.paddingLeft,
617 &image->info9Patch.paddingRight, &errorMsg, NULL, false) != NO_ERROR) {
618 errorPixel = image->info9Patch.paddingLeft;
619 errorEdge = "bottom";
620 goto getout;
621 }
622
623 // Find top and bottom of padding area...
624 if (get_vertical_ticks(image->rows, (W-1)*4, H, transparent, false, &image->info9Patch.paddingTop,
625 &image->info9Patch.paddingBottom, &errorMsg, NULL, false) != NO_ERROR) {
626 errorPixel = image->info9Patch.paddingTop;
627 errorEdge = "right";
628 goto getout;
629 }
630
631 // Find left and right of layout padding...
632 get_horizontal_layout_bounds_ticks(image->rows[H-1], W, transparent, false,
633 &image->layoutBoundsLeft,
634 &image->layoutBoundsRight, &errorMsg);
635
636 get_vertical_layout_bounds_ticks(image->rows, (W-1)*4, H, transparent, false,
637 &image->layoutBoundsTop,
638 &image->layoutBoundsBottom, &errorMsg);
639
640 image->haveLayoutBounds = image->layoutBoundsLeft != 0
641 || image->layoutBoundsRight != 0
642 || image->layoutBoundsTop != 0
643 || image->layoutBoundsBottom != 0;
644
645 if (image->haveLayoutBounds) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700646 if (kIsDebug) {
647 printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
648 image->layoutBoundsRight, image->layoutBoundsBottom);
649 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800650 }
651
Chris Craik47cd8e92014-07-08 17:13:08 -0700652 // use opacity of pixels to estimate the round rect outline
653 get_outline(image);
654
Adam Lesinski282e1812014-01-23 18:17:42 -0800655 // If padding is not yet specified, take values from size.
656 if (image->info9Patch.paddingLeft < 0) {
657 image->info9Patch.paddingLeft = xDivs[0];
658 image->info9Patch.paddingRight = W - 2 - xDivs[1];
659 } else {
660 // Adjust value to be correct!
661 image->info9Patch.paddingRight = W - 2 - image->info9Patch.paddingRight;
662 }
663 if (image->info9Patch.paddingTop < 0) {
664 image->info9Patch.paddingTop = yDivs[0];
665 image->info9Patch.paddingBottom = H - 2 - yDivs[1];
666 } else {
667 // Adjust value to be correct!
668 image->info9Patch.paddingBottom = H - 2 - image->info9Patch.paddingBottom;
669 }
670
Andreas Gampe2412f842014-09-30 20:55:57 -0700671 if (kIsDebug) {
672 printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName,
Andreas Gampe8daabce2014-10-01 23:34:43 -0700673 xDivs[0], xDivs[1],
674 yDivs[0], yDivs[1]);
Andreas Gampe2412f842014-09-30 20:55:57 -0700675 printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName,
676 image->info9Patch.paddingLeft, image->info9Patch.paddingRight,
677 image->info9Patch.paddingTop, image->info9Patch.paddingBottom);
678 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800679
680 // Remove frame from image.
681 image->rows = (png_bytepp)malloc((H-2) * sizeof(png_bytep));
682 for (i=0; i<(H-2); i++) {
683 image->rows[i] = image->allocRows[i+1];
684 memmove(image->rows[i], image->rows[i]+4, (W-2)*4);
685 }
686 image->width -= 2;
687 W = image->width;
688 image->height -= 2;
689 H = image->height;
690
691 // Figure out the number of rows and columns in the N-patch
692 numCols = numXDivs + 1;
693 if (xDivs[0] == 0) { // Column 1 is strechable
694 numCols--;
695 }
696 if (xDivs[numXDivs - 1] == W) {
697 numCols--;
698 }
699 numRows = numYDivs + 1;
700 if (yDivs[0] == 0) { // Row 1 is strechable
701 numRows--;
702 }
703 if (yDivs[numYDivs - 1] == H) {
704 numRows--;
705 }
706
707 // Make sure the amount of rows and columns will fit in the number of
708 // colors we can use in the 9-patch format.
709 if (numRows * numCols > 0x7F) {
710 errorMsg = "Too many rows and columns in 9-patch perimeter";
711 goto getout;
712 }
713
714 numColors = numRows * numCols;
715 image->info9Patch.numColors = numColors;
Narayan Kamath6381dd42014-03-03 17:12:03 +0000716 image->colors = (uint32_t*)malloc(numColors * sizeof(uint32_t));
Adam Lesinski282e1812014-01-23 18:17:42 -0800717
718 // Fill in color information for each patch.
719
720 uint32_t c;
721 top = 0;
722
723 // The first row always starts with the top being at y=0 and the bottom
724 // being either yDivs[1] (if yDivs[0]=0) of yDivs[0]. In the former case
725 // the first row is stretchable along the Y axis, otherwise it is fixed.
726 // The last row always ends with the bottom being bitmap.height and the top
727 // being either yDivs[numYDivs-2] (if yDivs[numYDivs-1]=bitmap.height) or
728 // yDivs[numYDivs-1]. In the former case the last row is stretchable along
729 // the Y axis, otherwise it is fixed.
730 //
731 // The first and last columns are similarly treated with respect to the X
732 // axis.
733 //
734 // The above is to help explain some of the special casing that goes on the
735 // code below.
736
737 // The initial yDiv and whether the first row is considered stretchable or
738 // not depends on whether yDiv[0] was zero or not.
739 for (j = (yDivs[0] == 0 ? 1 : 0);
740 j <= numYDivs && top < H;
741 j++) {
742 if (j == numYDivs) {
743 bottom = H;
744 } else {
745 bottom = yDivs[j];
746 }
747 left = 0;
748 // The initial xDiv and whether the first column is considered
749 // stretchable or not depends on whether xDiv[0] was zero or not.
750 for (i = xDivs[0] == 0 ? 1 : 0;
751 i <= numXDivs && left < W;
752 i++) {
753 if (i == numXDivs) {
754 right = W;
755 } else {
756 right = xDivs[i];
757 }
758 c = get_color(image->rows, left, top, right - 1, bottom - 1);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000759 image->colors[colorIndex++] = c;
Andreas Gampe2412f842014-09-30 20:55:57 -0700760 if (kIsDebug) {
761 if (c != Res_png_9patch::NO_COLOR)
762 hasColor = true;
763 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800764 left = right;
765 }
766 top = bottom;
767 }
768
769 assert(colorIndex == numColors);
770
771 for (i=0; i<numColors; i++) {
772 if (hasColor) {
773 if (i == 0) printf("Colors in %s:\n ", imageName);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000774 printf(" #%08x", image->colors[i]);
Adam Lesinski282e1812014-01-23 18:17:42 -0800775 if (i == numColors - 1) printf("\n");
776 }
777 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800778getout:
779 if (errorMsg) {
780 fprintf(stderr,
781 "ERROR: 9-patch image %s malformed.\n"
782 " %s.\n", imageName, errorMsg);
783 if (errorEdge != NULL) {
784 if (errorPixel >= 0) {
785 fprintf(stderr,
786 " Found at pixel #%d along %s edge.\n", errorPixel, errorEdge);
787 } else {
788 fprintf(stderr,
789 " Found along %s edge.\n", errorEdge);
790 }
791 }
792 return UNKNOWN_ERROR;
793 }
794 return NO_ERROR;
795}
796
Narayan Kamath6381dd42014-03-03 17:12:03 +0000797static void checkNinePatchSerialization(Res_png_9patch* inPatch, void* data)
Adam Lesinski282e1812014-01-23 18:17:42 -0800798{
Adam Lesinski282e1812014-01-23 18:17:42 -0800799 size_t patchSize = inPatch->serializedSize();
Narayan Kamath6381dd42014-03-03 17:12:03 +0000800 void* newData = malloc(patchSize);
Adam Lesinski282e1812014-01-23 18:17:42 -0800801 memcpy(newData, data, patchSize);
802 Res_png_9patch* outPatch = inPatch->deserialize(newData);
803 // deserialization is done in place, so outPatch == newData
804 assert(outPatch == newData);
805 assert(outPatch->numXDivs == inPatch->numXDivs);
806 assert(outPatch->numYDivs == inPatch->numYDivs);
807 assert(outPatch->paddingLeft == inPatch->paddingLeft);
808 assert(outPatch->paddingRight == inPatch->paddingRight);
809 assert(outPatch->paddingTop == inPatch->paddingTop);
810 assert(outPatch->paddingBottom == inPatch->paddingBottom);
811 for (int i = 0; i < outPatch->numXDivs; i++) {
812 assert(outPatch->xDivs[i] == inPatch->xDivs[i]);
813 }
814 for (int i = 0; i < outPatch->numYDivs; i++) {
815 assert(outPatch->yDivs[i] == inPatch->yDivs[i]);
816 }
817 for (int i = 0; i < outPatch->numColors; i++) {
818 assert(outPatch->colors[i] == inPatch->colors[i]);
819 }
820 free(newData);
821}
822
Adam Lesinski282e1812014-01-23 18:17:42 -0800823static void dump_image(int w, int h, png_bytepp rows, int color_type)
824{
825 int i, j, rr, gg, bb, aa;
826
827 int bpp;
828 if (color_type == PNG_COLOR_TYPE_PALETTE || color_type == PNG_COLOR_TYPE_GRAY) {
829 bpp = 1;
830 } else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
831 bpp = 2;
832 } else if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
833 // We use a padding byte even when there is no alpha
834 bpp = 4;
835 } else {
836 printf("Unknown color type %d.\n", color_type);
837 }
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,
877 int *paletteEntries, bool *hasTransparency, int *colorType,
878 png_bytepp outRows)
879{
880 int w = imageInfo.width;
881 int h = imageInfo.height;
882 int i, j, rr, gg, bb, aa, idx;
883 uint32_t colors[256], col;
884 int num_colors = 0;
885 int maxGrayDeviation = 0;
886
887 bool isOpaque = true;
888 bool isPalette = true;
889 bool isGrayscale = true;
890
891 // Scan the entire image and determine if:
892 // 1. Every pixel has R == G == B (grayscale)
893 // 2. Every pixel has A == 255 (opaque)
894 // 3. There are no more than 256 distinct RGBA colors
895
Andreas Gampe2412f842014-09-30 20:55:57 -0700896 if (kIsDebug) {
897 printf("Initial image data:\n");
898 dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA);
899 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800900
901 for (j = 0; j < h; j++) {
902 png_bytep row = imageInfo.rows[j];
903 png_bytep out = outRows[j];
904 for (i = 0; i < w; i++) {
905 rr = *row++;
906 gg = *row++;
907 bb = *row++;
908 aa = *row++;
909
910 int odev = maxGrayDeviation;
911 maxGrayDeviation = MAX(ABS(rr - gg), maxGrayDeviation);
912 maxGrayDeviation = MAX(ABS(gg - bb), maxGrayDeviation);
913 maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation);
914 if (maxGrayDeviation > odev) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700915 if (kIsDebug) {
916 printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
917 maxGrayDeviation, i, j, rr, gg, bb, aa);
918 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800919 }
920
921 // Check if image is really grayscale
922 if (isGrayscale) {
923 if (rr != gg || rr != bb) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700924 if (kIsDebug) {
925 printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n",
926 i, j, rr, gg, bb, aa);
927 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800928 isGrayscale = false;
929 }
930 }
931
932 // Check if image is really opaque
933 if (isOpaque) {
934 if (aa != 0xff) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700935 if (kIsDebug) {
936 printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n",
937 i, j, rr, gg, bb, aa);
938 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800939 isOpaque = false;
940 }
941 }
942
943 // Check if image is really <= 256 colors
944 if (isPalette) {
945 col = (uint32_t) ((rr << 24) | (gg << 16) | (bb << 8) | aa);
946 bool match = false;
947 for (idx = 0; idx < num_colors; idx++) {
948 if (colors[idx] == col) {
949 match = true;
950 break;
951 }
952 }
953
954 // Write the palette index for the pixel to outRows optimistically
955 // We might overwrite it later if we decide to encode as gray or
956 // gray + alpha
957 *out++ = idx;
958 if (!match) {
959 if (num_colors == 256) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700960 if (kIsDebug) {
961 printf("Found 257th color at %d, %d\n", i, j);
962 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800963 isPalette = false;
964 } else {
965 colors[num_colors++] = col;
966 }
967 }
968 }
969 }
970 }
971
972 *paletteEntries = 0;
973 *hasTransparency = !isOpaque;
974 int bpp = isOpaque ? 3 : 4;
975 int paletteSize = w * h + bpp * num_colors;
976
Andreas Gampe2412f842014-09-30 20:55:57 -0700977 if (kIsDebug) {
978 printf("isGrayscale = %s\n", isGrayscale ? "true" : "false");
979 printf("isOpaque = %s\n", isOpaque ? "true" : "false");
980 printf("isPalette = %s\n", isPalette ? "true" : "false");
981 printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n",
982 paletteSize, 2 * w * h, bpp * w * h);
983 printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance);
984 }
Adam Lesinski282e1812014-01-23 18:17:42 -0800985
986 // Choose the best color type for the image.
987 // 1. Opaque gray - use COLOR_TYPE_GRAY at 1 byte/pixel
988 // 2. Gray + alpha - use COLOR_TYPE_PALETTE if the number of distinct combinations
989 // is sufficiently small, otherwise use COLOR_TYPE_GRAY_ALPHA
990 // 3. RGB(A) - use COLOR_TYPE_PALETTE if the number of distinct colors is sufficiently
991 // small, otherwise use COLOR_TYPE_RGB{_ALPHA}
992 if (isGrayscale) {
993 if (isOpaque) {
994 *colorType = PNG_COLOR_TYPE_GRAY; // 1 byte/pixel
995 } else {
996 // Use a simple heuristic to determine whether using a palette will
997 // save space versus using gray + alpha for each pixel.
998 // This doesn't take into account chunk overhead, filtering, LZ
999 // compression, etc.
1000 if (isPalette && (paletteSize < 2 * w * h)) {
1001 *colorType = PNG_COLOR_TYPE_PALETTE; // 1 byte/pixel + 4 bytes/color
1002 } else {
1003 *colorType = PNG_COLOR_TYPE_GRAY_ALPHA; // 2 bytes per pixel
1004 }
1005 }
1006 } else if (isPalette && (paletteSize < bpp * w * h)) {
1007 *colorType = PNG_COLOR_TYPE_PALETTE;
1008 } else {
1009 if (maxGrayDeviation <= grayscaleTolerance) {
1010 printf("%s: forcing image to gray (max deviation = %d)\n", imageName, maxGrayDeviation);
1011 *colorType = isOpaque ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA;
1012 } else {
1013 *colorType = isOpaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA;
1014 }
1015 }
1016
1017 // Perform postprocessing of the image or palette data based on the final
1018 // color type chosen
1019
1020 if (*colorType == PNG_COLOR_TYPE_PALETTE) {
1021 // Create separate RGB and Alpha palettes and set the number of colors
1022 *paletteEntries = num_colors;
1023
1024 // Create the RGB and alpha palettes
1025 for (int idx = 0; idx < num_colors; idx++) {
1026 col = colors[idx];
1027 rgbPalette[idx].red = (png_byte) ((col >> 24) & 0xff);
1028 rgbPalette[idx].green = (png_byte) ((col >> 16) & 0xff);
1029 rgbPalette[idx].blue = (png_byte) ((col >> 8) & 0xff);
1030 alphaPalette[idx] = (png_byte) (col & 0xff);
1031 }
1032 } else if (*colorType == PNG_COLOR_TYPE_GRAY || *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
1033 // If the image is gray or gray + alpha, compact the pixels into outRows
1034 for (j = 0; j < h; j++) {
1035 png_bytep row = imageInfo.rows[j];
1036 png_bytep out = outRows[j];
1037 for (i = 0; i < w; i++) {
1038 rr = *row++;
1039 gg = *row++;
1040 bb = *row++;
1041 aa = *row++;
1042
1043 if (isGrayscale) {
1044 *out++ = rr;
1045 } else {
1046 *out++ = (png_byte) (rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
1047 }
1048 if (!isOpaque) {
1049 *out++ = aa;
1050 }
1051 }
1052 }
1053 }
1054}
1055
1056
1057static void write_png(const char* imageName,
1058 png_structp write_ptr, png_infop write_info,
1059 image_info& imageInfo, int grayscaleTolerance)
1060{
Adam Lesinski282e1812014-01-23 18:17:42 -08001061 png_uint_32 width, height;
1062 int color_type;
1063 int bit_depth, interlace_type, compression_type;
1064 int i;
1065
Chris Craik47cd8e92014-07-08 17:13:08 -07001066 png_unknown_chunk unknowns[3];
Adam Lesinski282e1812014-01-23 18:17:42 -08001067 unknowns[0].data = NULL;
1068 unknowns[1].data = NULL;
Chris Craik47cd8e92014-07-08 17:13:08 -07001069 unknowns[2].data = NULL;
Adam Lesinski282e1812014-01-23 18:17:42 -08001070
1071 png_bytepp outRows = (png_bytepp) malloc((int) imageInfo.height * sizeof(png_bytep));
1072 if (outRows == (png_bytepp) 0) {
1073 printf("Can't allocate output buffer!\n");
1074 exit(1);
1075 }
1076 for (i = 0; i < (int) imageInfo.height; i++) {
1077 outRows[i] = (png_bytep) malloc(2 * (int) imageInfo.width);
1078 if (outRows[i] == (png_bytep) 0) {
1079 printf("Can't allocate output buffer!\n");
1080 exit(1);
1081 }
1082 }
1083
1084 png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
1085
Andreas Gampe2412f842014-09-30 20:55:57 -07001086 if (kIsDebug) {
1087 printf("Writing image %s: w = %d, h = %d\n", imageName,
1088 (int) imageInfo.width, (int) imageInfo.height);
1089 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001090
1091 png_color rgbPalette[256];
1092 png_byte alphaPalette[256];
1093 bool hasTransparency;
1094 int paletteEntries;
1095
1096 analyze_image(imageName, imageInfo, grayscaleTolerance, rgbPalette, alphaPalette,
1097 &paletteEntries, &hasTransparency, &color_type, outRows);
1098
1099 // If the image is a 9-patch, we need to preserve it as a ARGB file to make
1100 // sure the pixels will not be pre-dithered/clamped until we decide they are
1101 if (imageInfo.is9Patch && (color_type == PNG_COLOR_TYPE_RGB ||
1102 color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE)) {
1103 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1104 }
1105
Andreas Gampe2412f842014-09-30 20:55:57 -07001106 if (kIsDebug) {
1107 switch (color_type) {
1108 case PNG_COLOR_TYPE_PALETTE:
1109 printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n",
1110 imageName, paletteEntries,
1111 hasTransparency ? " (with alpha)" : "");
1112 break;
1113 case PNG_COLOR_TYPE_GRAY:
1114 printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName);
1115 break;
1116 case PNG_COLOR_TYPE_GRAY_ALPHA:
1117 printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName);
1118 break;
1119 case PNG_COLOR_TYPE_RGB:
1120 printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName);
1121 break;
1122 case PNG_COLOR_TYPE_RGB_ALPHA:
1123 printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName);
1124 break;
1125 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001126 }
1127
1128 png_set_IHDR(write_ptr, write_info, imageInfo.width, imageInfo.height,
1129 8, color_type, PNG_INTERLACE_NONE,
1130 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1131
1132 if (color_type == PNG_COLOR_TYPE_PALETTE) {
1133 png_set_PLTE(write_ptr, write_info, rgbPalette, paletteEntries);
1134 if (hasTransparency) {
1135 png_set_tRNS(write_ptr, write_info, alphaPalette, paletteEntries, (png_color_16p) 0);
1136 }
1137 png_set_filter(write_ptr, 0, PNG_NO_FILTERS);
1138 } else {
1139 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
1140 }
1141
1142 if (imageInfo.is9Patch) {
Chris Craik47cd8e92014-07-08 17:13:08 -07001143 int chunk_count = 2 + (imageInfo.haveLayoutBounds ? 1 : 0);
1144 int p_index = imageInfo.haveLayoutBounds ? 2 : 1;
1145 int b_index = 1;
1146 int o_index = 0;
1147
1148 // Chunks ordered thusly because older platforms depend on the base 9 patch data being last
Adam Lesinski282e1812014-01-23 18:17:42 -08001149 png_byte *chunk_names = imageInfo.haveLayoutBounds
Chris Craik47cd8e92014-07-08 17:13:08 -07001150 ? (png_byte*)"npOl\0npLb\0npTc\0"
1151 : (png_byte*)"npOl\0npTc";
1152
1153 // base 9 patch data
Andreas Gampe2412f842014-09-30 20:55:57 -07001154 if (kIsDebug) {
1155 printf("Adding 9-patch info...\n");
1156 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001157 strcpy((char*)unknowns[p_index].name, "npTc");
Narayan Kamath6381dd42014-03-03 17:12:03 +00001158 unknowns[p_index].data = (png_byte*)imageInfo.serialize9patch();
Adam Lesinski282e1812014-01-23 18:17:42 -08001159 unknowns[p_index].size = imageInfo.info9Patch.serializedSize();
1160 // TODO: remove the check below when everything works
1161 checkNinePatchSerialization(&imageInfo.info9Patch, unknowns[p_index].data);
1162
Chris Craik47cd8e92014-07-08 17:13:08 -07001163 // automatically generated 9 patch outline data
1164 int chunk_size = sizeof(png_uint_32) * 6;
1165 strcpy((char*)unknowns[o_index].name, "npOl");
1166 unknowns[o_index].data = (png_byte*) calloc(chunk_size, 1);
1167 png_byte outputData[chunk_size];
1168 memcpy(&outputData, &imageInfo.outlineInsetsLeft, 4 * sizeof(png_uint_32));
1169 ((float*) outputData)[4] = imageInfo.outlineRadius;
Chris Craik77b5cad2014-07-30 18:23:07 -07001170 ((png_uint_32*) outputData)[5] = imageInfo.outlineAlpha;
Chris Craik47cd8e92014-07-08 17:13:08 -07001171 memcpy(unknowns[o_index].data, &outputData, chunk_size);
1172 unknowns[o_index].size = chunk_size;
1173
1174 // optional optical inset / layout bounds data
Adam Lesinski282e1812014-01-23 18:17:42 -08001175 if (imageInfo.haveLayoutBounds) {
1176 int chunk_size = sizeof(png_uint_32) * 4;
1177 strcpy((char*)unknowns[b_index].name, "npLb");
1178 unknowns[b_index].data = (png_byte*) calloc(chunk_size, 1);
1179 memcpy(unknowns[b_index].data, &imageInfo.layoutBoundsLeft, chunk_size);
1180 unknowns[b_index].size = chunk_size;
1181 }
1182
1183 for (int i = 0; i < chunk_count; i++) {
1184 unknowns[i].location = PNG_HAVE_PLTE;
1185 }
1186 png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS,
1187 chunk_names, chunk_count);
1188 png_set_unknown_chunks(write_ptr, write_info, unknowns, chunk_count);
1189#if PNG_LIBPNG_VER < 10600
1190 /* Deal with unknown chunk location bug in 1.5.x and earlier */
1191 png_set_unknown_chunk_location(write_ptr, write_info, 0, PNG_HAVE_PLTE);
1192 if (imageInfo.haveLayoutBounds) {
1193 png_set_unknown_chunk_location(write_ptr, write_info, 1, PNG_HAVE_PLTE);
1194 }
1195#endif
1196 }
1197
1198
1199 png_write_info(write_ptr, write_info);
1200
1201 png_bytepp rows;
1202 if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
1203 if (color_type == PNG_COLOR_TYPE_RGB) {
1204 png_set_filler(write_ptr, 0, PNG_FILLER_AFTER);
1205 }
1206 rows = imageInfo.rows;
1207 } else {
1208 rows = outRows;
1209 }
1210 png_write_image(write_ptr, rows);
1211
Andreas Gampe2412f842014-09-30 20:55:57 -07001212 if (kIsDebug) {
1213 printf("Final image data:\n");
1214 dump_image(imageInfo.width, imageInfo.height, rows, color_type);
1215 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001216
1217 png_write_end(write_ptr, write_info);
1218
1219 for (i = 0; i < (int) imageInfo.height; i++) {
1220 free(outRows[i]);
1221 }
1222 free(outRows);
1223 free(unknowns[0].data);
1224 free(unknowns[1].data);
Chris Craik47cd8e92014-07-08 17:13:08 -07001225 free(unknowns[2].data);
Adam Lesinski282e1812014-01-23 18:17:42 -08001226
1227 png_get_IHDR(write_ptr, write_info, &width, &height,
1228 &bit_depth, &color_type, &interlace_type,
1229 &compression_type, NULL);
1230
Andreas Gampe2412f842014-09-30 20:55:57 -07001231 if (kIsDebug) {
1232 printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
1233 (int)width, (int)height, bit_depth, color_type, interlace_type,
1234 compression_type);
1235 }
Adam Lesinski282e1812014-01-23 18:17:42 -08001236}
1237
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -07001238static bool read_png_protected(png_structp read_ptr, String8& printableName, png_infop read_info,
1239 const sp<AaptFile>& file, FILE* fp, image_info* imageInfo) {
1240 if (setjmp(png_jmpbuf(read_ptr))) {
1241 return false;
1242 }
1243
1244 png_init_io(read_ptr, fp);
1245
1246 read_png(printableName.string(), read_ptr, read_info, imageInfo);
1247
1248 const size_t nameLen = file->getPath().length();
1249 if (nameLen > 6) {
1250 const char* name = file->getPath().string();
1251 if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
1252 if (do_9patch(printableName.string(), imageInfo) != NO_ERROR) {
1253 return false;
1254 }
1255 }
1256 }
1257
1258 return true;
1259}
1260
1261static bool write_png_protected(png_structp write_ptr, String8& printableName, png_infop write_info,
1262 image_info* imageInfo, const Bundle* bundle) {
1263 if (setjmp(png_jmpbuf(write_ptr))) {
1264 return false;
1265 }
1266
1267 write_png(printableName.string(), write_ptr, write_info, *imageInfo,
1268 bundle->getGrayscaleTolerance());
1269
1270 return true;
1271}
1272
Andreas Gampe2412f842014-09-30 20:55:57 -07001273status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& /* assets */,
1274 const sp<AaptFile>& file, String8* /* outNewLeafName */)
Adam Lesinski282e1812014-01-23 18:17:42 -08001275{
1276 String8 ext(file->getPath().getPathExtension());
1277
1278 // We currently only process PNG images.
1279 if (strcmp(ext.string(), ".png") != 0) {
1280 return NO_ERROR;
1281 }
1282
1283 // Example of renaming a file:
1284 //*outNewLeafName = file->getPath().getBasePath().getFileName();
1285 //outNewLeafName->append(".nupng");
1286
1287 String8 printableName(file->getPrintableSource());
1288
1289 if (bundle->getVerbose()) {
1290 printf("Processing image: %s\n", printableName.string());
1291 }
1292
1293 png_structp read_ptr = NULL;
1294 png_infop read_info = NULL;
1295 FILE* fp;
1296
1297 image_info imageInfo;
1298
1299 png_structp write_ptr = NULL;
1300 png_infop write_info = NULL;
1301
1302 status_t error = UNKNOWN_ERROR;
1303
Adam Lesinski282e1812014-01-23 18:17:42 -08001304 fp = fopen(file->getSourceFile().string(), "rb");
1305 if (fp == NULL) {
1306 fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string());
1307 goto bail;
1308 }
1309
1310 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1311 (png_error_ptr)NULL);
1312 if (!read_ptr) {
1313 goto bail;
1314 }
1315
1316 read_info = png_create_info_struct(read_ptr);
1317 if (!read_info) {
1318 goto bail;
1319 }
1320
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -07001321 if (!read_png_protected(read_ptr, printableName, read_info, file, fp, &imageInfo)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001322 goto bail;
1323 }
1324
Adam Lesinski282e1812014-01-23 18:17:42 -08001325 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1326 (png_error_ptr)NULL);
1327 if (!write_ptr)
1328 {
1329 goto bail;
1330 }
1331
1332 write_info = png_create_info_struct(write_ptr);
1333 if (!write_info)
1334 {
1335 goto bail;
1336 }
1337
1338 png_set_write_fn(write_ptr, (void*)file.get(),
1339 png_write_aapt_file, png_flush_aapt_file);
1340
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -07001341 if (!write_png_protected(write_ptr, printableName, write_info, &imageInfo, bundle)) {
Adam Lesinski282e1812014-01-23 18:17:42 -08001342 goto bail;
1343 }
1344
Adam Lesinski282e1812014-01-23 18:17:42 -08001345 error = NO_ERROR;
1346
1347 if (bundle->getVerbose()) {
1348 fseek(fp, 0, SEEK_END);
1349 size_t oldSize = (size_t)ftell(fp);
1350 size_t newSize = file->getSize();
1351 float factor = ((float)newSize)/oldSize;
1352 int percent = (int)(factor*100);
1353 printf(" (processed image %s: %d%% size of source)\n", printableName.string(), percent);
1354 }
1355
1356bail:
1357 if (read_ptr) {
1358 png_destroy_read_struct(&read_ptr, &read_info, (png_infopp)NULL);
1359 }
1360 if (fp) {
1361 fclose(fp);
1362 }
1363 if (write_ptr) {
1364 png_destroy_write_struct(&write_ptr, &write_info);
1365 }
1366
1367 if (error != NO_ERROR) {
1368 fprintf(stderr, "ERROR: Failure processing PNG image %s\n",
1369 file->getPrintableSource().string());
1370 }
1371 return error;
1372}
1373
1374status_t preProcessImageToCache(const Bundle* bundle, const String8& source, const String8& dest)
1375{
1376 png_structp read_ptr = NULL;
1377 png_infop read_info = NULL;
1378
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
1388 if (bundle->getVerbose()) {
1389 printf("Processing image to cache: %s => %s\n", source.string(), dest.string());
1390 }
1391
1392 // Get a file handler to read from
1393 fp = fopen(source.string(),"rb");
1394 if (fp == NULL) {
1395 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.string());
1396 return error;
1397 }
1398
1399 // Call libpng to get a struct to read image data into
1400 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1401 if (!read_ptr) {
1402 fclose(fp);
1403 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1404 return error;
1405 }
1406
1407 // Call libpng to get a struct to read image info into
1408 read_info = png_create_info_struct(read_ptr);
1409 if (!read_info) {
1410 fclose(fp);
1411 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1412 return error;
1413 }
1414
1415 // Set a jump point for libpng to long jump back to on error
1416 if (setjmp(png_jmpbuf(read_ptr))) {
1417 fclose(fp);
1418 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1419 return error;
1420 }
1421
1422 // Set up libpng to read from our file.
1423 png_init_io(read_ptr,fp);
1424
1425 // Actually read data from the file
1426 read_png(source.string(), read_ptr, read_info, &imageInfo);
1427
1428 // We're done reading so we can clean up
1429 // Find old file size before releasing handle
1430 fseek(fp, 0, SEEK_END);
1431 size_t oldSize = (size_t)ftell(fp);
1432 fclose(fp);
1433 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1434
1435 // Check to see if we're dealing with a 9-patch
1436 // If we are, process appropriately
1437 if (source.getBasePath().getPathExtension() == ".9") {
1438 if (do_9patch(source.string(), &imageInfo) != NO_ERROR) {
1439 return error;
1440 }
1441 }
1442
1443 // Call libpng to create a structure to hold the processed image data
1444 // that can be written to disk
1445 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1446 if (!write_ptr) {
1447 png_destroy_write_struct(&write_ptr, &write_info);
1448 return error;
1449 }
1450
1451 // Call libpng to create a structure to hold processed image info that can
1452 // be written to disk
1453 write_info = png_create_info_struct(write_ptr);
1454 if (!write_info) {
1455 png_destroy_write_struct(&write_ptr, &write_info);
1456 return error;
1457 }
1458
1459 // Open up our destination file for writing
1460 fp = fopen(dest.string(), "wb");
1461 if (!fp) {
1462 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.string());
1463 png_destroy_write_struct(&write_ptr, &write_info);
1464 return error;
1465 }
1466
1467 // Set up libpng to write to our file
1468 png_init_io(write_ptr, fp);
1469
1470 // Set up a jump for libpng to long jump back on on errors
1471 if (setjmp(png_jmpbuf(write_ptr))) {
1472 fclose(fp);
1473 png_destroy_write_struct(&write_ptr, &write_info);
1474 return error;
1475 }
1476
1477 // Actually write out to the new png
1478 write_png(dest.string(), write_ptr, write_info, imageInfo,
1479 bundle->getGrayscaleTolerance());
1480
1481 if (bundle->getVerbose()) {
1482 // Find the size of our new file
1483 FILE* reader = fopen(dest.string(), "rb");
1484 fseek(reader, 0, SEEK_END);
1485 size_t newSize = (size_t)ftell(reader);
1486 fclose(reader);
1487
1488 float factor = ((float)newSize)/oldSize;
1489 int percent = (int)(factor*100);
1490 printf(" (processed image to cache entry %s: %d%% size of source)\n",
1491 dest.string(), percent);
1492 }
1493
1494 //Clean up
1495 fclose(fp);
1496 png_destroy_write_struct(&write_ptr, &write_info);
1497
1498 return NO_ERROR;
1499}
1500
Adam Lesinskie572c012014-09-19 15:10:04 -07001501status_t postProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets,
Adam Lesinski282e1812014-01-23 18:17:42 -08001502 ResourceTable* table, const sp<AaptFile>& file)
1503{
1504 String8 ext(file->getPath().getPathExtension());
1505
1506 // At this point, now that we have all the resource data, all we need to
1507 // do is compile XML files.
1508 if (strcmp(ext.string(), ".xml") == 0) {
Adam Lesinski9306a472014-10-17 14:40:17 -07001509 String16 resourceName(parseResourceName(file->getSourceFile().getPathLeaf()));
Adam Lesinskie572c012014-09-19 15:10:04 -07001510 return compileXmlFile(bundle, assets, resourceName, file, table);
Adam Lesinski282e1812014-01-23 18:17:42 -08001511 }
1512
1513 return NO_ERROR;
1514}