blob: 5368418f066dd268f30f388884ac9ffbc83ea542 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -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
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080011#include <androidfw/ResourceTypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012#include <utils/ByteOrder.h>
13
14#include <png.h>
John Recke982b722013-08-26 16:53:40 -070015#include <zlib.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080016
Andreas Gampe2412f842014-09-30 20:55:57 -070017// Change this to true for noisy debug output.
18static const bool kIsDebug = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080019
20static void
21png_write_aapt_file(png_structp png_ptr, png_bytep data, png_size_t length)
22{
John Recke982b722013-08-26 16:53:40 -070023 AaptFile* aaptfile = (AaptFile*) png_get_io_ptr(png_ptr);
24 status_t err = aaptfile->writeData(data, length);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025 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 */)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
Amith Yamasaniec4a5042012-04-04 10:27:15 -070074 // Layout padding, if relevant
75 bool haveLayoutBounds;
76 int32_t layoutBoundsLeft;
77 int32_t layoutBoundsTop;
78 int32_t layoutBoundsRight;
79 int32_t layoutBoundsBottom;
80
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 png_uint_32 allocHeight;
82 png_bytepp allocRows;
83};
84
85static void read_png(const char* imageName,
86 png_structp read_ptr, png_infop read_info,
87 image_info* outImageInfo)
88{
89 int color_type;
90 int bit_depth, interlace_type, compression_type;
91 int i;
92
93 png_read_info(read_ptr, read_info);
94
95 png_get_IHDR(read_ptr, read_info, &outImageInfo->width,
96 &outImageInfo->height, &bit_depth, &color_type,
97 &interlace_type, &compression_type, NULL);
98
99 //printf("Image %s:\n", imageName);
100 //printf("color_type=%d, bit_depth=%d, interlace_type=%d, compression_type=%d\n",
101 // color_type, bit_depth, interlace_type, compression_type);
102
103 if (color_type == PNG_COLOR_TYPE_PALETTE)
104 png_set_palette_to_rgb(read_ptr);
105
106 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
John Recke982b722013-08-26 16:53:40 -0700107 png_set_expand_gray_1_2_4_to_8(read_ptr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
109 if (png_get_valid(read_ptr, read_info, PNG_INFO_tRNS)) {
110 //printf("Has PNG_INFO_tRNS!\n");
111 png_set_tRNS_to_alpha(read_ptr);
112 }
113
114 if (bit_depth == 16)
115 png_set_strip_16(read_ptr);
116
117 if ((color_type&PNG_COLOR_MASK_ALPHA) == 0)
118 png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER);
119
120 if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
121 png_set_gray_to_rgb(read_ptr);
122
123 png_read_update_info(read_ptr, read_info);
124
125 outImageInfo->rows = (png_bytepp)malloc(
John Recke982b722013-08-26 16:53:40 -0700126 outImageInfo->height * sizeof(png_bytep));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 outImageInfo->allocHeight = outImageInfo->height;
128 outImageInfo->allocRows = outImageInfo->rows;
129
130 png_set_rows(read_ptr, read_info, outImageInfo->rows);
131
132 for (i = 0; i < (int)outImageInfo->height; i++)
133 {
134 outImageInfo->rows[i] = (png_bytep)
135 malloc(png_get_rowbytes(read_ptr, read_info));
136 }
137
138 png_read_image(read_ptr, outImageInfo->rows);
139
140 png_read_end(read_ptr, read_info);
141
Andreas Gampe2412f842014-09-30 20:55:57 -0700142 if (kIsDebug) {
143 printf("Image %s: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
144 imageName,
145 (int)outImageInfo->width, (int)outImageInfo->height,
146 bit_depth, color_type,
147 interlace_type, compression_type);
148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150 png_get_IHDR(read_ptr, read_info, &outImageInfo->width,
151 &outImageInfo->height, &bit_depth, &color_type,
152 &interlace_type, &compression_type, NULL);
153}
154
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700155#define COLOR_TRANSPARENT 0
156#define COLOR_WHITE 0xFFFFFFFF
157#define COLOR_TICK 0xFF000000
158#define COLOR_LAYOUT_BOUNDS_TICK 0xFF0000FF
159
160enum {
161 TICK_TYPE_NONE,
162 TICK_TYPE_TICK,
163 TICK_TYPE_LAYOUT_BOUNDS,
164 TICK_TYPE_BOTH
165};
166
167static int tick_type(png_bytep p, bool transparent, const char** outError)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168{
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700169 png_uint_32 color = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 if (transparent) {
172 if (p[3] == 0) {
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700173 return TICK_TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700175 if (color == COLOR_LAYOUT_BOUNDS_TICK) {
176 return TICK_TYPE_LAYOUT_BOUNDS;
177 }
178 if (color == COLOR_TICK) {
179 return TICK_TYPE_TICK;
180 }
181
182 // Error cases
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 if (p[3] != 0xff) {
184 *outError = "Frame pixels must be either solid or transparent (not intermediate alphas)";
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700185 return TICK_TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 }
187 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700188 *outError = "Ticks in transparent frame must be black or red";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700190 return TICK_TYPE_TICK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 }
192
193 if (p[3] != 0xFF) {
194 *outError = "White frame must be a solid color (no alpha)";
195 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700196 if (color == COLOR_WHITE) {
197 return TICK_TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700199 if (color == COLOR_TICK) {
200 return TICK_TYPE_TICK;
201 }
202 if (color == COLOR_LAYOUT_BOUNDS_TICK) {
203 return TICK_TYPE_LAYOUT_BOUNDS;
204 }
205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700207 *outError = "Ticks in white frame must be black or red";
208 return TICK_TYPE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700210 return TICK_TYPE_TICK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211}
212
213enum {
214 TICK_START,
215 TICK_INSIDE_1,
216 TICK_OUTSIDE_1
217};
218
219static status_t get_horizontal_ticks(
220 png_bytep row, int width, bool transparent, bool required,
221 int32_t* outLeft, int32_t* outRight, const char** outError,
222 uint8_t* outDivs, bool multipleAllowed)
223{
224 int i;
225 *outLeft = *outRight = -1;
226 int state = TICK_START;
227 bool found = false;
228
229 for (i=1; i<width-1; i++) {
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700230 if (TICK_TYPE_TICK == tick_type(row+i*4, transparent, outError)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 if (state == TICK_START ||
232 (state == TICK_OUTSIDE_1 && multipleAllowed)) {
233 *outLeft = i-1;
234 *outRight = width-2;
235 found = true;
236 if (outDivs != NULL) {
237 *outDivs += 2;
238 }
239 state = TICK_INSIDE_1;
240 } else if (state == TICK_OUTSIDE_1) {
241 *outError = "Can't have more than one marked region along edge";
242 *outLeft = i;
243 return UNKNOWN_ERROR;
244 }
245 } else if (*outError == NULL) {
246 if (state == TICK_INSIDE_1) {
247 // We're done with this div. Move on to the next.
248 *outRight = i-1;
249 outRight += 2;
250 outLeft += 2;
251 state = TICK_OUTSIDE_1;
252 }
253 } else {
254 *outLeft = i;
255 return UNKNOWN_ERROR;
256 }
257 }
258
259 if (required && !found) {
260 *outError = "No marked region found along edge";
261 *outLeft = -1;
262 return UNKNOWN_ERROR;
263 }
264
265 return NO_ERROR;
266}
267
268static status_t get_vertical_ticks(
269 png_bytepp rows, int offset, int height, bool transparent, bool required,
270 int32_t* outTop, int32_t* outBottom, const char** outError,
271 uint8_t* outDivs, bool multipleAllowed)
272{
273 int i;
274 *outTop = *outBottom = -1;
275 int state = TICK_START;
276 bool found = false;
277
278 for (i=1; i<height-1; i++) {
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700279 if (TICK_TYPE_TICK == tick_type(rows[i]+offset, transparent, outError)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 if (state == TICK_START ||
281 (state == TICK_OUTSIDE_1 && multipleAllowed)) {
282 *outTop = i-1;
283 *outBottom = height-2;
284 found = true;
285 if (outDivs != NULL) {
286 *outDivs += 2;
287 }
288 state = TICK_INSIDE_1;
289 } else if (state == TICK_OUTSIDE_1) {
290 *outError = "Can't have more than one marked region along edge";
291 *outTop = i;
292 return UNKNOWN_ERROR;
293 }
294 } else if (*outError == NULL) {
295 if (state == TICK_INSIDE_1) {
296 // We're done with this div. Move on to the next.
297 *outBottom = i-1;
298 outTop += 2;
299 outBottom += 2;
300 state = TICK_OUTSIDE_1;
301 }
302 } else {
303 *outTop = i;
304 return UNKNOWN_ERROR;
305 }
306 }
307
308 if (required && !found) {
309 *outError = "No marked region found along edge";
310 *outTop = -1;
311 return UNKNOWN_ERROR;
312 }
313
314 return NO_ERROR;
315}
316
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700317static status_t get_horizontal_layout_bounds_ticks(
Andreas Gampe2412f842014-09-30 20:55:57 -0700318 png_bytep row, int width, bool transparent, bool /* required */,
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700319 int32_t* outLeft, int32_t* outRight, const char** outError)
320{
321 int i;
322 *outLeft = *outRight = 0;
323
324 // Look for left tick
325 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(row + 4, transparent, outError)) {
326 // Starting with a layout padding tick
327 i = 1;
328 while (i < width - 1) {
329 (*outLeft)++;
330 i++;
331 int tick = tick_type(row + i * 4, transparent, outError);
332 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
333 break;
334 }
335 }
336 }
337
338 // Look for right tick
339 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(row + (width - 2) * 4, transparent, outError)) {
340 // Ending with a layout padding tick
341 i = width - 2;
342 while (i > 1) {
343 (*outRight)++;
344 i--;
345 int tick = tick_type(row+i*4, transparent, outError);
346 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
347 break;
348 }
349 }
350 }
351
352 return NO_ERROR;
353}
354
355static status_t get_vertical_layout_bounds_ticks(
Andreas Gampe2412f842014-09-30 20:55:57 -0700356 png_bytepp rows, int offset, int height, bool transparent, bool /* required */,
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700357 int32_t* outTop, int32_t* outBottom, const char** outError)
358{
359 int i;
360 *outTop = *outBottom = 0;
361
362 // Look for top tick
363 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(rows[1] + offset, transparent, outError)) {
364 // Starting with a layout padding tick
365 i = 1;
366 while (i < height - 1) {
367 (*outTop)++;
368 i++;
369 int tick = tick_type(rows[i] + offset, transparent, outError);
370 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
371 break;
372 }
373 }
374 }
375
376 // Look for bottom tick
377 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(rows[height - 2] + offset, transparent, outError)) {
378 // Ending with a layout padding tick
379 i = height - 2;
380 while (i > 1) {
381 (*outBottom)++;
382 i--;
383 int tick = tick_type(rows[i] + offset, transparent, outError);
384 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
385 break;
386 }
387 }
388 }
389
390 return NO_ERROR;
391}
392
393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394static uint32_t get_color(
395 png_bytepp rows, int left, int top, int right, int bottom)
396{
397 png_bytep color = rows[top] + left*4;
398
399 if (left > right || top > bottom) {
400 return Res_png_9patch::TRANSPARENT_COLOR;
401 }
402
403 while (top <= bottom) {
404 for (int i = left; i <= right; i++) {
405 png_bytep p = rows[top]+i*4;
406 if (color[3] == 0) {
407 if (p[3] != 0) {
408 return Res_png_9patch::NO_COLOR;
409 }
410 } else if (p[0] != color[0] || p[1] != color[1]
411 || p[2] != color[2] || p[3] != color[3]) {
412 return Res_png_9patch::NO_COLOR;
413 }
414 }
415 top++;
416 }
417
418 if (color[3] == 0) {
419 return Res_png_9patch::TRANSPARENT_COLOR;
420 }
421 return (color[3]<<24) | (color[0]<<16) | (color[1]<<8) | color[2];
422}
423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424static status_t do_9patch(const char* imageName, image_info* image)
425{
426 image->is9Patch = true;
427
428 int W = image->width;
429 int H = image->height;
430 int i, j;
431
The Android Open Source Project4df24232009-03-05 14:34:35 -0800432 int maxSizeXDivs = W * sizeof(int32_t);
433 int maxSizeYDivs = H * sizeof(int32_t);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000434 int32_t* xDivs = image->xDivs = (int32_t*) malloc(maxSizeXDivs);
435 int32_t* yDivs = image->yDivs = (int32_t*) malloc(maxSizeYDivs);
Elliott Hughesc367d482013-10-29 13:12:55 -0700436 uint8_t numXDivs = 0;
437 uint8_t numYDivs = 0;
438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 int8_t numColors;
440 int numRows;
441 int numCols;
442 int top;
443 int left;
444 int right;
445 int bottom;
446 memset(xDivs, -1, maxSizeXDivs);
447 memset(yDivs, -1, maxSizeYDivs);
448 image->info9Patch.paddingLeft = image->info9Patch.paddingRight =
449 image->info9Patch.paddingTop = image->info9Patch.paddingBottom = -1;
450
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700451 image->layoutBoundsLeft = image->layoutBoundsRight =
452 image->layoutBoundsTop = image->layoutBoundsBottom = 0;
453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 png_bytep p = image->rows[0];
455 bool transparent = p[3] == 0;
456 bool hasColor = false;
457
458 const char* errorMsg = NULL;
459 int errorPixel = -1;
Kenny Root9e652a62010-03-12 14:12:14 -0800460 const char* errorEdge = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461
462 int colorIndex = 0;
463
464 // Validate size...
465 if (W < 3 || H < 3) {
466 errorMsg = "Image must be at least 3x3 (1x1 without frame) pixels";
467 goto getout;
468 }
469
470 // Validate frame...
471 if (!transparent &&
472 (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) {
473 errorMsg = "Must have one-pixel frame that is either transparent or white";
474 goto getout;
475 }
476
477 // Find left and right of sizing areas...
478 if (get_horizontal_ticks(p, W, transparent, true, &xDivs[0],
479 &xDivs[1], &errorMsg, &numXDivs, true) != NO_ERROR) {
480 errorPixel = xDivs[0];
481 errorEdge = "top";
482 goto getout;
483 }
484
485 // Find top and bottom of sizing areas...
486 if (get_vertical_ticks(image->rows, 0, H, transparent, true, &yDivs[0],
487 &yDivs[1], &errorMsg, &numYDivs, true) != NO_ERROR) {
488 errorPixel = yDivs[0];
489 errorEdge = "left";
490 goto getout;
491 }
492
Elliott Hughesc367d482013-10-29 13:12:55 -0700493 // Copy patch size data into image...
494 image->info9Patch.numXDivs = numXDivs;
495 image->info9Patch.numYDivs = numYDivs;
496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 // Find left and right of padding area...
498 if (get_horizontal_ticks(image->rows[H-1], W, transparent, false, &image->info9Patch.paddingLeft,
499 &image->info9Patch.paddingRight, &errorMsg, NULL, false) != NO_ERROR) {
500 errorPixel = image->info9Patch.paddingLeft;
501 errorEdge = "bottom";
502 goto getout;
503 }
504
505 // Find top and bottom of padding area...
506 if (get_vertical_ticks(image->rows, (W-1)*4, H, transparent, false, &image->info9Patch.paddingTop,
507 &image->info9Patch.paddingBottom, &errorMsg, NULL, false) != NO_ERROR) {
508 errorPixel = image->info9Patch.paddingTop;
509 errorEdge = "right";
510 goto getout;
511 }
512
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700513 // Find left and right of layout padding...
514 get_horizontal_layout_bounds_ticks(image->rows[H-1], W, transparent, false,
515 &image->layoutBoundsLeft,
516 &image->layoutBoundsRight, &errorMsg);
517
518 get_vertical_layout_bounds_ticks(image->rows, (W-1)*4, H, transparent, false,
519 &image->layoutBoundsTop,
520 &image->layoutBoundsBottom, &errorMsg);
521
522 image->haveLayoutBounds = image->layoutBoundsLeft != 0
523 || image->layoutBoundsRight != 0
524 || image->layoutBoundsTop != 0
525 || image->layoutBoundsBottom != 0;
526
527 if (image->haveLayoutBounds) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700528 if (kIsDebug) {
529 printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
530 image->layoutBoundsRight, image->layoutBoundsBottom);
531 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700532 }
533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 // If padding is not yet specified, take values from size.
535 if (image->info9Patch.paddingLeft < 0) {
536 image->info9Patch.paddingLeft = xDivs[0];
537 image->info9Patch.paddingRight = W - 2 - xDivs[1];
538 } else {
539 // Adjust value to be correct!
540 image->info9Patch.paddingRight = W - 2 - image->info9Patch.paddingRight;
541 }
542 if (image->info9Patch.paddingTop < 0) {
543 image->info9Patch.paddingTop = yDivs[0];
544 image->info9Patch.paddingBottom = H - 2 - yDivs[1];
545 } else {
546 // Adjust value to be correct!
547 image->info9Patch.paddingBottom = H - 2 - image->info9Patch.paddingBottom;
548 }
549
Andreas Gampe2412f842014-09-30 20:55:57 -0700550 if (kIsDebug) {
551 printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName,
552 image->info9Patch.getXDivs()[0], image->info9Patch.getXDivs()[1],
553 image->info9Patch.getYDivs()[0], image->info9Patch.getYDivs()[1]);
554 printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName,
555 image->info9Patch.paddingLeft, image->info9Patch.paddingRight,
556 image->info9Patch.paddingTop, image->info9Patch.paddingBottom);
557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
559 // Remove frame from image.
John Recke982b722013-08-26 16:53:40 -0700560 image->rows = (png_bytepp)malloc((H-2) * sizeof(png_bytep));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 for (i=0; i<(H-2); i++) {
562 image->rows[i] = image->allocRows[i+1];
563 memmove(image->rows[i], image->rows[i]+4, (W-2)*4);
564 }
565 image->width -= 2;
566 W = image->width;
567 image->height -= 2;
568 H = image->height;
569
570 // Figure out the number of rows and columns in the N-patch
571 numCols = numXDivs + 1;
572 if (xDivs[0] == 0) { // Column 1 is strechable
573 numCols--;
574 }
575 if (xDivs[numXDivs - 1] == W) {
576 numCols--;
577 }
578 numRows = numYDivs + 1;
579 if (yDivs[0] == 0) { // Row 1 is strechable
580 numRows--;
581 }
582 if (yDivs[numYDivs - 1] == H) {
583 numRows--;
584 }
Kenny Root9e652a62010-03-12 14:12:14 -0800585
586 // Make sure the amount of rows and columns will fit in the number of
587 // colors we can use in the 9-patch format.
588 if (numRows * numCols > 0x7F) {
589 errorMsg = "Too many rows and columns in 9-patch perimeter";
590 goto getout;
591 }
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 numColors = numRows * numCols;
594 image->info9Patch.numColors = numColors;
Narayan Kamath6381dd42014-03-03 17:12:03 +0000595 image->colors = (uint32_t*)malloc(numColors * sizeof(uint32_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596
597 // Fill in color information for each patch.
598
599 uint32_t c;
600 top = 0;
601
602 // The first row always starts with the top being at y=0 and the bottom
603 // being either yDivs[1] (if yDivs[0]=0) of yDivs[0]. In the former case
604 // the first row is stretchable along the Y axis, otherwise it is fixed.
605 // The last row always ends with the bottom being bitmap.height and the top
606 // being either yDivs[numYDivs-2] (if yDivs[numYDivs-1]=bitmap.height) or
607 // yDivs[numYDivs-1]. In the former case the last row is stretchable along
608 // the Y axis, otherwise it is fixed.
609 //
610 // The first and last columns are similarly treated with respect to the X
611 // axis.
612 //
613 // The above is to help explain some of the special casing that goes on the
614 // code below.
615
616 // The initial yDiv and whether the first row is considered stretchable or
617 // not depends on whether yDiv[0] was zero or not.
618 for (j = (yDivs[0] == 0 ? 1 : 0);
619 j <= numYDivs && top < H;
620 j++) {
621 if (j == numYDivs) {
622 bottom = H;
623 } else {
624 bottom = yDivs[j];
625 }
626 left = 0;
627 // The initial xDiv and whether the first column is considered
628 // stretchable or not depends on whether xDiv[0] was zero or not.
629 for (i = xDivs[0] == 0 ? 1 : 0;
630 i <= numXDivs && left < W;
631 i++) {
632 if (i == numXDivs) {
633 right = W;
634 } else {
635 right = xDivs[i];
636 }
637 c = get_color(image->rows, left, top, right - 1, bottom - 1);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000638 image->colors[colorIndex++] = c;
Andreas Gampe2412f842014-09-30 20:55:57 -0700639 if (kIsDebug) {
640 if (c != Res_png_9patch::NO_COLOR)
641 hasColor = true;
642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 left = right;
644 }
645 top = bottom;
646 }
647
648 assert(colorIndex == numColors);
649
650 for (i=0; i<numColors; i++) {
651 if (hasColor) {
652 if (i == 0) printf("Colors in %s:\n ", imageName);
Narayan Kamath6381dd42014-03-03 17:12:03 +0000653 printf(" #%08x", image->colors[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 if (i == numColors - 1) printf("\n");
655 }
656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657getout:
658 if (errorMsg) {
659 fprintf(stderr,
660 "ERROR: 9-patch image %s malformed.\n"
661 " %s.\n", imageName, errorMsg);
Kenny Root9e652a62010-03-12 14:12:14 -0800662 if (errorEdge != NULL) {
663 if (errorPixel >= 0) {
664 fprintf(stderr,
665 " Found at pixel #%d along %s edge.\n", errorPixel, errorEdge);
666 } else {
667 fprintf(stderr,
668 " Found along %s edge.\n", errorEdge);
669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 }
671 return UNKNOWN_ERROR;
672 }
673 return NO_ERROR;
674}
675
Narayan Kamath6381dd42014-03-03 17:12:03 +0000676static void checkNinePatchSerialization(Res_png_9patch* inPatch, void* data)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 size_t patchSize = inPatch->serializedSize();
Narayan Kamath6381dd42014-03-03 17:12:03 +0000679 void* newData = malloc(patchSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 memcpy(newData, data, patchSize);
681 Res_png_9patch* outPatch = inPatch->deserialize(newData);
682 // deserialization is done in place, so outPatch == newData
683 assert(outPatch == newData);
684 assert(outPatch->numXDivs == inPatch->numXDivs);
685 assert(outPatch->numYDivs == inPatch->numYDivs);
686 assert(outPatch->paddingLeft == inPatch->paddingLeft);
687 assert(outPatch->paddingRight == inPatch->paddingRight);
688 assert(outPatch->paddingTop == inPatch->paddingTop);
689 assert(outPatch->paddingBottom == inPatch->paddingBottom);
690 for (int i = 0; i < outPatch->numXDivs; i++) {
691 assert(outPatch->xDivs[i] == inPatch->xDivs[i]);
692 }
693 for (int i = 0; i < outPatch->numYDivs; i++) {
694 assert(outPatch->yDivs[i] == inPatch->yDivs[i]);
695 }
696 for (int i = 0; i < outPatch->numColors; i++) {
697 assert(outPatch->colors[i] == inPatch->colors[i]);
698 }
699 free(newData);
700}
701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702static void dump_image(int w, int h, png_bytepp rows, int color_type)
703{
704 int i, j, rr, gg, bb, aa;
705
706 int bpp;
707 if (color_type == PNG_COLOR_TYPE_PALETTE || color_type == PNG_COLOR_TYPE_GRAY) {
708 bpp = 1;
709 } else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
710 bpp = 2;
711 } else if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
Kenny Root9e652a62010-03-12 14:12:14 -0800712 // We use a padding byte even when there is no alpha
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 bpp = 4;
714 } else {
715 printf("Unknown color type %d.\n", color_type);
716 }
717
718 for (j = 0; j < h; j++) {
719 png_bytep row = rows[j];
720 for (i = 0; i < w; i++) {
721 rr = row[0];
722 gg = row[1];
723 bb = row[2];
724 aa = row[3];
725 row += bpp;
726
727 if (i == 0) {
728 printf("Row %d:", j);
729 }
730 switch (bpp) {
731 case 1:
732 printf(" (%d)", rr);
733 break;
734 case 2:
735 printf(" (%d %d", rr, gg);
736 break;
737 case 3:
738 printf(" (%d %d %d)", rr, gg, bb);
739 break;
740 case 4:
741 printf(" (%d %d %d %d)", rr, gg, bb, aa);
742 break;
743 }
744 if (i == (w - 1)) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700745 printf("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747 }
748 }
749}
750
751#define MAX(a,b) ((a)>(b)?(a):(b))
752#define ABS(a) ((a)<0?-(a):(a))
753
754static void analyze_image(const char *imageName, image_info &imageInfo, int grayscaleTolerance,
755 png_colorp rgbPalette, png_bytep alphaPalette,
756 int *paletteEntries, bool *hasTransparency, int *colorType,
757 png_bytepp outRows)
758{
759 int w = imageInfo.width;
760 int h = imageInfo.height;
761 int i, j, rr, gg, bb, aa, idx;
762 uint32_t colors[256], col;
763 int num_colors = 0;
764 int maxGrayDeviation = 0;
765
766 bool isOpaque = true;
767 bool isPalette = true;
768 bool isGrayscale = true;
769
770 // Scan the entire image and determine if:
771 // 1. Every pixel has R == G == B (grayscale)
772 // 2. Every pixel has A == 255 (opaque)
773 // 3. There are no more than 256 distinct RGBA colors
774
Andreas Gampe2412f842014-09-30 20:55:57 -0700775 if (kIsDebug) {
776 printf("Initial image data:\n");
777 dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA);
778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779
780 for (j = 0; j < h; j++) {
781 png_bytep row = imageInfo.rows[j];
782 png_bytep out = outRows[j];
783 for (i = 0; i < w; i++) {
784 rr = *row++;
785 gg = *row++;
786 bb = *row++;
787 aa = *row++;
788
789 int odev = maxGrayDeviation;
790 maxGrayDeviation = MAX(ABS(rr - gg), maxGrayDeviation);
791 maxGrayDeviation = MAX(ABS(gg - bb), maxGrayDeviation);
792 maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation);
793 if (maxGrayDeviation > odev) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700794 if (kIsDebug) {
795 printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
796 maxGrayDeviation, i, j, rr, gg, bb, aa);
797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 }
799
800 // Check if image is really grayscale
801 if (isGrayscale) {
802 if (rr != gg || rr != bb) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700803 if (kIsDebug) {
804 printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n",
805 i, j, rr, gg, bb, aa);
806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 isGrayscale = false;
808 }
809 }
810
811 // Check if image is really opaque
812 if (isOpaque) {
813 if (aa != 0xff) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700814 if (kIsDebug) {
815 printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n",
816 i, j, rr, gg, bb, aa);
817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 isOpaque = false;
819 }
820 }
821
822 // Check if image is really <= 256 colors
823 if (isPalette) {
824 col = (uint32_t) ((rr << 24) | (gg << 16) | (bb << 8) | aa);
825 bool match = false;
826 for (idx = 0; idx < num_colors; idx++) {
827 if (colors[idx] == col) {
828 match = true;
829 break;
830 }
831 }
832
833 // Write the palette index for the pixel to outRows optimistically
834 // We might overwrite it later if we decide to encode as gray or
835 // gray + alpha
836 *out++ = idx;
837 if (!match) {
838 if (num_colors == 256) {
Andreas Gampe2412f842014-09-30 20:55:57 -0700839 if (kIsDebug) {
840 printf("Found 257th color at %d, %d\n", i, j);
841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 isPalette = false;
843 } else {
844 colors[num_colors++] = col;
845 }
846 }
847 }
848 }
849 }
850
851 *paletteEntries = 0;
852 *hasTransparency = !isOpaque;
853 int bpp = isOpaque ? 3 : 4;
854 int paletteSize = w * h + bpp * num_colors;
855
Andreas Gampe2412f842014-09-30 20:55:57 -0700856 if (kIsDebug) {
857 printf("isGrayscale = %s\n", isGrayscale ? "true" : "false");
858 printf("isOpaque = %s\n", isOpaque ? "true" : "false");
859 printf("isPalette = %s\n", isPalette ? "true" : "false");
860 printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n",
861 paletteSize, 2 * w * h, bpp * w * h);
862 printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance);
863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864
865 // Choose the best color type for the image.
866 // 1. Opaque gray - use COLOR_TYPE_GRAY at 1 byte/pixel
867 // 2. Gray + alpha - use COLOR_TYPE_PALETTE if the number of distinct combinations
868 // is sufficiently small, otherwise use COLOR_TYPE_GRAY_ALPHA
869 // 3. RGB(A) - use COLOR_TYPE_PALETTE if the number of distinct colors is sufficiently
870 // small, otherwise use COLOR_TYPE_RGB{_ALPHA}
871 if (isGrayscale) {
872 if (isOpaque) {
873 *colorType = PNG_COLOR_TYPE_GRAY; // 1 byte/pixel
874 } else {
875 // Use a simple heuristic to determine whether using a palette will
876 // save space versus using gray + alpha for each pixel.
877 // This doesn't take into account chunk overhead, filtering, LZ
878 // compression, etc.
879 if (isPalette && (paletteSize < 2 * w * h)) {
880 *colorType = PNG_COLOR_TYPE_PALETTE; // 1 byte/pixel + 4 bytes/color
881 } else {
882 *colorType = PNG_COLOR_TYPE_GRAY_ALPHA; // 2 bytes per pixel
883 }
884 }
885 } else if (isPalette && (paletteSize < bpp * w * h)) {
886 *colorType = PNG_COLOR_TYPE_PALETTE;
887 } else {
888 if (maxGrayDeviation <= grayscaleTolerance) {
889 printf("%s: forcing image to gray (max deviation = %d)\n", imageName, maxGrayDeviation);
890 *colorType = isOpaque ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA;
891 } else {
892 *colorType = isOpaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA;
893 }
894 }
895
896 // Perform postprocessing of the image or palette data based on the final
897 // color type chosen
898
899 if (*colorType == PNG_COLOR_TYPE_PALETTE) {
900 // Create separate RGB and Alpha palettes and set the number of colors
901 *paletteEntries = num_colors;
902
903 // Create the RGB and alpha palettes
904 for (int idx = 0; idx < num_colors; idx++) {
905 col = colors[idx];
906 rgbPalette[idx].red = (png_byte) ((col >> 24) & 0xff);
907 rgbPalette[idx].green = (png_byte) ((col >> 16) & 0xff);
908 rgbPalette[idx].blue = (png_byte) ((col >> 8) & 0xff);
909 alphaPalette[idx] = (png_byte) (col & 0xff);
910 }
911 } else if (*colorType == PNG_COLOR_TYPE_GRAY || *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
912 // If the image is gray or gray + alpha, compact the pixels into outRows
913 for (j = 0; j < h; j++) {
914 png_bytep row = imageInfo.rows[j];
915 png_bytep out = outRows[j];
916 for (i = 0; i < w; i++) {
917 rr = *row++;
918 gg = *row++;
919 bb = *row++;
920 aa = *row++;
Elliott Hughesc367d482013-10-29 13:12:55 -0700921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 if (isGrayscale) {
923 *out++ = rr;
924 } else {
925 *out++ = (png_byte) (rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
926 }
927 if (!isOpaque) {
928 *out++ = aa;
929 }
930 }
931 }
932 }
933}
934
935
936static void write_png(const char* imageName,
937 png_structp write_ptr, png_infop write_info,
938 image_info& imageInfo, int grayscaleTolerance)
939{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 png_uint_32 width, height;
941 int color_type;
942 int bit_depth, interlace_type, compression_type;
943 int i;
944
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700945 png_unknown_chunk unknowns[2];
Marco Nelissen6a1fade2009-04-20 16:16:01 -0700946 unknowns[0].data = NULL;
Amith Yamasaniec4a5042012-04-04 10:27:15 -0700947 unknowns[1].data = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948
John Recke982b722013-08-26 16:53:40 -0700949 png_bytepp outRows = (png_bytepp) malloc((int) imageInfo.height * sizeof(png_bytep));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 if (outRows == (png_bytepp) 0) {
951 printf("Can't allocate output buffer!\n");
952 exit(1);
953 }
954 for (i = 0; i < (int) imageInfo.height; i++) {
955 outRows[i] = (png_bytep) malloc(2 * (int) imageInfo.width);
956 if (outRows[i] == (png_bytep) 0) {
957 printf("Can't allocate output buffer!\n");
958 exit(1);
959 }
960 }
961
962 png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
963
Andreas Gampe2412f842014-09-30 20:55:57 -0700964 if (kIsDebug) {
965 printf("Writing image %s: w = %d, h = %d\n", imageName,
966 (int) imageInfo.width, (int) imageInfo.height);
967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968
969 png_color rgbPalette[256];
970 png_byte alphaPalette[256];
971 bool hasTransparency;
972 int paletteEntries;
973
974 analyze_image(imageName, imageInfo, grayscaleTolerance, rgbPalette, alphaPalette,
975 &paletteEntries, &hasTransparency, &color_type, outRows);
976
977 // If the image is a 9-patch, we need to preserve it as a ARGB file to make
978 // sure the pixels will not be pre-dithered/clamped until we decide they are
979 if (imageInfo.is9Patch && (color_type == PNG_COLOR_TYPE_RGB ||
980 color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE)) {
981 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
982 }
983
Andreas Gampe2412f842014-09-30 20:55:57 -0700984 if (kIsDebug) {
985 switch (color_type) {
986 case PNG_COLOR_TYPE_PALETTE:
987 printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n",
988 imageName, paletteEntries,
989 hasTransparency ? " (with alpha)" : "");
990 break;
991 case PNG_COLOR_TYPE_GRAY:
992 printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName);
993 break;
994 case PNG_COLOR_TYPE_GRAY_ALPHA:
995 printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName);
996 break;
997 case PNG_COLOR_TYPE_RGB:
998 printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName);
999 break;
1000 case PNG_COLOR_TYPE_RGB_ALPHA:
1001 printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName);
1002 break;
1003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 }
1005
1006 png_set_IHDR(write_ptr, write_info, imageInfo.width, imageInfo.height,
1007 8, color_type, PNG_INTERLACE_NONE,
1008 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1009
1010 if (color_type == PNG_COLOR_TYPE_PALETTE) {
1011 png_set_PLTE(write_ptr, write_info, rgbPalette, paletteEntries);
1012 if (hasTransparency) {
1013 png_set_tRNS(write_ptr, write_info, alphaPalette, paletteEntries, (png_color_16p) 0);
1014 }
1015 png_set_filter(write_ptr, 0, PNG_NO_FILTERS);
1016 } else {
1017 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
1018 }
1019
1020 if (imageInfo.is9Patch) {
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001021 int chunk_count = 1 + (imageInfo.haveLayoutBounds ? 1 : 0);
1022 int p_index = imageInfo.haveLayoutBounds ? 1 : 0;
1023 int b_index = 0;
1024 png_byte *chunk_names = imageInfo.haveLayoutBounds
1025 ? (png_byte*)"npLb\0npTc\0"
1026 : (png_byte*)"npTc";
Andreas Gampe2412f842014-09-30 20:55:57 -07001027 if (kIsDebug) {
1028 printf("Adding 9-patch info...\n");
1029 }
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001030 strcpy((char*)unknowns[p_index].name, "npTc");
Narayan Kamath6381dd42014-03-03 17:12:03 +00001031 unknowns[p_index].data = (png_byte*)imageInfo.serialize9patch();
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001032 unknowns[p_index].size = imageInfo.info9Patch.serializedSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 // TODO: remove the check below when everything works
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001034 checkNinePatchSerialization(&imageInfo.info9Patch, unknowns[p_index].data);
1035
1036 if (imageInfo.haveLayoutBounds) {
1037 int chunk_size = sizeof(png_uint_32) * 4;
1038 strcpy((char*)unknowns[b_index].name, "npLb");
1039 unknowns[b_index].data = (png_byte*) calloc(chunk_size, 1);
1040 memcpy(unknowns[b_index].data, &imageInfo.layoutBoundsLeft, chunk_size);
1041 unknowns[b_index].size = chunk_size;
1042 }
1043
John Recke982b722013-08-26 16:53:40 -07001044 for (int i = 0; i < chunk_count; i++) {
1045 unknowns[i].location = PNG_HAVE_PLTE;
1046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS,
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001048 chunk_names, chunk_count);
1049 png_set_unknown_chunks(write_ptr, write_info, unknowns, chunk_count);
John Recke982b722013-08-26 16:53:40 -07001050#if PNG_LIBPNG_VER < 10600
1051 /* Deal with unknown chunk location bug in 1.5.x and earlier */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 png_set_unknown_chunk_location(write_ptr, write_info, 0, PNG_HAVE_PLTE);
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001053 if (imageInfo.haveLayoutBounds) {
1054 png_set_unknown_chunk_location(write_ptr, write_info, 1, PNG_HAVE_PLTE);
1055 }
John Recke982b722013-08-26 16:53:40 -07001056#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 png_write_info(write_ptr, write_info);
1061
1062 png_bytepp rows;
1063 if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
John Recke982b722013-08-26 16:53:40 -07001064 if (color_type == PNG_COLOR_TYPE_RGB) {
1065 png_set_filler(write_ptr, 0, PNG_FILLER_AFTER);
1066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 rows = imageInfo.rows;
1068 } else {
1069 rows = outRows;
1070 }
1071 png_write_image(write_ptr, rows);
1072
Andreas Gampe2412f842014-09-30 20:55:57 -07001073 if (kIsDebug) {
1074 printf("Final image data:\n");
1075 dump_image(imageInfo.width, imageInfo.height, rows, color_type);
1076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077
1078 png_write_end(write_ptr, write_info);
1079
1080 for (i = 0; i < (int) imageInfo.height; i++) {
1081 free(outRows[i]);
1082 }
1083 free(outRows);
Marco Nelissen6a1fade2009-04-20 16:16:01 -07001084 free(unknowns[0].data);
Amith Yamasaniec4a5042012-04-04 10:27:15 -07001085 free(unknowns[1].data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086
1087 png_get_IHDR(write_ptr, write_info, &width, &height,
1088 &bit_depth, &color_type, &interlace_type,
1089 &compression_type, NULL);
1090
Andreas Gampe2412f842014-09-30 20:55:57 -07001091 if (kIsDebug) {
1092 printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
1093 (int)width, (int)height, bit_depth, color_type, interlace_type,
1094 compression_type);
1095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096}
1097
Andreas Gampe2412f842014-09-30 20:55:57 -07001098status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& /* assets */,
1099 const sp<AaptFile>& file, String8* /* outNewLeafName */)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100{
1101 String8 ext(file->getPath().getPathExtension());
1102
1103 // We currently only process PNG images.
1104 if (strcmp(ext.string(), ".png") != 0) {
1105 return NO_ERROR;
1106 }
1107
1108 // Example of renaming a file:
1109 //*outNewLeafName = file->getPath().getBasePath().getFileName();
1110 //outNewLeafName->append(".nupng");
1111
1112 String8 printableName(file->getPrintableSource());
1113
Dianne Hackborne6b68032011-10-13 16:26:02 -07001114 if (bundle->getVerbose()) {
1115 printf("Processing image: %s\n", printableName.string());
1116 }
1117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 png_structp read_ptr = NULL;
1119 png_infop read_info = NULL;
1120 FILE* fp;
1121
1122 image_info imageInfo;
1123
1124 png_structp write_ptr = NULL;
1125 png_infop write_info = NULL;
1126
1127 status_t error = UNKNOWN_ERROR;
1128
1129 const size_t nameLen = file->getPath().length();
1130
1131 fp = fopen(file->getSourceFile().string(), "rb");
1132 if (fp == NULL) {
1133 fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string());
1134 goto bail;
1135 }
1136
1137 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1138 (png_error_ptr)NULL);
1139 if (!read_ptr) {
1140 goto bail;
1141 }
1142
1143 read_info = png_create_info_struct(read_ptr);
1144 if (!read_info) {
1145 goto bail;
1146 }
1147
1148 if (setjmp(png_jmpbuf(read_ptr))) {
1149 goto bail;
1150 }
1151
1152 png_init_io(read_ptr, fp);
1153
1154 read_png(printableName.string(), read_ptr, read_info, &imageInfo);
1155
1156 if (nameLen > 6) {
1157 const char* name = file->getPath().string();
1158 if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
1159 if (do_9patch(printableName.string(), &imageInfo) != NO_ERROR) {
1160 goto bail;
1161 }
1162 }
1163 }
1164
1165 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1166 (png_error_ptr)NULL);
1167 if (!write_ptr)
1168 {
1169 goto bail;
1170 }
1171
1172 write_info = png_create_info_struct(write_ptr);
1173 if (!write_info)
1174 {
1175 goto bail;
1176 }
1177
1178 png_set_write_fn(write_ptr, (void*)file.get(),
1179 png_write_aapt_file, png_flush_aapt_file);
1180
1181 if (setjmp(png_jmpbuf(write_ptr)))
1182 {
1183 goto bail;
1184 }
1185
1186 write_png(printableName.string(), write_ptr, write_info, imageInfo,
1187 bundle->getGrayscaleTolerance());
1188
1189 error = NO_ERROR;
1190
1191 if (bundle->getVerbose()) {
1192 fseek(fp, 0, SEEK_END);
1193 size_t oldSize = (size_t)ftell(fp);
1194 size_t newSize = file->getSize();
1195 float factor = ((float)newSize)/oldSize;
1196 int percent = (int)(factor*100);
1197 printf(" (processed image %s: %d%% size of source)\n", printableName.string(), percent);
1198 }
1199
1200bail:
1201 if (read_ptr) {
1202 png_destroy_read_struct(&read_ptr, &read_info, (png_infopp)NULL);
1203 }
1204 if (fp) {
1205 fclose(fp);
1206 }
1207 if (write_ptr) {
1208 png_destroy_write_struct(&write_ptr, &write_info);
1209 }
1210
1211 if (error != NO_ERROR) {
1212 fprintf(stderr, "ERROR: Failure processing PNG image %s\n",
1213 file->getPrintableSource().string());
1214 }
1215 return error;
1216}
1217
Jeff Brownc0f73662012-03-16 22:17:41 -07001218status_t preProcessImageToCache(const Bundle* bundle, const String8& source, const String8& dest)
Josiah Gaskin8a39da82011-06-06 17:00:35 -07001219{
1220 png_structp read_ptr = NULL;
1221 png_infop read_info = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222
Josiah Gaskin8a39da82011-06-06 17:00:35 -07001223 FILE* fp;
1224
1225 image_info imageInfo;
1226
1227 png_structp write_ptr = NULL;
1228 png_infop write_info = NULL;
1229
1230 status_t error = UNKNOWN_ERROR;
1231
Dianne Hackborne6b68032011-10-13 16:26:02 -07001232 if (bundle->getVerbose()) {
1233 printf("Processing image to cache: %s => %s\n", source.string(), dest.string());
1234 }
1235
Josiah Gaskin8a39da82011-06-06 17:00:35 -07001236 // Get a file handler to read from
1237 fp = fopen(source.string(),"rb");
1238 if (fp == NULL) {
1239 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.string());
1240 return error;
1241 }
1242
1243 // Call libpng to get a struct to read image data into
1244 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1245 if (!read_ptr) {
1246 fclose(fp);
1247 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1248 return error;
1249 }
1250
1251 // Call libpng to get a struct to read image info into
1252 read_info = png_create_info_struct(read_ptr);
1253 if (!read_info) {
1254 fclose(fp);
1255 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1256 return error;
1257 }
1258
1259 // Set a jump point for libpng to long jump back to on error
1260 if (setjmp(png_jmpbuf(read_ptr))) {
1261 fclose(fp);
1262 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1263 return error;
1264 }
1265
1266 // Set up libpng to read from our file.
1267 png_init_io(read_ptr,fp);
1268
1269 // Actually read data from the file
1270 read_png(source.string(), read_ptr, read_info, &imageInfo);
1271
1272 // We're done reading so we can clean up
1273 // Find old file size before releasing handle
1274 fseek(fp, 0, SEEK_END);
1275 size_t oldSize = (size_t)ftell(fp);
1276 fclose(fp);
1277 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1278
1279 // Check to see if we're dealing with a 9-patch
1280 // If we are, process appropriately
1281 if (source.getBasePath().getPathExtension() == ".9") {
1282 if (do_9patch(source.string(), &imageInfo) != NO_ERROR) {
1283 return error;
1284 }
1285 }
1286
1287 // Call libpng to create a structure to hold the processed image data
1288 // that can be written to disk
1289 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1290 if (!write_ptr) {
1291 png_destroy_write_struct(&write_ptr, &write_info);
1292 return error;
1293 }
1294
1295 // Call libpng to create a structure to hold processed image info that can
1296 // be written to disk
1297 write_info = png_create_info_struct(write_ptr);
1298 if (!write_info) {
1299 png_destroy_write_struct(&write_ptr, &write_info);
1300 return error;
1301 }
1302
1303 // Open up our destination file for writing
1304 fp = fopen(dest.string(), "wb");
1305 if (!fp) {
1306 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.string());
1307 png_destroy_write_struct(&write_ptr, &write_info);
1308 return error;
1309 }
1310
1311 // Set up libpng to write to our file
1312 png_init_io(write_ptr, fp);
1313
1314 // Set up a jump for libpng to long jump back on on errors
1315 if (setjmp(png_jmpbuf(write_ptr))) {
1316 fclose(fp);
1317 png_destroy_write_struct(&write_ptr, &write_info);
1318 return error;
1319 }
1320
1321 // Actually write out to the new png
1322 write_png(dest.string(), write_ptr, write_info, imageInfo,
1323 bundle->getGrayscaleTolerance());
1324
1325 if (bundle->getVerbose()) {
1326 // Find the size of our new file
1327 FILE* reader = fopen(dest.string(), "rb");
1328 fseek(reader, 0, SEEK_END);
1329 size_t newSize = (size_t)ftell(reader);
1330 fclose(reader);
1331
1332 float factor = ((float)newSize)/oldSize;
1333 int percent = (int)(factor*100);
1334 printf(" (processed image to cache entry %s: %d%% size of source)\n",
1335 dest.string(), percent);
1336 }
1337
1338 //Clean up
1339 fclose(fp);
1340 png_destroy_write_struct(&write_ptr, &write_info);
1341
1342 return NO_ERROR;
1343}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344
1345status_t postProcessImage(const sp<AaptAssets>& assets,
1346 ResourceTable* table, const sp<AaptFile>& file)
1347{
1348 String8 ext(file->getPath().getPathExtension());
1349
1350 // At this point, now that we have all the resource data, all we need to
1351 // do is compile XML files.
1352 if (strcmp(ext.string(), ".xml") == 0) {
1353 return compileXmlFile(assets, file, table);
1354 }
1355
1356 return NO_ERROR;
1357}