1 /* This file is part of Shapes.
3 * Shapes is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
8 * Shapes is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with Shapes. If not, see <http://www.gnu.org/licenses/>.
16 * Copyright 2009 Henrik Tidefelt
19 #include "drawabletypes.h"
20 #include "rasterloaders.h"
21 #include "statetypes.h"
22 #include "autoonoff.h"
28 using namespace Shapes
;
41 Shapes_pnglib_error_fn( png_structp png_ptr
,
42 png_const_charp error_msg
)
44 throw Exceptions::ExternalError( strrefdup( error_msg
) );
48 Shapes_pnglib_warning_fn( png_structp png_ptr
,
49 png_const_charp warning_msg
)
51 std::cerr
<< "libpng warning: " << warning_msg
<< std::endl
;
55 Shapes_pnglib_read_data( png_structp png_ptr
,
59 std::istream
* iFile
= static_cast< std::istream
* >( png_get_io_ptr( png_ptr
) );
60 iFile
->read( reinterpret_cast< char * >( data
), length
);
68 void separateAlpha_bits( const unsigned char * row
, size_t rowBytes
, size_t bitsPerUnit
, std::ostream
& colorDst
, size_t colorUnits
, std::ostream
& alphaDst
, size_t alphaUnits
, const png_color_16
* transparentColor
, char * buf1
, char * buf2
);
70 void separateAlpha( const unsigned char * row
, size_t rowBytes
, std::ostream
& colorDst
, size_t colorUnts
, std::ostream
& alphaDst
, size_t alphaUnits
, const png_color_16
* transparentColor
, char * buf1
, char * buf2
);
71 void applyPalette( const unsigned char * row
, size_t rowBytes
, size_t index_depth
, const png_colorp palette
, const png_bytep trans
, int num_palette
, std::ostream
& colorDst
, std::ostream
& alphaDst
);
79 RefCountPtr
< const Lang::RasterImage
>
80 Shapes::Helpers::RasterLoader_PNG::load( RefCountPtr
< std::ifstream
> & filePtr
, const std::string
& full_filename
, Concrete::Length resolution
, bool override
, const char * core_title
, const Ast::SourceLocation
& callLoc
) const
83 throw Exceptions::BuildRequirement( "libpng", core_title
, callLoc
);
87 throw Exceptions::CoreRequirement( "The resolution must be given for raster image files of type PNG.", core_title
, callLoc
);
90 std::ifstream
& iFile
= *filePtr
;
92 const size_t SIGNATURE_SIZE
= 8;
94 char header
[ SIGNATURE_SIZE
+ 1 ];
95 iFile
.read( header
, SIGNATURE_SIZE
);
96 bool is_png
= png_sig_cmp( reinterpret_cast< png_bytep
>( header
), 0, SIGNATURE_SIZE
) == 0;
99 throw Exceptions::CoreRequirement( "The imported file does not have the magic signature of a PNG file.", core_title
, callLoc
);
103 png_structp png_ptr
= png_create_read_struct( PNG_LIBPNG_VER_STRING
,
104 static_cast< png_voidp
>( 0 ), /* Pointer to additional information passed to error and warning handlers? */
105 Kernel::Shapes_pnglib_error_fn
,
106 Kernel::Shapes_pnglib_warning_fn
);
108 /* We use two error handling mechanisms in parallel, since I don't understand exactly how to use the longjmp function in the uer-defined
109 * error handler Shapes_pnglib_error_fn. Hence, we both use setjmp in case someone uses longjmp, and use try/catch to handle the errors
110 * thrown by Shapes_pnglib_error_fn.
113 png_set_error_fn( png_ptr
,
114 static_cast< png_voidp
>( 0 ), /* Pointer to additional information passed to error and warning handlers? */
115 Kernel::Shapes_pnglib_error_fn
,
116 Kernel::Shapes_pnglib_warning_fn
);
120 throw Exceptions::ExternalError( "Failed to allocate read structure for reading a PNG file." );
123 png_infop info_ptr
= png_create_info_struct( png_ptr
);
126 png_destroy_read_struct( & png_ptr
,
127 static_cast< png_infopp
>( 0 ), static_cast< png_infopp
>( 0 ) );
128 throw Exceptions::ExternalError( "Failed to allocate info structure for reading a PNG file." );
131 png_infop end_info
= png_create_info_struct( png_ptr
);
134 png_destroy_read_struct( & png_ptr
, & info_ptr
,
135 static_cast< png_infopp
>( 0 ) );
136 throw Exceptions::ExternalError( "Failed to allocate end-info structure for reading a PNG file." );
139 if( setjmp( png_jmpbuf( png_ptr
) ) )
141 png_destroy_read_struct( & png_ptr
, & info_ptr
, & end_info
);
142 throw Exceptions::ExternalError( "Caught a longjmp from libpng while reading a PNG file." );
147 png_set_sig_bytes( png_ptr
, SIGNATURE_SIZE
);
149 png_set_read_fn( png_ptr
,
150 static_cast< voidp
>( filePtr
.getPtr( ) ),
151 Kernel::Shapes_pnglib_read_data
);
154 png_read_png( png_ptr
, info_ptr
, PNG_TRANSFORM_IDENTITY
, 0 );
160 int interlace_method
;
161 int compression_method
;
164 png_get_IHDR( png_ptr
, info_ptr
,
165 & size_x
, & size_y
, & size_depth
,
166 & color_type
, & interlace_method
, & compression_method
, & filter_method
);
168 RefCountPtr
< const Lang::ColorSpace
> colorSpace
= Lang::THE_COLOR_SPACE_DEVICE_GRAY
; /* Initialize with anything. */
169 bool hasAlpha
= false;
170 bool hasTransparentColor
= false;
171 bool hasPalette
= false;
176 case PNG_COLOR_TYPE_GRAY
:
177 /* Use the default value set above! */
179 case PNG_COLOR_TYPE_RGB
:
180 colorSpace
= Lang::THE_COLOR_SPACE_DEVICE_RGB
;
182 case PNG_COLOR_TYPE_GRAY_ALPHA
:
183 colorSpace
= Lang::THE_COLOR_SPACE_DEVICE_GRAY
;
186 case PNG_COLOR_TYPE_RGB_ALPHA
:
187 colorSpace
= Lang::THE_COLOR_SPACE_DEVICE_RGB
;
190 case PNG_COLOR_TYPE_PALETTE
:
191 /* The palette colors use 8 bit in each of the three channels. */
192 colorSpace
= Lang::THE_COLOR_SPACE_DEVICE_RGB
;
193 png_get_PLTE( png_ptr
, info_ptr
, & palette
, & num_palette
);
197 throw Exceptions::CoreRequirement( "The PNG file was using an unknown color type value.", core_title
, callLoc
);
200 png_bytep tRNS_trans
;
201 png_color_16p tRNS_trans_values
;
202 if( ( info_ptr
->valid
& PNG_INFO_tRNS
) != 0 )
206 png_get_tRNS( png_ptr
, info_ptr
, & tRNS_trans
, & tRNS_num_trans
, & tRNS_trans_values
);
209 if( tRNS_num_trans
!= num_palette
)
211 throw Exceptions::CoreRequirement( "The PNG file has a transparency pallete of different size compared to the color palette.", core_title
, callLoc
);
216 hasTransparentColor
= true;
220 size_t components
= colorSpace
->numberOfComponents( );
221 size_t png_channels
= png_get_channels( png_ptr
, info_ptr
);
223 Lang::RasterImage
* imagePtr
= Lang::RasterImage::newInstance( size_x
, size_y
, hasPalette
? 8 : size_depth
, resolution
, resolution
, colorSpace
);
224 RefCountPtr
< const Lang::RasterImage
> image
= RefCountPtr
< const Lang::RasterImage
>( RefCountPtr
< const Lang::RasterImage
>( imagePtr
) );
226 RefCountPtr
< SimplePDF::PDF_Stream_out
> maskStream
= RefCountPtr
< SimplePDF::PDF_Stream_out
>( NullPtr
< SimplePDF::PDF_Stream_out
>( ) );
228 SimplePDF::PDF_Stream_out
& stream
= *(imagePtr
->stream( ));
229 stream
[ "Filter" ] = SimplePDF::newName( "FlateDecode" );
232 Lang::RasterImage
* maskPtr
= Lang::RasterImage::newInstance( size_x
, size_y
, hasPalette
? 8 : size_depth
, resolution
, resolution
, Lang::THE_COLOR_SPACE_DEVICE_GRAY
);
233 imagePtr
->setSoftMask( RefCountPtr
< const Lang::RasterImage
>( RefCountPtr
< const Lang::RasterImage
>( maskPtr
) ) );
234 maskStream
= maskPtr
->stream( );
235 (*maskStream
)[ "Filter" ] = SimplePDF::newName( "FlateDecode" );
237 const SimplePDF::PDF_Version::Version SOFTMASK_VERSION
= SimplePDF::PDF_Version::PDF_1_4
;
238 if( Kernel::the_PDF_version
.greaterOrEqual( SOFTMASK_VERSION
) )
240 stream
[ "SMask" ] = maskPtr
->getResource( );
244 Kernel::the_PDF_version
.message( SOFTMASK_VERSION
, "A PNG alpha channel (soft mask) was ignored." );
248 size_t rowbytes
= png_get_rowbytes( png_ptr
, info_ptr
);
251 PossiblyDeleteOnExit
< char > buf1Deleter
;
252 PossiblyDeleteOnExit
< char > buf2Deleter
;
255 buf1
= new char[ rowbytes
];
256 buf1Deleter
.activate( buf1
);
257 buf2
= new char[ rowbytes
];
258 buf2Deleter
.activate( buf2
);
260 png_bytep
* rowBegin
= png_get_rows( png_ptr
, info_ptr
);
261 for( png_bytep
* srcRow
= rowBegin
; srcRow
< rowBegin
+ size_y
; ++srcRow
)
263 /* Note that image data in PDF starts each row on a fresh byte boundary.
269 Helpers::applyPalette( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, size_depth
, palette
, tRNS_trans
, num_palette
, stream
.data
, maskStream
->data
);
273 std::ostringstream ignore
;
274 Helpers::applyPalette( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, size_depth
, palette
, 0, num_palette
, stream
.data
, ignore
);
279 if( hasTransparentColor
)
281 /* There may be some kind of filler (byte or bits) in the data, that we need to discard. */
287 Helpers::separateAlpha_bits( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, size_depth
, stream
.data
, components
, maskStream
->data
, png_channels
- components
, tRNS_trans_values
, buf1
, buf2
);
290 Helpers::separateAlpha
< png_byte
>( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, stream
.data
, components
, maskStream
->data
, png_channels
- components
, tRNS_trans_values
, buf1
, buf2
);
293 Helpers::separateAlpha
< png_uint_16
>( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, stream
.data
, components
, maskStream
->data
, png_channels
- components
, tRNS_trans_values
, buf1
, buf2
);
296 throw Exceptions::InternalError( "Unexpected color depth in PNG image." );
306 Helpers::separateAlpha_bits( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, size_depth
, stream
.data
, components
, maskStream
->data
, 1, 0, buf1
, buf2
);
309 Helpers::separateAlpha
< png_byte
>( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, stream
.data
, components
, maskStream
->data
, 1, 0, buf1
, buf2
);
312 Helpers::separateAlpha
< png_uint_16
>( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, stream
.data
, components
, maskStream
->data
, 1, 0, buf1
, buf2
);
315 throw Exceptions::InternalError( "Unexpected color depth in PNG image." );
319 else if( png_channels
> components
)
321 /* There is some kind of filler (byte or bits) in the data, that we need to discard. */
322 std::ostringstream ignore
;
328 Helpers::separateAlpha_bits( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, size_depth
, stream
.data
, components
, ignore
, png_channels
- components
, 0, buf1
, buf2
);
331 Helpers::separateAlpha
< png_byte
>( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, stream
.data
, components
, ignore
, png_channels
- components
, 0, buf1
, buf2
);
334 Helpers::separateAlpha
< png_uint_16
>( reinterpret_cast< unsigned char * >( *srcRow
), rowbytes
, stream
.data
, components
, ignore
, png_channels
- components
, 0, buf1
, buf2
);
337 throw Exceptions::InternalError( "Unexpected color depth in PNG image." );
342 stream
.data
.write( reinterpret_cast< char * >( *srcRow
), rowbytes
);
346 /* If everything was OK, we just free allocated resources and return.
348 png_destroy_read_struct( & png_ptr
, & info_ptr
, & end_info
);
352 catch( const Exceptions::Exception
& ball
)
354 png_destroy_read_struct( & png_ptr
, & info_ptr
, & end_info
);
364 Helpers::separateAlpha_bits( const unsigned char * row
, size_t rowBytes
, size_t bitsPerUnit
, std::ostream
& colorDst
, size_t colorUnits
, std::ostream
& alphaDst
, size_t alphaUnits
, const png_color_16
* transparentColor
, char * bufCo
, char * bufAl
)
366 char * dstCo
= bufCo
;
367 char * dstAl
= bufAl
;
369 png_uint_16 transparentColorArray
[3];
370 if( transparentColor
!= 0 )
375 transparentColorArray
[0] = transparentColor
->gray
;
378 transparentColorArray
[0] = transparentColor
->red
;
379 transparentColorArray
[1] = transparentColor
->green
;
380 transparentColorArray
[2] = transparentColor
->blue
;
383 throw Exceptions::InternalError( "Unexpected number of color channels in PNG image alpha bit separation." );
386 const unsigned char * src
= row
;
387 const unsigned char * srcEnd
= row
+ rowBytes
;
388 unsigned char srcByte
= *src
;
390 unsigned char dstByteCo
= 0; /* Initialize to inhibit compiler warnings. */
391 unsigned char dstByteAl
= 0; /* Initialize to inhibit compiler warnings. */
392 unsigned char srcShift
= 8 - bitsPerUnit
;
393 unsigned char dstAvailCo
= 8;
394 unsigned char dstAvailAl
= 8;
396 switch( bitsPerUnit
)
408 throw Exceptions::InternalError( "Unexpected color depth in PNG image alpha bit separation." );
413 const png_uint_16
* transparentColorSrc
= transparentColorArray
;
414 for( size_t i
= 0; i
< colorUnits
; ++i
, ++transparentColorSrc
)
416 dstByteCo
= ( dstByteCo
<< bitsPerUnit
) | ( ( srcByte
>> srcShift
) & mask
);
417 if( transparentColor
!= 0 && ( ( srcByte
>> srcShift
) & mask
) != *transparentColorSrc
)
421 dstAvailCo
-= bitsPerUnit
;
422 if( dstAvailCo
== 0 )
424 *reinterpret_cast< unsigned char * >( dstCo
) = dstByteCo
;
438 srcShift
-= bitsPerUnit
;
440 if( transparentColor
== 0 )
442 for( size_t i
= 0; i
< alphaUnits
; ++i
)
444 dstByteAl
= ( dstByteAl
<< bitsPerUnit
) | ( ( srcByte
>> srcShift
) & mask
);
445 dstAvailAl
-= bitsPerUnit
;
446 if( dstAvailAl
== 0 )
448 *reinterpret_cast< unsigned char * >( dstAl
) = dstByteAl
;
462 srcShift
-= bitsPerUnit
;
467 dstByteAl
= ( dstByteAl
<< bitsPerUnit
) | ( trans
? mask
: 0 );
468 dstAvailAl
-= bitsPerUnit
;
469 if( dstAvailAl
== 0 )
471 *reinterpret_cast< unsigned char * >( dstAl
) = dstByteAl
;
476 /* Just ignore filler data. */
477 for( size_t i
= 0; i
< alphaUnits
; ++i
)
489 srcShift
-= bitsPerUnit
;
497 *reinterpret_cast< unsigned char * >( dstCo
) = ( dstByteCo
<< dstAvailCo
);
502 *reinterpret_cast< unsigned char * >( dstAl
) = ( dstByteAl
<< dstAvailAl
);
506 colorDst
.write( bufCo
, dstCo
- bufCo
);
507 alphaDst
.write( bufAl
, dstAl
- bufAl
);
512 Helpers::separateAlpha( const unsigned char * row
, size_t rowBytes
, std::ostream
& colorDst
, size_t colorUnits
, std::ostream
& alphaDst
, size_t alphaUnits
, const png_color_16
* transparentColor
, char * bufCo
, char * bufAl
)
514 C
* dstCo
= reinterpret_cast< C
* >( bufCo
);
515 C
* dstAl
= reinterpret_cast< C
* >( bufAl
);
519 png_uint_16 transparentColorArray
[3];
520 if( transparentColor
!= 0 )
525 transparentColorArray
[0] = transparentColor
->gray
;
528 transparentColorArray
[0] = transparentColor
->red
;
529 transparentColorArray
[1] = transparentColor
->green
;
530 transparentColorArray
[2] = transparentColor
->blue
;
533 throw Exceptions::InternalError( "Unexpected number of color channels in PNG image alpha bit separation." );
537 const C
* src
= reinterpret_cast< const C
* >( row
);
538 const C
* srcEnd
= reinterpret_cast< const C
* >( row
+ rowBytes
);
539 const C
* tmpEnd
= reinterpret_cast< const C
* >( row
);
540 for( ; src
< srcEnd
; )
543 const png_uint_16
* transparentColorSrc
= transparentColorArray
;
545 tmpEnd
+= colorUnits
;
546 for( ; src
!= tmpEnd
; ++src
, ++dstCo
, ++transparentColorSrc
)
548 *reinterpret_cast< unsigned char * >( dstCo
) = *src
;
549 if( transparentColor
!= 0 && *src
!= *transparentColorSrc
)
554 tmpEnd
+= alphaUnits
;
555 if( transparentColor
== 0 )
557 for( ; src
!= tmpEnd
; ++src
, ++dstAl
)
559 *reinterpret_cast< unsigned char * >( dstAl
) = *src
;
564 *dstAl
= trans
? (~OPAQUE
) : OPAQUE
;
567 /* Just ignore fill bytes. */
571 colorDst
.write( bufCo
, reinterpret_cast< char * >( dstCo
) - bufCo
);
572 alphaDst
.write( bufAl
, reinterpret_cast< char * >( dstAl
) - bufAl
);
576 Helpers::applyPalette( const unsigned char * row
, size_t rowBytes
, size_t index_depth
, const png_colorp palette
, const png_bytep trans
, int num_palette
, std::ostream
& colorDst
, std::ostream
& alphaDst
)
578 switch( index_depth
)
584 const unsigned char * src
= row
;
585 const unsigned char * srcEnd
= row
+ rowBytes
;
586 unsigned char srcByte
= *src
;
588 unsigned char srcShift
= 8 - index_depth
;
590 switch( index_depth
)
602 throw Exceptions::InternalError( "Switch in PNG palette application was out of range." );
606 unsigned char index
= ( srcByte
>> srcShift
) & mask
;
607 if( index
>= num_palette
)
609 throw Exceptions::ExternalError( "PNG palette index is out of bounds." );
611 unsigned char buf
[3];
612 buf
[0] = palette
[ index
].red
;
613 buf
[1] = palette
[ index
].green
;
614 buf
[2] = palette
[ index
].blue
;
615 colorDst
.write( reinterpret_cast< char * >( buf
), 3 );
618 alphaDst
.write( reinterpret_cast< char * >( & ( trans
[ index
] ) ), 1 );
630 srcShift
-= index_depth
;
636 const unsigned char * srcEnd
= row
+ rowBytes
;
637 for( const unsigned char * src
= row
; src
!= srcEnd
; ++src
)
639 if( *src
>= num_palette
)
641 throw Exceptions::ExternalError( "PNG palette index is out of bounds." );
643 unsigned char buf
[3];
644 buf
[0] = palette
[ *src
].red
;
645 buf
[1] = palette
[ *src
].green
;
646 buf
[2] = palette
[ *src
].blue
;
647 colorDst
.write( reinterpret_cast< char * >( buf
), 3 );
650 alphaDst
.write( reinterpret_cast< char * >( & ( trans
[ *src
] ) ), 1 );
656 throw Exceptions::InternalError( "Unexpected depth in PNG palette image (supported values are { 1, 2, 4, 8 })." );