-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.monkey
605 lines (457 loc) · 18.7 KB
/
decode.monkey
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
Strict
Public
' Friends:
Friend regal.png.image
Friend regal.png.util
' Imports (Public):
Import config
' Imports (Private):
Private
Import util
Import header
Import image
Import imageview
Import regal.inflate
'#If REGAL_PNG_SAFE
Import regal.util.memory
'#End
Public
' Classes:
Class PNGDecodeState Implements PNGEntity Final
Public
' Functions:
' This retrieves a color from 'line_view' at 'channel' and optionally scales it to 'scale_max'.
' If 'REGAL_PNG_DISABLE_GAMMA_CORRECTION' is defined, the 'gamma' argument does nothing.
Function GetColor:Int(line_view:ImageView, channel:Int, big_endian:Bool, scaled:Bool, gamma_enabled:Bool, gamma:Float, scale_max:Int=$FF) ' scale_max:Float
Local value:= line_view.Get(channel, big_endian)
If (scaled And value > 0) Then
Local view_max:= line_view.BitMask
If (Not gamma_enabled) Then
Return ScaleColor(value, view_max, scale_max)
Else
Return Int(ScaleColorWithGamma(value, view_max, scale_max, gamma))
Endif
Endif
Return value
End
Function ColorToSample:Float(channel_data:Int, channel_max:Int)
Return (Float(channel_data) / Float(channel_max))
End
Function SampleToColor:Int(sample:Float, channel_max:Int)
Return Int(ScaleSampleToColor(sample, Float(channel_max)))
End
' This performs a linear scale of 'value' using the maximum color-values provided.
Function ScaleColor:Int(value:Int, input_max:Int, output_max:Int)
Return Min(Int(Float(value) * (Float(output_max) / Float(input_max))), output_max)
End
' This attempts to accurately scale 'value' according to 'view_max' and 'scale_max' while applying 'gamma'.
Function ScaleColorWithGamma:Float(value:Int, view_max:Int, scale_max:Int, gamma:Float)
Local sample:= (Float(value) / Float(view_max))
Local display_input:= ApplyGammaToSample(sample, gamma)
Local framebuf_sample:= ScaleSampleToColor(display_input, scale_max)
Return framebuf_sample
End
Function ScaleSampleToColor:Float(sample:Float, channel_max:Float)
Return Floor((sample * channel_max) + 0.5)
End
Function ApplyGammaToSample:Float(sample:Float, gamma:Float)
Return Pow(sample, (1.0 / gamma)) ' (gamma * display_exponent)
End
Function ApplyGammaToColor:Int(color_data:Int, color_channel_max:Int, gamma:Float)
Local sample:= ColorToSample(color_data, color_channel_max)
sample = ApplyGammaToSample(sample, gamma)
Return SampleToColor(sample, color_channel_max)
End
' NOTE: Gamma isn't applied to alpha channels by design.
Function ApplyGammaToPalette:Void(palette:Int[], gamma:Float, image_type:Int=PNG_IMAGE_TYPE_RGBA)
Local color_channel_max:= GetChannelMaxByType(image_type)
For Local index:= 0 Until palette.Length
Local color:= palette[index]
Local r:= DecodeColor_R(color)
Local g:= DecodeColor_G(color)
Local b:= DecodeColor_B(color)
Local a:= DecodeColor_A(color)
r = ApplyGammaToColor(r, color_channel_max, gamma)
g = ApplyGammaToColor(g, color_channel_max, gamma)
b = ApplyGammaToColor(b, color_channel_max, gamma)
palette[index] = EncodeColor(r, g, b, a)
Next
End
' NOTE: Gamma is never applied to alpha channels by design.
' The return-value of this function indicates if the operation was successful.
Function TransferPixel:Bool(image_buffer:DataBuffer, line_view:ImageView, image_position:Int, channel_position:Int, color_type:Int, scale_colors:Bool=True, palette_data:Int[]=[], gamma:Float=1.0)
Local gamma_enabled:= GammaEnabled()
Select (color_type)
Case PNG_COLOR_TYPE_GRAYSCALE
Local gray:= GetColor(line_view, channel_position, True, scale_colors, gamma_enabled, gamma)
image_buffer.PokeInt(image_position, EncodeColor(gray, gray, gray))
Case PNG_COLOR_TYPE_TRUECOLOR
Local r:= GetColor(line_view, channel_position, False, scale_colors, gamma_enabled, gamma)
Local g:= GetColor(line_view, (channel_position + 1), False, scale_colors, gamma_enabled, gamma)
Local b:= GetColor(line_view, (channel_position + 2), False, scale_colors, gamma_enabled, gamma)
image_buffer.PokeInt(image_position, EncodeColor(r, g, b))
Case PNG_COLOR_TYPE_INDEXED
Local color_index:= line_view.Get(channel_position)
image_buffer.PokeInt(image_position, palette_data[color_index])
Case PNG_COLOR_TYPE_GRAYSCALE_ALPHA
Local gray:= GetColor(line_view, (channel_position), True, scale_colors, gamma_enabled, gamma)
Local alpha:= GetColor(line_view, (channel_position + 1), True, scale_colors, False, gamma)
image_buffer.PokeInt(image_position, EncodeColor(gray, gray, gray, alpha))
Case PNG_COLOR_TYPE_TRUECOLOR_ALPHA
Local r:= GetColor(line_view, channel_position, False, scale_colors, gamma_enabled, gamma)
Local g:= GetColor(line_view, (channel_position + 1), False, scale_colors, gamma_enabled, gamma)
Local b:= GetColor(line_view, (channel_position + 2), False, scale_colors, gamma_enabled, gamma)
Local a:= GetColor(line_view, (channel_position + 3), False, scale_colors, False, gamma)
image_buffer.PokeInt(image_position, EncodeColor(r, g, b, a))
Default
' The color-type specified is unsupported.
Return False
End
' Return the default response.
Return True
End
' Constructor(s):
Method New()
' Nothing so far.
End
' Destructor(s):
' This routine is currently experimental.
Method Close:Void()
Self.inflate_context = Null
Self.inflate_session = Null
End
' Methods:
' This reads the identity of a chunk; represented by the 'ChunkName' property.
' The return-value is the size of the subsequent chunk-segment.
Method ReadChunkHeader:Int(input:Stream)
Self.chunk_length = input.ReadInt()
Self.chunk_type = input.ReadString(PNG_CHUNK_IDENT_LENGTH, "ascii")
Return Self.chunk_length
End
' This initializes the internal scan-line buffer.
Method InitializeLineBuffer:Bool(header:PNGHeader)
#If REGAL_PNG_SAFE
If (Self.line_buffer <> Null) Then
Return False
Endif
#End
' Example of line layout for indexed PNG:
' FILTER | 0 2 0 0 1 1 1 0 0 2 0
' FILTER | 0 2 0 1 0 0 0 1 0 2 0
' FILTER | 3 2 0 0 1 1 1 0 0 2 3
' Where 'FILTER' is a one-byte filtering mode referenced
' in the header, but still available on each line.
Local line_length:= header.LineLength
' Allocate a raw image buffer to store decoded output from the data-stream.
' The size of this buffer is the maximum number of bytes required
' to store two lines of pixels from the data-stream described by 'header'.
Self.line_buffer = New DataBuffer(line_length * 2)
'#If REGAL_PNG_SAFE Or CONFIG = "debug"
SetBuffer(Self.line_buffer, 0)
'#End
' Create an image-view of our line-buffer.
Self.line_view = New ImageView(Self.line_buffer, header.ColorChannels, header.TotalDepth, line_length)
#If REGAL_PNG_SAFE
Return (Self.line_buffer <> Null) ' And (Self.line_buffer.Length > 0)
#Else
Return True
#End
End
Method InitializePaletteBuffer:Bool(chunk_length:Int)
' Ensure this chunk's length is divisible by 3 (RGB):
If ((chunk_length Mod 3) <> 0) Then
Return False
Endif
Self.Palette(New Int[chunk_length / 3], False)
' Return the default response.
Return True ' Self.palette_found
End
' This applies the contents of 'data' to the internal palette buffer.
' NOTE: If palettes aren't used in the decoding process, this will fail.
' The return-value of this method indicates if the desired operation took place.
Method PatchPalette:Bool(data:Int[], count:Int, data_offset:Int=0, internal_offset:Int=0)
If ((internal_offset+count) > Self.palette_data.Length Or (data_offset + count) > data.Length) Then
Return False
Endif
For Local index:= 0 Until count
Self.palette_data[(internal_offset + index)] = data[(data_offset + index)]
Next
' Return the default response.
Return True
End
Method PatchPalette:Bool(data:Int[])
Return PatchPalette(data, data.Length)
End
Method ApplyGammaToPalette:Void(image_type:Int)
ApplyGammaToPalette(Self.palette_data, Self.gamma, image_type)
End
' Decoding routines:
' This decodes the raw contents of a line from the inflation-stream.
' The 'file' argument must reference a valid 'PNG' object.
' The return-value of this command is an inflation response-code.
Method DecodeLine:Int(file:PNG, line_view:ImageView, line_length:Int) ' header:PNGHeader
Local inflate_response:Int
Local line_stream:= Self.inflate_session.destination
Local line_buffer:= line_view.Data ' line_stream.Data ' Self.line_buffer
Local start_position:= line_stream.Position
' Not the most efficient approach, but it works:
If (start_position = line_stream.Length) Then
' Make a copy of the second line and place it at the beginning of the buffer.
line_buffer.CopyBytes(line_length, line_buffer, 0, line_length)
' Now that the previous line has been copied to the beginning, seek back
' to the middle of the stream so that the current line may be placed there.
start_position = line_stream.Seek(line_length)
' Update the line-view to begin at the current line.
'line_view.Offset = line_length
Endif
' Get the filtering type from the input-stream, then fix the output-position:
inflate_response = InflateBytes(line_stream, Self, PNG_FILTER_HEADER_LENGTH)
' Check if we should continue:
If (inflate_response <> INF_OK) Then
Return inflate_response
Endif
' Load the filter-type from the line-stream.
'Self.filter_type = (line_stream.ReadByte() & $FF)
Self.filter_type = (line_buffer.PeekByte(line_view.Offset) & $FF)
' Seek back to where we were.
line_stream.Seek(start_position)
' Read a line from the data-stream:
While (line_stream.Position < (start_position + line_length))
inflate_response = Inflate_Checksum(Self.inflate_context, Self.inflate_session, True) ' Inflate
' Check if we're not continuing the line:
If (inflate_response <> INF_OK) Then
Exit ' Return inflate_response
Endif
Wend
Return inflate_response
End
' The return-value of this command indicates if the line was
' filtered according to the filtering type specified.
Method FilterLine:Bool(line_view:ImageView, line_width:Int, line_length:Int, filter_type:Int, filter_method:Int=PNG_FILTER_METHOD_DEFAULT)
Local line_buffer:= line_view.Data
Local offset:= line_view.Offset
Local stride:= line_view.DepthInBytes
' Check which filtering type was specified:
Select (filter_type)
Case PNG_FILTER_TYPE_NONE
Return True
Case PNG_FILTER_TYPE_SUB
Return FilterLine_Sub(line_buffer, line_length, offset, stride)
Case PNG_FILTER_TYPE_UP
Return FilterLine_Up(line_buffer, line_length, offset, stride)
Case PNG_FILTER_TYPE_AVERAGE
Return FilterLine_Average(line_buffer, line_length, offset, stride)
Case PNG_FILTER_TYPE_PAETH
Return FilterLine_Paeth(line_buffer, line_length, offset, stride)
End Select
' Return the default response.
Return False
End
' The first filter-type using filter-method zero.
Method FilterLine_Sub:Bool(line_buffer:DataBuffer, line_length:Int, view_offset:Int, pixel_stride:Int)
Local left_position:= view_offset
For Local I:= pixel_stride Until line_length
Local position:= (view_offset + I)
Local x:= (line_buffer.PeekByte(position) & $FF) ' Current
Local a:= (line_buffer.PeekByte(left_position) & $FF) ' Left
line_buffer.PokeByte(position, ((x + a) & $FF))
left_position += 1
Next
Return True
End
' The second filter-type using filter-method zero.
Method FilterLine_Up:Bool(line_buffer:DataBuffer, line_length:Int, view_offset:Int, pixel_stride:Int)
For Local I:= 0 Until line_length
Local position:= (view_offset + I)
Local x:= (line_buffer.PeekByte(position) & $FF) ' Current
Local b:= (line_buffer.PeekByte(I) & $FF) ' Up
line_buffer.PokeByte(position, ((x + b) & $FF))
Next
Return True
End
' The third filter-type using filter-method zero.
Method FilterLine_Average:Bool(line_buffer:DataBuffer, line_length:Int, view_offset:Int, pixel_stride:Int)
For Local I:= 0 Until line_length
Local position:= (view_offset + I)
Local x:= (line_buffer.PeekByte(position) & $FF) ' Current
Local a:Int ' Left
Local left_offset:= (I - pixel_stride)
If (left_offset < 0) Then
a = 0
Else
a = (line_buffer.PeekByte(left_offset + view_offset) & $FF)
Endif
Local b:= (line_buffer.PeekByte(I) & $FF) ' Up
line_buffer.PokeByte(position, (x + ((a + b) / 2)) & $FF) ' Shr 1
Next
Return True
End
' The fourth and final filter-type defined for filter-method zero.
Method FilterLine_Paeth:Bool(line_buffer:DataBuffer, line_length:Int, view_offset:Int, pixel_stride:Int)
For Local I:= 0 Until line_length
Local position:= (view_offset + I)
Local x:= (line_buffer.PeekByte(position) & $FF) ' Current
Local a:Int
Local c:Int
Local left_offset:= (I - pixel_stride)
If (left_offset < 0) Then
a = 0
c = 0
Else
a = (line_buffer.PeekByte(view_offset + left_offset) & $FF) ' Left
c = (line_buffer.PeekByte(left_offset) & $FF) ' Top-Left
Endif
Local b:= (line_buffer.PeekByte(I) & $FF) ' Up
Local p:= (a + b - c)
Local pa:= Abs(p - a)
Local pb:= Abs(p - b)
Local pc:= Abs(p - c)
Local pr:Int
If (pa <= pb And pa <= pc) Then
pr = a
Elseif (pb <= pc) Then
pr = b
Else
pr = c
Endif
line_buffer.PokeByte(position, ((x + pr) & $FF))
Next
Return True
End
' This transfers the contents of 'line_view' into 'image_buffer'.
Method TransferLine:Void(image_buffer:DataBuffer, line_view:ImageView, line_width:Int, pixel_stride:Int, color_type:Int, scale_colors:Bool) ' palette_data:Int[]
Local color_channels:= line_view.Channels
Local image_position:= ((line_width * Self.current_height) * pixel_stride)
Local channel_position:= 0
For Local x:= 0 Until line_width
TransferPixel(image_buffer, line_view, image_position, channel_position, color_type, scale_colors, palette_data, gamma) ' Self.palette_data ' Self.gamma
image_position += pixel_stride
channel_position += color_channels
Next
End
' Properties:
' This specifies if the IHDR chunk has been loaded.
' To view the header's contents, see 'Header'.
Method HeaderFound:Bool() Property
Return Self.header_found
End
#Rem
This specifies if all valid image data has been loaded.
This does not take final image-creation into account,
only that all raw data has been retrieved inflated correctly.
By definition, if this property reports 'True',
'ImageDataFound' must also report 'True'.
#End
Method ImageDataComplete:Bool() Property
Return Self.image_data_complete
End
' This specifies if at least one IDAT chunk has been loaded.
Method ImageDataFound:Bool() Property
Return Self.image_data_found
End
' This specifies if a PLTE was loaded
Method PaletteFound:Bool() Property
Return Self.palette_found
End
Method GammaFound:Bool() Property
Return Self.gamma_found
End
Method EndFound:Bool() Property
Return Self.end_found
End
' The length of the current chunk. (Same as the return-value of 'ReadChunkHeader')
Method ChunkLength:Int() Property
Return Self.chunk_length
End
' The name (ASCII String) of the current (Last acquired) chunk.
Method ChunkName:String() Property
Return Self.chunk_type ' chunk_name
End
' The integral equivalent of 'ChunkName'.
Method ChunkType:Int() Property
Local name:= Self.ChunkName
Return EncodeInt(name[0], name[1], name[2], name[3])
End
Method Gamma:Float() Property
Return Self.gamma
End
Method Gamma:Void(input:Float, __custom:Bool=True) Property
#If Not REGAL_PNG_DISABLE_GAMMA_CORRECTION
Self.gamma = input
Self.gamma_found = True
Self.custom_gamma = __custom ' True
#Else
' Throw ...
#End
End
' This represents the current palette data.
' If palette data has yet to be provided,
' this will supply an empty array.
Method Palette:Int[]() Property ' UInt[]
Return Self.palette_data
End
' This is used to manually assign/override the internal palette buffer.
' The palette data specified must be at least as large as the current palette buffer.
' For variable palette sizes, you must patch the existing buffer using 'PatchPalette'.
Method Palette:Bool(data:Int[], __custom:Bool=True) Property
' Empty palettes are automatically invalid:
If (data.Length = 0) Then
Return False
Endif
#If REGAL_PNG_SAFE
If (data.Length < Self.palette_data.Length) Then
Return False
Endif
#End
Self.palette_data = data
Self.palette_found = True ' (data.Length > 0) ' (Self.palette_data.Length > 0)
Self.custom_palette = __custom ' True
Return True
End
Private
' Global variable(s):
Global __inf_ctx:= New InfContext()
Protected
' Fields:
#Rem
This stores the current Y coordinate in the targeted 'PNG' object's image-buffer.
This variable is stored here in order to preserve its state between multiple decode-passes.
#End
Field current_height:Int
#Rem
The last known filter-type associated with
the current segment of the line-buffer.
This should not be confused with 'PNGHeader.filter_method',
which specifies a filtering method for early error detection.
#End
Field filter_type:Int
' Chunk meta-data:
Field chunk_length:Int
Field chunk_type:String ' chunk_name
' Flags:
Field header_found:Bool
Field image_data_found:Bool
Field image_data_complete:Bool
Field palette_found:Bool
Field gamma_found:Bool
Field end_found:Bool
Field custom_palette:Bool
Field custom_gamma:Bool
' Image-data:
' The gamma value used when converting color-data.
Field gamma:Float = 1.0
' An array of integers representing RGB(A) colors loaded from
' a required PLTE chunk when using 'COLOR_TYPE_INDEXED'.
Field palette_data:Int[] ' UInt[]
' Output:
' A buffer containing the current line-data last taken from a decompression stream.
' NOTE: This buffer also contains the filter-type header before the image-data.
Field line_buffer:DataBuffer
' A view of 'line_buffer' offset by the filter-type header.
Field line_view:ImageView
' Inflation functionality:
' This stores a reference to the shared inflation-session used to decode IDAT blocks.
Field inflate_session:InfSession
' This stores a reference to a global/shared inflation context.
Field inflate_context:= __inf_ctx
End