-
Notifications
You must be signed in to change notification settings - Fork 12
/
nimPNG.nim
3234 lines (2766 loc) · 111 KB
/
nimPNG.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Portable Network Graphics Encoder and Decoder written in Nim
#
# Copyright (c) 2015-2016 Andri Lim
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# this is a rewrite of LodePNG(www.lodev.org/lodepng)
# to be as idiomatic Nim as possible
# part of nimPDF sister projects
#-------------------------------------
import streams, endians, tables, hashes, math, typetraits
import nimPNG/[buffer, nimz, filters, results, utils]
import strutils
export typetraits, results
const
NIM_PNG_VERSION = "0.3.2"
type
PNGChunkType = distinct int32
Pixels* = seq[uint8]
PNGColorType* = enum
LCT_GREY = 0, # greyscale: 1,2,4,8,16 bit
LCT_RGB = 2, # RGB: 8,16 bit
LCT_PALETTE = 3, # palette: 1,2,4,8 bit
LCT_GREY_ALPHA = 4, # greyscale with alpha: 8,16 bit
LCT_RGBA = 6 # RGB with alpha: 8,16 bit
PNGSettings = ref object of RootObj
PNGDecoder* = ref object of PNGSettings
colorConvert*: bool
#if false but rememberUnknownChunks is true, they're stored in the unknown chunks
#(off by default, useful for a png editor)
readTextChunks*: bool
rememberUnknownChunks*: bool
ignoreCRC*: bool
ignoreAdler32*: bool
PNGInterlace* = enum
IM_NONE = 0, IM_INTERLACED = 1
PNGChunk = ref object of RootObj
length: int #range[0..0x7FFFFFFF]
chunkType: PNGChunkType
crc: uint32
data: string
pos: int
PNGHeader = ref object of PNGChunk
width, height: int #range[1..0x7FFFFFFF]
bitDepth: int
colorType: PNGColorType
compressionMethod: int
filterMethod: int
interlaceMethod: PNGInterlace
RGBA8* = object
r*, g*, b*, a*: char
RGBA16* = object
r*, g*, b*, a*: uint16
ColorTree8 = Table[RGBA8, int]
PNGPalette = ref object of PNGChunk
palette: seq[RGBA8]
PNGData = ref object of PNGChunk
idat: string
PNGTime = ref object of PNGChunk
year: int #range[0..65535]
month: int #range[1..12]
day: int #range[1..31]
hour: int #range[0..23]
minute: int #range[0..59]
second: int #range[0..60] #to allow for leap seconds
PNGPhys = ref object of PNGChunk
physX, physY: int
unit: int
PNGTrans = ref object of PNGChunk
keyR, keyG, keyB: int
PNGBackground = ref object of PNGChunk
bkgdR, bkgdG, bkgdB: int
PNGText = ref object of PNGChunk
keyword: string
text: string
PNGZtxt = ref object of PNGChunk
keyword: string
text: string
PNGItxt = ref object of PNGChunk
keyword: string
text: string
languageTag: string
translatedKeyword: string
PNGGamma = ref object of PNGChunk
gamma: int
PNGChroma = ref object of PNGChunk
whitePointX, whitePointY: int
redX, redY: int
greenX, greenY: int
blueX, blueY: int
PNGStandarRGB = ref object of PNGChunk
renderingIntent: int
PNGICCProfile = ref object of PNGChunk
profileName: string
profile: string
PNGSPEntry = object
red, green, blue, alpha, frequency: int
PNGSPalette = ref object of PNGChunk
paletteName: string
sampleDepth: int
palette: seq[PNGSPEntry]
PNGHist = ref object of PNGChunk
histogram: seq[int]
PNGSbit = ref object of PNGChunk
APNGAnimationControl = ref object of PNGChunk
numFrames: int
numPlays: int
APNG_DISPOSE_OP* = enum
APNG_DISPOSE_OP_NONE
APNG_DISPOSE_OP_BACKGROUND
APNG_DISPOSE_OP_PREVIOUS
APNG_BLEND_OP* = enum
APNG_BLEND_OP_SOURCE
APNG_BLEND_OP_OVER
APNGFrameChunk = ref object of PNGChunk
sequenceNumber: int
APNGFrameControl* = ref object of APNGFrameChunk
width*: int
height*: int
xOffset*: int
yOffset*: int
delayNum*: int
delayDen*: int
disposeOp*: APNG_DISPOSE_OP
blendOp*: APNG_BLEND_OP
APNGFrameData = ref object of APNGFrameChunk
# during decoding frameDataPos points to chunk.data[pos]
# during encoding frameDataPos points to png.apngPixels[pos] and png.apngChunks[pos]
frameDataPos: int
PNGColorMode* = ref object
colorType*: PNGColorType
bitDepth*: int
paletteSize*: int
palette*: seq[RGBA8]
keyDefined*: bool
keyR*, keyG*, keyB*: int
PNGInfo* = ref object
width*: int
height*: int
mode*: PNGColorMode
backgroundDefined*: bool
backgroundR*, backgroundG*, backgroundB*: int
physDefined*: bool
physX*, physY*, physUnit*: int
timeDefined*: bool
year*: int #range[0..65535]
month*: int #range[1..12]
day*: int #range[1..31]
hour*: int #range[0..23]
minute*: int #range[0..59]
second*: int #range[0..60] #to allow for leap seconds
PNG*[T] = ref object
# during encoding, settings is PNGEncoder
# during decoding, settings is PNGDecoder
settings*: PNGSettings
chunks*: seq[PNGChunk]
pixels*: T
# w & h used during encoding process
width*, height*: int
# during encoding, apngChunks contains only fcTL chunks
# during decoding, apngChunks contains both fcTL and fdAT chunks
apngChunks*: seq[APNGFrameChunk]
firstFrameIsDefaultImage*: bool
isAPNG*: bool
apngPixels*: seq[T]
APNGFrame*[T] = ref object
ctl*: APNGFramecontrol
data*: T
PNGResult*[T] = ref object
width*: int
height*: int
data*: T
frames*: seq[APNGFrame[T]]
PNGError* = object of CatchableError
proc signatureMaker(): string {. compiletime .} =
const signatureBytes = [137, 80, 78, 71, 13, 10, 26, 10]
result = ""
for c in signatureBytes: result.add chr(c)
proc makeChunkType*(val: string): PNGChunkType =
assert(val.len == 4)
result = PNGChunkType((ord(val[0]) shl 24) or (ord(val[1]) shl 16) or (ord(val[2]) shl 8) or ord(val[3]))
proc `$`*(tag: PNGChunkType): string =
result = newString(4)
let t = int(tag)
result[0] = chr(uint32(t shr 24) and 0xFF)
result[1] = chr(uint32(t shr 16) and 0xFF)
result[2] = chr(uint32(t shr 8) and 0xFF)
result[3] = chr(uint32(t) and 0xFF)
proc `==`*(a, b: PNGChunkType): bool = int(a) == int(b)
#proc isAncillary(a: PNGChunkType): bool = (int(a) and (32 shl 24)) != 0
#proc isPrivate(a: PNGChunkType): bool = (int(a) and (32 shl 16)) != 0
#proc isSafeToCopy(a: PNGChunkType): bool = (int(a) and 32) != 0
proc crc32(crc: uint32, buf: string): uint32 =
const kcrc32 = [ 0'u32, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190,
0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320'u32, 0xf00f9344'u32, 0xd6d6a3e8'u32,
0xcb61b38c'u32, 0x9b64c2b0'u32, 0x86d3d2d4'u32, 0xa00ae278'u32, 0xbdbdf21c'u32]
var crcu32 = not crc
for b in buf:
crcu32 = (crcu32 shr 4) xor kcrc32[int((crcu32 and 0xF) xor (uint32(b) and 0xF'u32))]
crcu32 = (crcu32 shr 4) xor kcrc32[int((crcu32 and 0xF) xor (uint32(b) shr 4'u32))]
result = not crcu32
template getUnderlyingType[T](_: openArray[T]): untyped = T
template getUnderlyingType[T](_: type openArray[T]): untyped = T
template newStorage[T](size: int): auto =
when T is string:
newStringWithDefault(size)
else:
type TT = getUnderlyingType(T)
newSeq[TT](size)
const
PNGSignature = signatureMaker()
IHDR = makeChunkType("IHDR")
IEND = makeChunkType("IEND")
PLTE = makeChunkType("PLTE")
IDAT = makeChunkType("IDAT")
tRNS = makeChunkType("tRNS")
bKGD = makeChunkType("bKGD")
pHYs = makeChunkType("pHYs")
tIME = makeChunkType("tIME")
iTXt = makeChunkType("iTXt")
zTXt = makeChunkType("zTXt")
tEXt = makeChunkType("tEXt")
gAMA = makeChunkType("gAMA")
cHRM = makeChunkType("cHRM")
sRGB = makeChunkType("sRGB")
iCCP = makeChunkType("iCCP")
sBIT = makeChunkType("sBIT")
sPLT = makeChunkType("sPLT")
hIST = makeChunkType("hIST")
# APNG chunks
acTL = makeChunkType("acTL")
fcTL = makeChunkType("fcTL")
fdAT = makeChunkType("fdAT")
template PNGFatal(msg: string): untyped =
newException(PNGError, msg)
proc newColorMode*(colorType=LCT_RGBA, bitDepth=8): PNGColorMode =
new(result)
result.keyDefined = false
result.keyR = 0
result.keyG = 0
result.keyB = 0
result.colorType = colorType
result.bitDepth = bitDepth
result.paletteSize = 0
proc copyTo*(src, dest: PNGColorMode) =
dest.keyDefined = src.keyDefined
dest.keyR = src.keyR
dest.keyG = src.keyG
dest.keyB = src.keyB
dest.colorType = src.colorType
dest.bitDepth = src.bitDepth
dest.paletteSize = src.paletteSize
newSeq(dest.palette, src.paletteSize)
for i in 0..src.palette.len-1: dest.palette[i] = src.palette[i]
proc newColorMode*(mode: PNGColorMode): PNGColorMode =
new(result)
mode.copyTo(result)
proc addPalette*(mode: PNGColorMode, r, g, b, a: int) =
mode.palette.add RGBA8(r: chr(r), g: chr(g), b: chr(b), a: chr(a))
mode.paletteSize = mode.palette.len
proc `==`(a, b: PNGColorMode): bool =
if a.colorType != b.colorType: return false
if a.bitDepth != b.bitDepth: return false
if a.keyDefined != b.keyDefined: return false
if a.keyDefined:
if a.keyR != b.keyR: return false
if a.keyG != b.keyG: return false
if a.keyB != b.keyB: return false
if a.paletteSize != b.paletteSize: return false
for i in 0..a.palette.len-1:
if a.palette[i] != b.palette[i]: return false
result = true
proc `!=`(a, b: PNGColorMode): bool = not (a == b)
proc readInt32(s: PNGChunk): int =
if s.pos + 4 > s.data.len: raise PNGFatal("index out of bound 4")
result = ord(s.data[s.pos]) shl 8
result = (result + ord(s.data[s.pos + 1])) shl 8
result = (result + ord(s.data[s.pos + 2])) shl 8
result = result + ord(s.data[s.pos + 3])
inc(s.pos, 4)
proc readInt16(s: PNGChunk): int =
if s.pos + 2 > s.data.len: raise PNGFatal("index out of bound 2")
result = ord(s.data[s.pos]) shl 8
result = result + ord(s.data[s.pos + 1])
inc(s.pos, 2)
when defined(js):
{.emit: """
var gEndianConverterFrom = new Uint32Array(1);
var gEndianConverter = new DataView(gEndianConverterFrom.buffer);
""".}
proc bigEndian32(dst, src: ptr int32) =
{.emit: """
gEndianConverterFrom[0] = `src`[`src`_Idx];
`dst`[`dst`_Idx] = gEndianConverter.getInt32(0);
""".}
proc readInt32BE(s: Stream): int =
var val = s.readInt32()
var tmp : int32
bigEndian32(addr(tmp), addr(val))
result = tmp
proc readByte(s: PNGChunk): int =
if s.pos + 1 > s.data.len: raise PNGFatal("index out of bound 1")
result = ord(s.data[s.pos])
inc s.pos
proc readColorType(s: PNGChunk): PNGColorType =
let ct = readByte(s).int
case ct
of 0: return LCT_GREY
of 2: return LCT_RGB
of 3: return LCT_PALETTE
of 4: return LCT_GREY_ALPHA
of 6: return LCT_RGBA
else:
raise PNGFatal("Wrong ColorType value: " & $ct)
proc setPosition(s: PNGChunk, pos: int) =
if pos < 0 or pos > s.data.len: raise PNGFatal("set position error")
s.pos = pos
proc hasChunk*(png: PNG, chunkType: PNGChunkType): bool =
for c in png.chunks:
if c.chunkType == chunkType: return true
result = false
proc apngHasChunk*(png: PNG, chunkType: PNGChunkType): bool =
for c in png.apngChunks:
if c.chunkType == chunkType: return true
result = false
proc getChunk*(png: PNG, chunkType: PNGChunkType): PNGChunk =
for c in png.chunks:
if c.chunkType == chunkType: return c
proc apngGetChunk*(png: PNG, chunkType: PNGChunkType): PNGChunk =
for c in png.apngChunks:
if c.chunkType == chunkType: return c
proc bitDepthAllowed(colorType: PNGColorType, bitDepth: int): bool =
case colorType
of LCT_GREY : result = bitDepth in {1, 2, 4, 8, 16}
of LCT_PALETTE: result = bitDepth in {1, 2, 4, 8}
else: result = bitDepth in {8, 16}
proc validateChunk(header: PNGHeader, png: PNG): bool =
if header.width < 1 or header.width > 0x7FFFFFFF:
raise PNGFatal("image width not allowed: " & $header.width)
if header.height < 1 or header.height > 0x7FFFFFFF:
raise PNGFatal("image width not allowed: " & $header.height)
if header.colorType notin {LCT_GREY, LCT_RGB, LCT_PALETTE, LCT_GREY_ALPHA, LCT_RGBA}:
raise PNGFatal("color type not allowed: " & $int(header.colorType))
if not bitDepthAllowed(header.colorType, header.bitDepth):
raise PNGFatal("bit depth not allowed: " & $header.bitDepth)
if header.compressionMethod != 0:
raise PNGFatal("unsupported compression method")
if header.filterMethod != 0:
raise PNGFatal("unsupported filter method")
if header.interlaceMethod notin {IM_NONE, IM_INTERLACED}:
raise PNGFatal("unsupported interlace method")
result = true
proc parseChunk(chunk: PNGHeader, png: PNG): bool =
if chunk.length != 13: return false
chunk.width = chunk.readInt32()
chunk.height = chunk.readInt32()
chunk.bitDepth = chunk.readByte()
chunk.colorType = chunk.readColorType()
chunk.compressionMethod = chunk.readByte()
chunk.filterMethod = chunk.readByte()
chunk.interlaceMethod = PNGInterlace(chunk.readByte())
result = true
proc parseChunk(chunk: PNGPalette, png: PNG): bool =
let paletteSize = chunk.length div 3
if paletteSize > 256: raise PNGFatal("palette size to big")
newSeq(chunk.palette, paletteSize)
for px in mitems(chunk.palette):
px.r = chr(chunk.readByte())
px.g = chr(chunk.readByte())
px.b = chr(chunk.readByte())
px.a = chr(255)
result = true
proc numChannels(colorType: PNGColorType): int =
case colorType
of LCT_GREY: result = 1
of LCT_RGB : result = 3
of LCT_PALETTE: result = 1
of LCT_GREY_ALPHA: result = 2
of LCT_RGBA: result = 4
proc LCTBPP(colorType: PNGColorType, bitDepth: int): int =
# bits per pixel is amount of channels * bits per channel
result = numChannels(colorType) * bitDepth
proc getBPP(header: PNGHeader): int =
# calculate bits per pixel out of colorType and bitDepth
result = LCTBPP(header.colorType, header.bitDepth)
proc getBPP(color: PNGColorMode): int =
# calculate bits per pixel out of colorType and bitDepth
result = LCTBPP(color.colorType, color.bitDepth)
proc idatRawSize(w, h: int, header: PNGHeader): int =
result = h * ((w * getBPP(header) + 7) div 8)
proc getRawSize(w, h: int, color: PNGColorMode): int =
result = (w * h * getBPP(color) + 7) div 8
#proc getRawSizeLct(w, h: int, colorType: PNGColorType, bitDepth: int): int =
# result = (w * h * LCTBPP(colorType, bitDepth) + 7) div 8
proc validateChunk(chunk: PNGData, png: PNG): bool =
var header = PNGHeader(png.getChunk(IHDR))
var predict = 0
if header.interlaceMethod == IM_NONE:
# The extra header.height is added because this are the filter bytes every scanLine starts with
predict = idatRawSize(header.width, header.height, header) + header.height
else:
# Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes
let w = header.width
let h = header.height
predict += idatRawSize((w + 7) div 8, (h + 7) div 8, header) + (h + 7) div 8
if w > 4: predict += idatRawSize((w + 3) div 8, (h + 7) div 8, header) + (h + 7) div 8
predict += idatRawSize((w + 3) div 4, (h + 3) div 8, header) + (h + 3) div 8
if w > 2: predict += idatRawSize((w + 1) div 4, (h + 3) div 4, header) + (h + 3) div 4
predict += idatRawSize((w + 1) div 2, (h + 1) div 4, header) + (h + 1) div 4
if w > 1: predict += idatRawSize((w + 0) div 2, (h + 1) div 2, header) + (h + 1) div 2
predict += idatRawSize((w + 0) div 1, (h + 0) div 2, header) + (h + 0) div 2
if chunk.idat.len != predict: raise PNGFatal("Decompress size doesn't match predict")
result = true
proc parseChunk(chunk: PNGData, png: PNG): bool =
var nz = nzInflateInit(chunk.data)
nz.ignoreAdler32 = PNGDecoder(png.settings).ignoreAdler32
chunk.idat = zlib_decompress(nz)
result = true
proc parseChunk(chunk: PNGTrans, png: PNG): bool =
var header = PNGHeader(png.getChunk(IHDR))
if header == nil: return false
if header.colorType == LCT_PALETTE:
var plte = PNGPalette(png.getChunk(PLTE))
if plte == nil: return false
# error: more alpha values given than there are palette entries
if chunk.length > plte.palette.len:
raise PNGFatal("more alpha value than palette entries")
#can contain fewer values than palette entries
for i in 0..chunk.length-1: plte.palette[i].a = chr(chunk.readByte())
elif header.colorType == LCT_GREY:
# error: this chunk must be 2 bytes for greyscale image
if chunk.length != 2: raise PNGFatal("tRNS must be 2 bytes")
chunk.keyR = chunk.readInt16()
chunk.keyG = chunk.keyR
chunk.keyB = chunk.keyR
elif header.colorType == LCT_RGB:
# error: this chunk must be 6 bytes for RGB image
if chunk.length != 6: raise PNGFatal("tRNS must be 6 bytes")
chunk.keyR = chunk.readInt16()
chunk.keyG = chunk.readInt16()
chunk.keyB = chunk.readInt16()
else:
raise PNGFatal("tRNS chunk not allowed for other color models")
result = true
proc parseChunk(chunk: PNGBackground, png: PNG): bool =
var header = PNGHeader(png.getChunk(IHDR))
if header.colorType == LCT_PALETTE:
# error: this chunk must be 1 byte for indexed color image
if chunk.length != 1: raise PNGFatal("bkgd must be 1 byte")
chunk.bkgdR = chunk.readByte()
chunk.bkgdG = chunk.bkgdR
chunk.bkgdB = chunk.bkgdR
elif header.colorType in {LCT_GREY, LCT_GREY_ALPHA}:
# error: this chunk must be 2 bytes for greyscale image
if chunk.length != 2: raise PNGFatal("bkgd must be 2 byte")
chunk.bkgdR = chunk.readInt16()
chunk.bkgdG = chunk.bkgdR
chunk.bkgdB = chunk.bkgdR
elif header.colorType in {LCT_RGB, LCT_RGBA}:
# error: this chunk must be 6 bytes for greyscale image
if chunk.length != 6: raise PNGFatal("bkgd must be 6 byte")
chunk.bkgdR = chunk.readInt16()
chunk.bkgdG = chunk.readInt16()
chunk.bkgdB = chunk.readInt16()
result = true
proc initChunk(chunk: PNGChunk, chunkType: PNGChunkType, data: string, crc: uint32) =
chunk.length = data.len
chunk.crc = crc
chunk.chunkType = chunkType
chunk.data = data
chunk.pos = 0
proc validateChunk(chunk: PNGTime, png: PNG): bool =
if chunk.year < 0 or chunk.year > 65535: raise PNGFatal("invalid year range[0..65535]")
if chunk.month < 1 or chunk.month > 12: raise PNGFatal("invalid month range[1..12]")
if chunk.day < 1 or chunk.day > 31: raise PNGFatal("invalid day range[1..32]")
if chunk.hour < 0 or chunk.hour > 23: raise PNGFatal("invalid hour range[0..23]")
if chunk.minute < 0 or chunk.minute > 59: raise PNGFatal("invalid minute range[0..59]")
#to allow for leap seconds
if chunk.second < 0 or chunk.second > 60: raise PNGFatal("invalid second range[0..60]")
result = true
proc parseChunk(chunk: PNGTime, png: PNG): bool =
if chunk.length != 7: raise PNGFatal("tIME must be 7 bytes")
chunk.year = chunk.readInt16()
chunk.month = chunk.readByte()
chunk.day = chunk.readByte()
chunk.hour = chunk.readByte()
chunk.minute = chunk.readByte()
chunk.second = chunk.readByte()
result = true
proc parseChunk(chunk: PNGPhys, png: PNG): bool =
if chunk.length != 9: raise PNGFatal("pHYs must be 9 bytes")
chunk.physX = chunk.readInt32()
chunk.physY = chunk.readInt32()
chunk.unit = chunk.readByte()
result = true
proc validateChunk(chunk: PNGText, png: PNG): bool =
if(chunk.keyword.len < 1) or (chunk.keyword.len > 79):
raise PNGFatal("keyword too short or too long")
result = true
proc parseChunk(chunk: PNGText, png: PNG): bool =
var len = 0
while(len < chunk.length) and (chunk.data[len] != chr(0)): inc len
if(len < 1) or (len > 79): raise PNGFatal("keyword too short or too long")
chunk.keyword = chunk.data.substr(0, len)
var textBegin = len + 1 # skip keyword null terminator
chunk.text = chunk.data.substr(textBegin)
result = true
proc validateChunk(chunk: PNGZtxt, png: PNG): bool =
if(chunk.keyword.len < 1) or (chunk.keyword.len > 79):
raise PNGFatal("keyword too short or too long")
result = true
proc parseChunk(chunk: PNGZtxt, png: PNG): bool =
var len = 0
while(len < chunk.length) and (chunk.data[len] != chr(0)): inc len
if(len < 1) or (len > 79): raise PNGFatal("keyword too short or too long")
chunk.keyword = chunk.data.substr(0, len)
var compproc = ord(chunk.data[len + 1]) # skip keyword null terminator
if compproc != 0: raise PNGFatal("unsupported comp proc")
var nz = nzInflateInit(chunk.data.substr(len + 2))
nz.ignoreAdler32 = PNGDecoder(png.settings).ignoreAdler32
chunk.text = zlib_decompress(nz)
result = true
proc validateChunk(chunk: PNGItxt, png: PNG): bool =
if(chunk.keyword.len < 1) or (chunk.keyword.len > 79):
raise PNGFatal("keyword too short or too long")
result = true
proc parseChunk(chunk: PNGItxt, png: PNG): bool =
if chunk.length < 5: raise PNGFatal("iTXt len too short")
var len = 0
while(len < chunk.length) and (chunk.data[len] != chr(0)): inc len
if(len + 3) >= chunk.length: raise PNGFatal("no null termination char, corrupt?")
if(len < 1) or (len > 79): raise PNGFatal("keyword too short or too long")
chunk.keyword = chunk.data.substr(0, len)
var compressed = ord(chunk.data[len + 1]) == 1 # skip keyword null terminator
var compproc = ord(chunk.data[len + 2])
if compproc != 0: raise PNGFatal("unsupported comp proc")
len = 0
var i = len + 3
while(i < chunk.length) and (chunk.data[i] != chr(0)):
inc len
inc i
chunk.languageTag = chunk.data.substr(i, i + len)
len = 0
i += len + 1
while(i < chunk.length) and (chunk.data[i] != chr(0)):
inc len
inc i
chunk.translatedKeyword = chunk.data.substr(i, i + len)
let textBegin = i + len + 1
if compressed:
var nz = nzInflateInit(chunk.data.substr(textBegin))
nz.ignoreAdler32 = PNGDecoder(png.settings).ignoreAdler32
chunk.text = zlib_decompress(nz)
else:
chunk.text = chunk.data.substr(textBegin)
result = true
proc parseChunk(chunk: PNGGamma, png: PNG): bool =
if chunk.length != 4: raise PNGFatal("invalid gAMA length")
chunk.gamma = chunk.readInt32()
result = true
proc parseChunk(chunk: PNGChroma, png: PNG): bool =
if chunk.length != 32: raise PNGFatal("invalid Chroma length")
chunk.whitePointX = chunk.readInt32()
chunk.whitePointY = chunk.readInt32()
chunk.redX = chunk.readInt32()
chunk.redY = chunk.readInt32()
chunk.greenX = chunk.readInt32()
chunk.greenY = chunk.readInt32()
chunk.blueX = chunk.readInt32()
chunk.blueY = chunk.readInt32()
result = true
proc parseChunk(chunk: PNGStandarRGB, png: PNG): bool =
if chunk.length != 1: raise PNGFatal("invalid sRGB length")
chunk.renderingIntent = chunk.readByte()
result = true
proc validateChunk(chunk: PNGICCProfile, png: PNG): bool =
if(chunk.profileName.len < 1) or (chunk.profileName.len > 79):
raise PNGFatal("keyword too short or too long")
result = true
proc parseChunk(chunk: PNGICCProfile, png: PNG): bool =
var len = 0
while(len < chunk.length) and (chunk.data[len] != chr(0)): inc len
if(len < 1) or (len > 79): raise PNGFatal("keyword too short or too long")
chunk.profileName = chunk.data.substr(0, len)
var compproc = ord(chunk.data[len + 1]) # skip keyword null terminator
if compproc != 0: raise PNGFatal("unsupported comp proc")
var nz = nzInflateInit(chunk.data.substr(len + 2))
nz.ignoreAdler32 = PNGDecoder(png.settings).ignoreAdler32
chunk.profile = zlib_decompress(nz)
result = true
proc parseChunk(chunk: PNGSPalette, png: PNG): bool =
var len = 0
while(len < chunk.length) and (chunk.data[len] != chr(0)): inc len
if(len < 1) or (len > 79): raise PNGFatal("keyword too short or too long")
chunk.paletteName = chunk.data.substr(0, len)
chunk.setPosition(len + 1)
chunk.sampleDepth = chunk.readByte()
if chunk.sampleDepth notin {8, 16}: raise PNGFatal("palette sample depth error")
let remainingLength = (chunk.length - (len + 2))
if chunk.sampleDepth == 8:
if (remainingLength mod 6) != 0: raise PNGFatal("palette length not divisible by 6")
let numSamples = remainingLength div 6
newSeq(chunk.palette, numSamples)
for p in mitems(chunk.palette):
p.red = chunk.readByte()
p.green = chunk.readByte()
p.blue = chunk.readByte()
p.alpha = chunk.readByte()
p.frequency = chunk.readInt16()
else: # chunk.sampleDepth == 16:
if (remainingLength mod 10) != 0: raise PNGFatal("palette length not divisible by 10")
let numSamples = remainingLength div 10
newSeq(chunk.palette, numSamples)
for p in mitems(chunk.palette):
p.red = chunk.readInt16()
p.green = chunk.readInt16()
p.blue = chunk.readInt16()
p.alpha = chunk.readInt16()
p.frequency = chunk.readInt16()
result = true
proc parseChunk(chunk: PNGHist, png: PNG): bool =
if not png.hasChunk(PLTE): raise PNGFatal("Histogram need PLTE")
var plte = PNGPalette(png.getChunk(PLTE))
if plte.palette.len != (chunk.length div 2): raise PNGFatal("invalid histogram length")
newSeq(chunk.histogram, plte.palette.len)
for i in 0..chunk.histogram.high:
chunk.histogram[i] = chunk.readInt16()
result = true
proc parseChunk(chunk: PNGSbit, png: PNG): bool =
let header = PNGHEader(png.getChunk(IHDR))
var expectedLen = 0
case header.colorType
of LCT_GREY: expectedLen = 1
of LCT_RGB: expectedLen = 3
of LCT_PALETTE: expectedLen = 3
of LCT_GREY_ALPHA: expectedLen = 2
of LCT_RGBA: expectedLen = 4
if chunk.length != expectedLen: raise PNGFatal("invalid sBIT length")
var expectedDepth = 8 #LCT_PALETTE
if header.colorType != LCT_PALETTE: expectedDepth = header.bitDepth
for c in chunk.data:
if (ord(c) == 0) or (ord(c) > expectedDepth): raise PNGFatal("invalid sBIT value")
result = true
proc parseChunk(chunk: APNGAnimationControl, png: PNG): bool =
chunk.numFrames = chunk.readInt32()
chunk.numPlays = chunk.readInt32()
result = true
proc parseChunk(chunk: APNGFrameControl, png: PNG): bool =
chunk.sequenceNumber = chunk.readInt32()
chunk.width = chunk.readInt32()
chunk.height = chunk.readInt32()
chunk.xOffset = chunk.readInt32()
chunk.yOffset = chunk.readInt32()
chunk.delayNum = chunk.readInt16()
chunk.delayDen = chunk.readInt16()
chunk.disposeOp = chunk.readByte().APNG_DISPOSE_OP
chunk.blendOp = chunk.readByte().APNG_BLEND_OP
result = true
proc validateChunk(chunk: APNGFrameControl, png: PNG): bool =
let header = PNGHEader(png.getChunk(IHDR))
result = true
result = result and (chunk.xOffset >= 0)
result = result and (chunk.yOffset >= 0)
result = result and (chunk.width > 0)
result = result and (chunk.height > 0)
result = result and (chunk.xOffset + chunk.width <= header.width)
result = result and (chunk.yOffset + chunk.height <= header.height)
proc parseChunk(chunk: APNGFrameData, png: PNG): bool =
chunk.sequenceNumber = chunk.readInt32()
chunk.frameDataPos = chunk.pos
result = true
proc make[T](): T = new(result)
proc createChunk(png: PNG, chunkType: PNGChunkType, data: string, crc: uint32): PNGChunk =
var settings = PNGDecoder(png.settings)
result = nil
case chunkType
of IHDR: result = make[PNGHeader]()
of PLTE: result = make[PNGPalette]()
of IDAT:
if png.apngHasChunk(fcTL): png.firstFrameIsDefaultImage = true
if not png.hasChunk(IDAT): result = make[PNGData]()
else:
var idat = PNGData(png.getChunk(IDAT))
idat.data.add data
return idat
of tRNS: result = make[PNGTrans]()
of bKGD: result = make[PNGBackground]()
of tIME: result = make[PNGTime]()
of pHYs: result = make[PNGPhys]()
of tEXt:
if settings.readTextChunks: result = make[PNGTExt]()
else:
if settings.rememberUnknownChunks: new(result)
of zTXt:
if settings.readTextChunks: result = make[PNGZtxt]()
else:
if settings.rememberUnknownChunks: new(result)
of iTXt:
if settings.readTextChunks: result = make[PNGItxt]()
else:
if settings.rememberUnknownChunks: new(result)
of gAMA: result = make[PNGGamma]()
of cHRM: result = make[PNGChroma]()
of iCCP: result = make[PNGICCProfile]()
of sRGB: result = make[PNGStandarRGB]()
of sPLT: result = make[PNGSPalette]()
of hIST: result = make[PNGHist]()
of sBIT: result = make[PNGSbit]()
of acTL:
# acTL chunk must precede IDAT chunk
# to be recognized as APNG
if not png.hasChunk(IDAT): png.isAPNG = true
result = make[APNGAnimationControl]()
of fcTL: result = make[APNGFrameControl]()
of fdAT: result = make[APNGFrameData]()
else:
if settings.rememberUnknownChunks: new(result)
if result != nil:
result.initChunk(chunkType, data, crc)
proc makePNGDecoder*(): PNGDecoder =
var s: PNGDecoder
new(s)
s.colorConvert = true
s.readTextChunks = false
s.rememberUnknownChunks = false
s.ignoreCRC = false
s.ignoreAdler32 = false
result = s
proc parseChunk(chunk: PNGChunk, png: PNG): bool =
case chunk.chunkType
of IHDR: result = parseChunk(PNGHeader(chunk), png)
of PLTE: result = parseChunk(PNGPalette(chunk), png)
of IDAT: result = parseChunk(PNGData(chunk), png)
of tRNS: result = parseChunk(PNGTrans(chunk), png)
of bKGD: result = parseChunk(PNGBackground(chunk), png)
of tIME: result = parseChunk(PNGTime(chunk), png)
of pHYs: result = parseChunk(PNGPhys(chunk), png)
of tEXt: result = parseChunk(PNGTExt(chunk), png)
of zTXt: result = parseChunk(PNGZtxt(chunk), png)
of iTXt: result = parseChunk(PNGItxt(chunk), png)
of gAMA: result = parseChunk(PNGGamma(chunk), png)
of cHRM: result = parseChunk(PNGChroma(chunk), png)
of iCCP: result = parseChunk(PNGICCProfile(chunk), png)
of sRGB: result = parseChunk(PNGStandarRGB(chunk), png)
of sPLT: result = parseChunk(PNGSPalette(chunk), png)
of hIST: result = parseChunk(PNGHist(chunk), png)
of sBIT: result = parseChunk(PNGSbit(chunk), png)
of acTL: result = parseChunk(APNGAnimationControl(chunk), png)
of fcTL: result = parseChunk(APNGFrameControl(chunk), png)
of fdAT: result = parseChunk(APNGFrameData(chunk), png)
else: result = true
proc validateChunk(chunk: PNGChunk, png: PNG): bool =
case chunk.chunkType
of IHDR: result = validateChunk(PNGHeader(chunk), png)
of IDAT: result = validateChunk(PNGData(chunk), png)
of tIME: result = validateChunk(PNGTime(chunk), png)
of tEXt: result = validateChunk(PNGTExt(chunk), png)
of zTXt: result = validateChunk(PNGZtxt(chunk), png)
of iTXt: result = validateChunk(PNGItxt(chunk), png)
of iCCP: result = validateChunk(PNGICCProfile(chunk), png)
of fcTL: result = validateChunk(APNGFrameControl(chunk), png)
else: result = true
proc parsePNG[T](s: Stream, settings: PNGDecoder): PNG[T] =
var png: PNG[T]
new(png)
png.chunks = @[]
png.apngChunks = @[]
if settings == nil: png.settings = makePNGDecoder()
else: png.settings = settings
let signature = s.readStr(8)
if signature != PNGSignature:
raise PNGFatal("signature mismatch")
while not s.atEnd():
let length = s.readInt32BE()
let chunkType = PNGChunkType(s.readInt32BE())
let data = if length <= 0: "" else: s.readStr(length)
let crc = cast[uint32](s.readInt32BE())
let calculatedCRC = crc32(crc32(0, $chunkType), data)
if calculatedCRC != crc and not PNGDecoder(png.settings).ignoreCRC:
raise PNGFatal("wrong crc for: " & $chunkType)
var chunk = png.createChunk(chunkType, data, crc)
if chunkType != IDAT and chunk != nil:
if not chunk.parseChunk(png): raise PNGFatal("error parse chunk: " & $chunkType)
if not chunk.validateChunk(png): raise PNGFatal("invalid chunk: " & $chunkType)
if chunk != nil:
if chunkType == fcTL or chunkType == fdAT:
png.apngChunks.add APNGFrameChunk(chunk)
else: png.chunks.add chunk
if chunkType == IEND: break
if not png.hasChunk(IHDR): raise PNGFatal("no IHDR found")
if not png.hasChunk(IDAT): raise PNGFatal("no IDAT found")
var header = PNGHeader(png.getChunk(IHDR))
if header.colorType == LCT_PALETTE and not png.hasChunk(PLTE):
raise PNGFatal("expected PLTE not found")
# IDAT get special treatment because it can appear in multiple chunk
var idat = PNGData(png.getChunk(IDAT))
if not idat.parseChunk(png): raise PNGFatal("IDAT parse error")
if not idat.validateChunk(png): raise PNGFatal("bad IDAT")
result = png
proc postProcessScanLines[T, A, B](png: PNG[T]; header: PNGHeader, w, h: int; input: var openArray[A],
output: var openArray[B]) =
# This function converts the filtered-padded-interlaced data
# into pure 2D image buffer with the PNG's colorType.
# Steps:
# *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanLine if bpp < 8)
# *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
# NOTE: the input buffer will be overwritten with intermediate data!
let bpp = header.getBPP()
let bitsPerLine = w * bpp
let bitsPerPaddedLine = ((w * bpp + 7) div 8) * 8
if header.interlaceMethod == IM_NONE:
if(bpp < 8) and (bitsPerLine != bitsPerPaddedLine):
unfilter(input, input, w, h, bpp)
removePaddingBits(output, input, bitsPerLine, bitsPerPaddedLine, h)
else:
# we can immediatly filter into the out buffer, no other steps needed
unfilter(output, input, w, h, bpp)
else: # interlace_proc is 1 (Adam7)
var pass: PNGPass
adam7PassValues(pass, w, h, bpp)
for i in 0..6:
unfilter(input.toOpenArray(pass.paddedStart[i], input.len-1),
input.toOpenArray(pass.filterStart[i], input.len-1),
pass.w[i], pass.h[i], bpp
)
# TODO: possible efficiency improvement:
# if in this reduced image the bits fit nicely in 1 scanLine,
# move bytes instead of bits or move not at all