xref: /haiku/src/add-ons/translators/png/PNGTranslator.cpp (revision 945566ff43583e4f8102b4440c88f53dae775cb4)
1 /*****************************************************************************/
2 // PNGTranslator
3 // Written by Michael Wilber, OBOS Translation Kit Team
4 //
5 // PNGTranslator.cpp
6 //
7 // This BTranslator based object is for opening and writing
8 // PNG images.
9 //
10 //
11 // Copyright (c) 2003, OpenBeOS Project
12 // Copyright (c) 2009, Haiku, Inc. All rights reserved.
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining a
15 // copy of this software and associated documentation files (the "Software"),
16 // to deal in the Software without restriction, including without limitation
17 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
18 // and/or sell copies of the Software, and to permit persons to whom the
19 // Software is furnished to do so, subject to the following conditions:
20 //
21 // The above copyright notice and this permission notice shall be included
22 // in all copies or substantial portions of the Software.
23 //
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
30 // DEALINGS IN THE SOFTWARE.
31 /*****************************************************************************/
32 
33 
34 #include "PNGTranslator.h"
35 
36 #include <stdio.h>
37 #include <string.h>
38 
39 #include <Catalog.h>
40 #include <OS.h>
41 #define PNG_NO_PEDANTIC_WARNINGS
42 #include <png.h>
43 
44 #include "PNGView.h"
45 
46 #undef B_TRANSLATION_CONTEXT
47 #define B_TRANSLATION_CONTEXT "PNGTranslator"
48 
49 // The input formats that this translator supports.
50 static const translation_format sInputFormats[] = {
51 	{
52 		B_PNG_FORMAT,
53 		B_TRANSLATOR_BITMAP,
54 		PNG_IN_QUALITY,
55 		PNG_IN_CAPABILITY,
56 		"image/png",
57 		"PNG image"
58 	},
59 	{
60 		B_PNG_FORMAT,
61 		B_TRANSLATOR_BITMAP,
62 		PNG_IN_QUALITY,
63 		PNG_IN_CAPABILITY,
64 		"image/x-png",
65 		"PNG image"
66 	},
67 	{
68 		B_TRANSLATOR_BITMAP,
69 		B_TRANSLATOR_BITMAP,
70 		BBT_IN_QUALITY,
71 		BBT_IN_CAPABILITY,
72 		"image/x-be-bitmap",
73 		"Be Bitmap Format (PNGTranslator)"
74 	}
75 };
76 
77 // The output formats that this translator supports.
78 static const translation_format sOutputFormats[] = {
79 	{
80 		B_PNG_FORMAT,
81 		B_TRANSLATOR_BITMAP,
82 		PNG_OUT_QUALITY,
83 		PNG_OUT_CAPABILITY,
84 		"image/png",
85 		"PNG image"
86 	},
87 	{
88 		B_TRANSLATOR_BITMAP,
89 		B_TRANSLATOR_BITMAP,
90 		BBT_OUT_QUALITY,
91 		BBT_OUT_CAPABILITY,
92 		"image/x-be-bitmap",
93 		"Be Bitmap Format (PNGTranslator)"
94 	}
95 };
96 
97 // Default settings for the Translator
98 static const TranSetting sDefaultSettings[] = {
99 	{B_TRANSLATOR_EXT_HEADER_ONLY, TRAN_SETTING_BOOL, false},
100 	{B_TRANSLATOR_EXT_DATA_ONLY, TRAN_SETTING_BOOL, false},
101 	{PNG_SETTING_INTERLACE, TRAN_SETTING_INT32, PNG_INTERLACE_NONE}
102 		// interlacing is off by default
103 };
104 
105 const uint32 kNumInputFormats = sizeof(sInputFormats) / sizeof(translation_format);
106 const uint32 kNumOutputFormats = sizeof(sOutputFormats) / sizeof(translation_format);
107 const uint32 kNumDefaultSettings = sizeof(sDefaultSettings) / sizeof(TranSetting);
108 
109 
110 // ---------------------------------------------------------------
111 // make_nth_translator
112 //
113 // Creates a PNGTranslator object to be used by BTranslatorRoster
114 //
115 // Preconditions:
116 //
117 // Parameters: n,		The translator to return. Since
118 //						PNGTranslator only publishes one
119 //						translator, it only returns a
120 //						PNGTranslator if n == 0
121 //
122 //             you, 	The image_id of the add-on that
123 //						contains code (not used).
124 //
125 //             flags,	Has no meaning yet, should be 0.
126 //
127 // Postconditions:
128 //
129 // Returns: NULL if n is not zero,
130 //          a new PNGTranslator if n is zero
131 // ---------------------------------------------------------------
132 BTranslator *
133 make_nth_translator(int32 n, image_id you, uint32 flags, ...)
134 {
135 	if (!n)
136 		return new PNGTranslator();
137 	else
138 		return NULL;
139 }
140 
141  /* The png_jmpbuf() macro, used in error handling, became available in
142   * libpng version 1.0.6.  If you want to be able to run your code with older
143   * versions of libpng, you must define the macro yourself (but only if it
144   * is not already defined by libpng!).
145   */
146 
147 #ifndef png_jmpbuf
148 #  define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
149 #endif
150 
151 //// libpng Callback functions!
152 
153 BPositionIO *
154 get_pio(png_structp ppng)
155 {
156 	BPositionIO *pio = NULL;
157 	pio = static_cast<BPositionIO *>(png_get_io_ptr(ppng));
158 	return pio;
159 }
160 
161 void
162 pngcb_read_data(png_structp ppng, png_bytep pdata, png_size_t length)
163 {
164 	BPositionIO *pio = get_pio(ppng);
165 	pio->Read(pdata, static_cast<size_t>(length));
166 }
167 
168 void
169 pngcb_write_data(png_structp ppng, png_bytep pdata, png_size_t length)
170 {
171 	BPositionIO *pio = get_pio(ppng);
172 	pio->Write(pdata, static_cast<size_t>(length));
173 }
174 
175 void
176 pngcb_flush_data(png_structp ppng)
177 {
178 	// I don't think I really need to do anything here
179 }
180 
181 // ---------------------------------------------------------------
182 // Constructor
183 //
184 // Sets up the version info and the name of the translator so that
185 // these values can be returned when they are requested.
186 //
187 // Preconditions:
188 //
189 // Parameters:
190 //
191 // Postconditions:
192 //
193 // Returns:
194 // ---------------------------------------------------------------
195 PNGTranslator::PNGTranslator()
196 	: BaseTranslator(B_TRANSLATE("PNG images"),
197 		B_TRANSLATE("PNG image translator"),
198 		PNG_TRANSLATOR_VERSION,
199 		sInputFormats, kNumInputFormats,
200 		sOutputFormats, kNumOutputFormats,
201 		"PNGTranslator_Settings",
202 		sDefaultSettings, kNumDefaultSettings,
203 		B_TRANSLATOR_BITMAP, B_PNG_FORMAT)
204 {
205 }
206 
207 // ---------------------------------------------------------------
208 // Destructor
209 //
210 // Does nothing
211 //
212 // Preconditions:
213 //
214 // Parameters:
215 //
216 // Postconditions:
217 //
218 // Returns:
219 // ---------------------------------------------------------------
220 PNGTranslator::~PNGTranslator()
221 {
222 }
223 
224 status_t
225 identify_png_header(BPositionIO *inSource, translator_info *outInfo)
226 {
227 	const int32 kSigSize = 8;
228 	uint8 buf[kSigSize];
229 	if (inSource->Read(buf, kSigSize) != kSigSize)
230 		return B_NO_TRANSLATOR;
231 	if (png_sig_cmp(buf, 0, kSigSize))
232 		// if first 8 bytes of stream don't match PNG signature bail
233 		return B_NO_TRANSLATOR;
234 
235 	if (outInfo) {
236 		outInfo->type = B_PNG_FORMAT;
237 		outInfo->group = B_TRANSLATOR_BITMAP;
238 		outInfo->quality = PNG_IN_QUALITY;
239 		outInfo->capability = PNG_IN_CAPABILITY;
240 		strcpy(outInfo->MIME, "image/png");
241 		strlcpy(outInfo->name, B_TRANSLATE("PNG image"),
242 			sizeof(outInfo->name));
243 	}
244 
245 	return B_OK;
246 }
247 
248 // ---------------------------------------------------------------
249 // DerivedIdentify
250 //
251 // Examines the data from inSource and determines if it is in a
252 // format that this translator knows how to work with.
253 //
254 // Preconditions:
255 //
256 // Parameters:	inSource,	where the data to examine is
257 //
258 //				inFormat,	a hint about the data in inSource,
259 //							it is ignored since it is only a hint
260 //
261 //				ioExtension,	configuration settings for the
262 //								translator (not used)
263 //
264 //				outInfo,	information about what data is in
265 //							inSource and how well this translator
266 //							can handle that data is stored here
267 //
268 //				outType,	The format that the user wants
269 //							the data in inSource to be
270 //							converted to
271 //
272 // Postconditions:
273 //
274 // Returns: B_NO_TRANSLATOR,	if this translator can't handle
275 //								the data in inSource
276 //
277 // B_ERROR,	if there was an error converting the data to the host
278 //			format
279 //
280 // B_BAD_VALUE, if the settings in ioExtension are bad
281 //
282 // B_OK,	if this translator understood the data and there were
283 //			no errors found
284 //
285 // Other errors if BPositionIO::Read() returned an error value
286 // ---------------------------------------------------------------
287 status_t
288 PNGTranslator::DerivedIdentify(BPositionIO *inSource,
289 	const translation_format *inFormat, BMessage *ioExtension,
290 	translator_info *outInfo, uint32 outType)
291 {
292 	return identify_png_header(inSource, outInfo);
293 }
294 
295 
296 // Workaround for gcc2 complaining about clobbered variables when we do a
297 // setjmp, even though the variables are not accessed when returning from
298 // a longjmp. Moving setjmp to a different function is enough to hide the
299 // problem from gcc2.
300 static int
301 setjmp_wrapper(jmp_buf buf)
302 {
303 	return setjmp(buf);
304 }
305 
306 
307 status_t
308 PNGTranslator::translate_from_png_to_bits(BPositionIO *inSource,
309 	BPositionIO *outDestination)
310 {
311 	if (identify_png_header(inSource, NULL) != B_OK)
312 		return B_NO_TRANSLATOR;
313 
314 	status_t result = B_ERROR;
315 		// if a libpng errors before this is set
316 		// to a different value, the above is what
317 		// will be returned from this function
318 
319 	bool bheaderonly = false, bdataonly = false;
320 
321 	// for storing decoded PNG row data
322 	uint8 **prows = NULL, *prow = NULL;
323 	png_uint_32 nalloc = 0;
324 
325 	png_structp ppng = NULL;
326 	png_infop pinfo = NULL;
327 	while (ppng == NULL) {
328 		// create PNG read pointer with default error handling routines
329 		ppng = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
330 		if (!ppng)
331 			break;
332 		// alocate / init memory for image information
333 		pinfo = png_create_info_struct(ppng);
334 		if (!pinfo)
335 			break;
336 		// set error handling
337 		if (setjmp_wrapper(png_jmpbuf(ppng)))
338 			// When an error occurs in libpng, it uses
339 			// the longjmp function to continue execution
340 			// from this point
341 			break;
342 
343 		// set read callback function
344 		png_set_read_fn(ppng, static_cast<void *>(inSource), pngcb_read_data);
345 
346 		// Read in PNG image info
347 		png_set_sig_bytes(ppng, 8);
348 		png_read_info(ppng, pinfo);
349 
350 		png_uint_32 width, height;
351 		int bit_depth, color_type, interlace_type;
352 		png_get_IHDR(ppng, pinfo, &width, &height, &bit_depth, &color_type,
353 			&interlace_type, NULL, NULL);
354 
355 		// Setup image transformations to make converting it easier
356 		bool balpha = false;
357 
358 		if (bit_depth == 16)
359 			png_set_strip_16(ppng);
360 		else if (bit_depth < 8)
361 			png_set_packing(ppng);
362 
363 		if (color_type == PNG_COLOR_TYPE_PALETTE)
364 			png_set_palette_to_rgb(ppng);
365 
366 		if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
367 			// In order to convert from low-depth gray images to RGB,
368 			// I first need to convert them to grayscale, 8 bpp
369 			png_set_expand_gray_1_2_4_to_8(ppng);
370 
371 		if (png_get_valid(ppng, pinfo, PNG_INFO_tRNS)) {
372 			// if there is transparency data in the
373 			// PNG, but not in the form of an alpha channel
374 			balpha = true;
375 			png_set_tRNS_to_alpha(ppng);
376 		}
377 
378 		// change RGB to BGR as it is in 'bits'
379 		if (color_type & PNG_COLOR_MASK_COLOR)
380 			png_set_bgr(ppng);
381 
382 		// have libpng convert gray to RGB for me
383 		if (color_type == PNG_COLOR_TYPE_GRAY ||
384 			color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
385 			png_set_gray_to_rgb(ppng);
386 
387 		if (color_type & PNG_COLOR_MASK_ALPHA)
388 			// if image contains an alpha channel
389 			balpha = true;
390 
391 		if (!balpha)
392 			// add filler byte for images without alpha
393 			// so that the pixels are 4 bytes each
394 			png_set_filler(ppng, 0xff, PNG_FILLER_AFTER);
395 
396 		// Check that transformed PNG rowbytes matches
397 		// what is expected
398 		const int32 kbytes = 4;
399 		png_uint_32 rowbytes = png_get_rowbytes(ppng, pinfo);
400 		if (rowbytes < kbytes * width)
401 			rowbytes = kbytes * width;
402 
403 		if (!bdataonly) {
404 			// Write out the data to outDestination
405 			// Construct and write Be bitmap header
406 			TranslatorBitmap bitsHeader;
407 			bitsHeader.magic = B_TRANSLATOR_BITMAP;
408 			bitsHeader.bounds.left = 0;
409 			bitsHeader.bounds.top = 0;
410 			bitsHeader.bounds.right = width - 1;
411 			bitsHeader.bounds.bottom = height - 1;
412 			bitsHeader.rowBytes = 4 * width;
413 			if (balpha)
414 				bitsHeader.colors = B_RGBA32;
415 			else
416 				bitsHeader.colors = B_RGB32;
417 			bitsHeader.dataSize = bitsHeader.rowBytes * height;
418 			if (swap_data(B_UINT32_TYPE, &bitsHeader,
419 				sizeof(TranslatorBitmap), B_SWAP_HOST_TO_BENDIAN) != B_OK) {
420 				result = B_ERROR;
421 				break;
422 			}
423 			outDestination->Write(&bitsHeader, sizeof(TranslatorBitmap));
424 
425 			if (bheaderonly) {
426 				result = B_OK;
427 				break;
428 			}
429 		}
430 
431 		if (interlace_type == PNG_INTERLACE_NONE) {
432 			// allocate buffer for storing PNG row
433 			prow = new uint8[rowbytes];
434 			if (!prow) {
435 				result = B_NO_MEMORY;
436 				break;
437 			}
438 			for (png_uint_32 i = 0; i < height; i++) {
439 				png_read_row(ppng, prow, NULL);
440 				outDestination->Write(prow, width * kbytes);
441 			}
442 			result = B_OK;
443 				// Set OK status here, because, in the event of
444 				// an error, png_read_end() will longjmp to error
445 				// handler above and not execute lines below it
446 
447 			// finish reading, pass NULL for info because I
448 			// don't need the extra data
449 			png_read_end(ppng, NULL);
450 
451 			break;
452 
453 		} else {
454 			// interlaced PNG image
455 			prows = new uint8 *[height];
456 			if (!prows) {
457 				result = B_NO_MEMORY;
458 				break;
459 			}
460 			// allocate enough memory to store the whole image
461 			for (nalloc = 0; nalloc < height; nalloc++) {
462 				prows[nalloc] = new uint8[rowbytes];
463 				if (!prows[nalloc])
464 					break;
465 			}
466 
467 			if (nalloc < height)
468 				result = B_NO_MEMORY;
469 			else {
470 				png_read_image(ppng, prows);
471 
472 				for (png_uint_32 i = 0; i < height; i++)
473 					outDestination->Write(prows[i], width * kbytes);
474 				result = B_OK;
475 					// Set OK status here, because, in the event of
476 					// an error, png_read_end() will longjmp to error
477 					// handler above and not execute lines below it
478 
479 				png_read_end(ppng, NULL);
480 			}
481 
482 			break;
483 		}
484 	}
485 
486 	if (ppng) {
487 		delete[] prow;
488 		prow = NULL;
489 
490 		// delete row pointers and array of pointers to rows
491 		while (nalloc) {
492 			nalloc--;
493 			delete[] prows[nalloc];
494 		}
495 		delete[] prows;
496 		prows = NULL;
497 
498 		// free PNG handle / info structures
499 		if (!pinfo)
500 			png_destroy_read_struct(&ppng, NULL, NULL);
501 		else
502 			png_destroy_read_struct(&ppng, &pinfo, NULL);
503 	}
504 
505 	return result;
506 }
507 
508 status_t
509 PNGTranslator::translate_from_png(BPositionIO *inSource, uint32 outType,
510 	BPositionIO *outDestination)
511 {
512 	if (outType == B_TRANSLATOR_BITMAP)
513 		return translate_from_png_to_bits(inSource, outDestination);
514 	else {
515 		// Translate from PNG to PNG
516 		translate_direct_copy(inSource, outDestination);
517 		return B_OK;
518 	}
519 }
520 
521 // Convert width pixels from pbits to PNG format, storing the
522 // result in ppng
523 status_t
524 pix_bits_to_png(uint8 *pbits, uint8 *ppng, color_space fromspace,
525 	uint32 width, const color_map *pmap, int32 bitsBytesPerPixel)
526 {
527 	status_t bytescopied = 0;
528 	uint16 val;
529 
530 	switch (fromspace) {
531 		case B_RGBA32:
532 			bytescopied = width * bitsBytesPerPixel;
533 			memcpy(ppng, pbits, bytescopied);
534 			break;
535 
536 		case B_RGB32:
537 		case B_RGB24:
538 			bytescopied = width * bitsBytesPerPixel;
539 			while (width--) {
540 				memcpy(ppng, pbits, 3);
541 				ppng += 3;
542 				pbits += bitsBytesPerPixel;
543 			}
544 			break;
545 
546 		case B_RGBA32_BIG:
547 			bytescopied = width * 4;
548 			while (width--) {
549 				ppng[0] = pbits[3];
550 				ppng[1] = pbits[2];
551 				ppng[2] = pbits[1];
552 				ppng[3] = pbits[0];
553 
554 				ppng += 4;
555 				pbits += 4;
556 			}
557 			break;
558 
559 		case B_CMYA32:
560 			bytescopied = width * 4;
561 			while (width--) {
562 				ppng[0] = 255 - pbits[2];
563 				ppng[1] = 255 - pbits[1];
564 				ppng[2] = 255 - pbits[0];
565 				ppng[3] = pbits[3];
566 
567 				ppng += 4;
568 				pbits += 4;
569 			}
570 			break;
571 
572 		case B_CMYK32:
573 		{
574 			int32 comp;
575 			bytescopied = width * 3;
576 			while (width--) {
577 				comp = 255 - pbits[2] - pbits[3];
578 				ppng[0] = (comp < 0) ? 0 : comp;
579 
580 				comp = 255 - pbits[1] - pbits[3];
581 				ppng[1] = (comp < 0) ? 0 : comp;
582 
583 				comp = 255 - pbits[0] - pbits[3];
584 				ppng[2] = (comp < 0) ? 0 : comp;
585 
586 				ppng += 3;
587 				pbits += 4;
588 			}
589 			break;
590 		}
591 
592 		case B_CMY32:
593 		case B_CMY24:
594 			bytescopied = width * 3;
595 			while (width--) {
596 				ppng[0] = 255 - pbits[2];
597 				ppng[1] = 255 - pbits[1];
598 				ppng[2] = 255 - pbits[0];
599 
600 				ppng += 3;
601 				pbits += bitsBytesPerPixel;
602 			}
603 			break;
604 
605 		case B_RGB16:
606 		case B_RGB16_BIG:
607 			bytescopied = width * 3;
608 			while (width--) {
609 				if (fromspace == B_RGB16)
610 					val = pbits[0] + (pbits[1] << 8);
611 				else
612 					val = pbits[1] + (pbits[0] << 8);
613 
614 				ppng[0] =
615 					((val & 0x1f) << 3) | ((val & 0x1f) >> 2);
616 				ppng[1] =
617 					((val & 0x7e0) >> 3) | ((val & 0x7e0) >> 9);
618 				ppng[2] =
619 					((val & 0xf800) >> 8) | ((val & 0xf800) >> 13);
620 
621 				ppng += 3;
622 				pbits += 2;
623 			}
624 			break;
625 
626 		case B_RGB15:
627 		case B_RGB15_BIG:
628 			bytescopied = width * 3;
629 			while (width--) {
630 				if (fromspace == B_RGB15)
631 					val = pbits[0] + (pbits[1] << 8);
632 				else
633 					val = pbits[1] + (pbits[0] << 8);
634 				ppng[0] =
635 					((val & 0x1f) << 3) | ((val & 0x1f) >> 2);
636 				ppng[1] =
637 					((val & 0x3e0) >> 2) | ((val & 0x3e0) >> 7);
638 				ppng[2] =
639 					((val & 0x7c00) >> 7) | ((val & 0x7c00) >> 12);
640 
641 				ppng += 3;
642 				pbits += 2;
643 			}
644 			break;
645 
646 		case B_RGBA15:
647 		case B_RGBA15_BIG:
648 			bytescopied = width * 4;
649 			while (width--) {
650 				if (fromspace == B_RGBA15)
651 					val = pbits[0] + (pbits[1] << 8);
652 				else
653 					val = pbits[1] + (pbits[0] << 8);
654 				ppng[0] =
655 					((val & 0x1f) << 3) | ((val & 0x1f) >> 2);
656 				ppng[1] =
657 					((val & 0x3e0) >> 2) | ((val & 0x3e0) >> 7);
658 				ppng[2] =
659 					((val & 0x7c00) >> 7) | ((val & 0x7c00) >> 12);
660 				ppng[3] = (val & 0x8000) ? 255 : 0;
661 
662 				ppng += 4;
663 				pbits += 2;
664 			}
665 			break;
666 
667 		case B_RGB32_BIG:
668 			bytescopied = width * 3;
669 			while (width--) {
670 				ppng[0] = pbits[3];
671 				ppng[1] = pbits[2];
672 				ppng[2] = pbits[1];
673 
674 				ppng += 3;
675 				pbits += 4;
676 			}
677 			break;
678 
679 		case B_RGB24_BIG:
680 			bytescopied = width * 3;
681 			while (width--) {
682 				ppng[0] = pbits[2];
683 				ppng[1] = pbits[1];
684 				ppng[2] = pbits[0];
685 
686 				ppng += 3;
687 				pbits += 3;
688 			}
689 			break;
690 
691 		case B_CMAP8:
692 		{
693 			rgb_color c;
694 			bytescopied = width * 3;
695 			while (width--) {
696 				c = pmap->color_list[pbits[0]];
697 				ppng[0] = c.blue;
698 				ppng[1] = c.green;
699 				ppng[2] = c.red;
700 
701 				ppng += 3;
702 				pbits++;
703 			}
704 			break;
705 		}
706 
707 		case B_GRAY8:
708 			bytescopied = width;
709 			memcpy(ppng, pbits, bytescopied);
710 			break;
711 
712 		default:
713 			bytescopied = B_ERROR;
714 			break;
715 	} // switch (fromspace)
716 
717 	return bytescopied;
718 }
719 
720 status_t
721 PNGTranslator::translate_from_bits_to_png(BPositionIO *inSource,
722 	BPositionIO *outDestination)
723 {
724 	TranslatorBitmap bitsHeader;
725 
726 	status_t result;
727 
728 	result = identify_bits_header(inSource, NULL, &bitsHeader);
729 	if (result != B_OK)
730 		return result;
731 
732 	const color_map *pmap = NULL;
733 	if (bitsHeader.colors == B_CMAP8) {
734 		pmap = system_colors();
735 		if (!pmap)
736 			return B_ERROR;
737 	}
738 
739 	png_uint_32 width, height;
740 	width = static_cast<png_uint_32>(bitsHeader.bounds.Width() + 1);
741 	height = static_cast<png_uint_32>(bitsHeader.bounds.Height() + 1);
742 
743 	int32 pngBytesPerPixel = 0;
744 	int bit_depth, color_type, interlace_type;
745 	bit_depth = 8;
746 	switch (bitsHeader.colors) {
747 		case B_RGBA32:
748 		case B_RGBA32_BIG:
749 		case B_CMYA32:
750 		case B_RGBA15:
751 		case B_RGBA15_BIG:
752 			pngBytesPerPixel = 4;
753 			color_type = PNG_COLOR_TYPE_RGB_ALPHA;
754 			break;
755 
756 		case B_RGB32:
757 		case B_RGB32_BIG:
758 		case B_RGB24:
759 		case B_RGB24_BIG:
760 		case B_CMY32:
761 		case B_CMYK32:
762 		case B_CMY24:
763 		case B_RGB16:
764 		case B_RGB16_BIG:
765 		case B_RGB15:
766 		case B_RGB15_BIG:
767 			pngBytesPerPixel = 3;
768 			color_type = PNG_COLOR_TYPE_RGB;
769 			break;
770 
771 		// ADD SUPPORT FOR B_CMAP8 HERE (later)
772 
773 		case B_GRAY8:
774 			pngBytesPerPixel = 1;
775 			color_type = PNG_COLOR_TYPE_GRAY;
776 			break;
777 
778 		default:
779 			return B_NO_TRANSLATOR;
780 	}
781 	interlace_type = fSettings->SetGetInt32(PNG_SETTING_INTERLACE);
782 
783 	int32 bitsBytesPerPixel = 0;
784 	switch (bitsHeader.colors) {
785 		case B_RGBA32:
786 		case B_RGBA32_BIG:
787 		case B_RGB32:
788 		case B_RGB32_BIG:
789 		case B_CMYA32:
790 		case B_CMYK32:
791 		case B_CMY32:
792 			bitsBytesPerPixel = 4;
793 			break;
794 
795 		case B_RGB24:
796 		case B_RGB24_BIG:
797 		case B_CMY24:
798 			bitsBytesPerPixel = 3;
799 			break;
800 
801 		case B_RGB16:
802 		case B_RGB16_BIG:
803 		case B_RGBA15:
804 		case B_RGBA15_BIG:
805 		case B_RGB15:
806 		case B_RGB15_BIG:
807 			bitsBytesPerPixel = 2;
808 			break;
809 
810 		case B_GRAY8:
811 		case B_CMAP8:
812 			bitsBytesPerPixel = 1;
813 			break;
814 
815 		default:
816 			return B_NO_TRANSLATOR;
817 	};
818 
819 	uint8 *pbitsrow = NULL, *prow = NULL;
820 		// row buffers
821 	// image buffer for writing whole png image at once
822 	uint8 **prows = NULL;
823 	png_uint_32 nalloc = 0;
824 
825 	png_structp ppng = NULL;
826 	png_infop pinfo = NULL;
827 
828 	result = B_NO_TRANSLATOR;
829 	while (ppng == NULL) {
830 		// create PNG read pointer with default error handling routines
831 		ppng = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL,
832 			NULL, NULL);
833 		if (!ppng) {
834 			result = B_ERROR;
835 			break;
836 		}
837 		// alocate / init memory for image information
838 		pinfo = png_create_info_struct(ppng);
839 		if (!pinfo) {
840 			result = B_ERROR;
841 			break;
842 		}
843 		// set error handling
844 		if (setjmp_wrapper(png_jmpbuf(ppng))) {
845 			// When an error occurs in libpng, it uses
846 			// the longjmp function to continue execution
847 			// from this point
848 			result = B_ERROR;
849 			break;
850 		}
851 
852 		png_set_write_fn(ppng, static_cast<void *>(outDestination),
853 			pngcb_write_data, pngcb_flush_data);
854 
855 		// Allocate memory needed to buffer image data
856 		pbitsrow = new uint8[bitsHeader.rowBytes];
857 		if (!pbitsrow) {
858 			result = B_NO_MEMORY;
859 			break;
860 		}
861 		if (interlace_type == PNG_INTERLACE_NONE) {
862 			prow = new uint8[width * pngBytesPerPixel];
863 			if (!prow) {
864 				result = B_NO_MEMORY;
865 				break;
866 			}
867 		} else {
868 			prows = new uint8 *[height];
869 			if (!prows) {
870 				result = B_NO_MEMORY;
871 				break;
872 			}
873 			// allocate enough memory to store the whole image
874 			for (nalloc = 0; nalloc < height; nalloc++) {
875 				prows[nalloc] = new uint8[width * pngBytesPerPixel];
876 				if (!prows[nalloc])
877 					break;
878 			}
879 			if (nalloc < height) {
880 				result = B_NO_MEMORY;
881 				// clear out rest of the pointers,
882 				// so we don't call delete[] with invalid pointers
883 				for (; nalloc < height; nalloc++)
884 					prows[nalloc] = NULL;
885 				break;
886 			}
887 		}
888 
889 		// Specify image info
890 		png_set_IHDR(ppng, pinfo, width, height, bit_depth, color_type,
891 			interlace_type, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
892 		png_write_info(ppng, pinfo);
893 
894 		png_set_bgr(ppng);
895 
896 		// write out image data
897 		if (interlace_type == PNG_INTERLACE_NONE) {
898 			for (png_uint_32 i = 0; i < height; i++) {
899 				inSource->Read(pbitsrow, bitsHeader.rowBytes);
900 
901 				pix_bits_to_png(pbitsrow, prow, bitsHeader.colors, width,
902 					pmap, bitsBytesPerPixel);
903 
904 				png_write_row(ppng, prow);
905 			}
906 		} else {
907 			for (png_uint_32 i = 0; i < height; i++) {
908 				inSource->Read(pbitsrow, bitsHeader.rowBytes);
909 
910 				pix_bits_to_png(pbitsrow, prows[i], bitsHeader.colors, width,
911 					pmap, bitsBytesPerPixel);
912 			}
913 			png_write_image(ppng, prows);
914 		}
915 		png_write_end(ppng, NULL);
916 
917 		result = B_OK;
918 		break;
919 	}
920 
921 	if (ppng) {
922 		delete[] pbitsrow;
923 		pbitsrow = NULL;
924 
925 		delete[] prow;
926 		prow = NULL;
927 
928 		// delete row pointers and array of pointers to rows
929 		while (nalloc) {
930 			nalloc--;
931 			delete[] prows[nalloc];
932 		}
933 		delete[] prows;
934 		prows = NULL;
935 
936 		// free PNG handle / info structures
937 		if (!pinfo)
938 			png_destroy_write_struct(&ppng, NULL);
939 		else
940 			png_destroy_write_struct(&ppng, &pinfo);
941 	}
942 
943 	return result;
944 }
945 
946 // ---------------------------------------------------------------
947 // DerivedTranslate
948 //
949 // Translates the data in inSource to the type outType and stores
950 // the translated data in outDestination.
951 //
952 // Preconditions:
953 //
954 // Parameters:	inSource,	the data to be translated
955 //
956 //				inInfo,	hint about the data in inSource (not used)
957 //
958 //				ioExtension,	configuration options for the
959 //								translator
960 //
961 //				outType,	the type to convert inSource to
962 //
963 //				outDestination,	where the translated data is
964 //								put
965 //
966 //				baseType, indicates whether inSource is in the
967 //				          bits format, not in the bits format or
968 //				          is unknown
969 //
970 // Postconditions:
971 //
972 // Returns: B_BAD_VALUE, if the options in ioExtension are bad
973 //
974 // B_NO_TRANSLATOR, if this translator doesn't understand the data
975 //
976 // B_ERROR, if there was an error allocating memory or converting
977 //          data
978 //
979 // B_OK, if all went well
980 // ---------------------------------------------------------------
981 status_t
982 PNGTranslator::DerivedTranslate(BPositionIO *inSource,
983 	const translator_info *inInfo, BMessage *ioExtension, uint32 outType,
984 	BPositionIO *outDestination, int32 baseType)
985 {
986 	if (baseType == 1)
987 		// if inSource is in bits format
988 		return translate_from_bits_to_png(inSource, outDestination);
989 	else if (baseType == 0)
990 		// if inSource is NOT in bits format
991 		return translate_from_png(inSource, outType, outDestination);
992 	else
993 		return B_NO_TRANSLATOR;
994 }
995 
996 BView *
997 PNGTranslator::NewConfigView(TranslatorSettings *settings)
998 {
999 	return new PNGView(BRect(0, 0, PNG_VIEW_WIDTH, PNG_VIEW_HEIGHT),
1000 		B_TRANSLATE("PNGTranslator Settings"), B_FOLLOW_ALL,
1001 		B_WILL_DRAW, settings);
1002 }
1003 
1004