Debian Codegraph @

src/images/castleimages_libpng.inc

raw
1 {%MainUnit castleimages.pas}
2 {
3 Copyright 2002-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { Handle PNG format using libpng.
18
19 Important references:
20 - LibPng manual ( linked from http://www.libpng.org/pub/png/pngdocs.html ,
21 version for 1.2.5: http://www.libpng.org/pub/png/libpng-1.2.5-manual.html )
22 - PNG test suite ( http://www.schaik.com/pngsuite/ ).
23 It is easy to check with castle-image-viewer.
24 }
25
26 {$if defined(CASTLE_PNG_DYNAMIC) or defined(CASTLE_PNG_STATIC)}
27
28 type
29 ELibPngNotAvailable = class(Exception);
30 EPngTransformError = class(Exception);
31
32 { Return the version of used dynamic libpng library
33 (taken by querying png_access_version_number).
34
35 Raises ELibPngNotAvailable exception if libpng library
36 was not available or had incorrect version (not CastlePngInitialized). }
37 function CurrentLibpngVersion: PAnsiChar; forward;
38
39 { Use all functions below ONLY when CastlePngInitialized = true. }
40
41 function PngColorTypeToStr(const PngColorType: Int32): string; forward;
42 function PngInterlaceTypeToStr(const PngInterlaceType: Int32): string; forward;
43 function PngTextCompressionToStr(const PngTextCompression: Int32): string; forward;
44
45 var
46 { Call InitializePNG to set these variables }
47 FCurrentLibpngVersion: AnsiString;
48 FCurrentLibpngVersionMajor,
49 FCurrentLibpngVersionMinor,
50 FCurrentLibpngVersionRelease: Integer;
51
52 function CurrentLibpngVersion: PAnsiChar;
53 begin
54 if not CastlePngInitialized then
55 raise ELibPngNotAvailable.Create('LibPng (or it''s dependency, ZLib) is not available, or has incorrect version. Make sure that the dynamic libraries for LibPng and ZLib are installed (or placed alongside the exe file on Windows).');
56
57 Result := PAnsiChar(FCurrentLibpngVersion);
58 end;
59
60 { TPngFormat ----------------------------------------------------------------- }
61
62 type
63 { Current image format information and transformations that change the format. }
64 TPngFormat = record
65 strict private
66 { Is BitDepth 8 or 16. }
67 function BitDepthFinal: Boolean;
68
69 { Make sure you have grayscale image, with 8 / 16 bits.
70 Assumes we already have stripped palette, so it's "true" color per pixel.
71
72 Alpha channel is never added/stripped by this, although it will
73 be converted to 8 / 16 bits too if exists. }
74 procedure RgbToGrayscale;
75
76 { Make sure you have RGB (not grayscale) image, with 8 / 16 bits.
77
78 Assumes we already have stripped palette, so it's "true" color per pixel.
79
80 Alpha channel is never added/stripped by this, although it will
81 be converted to 8 / 16 bits too if exists. }
82 procedure SomeGrayscaleToSomeRgb;
83
84 { Remove alpha from image, if it has alpha. }
85 procedure RemoveAlpha;
86
87 { Removes palette from the image, making the image RGB (possibly with alpha). }
88 procedure PaletteToRgb;
89
90 { If we have tRNS chunk, and no alpha channel, convert it to alpha channel. }
91 procedure TrnsChunkToAlphaChannel;
92
93 { Add alpha channel (fully opaque), if no alpha chnannel exists now.
94 Should be done only after TrnsChunkToAlphaChannel, never before --
95 to let TrnsChunkToAlphaChannel have a chance to convert tRNS
96 to alpha channel. }
97 procedure AddAlphaIfNecessary;
98 public
99 { LibPng structures to pass around to LibPng functions. }
100 png_ptr: png_structp;
101 info_ptr: png_infop;
102
103 { Format information updated on our side.
104
105 Note that we need to update ColorType, BitDepth on our side,
106 after using any LibPng transformation functions (like png_set_rgb_to_gray_fixed).
107
108 Reason: The LibPng transformations:
109
110 - change png_ptr (png_structp).
111 - but don't change info_ptr (png_infop).
112
113 I had an idea once to use png_read_update_info and then png_get_IHDR
114 (the png_get_IHDR alone is definitely not good enough,
115 png_read_update_info must be done to update info_ptr).
116 But using png_read_update_info more than once causes warnings
117 """Ignoring extra png_read_update_info() call; row buffer not reallocated"""
118 And then we have errors when reading image """Decompression error""".
119 So we can use png_read_update_info only once.
120 }
121 ColorType, BitDepth: UInt32;
122 TrnsExists: Boolean;
123
124 procedure Init(const Apng_ptr: png_structp; const Ainfo_ptr: png_infop);
125
126 { Transform any PNG to grayscale, 8 / 16 bits. }
127 procedure AnyToGrayscale;
128
129 { Transform any PNG to grayscale + alpha, 8 / 16 bits. }
130 procedure AnyToGrayscaleAlpha;
131
132 { Transform any PNG to RGB, 8 / 16 bits.
133
134 This means:
135 - palette must be converted to non-palette,
136 - grayscale must be expanded to RGB,
137 - bytes got to have appropriate order,
138 - alpha channel must be thrown out. }
139 procedure AnyToRGB;
140
141 { Transform any PNG to RGBA, 8 / 16 bits.
142
143 This means:
144 - palette must be converted to non-palette,
145 - grayscale must be expanded to RGB,
146 - bytes got to have appropriate order,
147 - alpha channel must be added, if not already present in file, with full opaque. }
148 procedure AnyToRGBAlpha;
149 end;
150
151 procedure TPngFormat.Init(const Apng_ptr: png_structp; const Ainfo_ptr: png_infop);
152 begin
153 png_ptr := Apng_ptr;
154 info_ptr := Ainfo_ptr;
155 BitDepth := png_get_bit_depth(png_ptr, info_ptr);
156 ColorType := png_get_color_type(png_ptr, info_ptr);
157 TrnsExists := png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) <> 0;
158 end;
159
160 function TPngFormat.BitDepthFinal: Boolean;
161 begin
162 Result := (BitDepth = 8) or (BitDepth = 16);
163 end;
164
165 procedure TPngFormat.RgbToGrayscale;
166 begin
167 { rgb -> grayscale }
168 if (ColorType and PNG_COLOR_MASK_COLOR) <> 0 then
169 begin
170 png_set_rgb_to_gray_fixed(png_ptr,
171 { Error_action = 1 means "silently do the conversion" }
172 1,
173 { Negative weights means "use the default weight" (matches my
174 GrayscaleValuesByte weights, actually my GrayscaleValuesByte
175 was copied from libpng documentation...) }
176 -1, -1);
177 ColorType := ColorType and (not PNG_COLOR_MASK_COLOR);
178 end;
179
180 { grayscale-non-8-bit -> 8bit grayscale }
181 if BitDepth < 8 then
182 begin
183 {$ifdef CASTLE_PNG_STATIC}
184 png_set_expand_gray_1_2_4_to_8(png_ptr);
185 {$else}
186 if Assigned(png_set_expand_gray_1_2_4_to_8) then
187 png_set_expand_gray_1_2_4_to_8(png_ptr) else
188 raise EPngTransformError.Create('Your png library doesn''t have png_set_expand_gray_1_2_4_to_8, needed to handle this image');
189 {$endif}
190
191 BitDepth := 8;
192 end;
193
194 { now he have grayscale 8/16 bitDepth + maybe alpha, maybe unapplied tRNS }
195 end;
196
197 procedure TPngFormat.SomeGrayscaleToSomeRgb;
198 begin
199 { grayscale -> 8bit rgb }
200 if (ColorType and PNG_COLOR_MASK_COLOR) = 0 then
201 begin
202 if BitDepth < 8 then
203 begin
204 {$ifdef CASTLE_PNG_STATIC}
205 png_set_expand_gray_1_2_4_to_8(png_ptr);
206 {$else}
207 if Assigned(png_set_expand_gray_1_2_4_to_8) then
208 png_set_expand_gray_1_2_4_to_8(png_ptr) else
209 raise EPngTransformError.Create('Your png library doesn''t have png_set_expand_gray_1_2_4_to_8, needed to handle this image');
210 {$endif}
211 BitDepth := 8;
212 end;
213
214 png_set_gray_to_rgb(png_ptr);
215 {gray color means ColorType = PNG_COLOR_TYPE_GRAY or GRAY_ALPHA
216 = 0 or MASK_ALPHA
217 and that's why here we can simply combine it bitwise with MASK_COOR }
218 ColorType := ColorType or PNG_COLOR_MASK_COLOR;
219 end;
220
221 { now he have rgb 8/16 bitDepth + maybe alpha, maybe unapplied tRNS }
222 end;
223
224 procedure TPngFormat.RemoveAlpha;
225 var
226 bKGD_col_ptr: png_color_16p;
227 {my_background_col: png_color_16;}
228 begin
229 { handle alpha and tRNS by combining image with color in bKGD header part
230 (we do it just to get rid of alpha channel; in case of PngGraphic bedziemy
231 aplikowac pozniej filler jako czwarty bajt i bedziemy ten czwarty bajt
232 ignorowac ale generalnie tak czy siak nalezy skombinowac alpha channel
233 z obrazkiem zeby obrazek wygladal tak jakby sie tego mogl spodziewac
234 autor obrazka.) }
235 if (ColorType and PNG_COLOR_MASK_ALPHA) <> 0 then
236 begin
237 { combinig with background requires a few parameters.
238 We set need_expand (4th parameter) to 1 when we take color from file because
239 in file it's written in file's original format and so it must be expanded
240 to the currently set format (8 bit rgb). However, we are supplying
241 my_background_col in 8bit rgb format already so there we set need_expand to 0.
242
243 We set background_gamma (5th parameter) always as 1.0 - bacause that's
244 considered the "default" and we want do just the default thing
245 (we want to do what author of the image expected). }
246 if png_get_bKGD(png_ptr, info_ptr, @bKGD_col_ptr) <> 0 then
247 begin { combine it with supplied bKGD color }
248 png_set_background(png_ptr, bKGD_col_ptr, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
249 end else
250 begin
251 { What should we do now ?
252 We can apply image on an arbitrary background color
253 (but which one ?) or we can just strip alpha channel.
254
255 Some interesting case from testing:
256
257 - png/bufferfs.png: requires stripping, only then looks good.
258 Possibly it's just a bad image ? Opening in GIMP, it shows
259 only as a text (butterflies not visible), everything else
260 is completely transparent. That's why
261 - doing png_set_background with my_background_col = white
262 makes this image just a text on clear white background and
263 - doing png_set_background with my_background_col = black
264 makes this image just a text on clear black background
265 If you want to see butterflies there, you cannot use
266 png_set_background, you must just strip alpha channel.
267
268 - png/moose/customize-m.png (online, similar version on
269 http://lofotenmoose.info/css/destroy/buttons/xl.png):
270
271 This is an interesting hack... The intended result is the
272 grayscale image of Michelle Pfeiffer (visible on webpage when composed
273 against white bg: http://lofotenmoose.info/css/destroy/buttons/).
274 The image file has an alpha channel, that contains the grayscale
275 *negative* of the image, and pure black color in normal RGB channels.
276 The effect: when applied against white background, the image looks
277 good (black alpha channel means to take background, which is white,
278 and white alpha channel means to take image, which is black...).
279 In some other circumstances, it may look unsensible, e.g. composing
280 the image against black background, or simply stripping the alpha
281 channel, leaves you with pure black image...
282
283 IOW, to convert this image to RGB, I have to use the alpha channel and
284 combine it with white background to make the result look good.
285 So when loading to TRGBImage, I should do png_set_background like this:
286
287 with my_background_col do
288 begin
289 // my_background_col := white color
290 red := $FF; green := $FF; blue := $FF;
291 end;
292 png_set_background(png_ptr, @my_background_col, PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
293
294 But this is non-standard, by default I simply strip alpha
295 when converting RGBA image to RGB memory, so I don't do it.
296 Image doesn't contain bKGD chunk, so I cannot arbitrarily choose
297 to compose it against white background. So I'll strip alpha,
298 thereby destroying the image (making it black).
299
300 This image can be viewed correctly when loaded to (default for this
301 PNG color type) TRGBAlphaImage, and presented against white background.
302 So my reading code is correct, the image can be rendered correctly.
303 }
304
305 { Version with stripping }
306 png_set_strip_alpha(png_ptr);
307 end;
308 ColorType := ColorType and UInt32(not PNG_COLOR_MASK_ALPHA);
309 end;
310 end;
311
312 procedure TPngFormat.PaletteToRgb;
313 begin
314 { palette -> true color (palette is always rgb 8 bit, maybe with alpha) }
315 if (ColorType and PNG_COLOR_MASK_PALETTE) <> 0 then
316 begin
317 png_set_palette_to_rgb(png_ptr);
318
319 { we converted palette to rgb; actually it may be RGB or RGBA;
320 paletted images can contain alpha channel only using tRNS chunk
321 so here we can check whether we got RGB or RGBA by checking
322 whether there exists tRNS chunk;
323 Ufff; this was a bug corrected after a long day : 21.12.2002}
324 if TrnsExists then
325 begin
326 ColorType := PNG_COLOR_TYPE_RGB_ALPHA;
327 TrnsExists := false;
328 end else
329 ColorType := PNG_COLOR_TYPE_RGB;
330
331 { when expanding palette we always get 8 bit depth because pallete entries
332 are always in 8bit RGB }
333 BitDepth := 8;
334 end;
335 end;
336
337 procedure TPngFormat.TrnsChunkToAlphaChannel;
338 begin
339 if TrnsExists and
340 (ColorType and PNG_COLOR_MASK_ALPHA = 0) then
341 begin
342 png_set_tRNS_to_alpha(png_ptr);
343 TrnsExists := false;
344 end;
345
346 { In case of some invalid image (Like an image with alpha channel
347 and also tRNS chunk ? Does libPNG allow such things ?)
348 probably (not confirmed) we may be left here with TrnsExists = false.
349 Ignore this. }
350 end;
351
352 procedure TPngFormat.AddAlphaIfNecessary;
353 begin
354 if ColorType and PNG_COLOR_MASK_ALPHA = 0 then
355 begin
356 if BitDepth <= 8 then
357 png_set_filler(png_ptr, High(Byte), PNG_FILLER_AFTER)
358 else
359 begin
360 Assert(BitDepth = 16); // there are no PNGs above 16-bit
361 png_set_filler(png_ptr, High(UInt16), PNG_FILLER_AFTER);
362 end;
363 ColorType := ColorType or PNG_COLOR_MASK_ALPHA;
364 end;
365 end;
366
367 procedure TPngFormat.AnyToGrayscale;
368 begin
369 PaletteToRgb;
370 RgbToGrayscale;
371 RemoveAlpha;
372 Assert(
373 (ColorType = PNG_COLOR_TYPE_GRAY) and BitDepthFinal,
374 'PngTransformAnyToGrayscale failed to apply good png transformations');
375 end;
376
377 procedure TPngFormat.AnyToGrayscaleAlpha;
378 begin
379 PaletteToRgb;
380 RgbToGrayscale;
381 TrnsChunkToAlphaChannel;
382 AddAlphaIfNecessary;
383 Assert(
384 (ColorType = PNG_COLOR_TYPE_GRAY_ALPHA) and BitDepthFinal,
385 'PngTransformAnyToGrayscaleAlpha failed to apply good png transformations');
386 end;
387
388 procedure TPngFormat.AnyToRGB;
389 begin
390 PaletteToRgb;
391 SomeGrayscaleToSomeRgb;
392 RemoveAlpha;
393 Assert(
394 (ColorType = PNG_COLOR_TYPE_RGB) and BitDepthFinal,
395 'PngTransformAnyToRGB failed to apply good png transformations');
396 end;
397
398 procedure TPngFormat.AnyToRGBAlpha;
399 begin
400 PaletteToRgb;
401 SomeGrayscaleToSomeRgb;
402 TrnsChunkToAlphaChannel;
403 AddAlphaIfNecessary;
404 Assert(
405 (ColorType = PNG_COLOR_TYPE_RGB_ALPHA) and BitDepthFinal,
406 'PngTransformAnyToRGBAlpha failed to apply good png transformations');
407 end;
408
409 { *ToStr -------------------------------------------------------------- }
410
411 function PngColorTypeToStr(const PngColorType: Int32): string;
412 begin
413 case PngColorType of
414 PNG_COLOR_TYPE_GRAY : Result := 'Gray';
415 PNG_COLOR_TYPE_GRAY_ALPHA: Result := 'Gray with alpha';
416 PNG_COLOR_TYPE_PALETTE : Result := 'Paletted';
417 PNG_COLOR_TYPE_RGB : Result := 'RGB';
418 PNG_COLOR_TYPE_RGB_ALPHA : Result := 'RGB with alpha';
419 else Result := 'unknown';
420 end;
421 end;
422
423 function PngInterlaceTypeToStr(const PngInterlaceType: Int32): string;
424 begin
425 case PngInterlaceType of
426 PNG_INTERLACE_NONE : Result := 'None';
427 PNG_INTERLACE_ADAM7: Result := 'Adam7';
428 else Result := 'unknown';
429 end;
430 end;
431
432 function PngTextCompressionToStr(const PngTextCompression: Int32): string;
433 begin
434 case PngTextCompression of
435 PNG_TEXT_COMPRESSION_NONE: Result := 'None';
436 PNG_TEXT_COMPRESSION_zTXT: Result := 'zTXT';
437 else Result := 'unknown';
438 end;
439 end;
440
441 { initialize ----------------------------------------------------------------- }
442
443 procedure InitializePNGUsingLibpng;
444 var
445 VerNumber: png_uint_32;
446 begin
447 if CastlePngInitialized then
448 begin
449 { Repeated calls to InitializePNGUsingLibpng should do nothing.
450 This is useful because we call it now from LoadPNG, as we need to do it
451 later than "initialization" on Android. }
452 if FCurrentLibpngVersion = '' then
453 begin
454 VerNumber := png_access_version_number();
455 FCurrentLibpngVersionRelease := VerNumber mod 100;
456 FCurrentLibpngVersionMinor := (VerNumber mod 10000) div 100;
457 FCurrentLibpngVersionMajor := VerNumber div 10000;
458 FCurrentLibpngVersion := AnsiString(Format('%d.%d.%d', [
459 FCurrentLibpngVersionMajor,
460 FCurrentLibpngVersionMinor,
461 FCurrentLibpngVersionRelease
462 ]));
463 WritelnLog('LibPng detected (version %s).', [FCurrentLibpngVersion]);
464 end;
465 end;
466 { Note: Do not report warning, it will be done by WarningNoLibPng if we'll load any PNG. }
467 end;
468
469 { error / warning handlers --------------------------------------------------- }
470
471 { function our_png_error_fn and our_png_warning_fn are used as libpng
472 error and warning handlers in both SavePNG_LibPng and LoadPNG_LibPng.
473
474 They could use png_get_error_ptr(png_ptr) for some pointer data,
475 but for now it is not used. }
476
477 procedure our_png_error_fn(png_ptr : png_structp; s : png_const_charp);
478 {$ifndef LIBPNG_CDECL} stdcall {$else} cdecl {$endif};
479 begin
480 raise EInvalidPng.Create('PNG error ' + S);
481 end;
482
483 procedure our_png_warning_fn(png_ptr : png_structp; s : png_const_charp);
484 {$ifndef LIBPNG_CDECL} stdcall {$else} cdecl {$endif};
485 begin
486 { Ignore this warning.
487
488 It can be safely ignored as I can see:
489 https://stackoverflow.com/questions/22745076/libpng-warning-iccp-known-incorrect-srgb-profile
490 https://tex.stackexchange.com/questions/125612/warning-pdflatex-libpng-warning-iccp-known-incorrect-srgb-profile
491
492 Not ignoring this would be bothersome, as it seems Photoshop produces
493 such files by default. We can get flooded with these warnings easily. }
494 if S = 'iCCP: known incorrect sRGB profile' then Exit;
495
496 WritelnWarning('PNG', S);
497 end;
498
499 { read / write functions -----------------------------------------------------
500
501 Both treat png_get_io_ptr(png_ptr) as TStream
502 and read/write from/to that stream. Exceptions are raised if operation
503 is not posiible (for example, stream end --- this will happen if PNG file
504 is truncated; since we never give back to PNG the number of bytes read,
505 it is obvious that we have to detect unexpected stream end ourselves). }
506
507 procedure our_png_read_fn(png_ptr: png_structp; data: png_bytep; len: png_size_t);
508 {$ifndef LIBPNG_CDECL} stdcall {$else} cdecl {$endif};
509 begin
510 TStream(png_get_io_ptr(png_ptr)).ReadBuffer(data^, len);
511 end;
512
513 procedure our_png_write_fn(png_ptr: png_structp; data: png_bytep; len: png_size_t);
514 {$ifndef LIBPNG_CDECL} stdcall {$else} cdecl {$endif};
515 begin
516 TStream(png_get_io_ptr(png_ptr)).WriteBuffer(data^, len);
517 end;
518
519 procedure our_png_flush_fn(png_ptr: png_structp);
520 {$ifndef LIBPNG_CDECL} stdcall {$else} cdecl {$endif};
521 begin
522 { we would like to do here something like TStream(png_get_io_ptr(png_ptr)).Flush;
523 but there is no "flush" method in TStream. }
524 end;
525
526 { LoadPNG_LibPng ------------------------------------------------------------------- }
527
528 function LoadPNG_LibPng(const Stream: TStream;
529 const AllowedImageClasses: array of TEncodedImageClass): TEncodedImage;
530
531 function ClassAllowed(ImageClass: TEncodedImageClass): boolean;
532 begin
533 Result := CastleImages.ClassAllowed(ImageClass, AllowedImageClasses);
534 end;
535
536 var
537 ImgResult: TCastleImage absolute Result;
538 AllocateWidth, AllocateHeight: Cardinal;
539 png_ptr: png_structp;
540 info_ptr: png_infop;
541
542 { Allocates Result to given class and applies libpng transforms to
543 make resulting data matching given Result class.
544
545 When CheckTargetClass, it checks (and returns @true only when it is OK)
546 whether ImageClass is in AllowedImageClasses. }
547 function TransformPng(const ImageClass: TCastleImageClass; const CheckTargetClass: Boolean = true): boolean;
548 var
549 PngFormat: TPngFormat;
550 begin
551 Result := (not CheckTargetClass) or ClassAllowed(ImageClass);
552
553 if Result then
554 begin
555 ImgResult := ImageClass.Create(AllocateWidth, AllocateHeight);
556 PngFormat.Init(png_ptr, info_ptr);
557
558 if (ImageClass = TGrayscaleImage) or (ImageClass = TGrayscaleFloatImage) then
559 PngFormat.AnyToGrayscale
560 else
561 if (ImageClass = TGrayscaleAlphaImage) or (ImageClass = TGrayscaleAlphaFloatImage) then
562 PngFormat.AnyToGrayscaleAlpha
563 else
564 if (ImageClass = TRGBImage) or (ImageClass = TRGBFloatImage) then
565 PngFormat.AnyToRGB
566 else
567 if (ImageClass = TRGBAlphaImage) or (ImageClass = TRGBAlphaFloatImage) then
568 PngFormat.AnyToRGBAlpha;
569 end;
570 end;
571
572 function PngIsGrayscale(const png_ptr: png_structp; const info_ptr: png_infop): Boolean;
573 var
574 ColorType: UInt32;
575 begin
576 ColorType := png_get_color_type(png_ptr, info_ptr);
577 Result := (ColorType and PNG_COLOR_MASK_COLOR) = 0;
578 end;
579
580 { PNG file has some alpha - either alpha channel (in addition to grayscale or rgb)
581 or if it has tRNS chunk (for paletted image this stores alpha values
582 for each palette color, for grayscale/rgb it determines one particular
583 color to mean "transparent"). }
584 function PngIsAlpha(const png_ptr: png_structp; const info_ptr: png_infop): Boolean;
585 var
586 ColorType: UInt32;
587 begin
588 ColorType := png_get_color_type(png_ptr, info_ptr);
589 Result := ( (ColorType and PNG_COLOR_MASK_ALPHA) <> 0) or
590 (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) <> 0);
591 end;
592
593 function PngImpliesFloatFormat(const png_ptr: png_structp; const info_ptr: png_infop): Boolean;
594 var
595 BitDepth: UInt32;
596 begin
597 BitDepth := png_get_bit_depth(png_ptr, info_ptr);
598 // There are no PNGs above 16-bit (if there will be, they'll need special handling)
599 Assert(BitDepth <= 16);
600 Result := BitDepth > 8;
601 end;
602
603 { Create ImgResult with the most suitable class, and apply libpng transformations
604 to make it match this class. }
605 procedure CreateAndTransform;
606 var
607 IsAlpha, IsGrayscale, IsFloat: boolean;
608 begin
609 IsAlpha := PngIsAlpha(png_ptr, info_ptr);
610 IsGrayscale := PngIsGrayscale(png_ptr, info_ptr);
611 IsFloat := PngImpliesFloatFormat(png_ptr, info_ptr);
612
613 { First, check to what TEncodedImage descendant our image file most matches.
614
615 If it's not on the list of allowed classes, try to transform
616 it to the most matching class. When doing this, we try to perform
617 the most lossless conversion --- this means that we prefer to
618 add image channel or expand grayscale->RGB than the other way around.
619 For example, if image file is grayscale+alpha, we prefer to make
620 it RGB+alpha (expand grayscale to RGB) than to grayscale (strip alpha).
621 }
622
623 if IsFloat then
624 begin
625 if IsGrayScale then
626 begin
627 if IsAlpha then
628 begin
629 if not TransformPng(TGrayscaleAlphaFloatImage) then
630 if not TransformPng(TRGBAlphaFloatImage) then
631 if not TransformPng(TGrayscaleFloatImage) then
632 if not TransformPng(TRGBFloatImage) then
633 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
634 TransformPng(TGrayscaleAlphaFloatImage, false);
635 end else
636 begin
637 if not TransformPng(TGrayscaleFloatImage) then
638 if not TransformPng(TGrayscaleAlphaFloatImage) then
639 if not TransformPng(TRGBFloatImage) then
640 if not TransformPng(TRGBAlphaFloatImage) then
641 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
642 TransformPng(TGrayscaleFloatImage, false);
643 end;
644 end else
645 begin
646 if IsAlpha then
647 begin
648 if not TransformPng(TRGBAlphaFloatImage) then
649 if not TransformPng(TRGBFloatImage) then
650 if not TransformPng(TGrayscaleAlphaFloatImage) then
651 if not TransformPng(TGrayscaleFloatImage) then
652 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
653 TransformPng(TRGBAlphaFloatImage, false);
654 end else
655 begin
656 if not TransformPng(TRGBFloatImage) then
657 if not TransformPng(TRGBAlphaFloatImage) then
658 if not TransformPng(TGrayscaleFloatImage) then
659 if not TransformPng(TGrayscaleAlphaFloatImage) then
660 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
661 TransformPng(TRGBFloatImage, false);
662 end;
663 end;
664 end else
665 begin
666 { IsFloat = false }
667 if IsGrayScale then
668 begin
669 if IsAlpha then
670 begin
671 if not TransformPng(TGrayscaleAlphaImage) then
672 if not TransformPng(TRGBAlphaImage) then
673 if not TransformPng(TGrayscaleImage) then
674 if not TransformPng(TRGBImage) then
675 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
676 TransformPng(TGrayscaleAlphaImage, false);
677 end else
678 begin
679 if not TransformPng(TGrayscaleImage) then
680 if not TransformPng(TGrayscaleAlphaImage) then
681 if not TransformPng(TRGBImage) then
682 if not TransformPng(TRGBAlphaImage) then
683 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
684 TransformPng(TGrayscaleImage, false);
685 end;
686 end else
687 begin
688 if IsAlpha then
689 begin
690 if not TransformPng(TRGBAlphaImage) then
691 if not TransformPng(TRGBImage) then
692 if not TransformPng(TGrayscaleAlphaImage) then
693 if not TransformPng(TGrayscaleImage) then
694 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
695 TransformPng(TRGBAlphaImage, false);
696 end else
697 begin
698 if not TransformPng(TRGBImage) then
699 if not TransformPng(TRGBAlphaImage) then
700 if not TransformPng(TGrayscaleImage) then
701 if not TransformPng(TGrayscaleAlphaImage) then
702 // ignore AllowedImageClasses if we cannot satisfy it, LoadEncodedImage will fix it
703 TransformPng(TRGBImage, false);
704 end;
705 end;
706 end;
707 end;
708
709 { Convert 16-bit row (input) to a row with Single (output).
710 Contain Count values (on input and output). }
711 procedure ConvertRow16ToFloat(const Row16: PUInt16; const RowSingle: PSingle;
712 const Count: Cardinal);
713 var
714 Row16Ptr: PUInt16;
715 RowSinglePtr: PSingle;
716 I: Integer;
717 begin
718 Row16Ptr := Row16;
719 RowSinglePtr := RowSingle;
720 for I := 0 to Integer(Count) - 1 do
721 begin
722 // Integers in PNG are in big-endian order ( https://www.w3.org/TR/png/#7Integers-and-byte-order )
723 Row16Ptr^ := BEtoN(Row16Ptr^);
724 RowSinglePtr^ := Row16Ptr^ / High(UInt16);
725 Inc(Row16Ptr);
726 Inc(RowSinglePtr);
727 end;
728 end;
729
730 { Is Img encoded as floating-point values (we use this when PNG has 16-bit per channel). }
731 function IsImgFloat(const Img: TEncodedImage): Boolean;
732 begin
733 Result :=
734 (Img is TGrayscaleFloatImage) or
735 (Img is TGrayscaleAlphaFloatImage) or
736 (Img is TRGBFloatImage) or
737 (Img is TRGBAlphaFloatImage);
738 end;
739
740 { Check PNG reported row size in bytes is as we expect, as ReadRows expect.
741 If this check fails, then ReadRows cannot be run -- the memory layout
742 from LibPNG is not as it would expect. }
743 procedure CheckRowSize;
744 var
745 ImgPixelSize: Cardinal;
746 begin
747 ImgPixelSize := ImgResult.PixelSize;
748 { Account that for float images, we will read UInt16 per each Single
749 This in practice makes ImgPixelSize 2x smaller. }
750 if IsImgFloat(ImgResult) then
751 ImgPixelSize := ImgPixelSize * SizeOf(Uint16) div SizeOf(Single);
752
753 png_read_update_info(png_ptr, info_ptr);
754 if png_get_rowbytes(png_ptr, info_ptr) <> ImgPixelSize * ImgResult.Width then
755 raise EInternalError.CreateFmt('PNG transformations resulted in wrong row size. Our image class %s, width: %d, will be read using bytes per pixel: %d, row size: %d. PNG reported row size: %d', [
756 ImgResult.ClassName,
757 ImgResult.Width,
758 ImgPixelSize,
759 ImgPixelSize * ImgResult.Width,
760 png_get_rowbytes(png_ptr, info_ptr)
761 ]);
762 end;
763
764 { Read PNG rows and uncompress them to ImgResult data. }
765 procedure ReadRows;
766 var
767 RowPointers: {$ifdef FPC}TFPList{$else}TList{$endif};
768 I: Cardinal;
769 TempMemory16: Pointer;
770 RowSize16: PtrUInt;
771 begin
772 { now ready RowPointers as ScanLines }
773 RowPointers := {$ifdef FPC}TFPList{$else}TList{$endif}.Create;
774 try
775 RowPointers.Count := Result.Height;
776 // Handle 8-bit data
777 if (ImgResult is TGrayscaleImage) or
778 (ImgResult is TGrayscaleAlphaImage) or
779 (ImgResult is TRGBImage) or
780 (ImgResult is TRGBAlphaImage) then
781 begin
782 for I := 0 to Result.Height - 1 do
783 RowPointers[I] := ImgResult.RowPtr(ImgResult.Height - I - 1);
784 { Actually uncompress PNG data }
785 png_read_image(png_ptr, PPPng_Byte(RowPointers.List));
786 end else
787 // Handle 16-bit data that we load into float-based classes
788 begin
789 Assert(IsImgFloat(ImgResult));
790 RowSize16 := ImgResult.Width * ImgResult.ColorComponentsCount * SizeOf(UInt16);
791 TempMemory16 := GetMem(ImgResult.Height * RowSize16);
792 try
793 for I := 0 to Result.Height - 1 do
794 RowPointers[I] := Pointer(PtrUInt(TempMemory16) + I * RowSize16);
795 { Actually uncompress PNG data }
796 png_read_image(png_ptr, PPPng_Byte(RowPointers.List));
797 for I := 0 to Result.Height - 1 do
798 ConvertRow16ToFloat(RowPointers[I], ImgResult.RowPtr(ImgResult.Height - I - 1),
799 ImgResult.Width * ImgResult.ColorComponentsCount);
800 finally
801 FreeMemNiling(TempMemory16);
802 end;
803 end;
804 finally
805 FreeAndNil(RowPointers);
806 end;
807 end;
808
809 begin
810 png_ptr := nil;
811 try
812 { Passing here CurrentLibpngVersion (which is obtained by querying libpng
813 library) is a little trick.
814
815 Libpng docs instead advise to pass here PNG_LIBPNG_VER_STRING constant,
816 which should be a constant reflecing the libpng API version we have defined
817 in CastleInternalPng.
818 Then libpng would check whether version is compatible, and eventually
819 report error "png.h and png.c versions not compatible".
820
821 However, this check is too strict in our experience.
822 As we use only a tiny subset of libpng API (and dynamically check
823 for some functions existence, e.g. "Assigned(png_set_expand_gray_1_2_4_to_8)"),
824 we work with any libpng 1.x in practice now.
825 Our own version check (done in each CurrentLibpngVersion call)
826 is sufficient for us. }
827 png_ptr := png_create_read_struct(CurrentLibpngVersion,
828 nil { we could pass here data to warning/error handlers },
829 {$ifdef FPC} @ {$endif} our_png_error_fn,
830 {$ifdef FPC} @ {$endif} our_png_warning_fn);
831 Check( png_ptr <> nil, 'png_create_read_struct failed');
832
833 info_ptr := png_create_info_struct(png_ptr);
834 Check( info_ptr <> nil, 'png_create_info_struct failed');
835
836 png_set_read_fn(png_ptr, Stream,
837 {$ifdef FPC} @ {$endif} our_png_read_fn);
838
839 { Note: We could use png_set_read_status_fn to show progress bar of loading.
840 Doesn't seem actually necessary, PNG would have to be truly huge to matter. }
841
842 png_read_info(png_ptr, info_ptr);
843 AllocateWidth := png_get_image_width(png_ptr, info_ptr);
844 AllocateHeight := png_get_image_height(png_ptr, info_ptr);
845 Result := nil; // initialize Result to allow easier try..except syntax below
846
847 { Avoid the warning "Interlace handling should be turned on when using png_read_image"
848 on interlaced images.
849 See also:
850 https://sourceforge.net/p/libpng/bugs/165/
851 (the bug there can cause this warning in other cases too)
852 https://stackoverflow.com/questions/22125146/how-to-fix-libpng-warning-when-reading-interlaced-png }
853 png_set_interlace_handling(png_ptr);
854
855 try
856 CreateAndTransform;
857 CheckRowSize;
858 ReadRows;
859 png_read_end(png_ptr, nil);
860 except
861 Result.Free;
862 raise;
863 end;
864
865 finally
866 if png_ptr <> nil then
867 begin
868 if info_ptr = nil then
869 png_destroy_read_struct(@png_ptr, nil, nil)
870 else
871 png_destroy_read_struct(@png_ptr, @info_ptr, nil);
872 end;
873 end;
874 end;
875
876 { SavePNG_LibPng --------------------------------------------------------------------- }
877
878 procedure SavePNG_LibPng(const Img: TEncodedImage; const Stream: TStream; const Interlaced: boolean = false);
879 var
880 png_ptr: png_structp;
881 info_ptr: png_infop;
882 InterlaceType: UInt32;
883 RowPointers: {$ifdef FPC}TFPList{$else}TList{$endif};
884 i: Cardinal;
885 ColorType: Int32;
886 begin
887 if not (Img is TCastleImage) then
888 raise EImageSaveError.CreateFmt('Saving to PNG image class %s not possible', [Img.ClassName]);
889
890 png_ptr := nil;
891 try
892 png_ptr := png_create_write_struct(CurrentLibpngVersion,
893 nil { we could pass here data to warning/error handlers },
894 {$ifdef FPC} @ {$endif} our_png_error_fn,
895 {$ifdef FPC} @ {$endif} our_png_warning_fn);
896 Check( png_ptr <> nil, 'png_create_write_struct failed');
897
898 info_ptr := png_create_info_struct(png_ptr);
899 Check( info_ptr <> nil, 'png_create_info_struct failed');
900
901 png_set_write_fn(png_ptr, Stream,
902 {$ifdef FPC} @ {$endif} our_png_write_fn,
903 {$ifdef FPC} @ {$endif} our_png_flush_fn);
904
905 if interlaced then
906 interlaceType := PNG_INTERLACE_ADAM7
907 else
908 interlaceType := PNG_INTERLACE_NONE;
909
910 if Img is TRGBImage then
911 ColorType := PNG_COLOR_TYPE_RGB
912 else
913 if Img is TRGBAlphaImage then
914 ColorType := PNG_COLOR_TYPE_RGBA
915 else
916 if Img is TGrayscaleImage then
917 ColorType := PNG_COLOR_TYPE_GRAY
918 else
919 if Img is TGrayscaleAlphaImage then
920 ColorType := PNG_COLOR_TYPE_GRAY_ALPHA
921 else
922 raise EImageSaveError.CreateFmt('Saving to PNG image class %s not possible', [Img.ClassName]);
923
924 png_set_IHDR(png_ptr, info_ptr, Img.Width, Img.Height, 8, ColorType,
925 interlaceType, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
926 png_write_info(png_ptr, info_ptr);
927
928 { After writing the header, we can write the image contents,
929 in the same format we use for TCastleImage.
930 This is much simpler than LoadPNG_LibPng, since we don't need to transform
931 the format, e.g. we just use always 8 bits per channel. }
932
933 RowPointers := {$ifdef FPC}TFPList{$else}TList{$endif}.Create;
934 try
935 RowPointers.Count := Img.Height;
936 for i := 0 to Img.Height-1 do
937 RowPointers[i] := TCastleImage(Img).RowPtr(Img.Height-i-1);
938 png_write_image(png_ptr, PPPng_Byte(RowPointers.List));
939 finally
940 FreeAndNil(RowPointers);
941 end;
942
943 png_write_end(png_ptr, nil);
944 finally
945 if png_ptr <> nil then
946 begin
947 if info_ptr <> nil then
948 png_destroy_write_struct(@png_ptr, @info_ptr)
949 else
950 png_destroy_write_struct(@png_ptr, nil);
951 end;
952 end;
953 end;
954
955 {$endif} // defined(CASTLE_PNG_DYNAMIC) or defined(CASTLE_PNG_STATIC)