-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
gid-decoding_png.adb
1620 lines (1469 loc) · 57.8 KB
/
gid-decoding_png.adb
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
-- A PNG stream is made of several "chunks" (see type PNG_Chunk_tag).
-- The image itself is contained in the IDAT chunk(s).
--
-- Steps for decoding an image (step numbers are from the ISO standard):
--
-- 10: Inflate deflated data; at each output buffer (slide),
-- process with step 9.
-- 9: Read filter code (row begin), or unfilter bytes, go with step 8
-- 8: Display pixels these bytes represent;
-- eventually, locate the interlaced image current point
--
-- Reference: Portable Network Graphics (PNG) Specification (Third Edition)
-- W3C Recommendation 21 September 2023
-- http://www.w3.org/TR/PNG/
--
with GID.Buffering,
GID.Decoding_PNG.Huffman;
with Ada.Text_IO;
package body GID.Decoding_PNG is
use Interfaces;
generic
type Number is mod <>;
procedure Big_Endian_Number
(from : in out Input_Buffer;
n : out Number);
pragma Inline (Big_Endian_Number);
procedure Big_Endian_Number
(from : in out Input_Buffer;
n : out Number)
is
b : U8;
begin
n := 0;
for i in 1 .. Number'Size / 8 loop
Buffering.Get_Byte (from, b);
n := n * 256 + Number (b);
end loop;
end Big_Endian_Number;
procedure Big_Endian is new Big_Endian_Number (U16);
procedure Big_Endian is new Big_Endian_Number (U32);
function Chunk_Info (kind : PNG_Chunk_Tag) return String is
(case kind is
when IHDR => "Image Header", -- 11.2.1
when PLTE => "Palette", -- 11.2.2
when IDAT => "Image Data", -- 11.2.3
when IEND => "Image Trailer", -- 11.2.4
when tEXt => "Textual Data", -- 11.3.3.2
when acTL => "Animation Control Chunk", -- 11.3.6.1 (APNG)
when fcTL => "Frame Control Chunk", -- 11.3.6.2 (APNG)
when fdAT => "Frame Data Chunk", -- 11.3.6.3 (APNG)
when unknown_ancillary_chunk =>
"(unknown)",
when others =>
"");
procedure Read_Chunk_Header
(image : in out Image_Descriptor; ch : out Chunk_Header)
is
str4 : String (1 .. 4);
b : U8;
begin
Big_Endian (image.buffer, ch.length);
for i in str4'Range loop
Buffering.Get_Byte (image.buffer, b);
str4 (i) := Character'Val (b);
end loop;
begin
ch.kind := PNG_Chunk_Tag'Value (str4);
exception
-- 13.1 Error handling
when Constraint_Error =>
if str4 (1) in 'a' .. 'z' then
-- "Encountering an unknown ancillary chunk is never an error.
-- The chunk can simply be ignored."
ch.kind := unknown_ancillary_chunk;
else
-- Anything else than 'a' .. 'z':
-- an unknown critical chunk ('A' .. 'Z'), or corrupt data.
-- "Encountering an unknown critical chunk is a fatal condition"
raise error_in_image_data with
"PNG chunk is unknown: " &
Character'Pos (str4 (1))'Image &
Character'Pos (str4 (2))'Image &
Character'Pos (str4 (3))'Image &
Character'Pos (str4 (4))'Image &
" (" & str4 & "), or PNG data is corrupt";
end if;
end;
if some_trace then
Ada.Text_IO.Put_Line
("Chunk [" & str4 & "], length:" & ch.length'Image &
" " & Chunk_Info (ch.kind));
end if;
end Read_Chunk_Header;
----------
-- Load --
----------
procedure Load
(image : in out Image_Descriptor;
next_frame : out Ada.Calendar.Day_Duration)
is
ch : Chunk_Header;
----------------------
-- Load_specialized --
----------------------
generic
-- These values are invariant through the whole picture,
-- so we can make them generic parameters. As a result, all
-- "if", "case", etc. using them at the center of the decoding
-- are optimized out at compile-time.
interlaced : Boolean;
png_bits_per_pixel : Positive;
bytes_to_unfilter : Positive;
-- ^ amount of bytes to unfilter at a time
-- = Integer'Max(1, bits_per_pixel / 8);
subformat_id : Natural;
procedure Load_specialized;
--
procedure Load_specialized is
frame_width : constant Positive := Positive (image.PNG_stuff.frame_width);
frame_height : constant Positive := Positive (image.PNG_stuff.frame_height);
x_offset : constant Natural := Natural (image.PNG_stuff.x_offset);
y_offset : constant Natural := Natural (image.PNG_stuff.y_offset);
-- The target Y coordinates are bottom-up (0 is the absolute bottom).
frame_top : constant Natural := Positive (image.height) - 1 - y_offset;
subtype Mem_row_bytes_array is Byte_Array (0 .. frame_width * 8);
--
mem_row_bytes : array (0 .. 1) of Mem_row_bytes_array;
-- We need to memorize two image rows, for un-filtering
curr_row : Natural := 1;
-- either current is 1 and old is 0, or the reverse
subtype X_range is Integer range -1 .. frame_width - 1;
subtype Y_range is Integer range 0 .. frame_height - 1;
-- X position -1 is for the row's filter methode code
-- Coordinates are relative to the frame's corner.
x : X_range := X_range'First;
y : Y_range := Y_range'First;
x_max : X_range; -- for non-interlaced images: = X_range'Last
y_max : Y_range; -- for non-interlaced images: = Y_range'Last
pass : Positive range 1 .. 7 := 1;
--------------------------
-- ** 9: Unfiltering ** --
--------------------------
-- http://www.w3.org/TR/PNG/#9Filters
type Filter_method_0 is (None, Sub, Up, Average, Paeth);
current_filter : Filter_method_0;
procedure Unfilter_bytes
(f : in Byte_Array; -- filtered
u : out Byte_Array) -- unfiltered
is
pragma Inline (Unfilter_bytes);
-- Byte positions (f is the byte to be unfiltered):
--
-- c b
-- a f
a, b, c, p, pa, pb, pc, pr : Integer;
j : Integer := 0;
begin
if full_trace and then x = 0 then
if y = 0 then
Ada.Text_IO.New_Line;
end if;
Ada.Text_IO.Put_Line
("row" & y'Image & ": filter= " & current_filter'Image);
end if;
--
-- !! find a way to have f99n0g04.png decoded correctly...
-- seems a filter issue.
--
case current_filter is
when None =>
-- Recon(x) = Filt(x)
u := f;
when Sub =>
-- Recon(x) = Filt(x) + Recon(a)
if x > 0 then
for i in f'Range loop
u (u'First + j) := f (i) + mem_row_bytes (curr_row)((x - 1) * bytes_to_unfilter + j);
j := j + 1;
end loop;
else
u := f;
end if;
when Up =>
-- Recon(x) = Filt(x) + Recon(b)
if y > 0 then
for i in f'Range loop
u (u'First + j) := f (i) + mem_row_bytes (1 - curr_row)(x * bytes_to_unfilter + j);
j := j + 1;
end loop;
else
u := f;
end if;
when Average =>
-- Recon(x) = Filt(x) + floor((Recon(a) + Recon(b)) / 2)
for i in f'Range loop
if x > 0 then
a := Integer (mem_row_bytes (curr_row)((x - 1) * bytes_to_unfilter + j));
else
a := 0;
end if;
if y > 0 then
b := Integer (mem_row_bytes (1 - curr_row)(x * bytes_to_unfilter + j));
else
b := 0;
end if;
u (u'First + j) := U8 ((Integer (f (i)) + (a + b) / 2) mod 256);
j := j + 1;
end loop;
when Paeth =>
-- Recon(x) = Filt(x) + PaethPredictor(Recon(a), Recon(b), Recon(c))
for i in f'Range loop
if x > 0 then
a := Integer (mem_row_bytes (curr_row)((x - 1) * bytes_to_unfilter + j));
else
a := 0;
end if;
if y > 0 then
b := Integer (mem_row_bytes (1 - curr_row)(x * bytes_to_unfilter + j));
else
b := 0;
end if;
if x > 0 and y > 0 then
c := Integer (mem_row_bytes (1 - curr_row)((x - 1) * bytes_to_unfilter + j));
else
c := 0;
end if;
p := a + b - c;
pa := abs (p - a);
pb := abs (p - b);
pc := abs (p - c);
if pa <= pb and then pa <= pc then
pr := a;
elsif pb <= pc then
pr := b;
else
pr := c;
end if;
u (u'First + j) := f (i) + U8 (pr);
j := j + 1;
end loop;
end case;
j := 0;
for i in u'Range loop
mem_row_bytes (curr_row)(x * bytes_to_unfilter + j) := u (i);
j := j + 1;
end loop;
-- if u'Length /= bytes_to_unfilter then
-- raise Constraint_Error;
-- end if;
end Unfilter_bytes;
filter_stat : array (Filter_method_0) of Natural := (others => 0);
----------------------------------------------
-- ** 8: Interlacing and pass extraction ** --
----------------------------------------------
-- http://www.w3.org/TR/PNG/#8Interlace
-- Output bytes from decompression
--
procedure Output_uncompressed (
data : in Byte_Array;
reject : out Natural
-- amount of bytes to be resent here next time,
-- in order to have a full multi-byte pixel
)
is
-- Display of pixels coded on 8 bits per channel in the PNG stream
procedure Out_Pixel_8 (br, bg, bb, ba : U8) is
pragma Inline (Out_Pixel_8);
function Times_257 (x : Primary_Color_Range) return Primary_Color_Range
is
(16 * (16 * x) + x) with Inline; -- This is 257 * x, = 16#0101# * x
-- Numbers are 8-bit -> no OA warning at instantiation.
-- Returns x if type Primary_Color_Range is mod 2**8.
begin
case Primary_Color_Range'Modulus is
when 256 =>
Put_Pixel
(Primary_Color_Range (br),
Primary_Color_Range (bg),
Primary_Color_Range (bb),
Primary_Color_Range (ba));
when 65_536 =>
Put_Pixel
(Times_257 (Primary_Color_Range (br)),
Times_257 (Primary_Color_Range (bg)),
Times_257 (Primary_Color_Range (bb)),
Times_257 (Primary_Color_Range (ba)));
-- Times_257 makes max intensity FF go to FFFF
when others =>
raise invalid_primary_color_range
with "PNG: color range not supported";
end case;
end Out_Pixel_8;
procedure Out_Pixel_Palette (ix : U8) is
pragma Inline (Out_Pixel_Palette);
color_idx : constant Natural := Integer (ix);
begin
Out_Pixel_8 (
image.palette (color_idx).red,
image.palette (color_idx).green,
image.palette (color_idx).blue,
255
);
end Out_Pixel_Palette;
-- Display of pixels coded on 16 bits per channel in the PNG stream
procedure Out_Pixel_16 (br, bg, bb, ba : U16) is
pragma Inline (Out_Pixel_16);
begin
case Primary_Color_Range'Modulus is
when 256 =>
Put_Pixel (
Primary_Color_Range (br / 256),
Primary_Color_Range (bg / 256),
Primary_Color_Range (bb / 256),
Primary_Color_Range (ba / 256)
);
when 65_536 =>
Put_Pixel (
Primary_Color_Range (br),
Primary_Color_Range (bg),
Primary_Color_Range (bb),
Primary_Color_Range (ba)
);
when others =>
raise invalid_primary_color_range with "PNG: color range not supported";
end case;
end Out_Pixel_16;
procedure Inc_XY is
pragma Inline (Inc_XY);
xm, ym : Integer;
begin
if x < x_max then
x := x + 1;
if interlaced then
-- Position of pixels depending on pass:
--
-- 1 6 4 6 2 6 4 6
-- 7 7 7 7 7 7 7 7
-- 5 6 5 6 5 6 5 6
-- 7 7 7 7 7 7 7 7
-- 3 6 4 6 3 6 4 6
-- 7 7 7 7 7 7 7 7
-- 5 6 5 6 5 6 5 6
-- 7 7 7 7 7 7 7 7
case pass is
when 1 =>
Set_X_Y (x_offset + x * 8, frame_top - y * 8);
when 2 =>
Set_X_Y (x_offset + 4 + x * 8, frame_top - y * 8);
when 3 =>
Set_X_Y (x_offset + x * 4, frame_top - 4 - y * 8);
when 4 =>
Set_X_Y (x_offset + 2 + x * 4, frame_top - y * 4);
when 5 =>
Set_X_Y (x_offset + x * 2, frame_top - 2 - y * 4);
when 6 =>
Set_X_Y (x_offset + 1 + x * 2, frame_top - y * 2);
when 7 =>
null; -- Nothing to to, pixels are contiguous
end case;
end if;
else
-- New row
x := X_range'First;
if y < y_max then
y := y + 1;
curr_row := 1 - curr_row; -- Swap row index for filtering
if not interlaced then
Feedback ((y * 100) / frame_height);
end if;
if x_offset /= 0 then
Set_X_Y (x_offset, frame_top - y);
end if;
elsif interlaced then -- Last row has beed displayed
while pass < 7 loop
pass := pass + 1;
y := 0;
case pass is
when 1 =>
null;
when 2 =>
xm := (frame_width + 3) / 8 - 1;
ym := (frame_height + 7) / 8 - 1;
when 3 =>
xm := (frame_width + 3) / 4 - 1;
ym := (frame_height + 3) / 8 - 1;
when 4 =>
xm := (frame_width + 1) / 4 - 1;
ym := (frame_height + 3) / 4 - 1;
when 5 =>
xm := (frame_width + 1) / 2 - 1;
ym := (frame_height + 1) / 4 - 1;
when 6 =>
xm := (frame_width) / 2 - 1;
ym := (frame_height + 1) / 2 - 1;
when 7 =>
xm := frame_width - 1;
ym := frame_height / 2 - 1;
end case;
if xm >= 0 and xm <= X_range'Last and ym in Y_range then
-- This pass is not empty (otherwise, we will continue
-- to the next one, if any).
x_max := xm;
y_max := ym;
exit;
end if;
end loop;
end if;
end if;
end Inc_XY;
uf : Byte_Array (0 .. 15); -- Unfiltered bytes for a pixel
w1, w2 : U16;
i : Integer;
begin
if some_trace then
Ada.Text_IO.Put_Line
("[Output Uncompressed]; frame: " &
frame_width'Image & " x " & frame_height'Image);
end if;
-- Depending on the row size, bpp, etc., we can have
-- several rows, or less than one, being displayed
-- with the present uncompressed data batch.
--
i := data'First;
if i > data'Last then
reject := 0;
return; -- Data is empty, do nothing
end if;
--
-- Main loop over data
--
loop
if x = X_range'First then -- Pseudo-column for filter method
exit when i > data'Last;
begin
current_filter := Filter_method_0'Val (data (i));
if some_trace then
filter_stat (current_filter) := filter_stat (current_filter) + 1;
end if;
exception
when Constraint_Error =>
raise error_in_image_data with
"PNG: wrong filter code, row #" & y'Image &
" code:" & data (i)'Image;
end;
if interlaced then
case pass is
when 1 .. 6 =>
null; -- Set_X_Y is called for each pixel
when 7 =>
Set_X_Y (x_offset, frame_top - 1 - y * 2);
end case;
else
Set_X_Y (x_offset, frame_top - y);
end if;
i := i + 1;
else -- Normal pixel
--
-- We quit the loop if all data has been used
-- (except for a possible incomplete pixel)
exit when i > data'Last - (bytes_to_unfilter - 1);
-- NB, for per-channel bpp < 8:
-- 7.2 Scanlines - some low-order bits of the
-- last byte of a scanline may go unused.
case subformat_id is
when 0 =>
-----------------------
-- Type 0: Greyscale --
-----------------------
case png_bits_per_pixel is
when 1 | 2 | 4 =>
Unfilter_bytes (data (i .. i), uf (0 .. 0));
i := i + 1;
declare
b : U8;
shift : Integer := 8 - png_bits_per_pixel;
max : constant U8 := U8 (Shift_Left (Unsigned_32'(1), png_bits_per_pixel) - 1);
-- Scaling factor to obtain the correct color value on a 0..255 range.
-- The division is exact in all cases (bpp=8,4,2,1),
-- since 255 = 3 * 5 * 17 and max = 255, 15, 3 or 1.
-- This factor ensures: 0 -> 0, max -> 255
factor : constant U8 := 255 / max;
begin
-- Loop through the number of pixels in this byte:
for k in reverse 1 .. 8 / png_bits_per_pixel loop
b := (max and U8 (Shift_Right (Unsigned_8 (uf (0)), shift))) * factor;
shift := shift - png_bits_per_pixel;
Out_Pixel_8 (b, b, b, 255);
exit when x >= x_max or k = 1;
Inc_XY;
end loop;
end;
when 8 =>
-- NB: with bpp as generic param, this case could be merged
-- into the general 1,2,4[,8] case without loss of performance
-- if the compiler is smart enough to simplify the code, given
-- the value of bits_per_pixel.
-- But we let it here for two reasons:
-- 1) a compiler might be not smart enough
-- 2) it is a very simple case, perhaps helpful for
-- understanding the algorithm.
Unfilter_bytes (data (i .. i), uf (0 .. 0));
i := i + 1;
Out_Pixel_8 (uf (0), uf (0), uf (0), 255);
when 16 =>
Unfilter_bytes (data (i .. i + 1), uf (0 .. 1));
i := i + 2;
w1 := U16 (uf (0)) * 256 + U16 (uf (1));
Out_Pixel_16 (w1, w1, w1, 65535);
when others =>
null; -- undefined in PNG standard
end case;
when 2 =>
-----------------
-- Type 2: RGB --
-----------------
case png_bits_per_pixel is
when 24 =>
Unfilter_bytes (data (i .. i + 2), uf (0 .. 2));
i := i + 3;
Out_Pixel_8 (uf (0), uf (1), uf (2), 255);
when 48 =>
Unfilter_bytes (data (i .. i + 5), uf (0 .. 5));
i := i + 6;
Out_Pixel_16 (
U16 (uf (0)) * 256 + U16 (uf (1)),
U16 (uf (2)) * 256 + U16 (uf (3)),
U16 (uf (4)) * 256 + U16 (uf (5)),
65_535
);
when others =>
null;
end case;
when 3 =>
------------------------------
-- Type 3: RGB with palette --
------------------------------
Unfilter_bytes (data (i .. i), uf (0 .. 0));
i := i + 1;
case png_bits_per_pixel is
when 1 | 2 | 4 =>
declare
shift : Integer := 8 - png_bits_per_pixel;
max : constant U8 := U8 (Shift_Left (Unsigned_32'(1), png_bits_per_pixel) - 1);
begin
-- Loop through the number of pixels in this byte:
for k in reverse 1 .. 8 / png_bits_per_pixel loop
Out_Pixel_Palette (max and U8 (Shift_Right (Unsigned_8 (uf (0)), shift)));
shift := shift - png_bits_per_pixel;
exit when x >= x_max or k = 1;
Inc_XY;
end loop;
end;
when 8 =>
-- Same remark for this case (8bpp) as
-- within Image Type 0 / Greyscale above
Out_Pixel_Palette (uf (0));
when others =>
null;
end case;
when 4 =>
-------------------------------
-- Type 4: Greyscale & Alpha --
-------------------------------
case png_bits_per_pixel is
when 16 =>
Unfilter_bytes (data (i .. i + 1), uf (0 .. 1));
i := i + 2;
Out_Pixel_8 (uf (0), uf (0), uf (0), uf (1));
when 32 =>
Unfilter_bytes (data (i .. i + 3), uf (0 .. 3));
i := i + 4;
w1 := U16 (uf (0)) * 256 + U16 (uf (1));
w2 := U16 (uf (2)) * 256 + U16 (uf (3));
Out_Pixel_16 (w1, w1, w1, w2);
when others =>
null; -- Undefined in PNG standard
end case;
when 6 =>
------------------
-- Type 6: RGBA --
------------------
case png_bits_per_pixel is
when 32 =>
Unfilter_bytes (data (i .. i + 3), uf (0 .. 3));
i := i + 4;
Out_Pixel_8 (uf (0), uf (1), uf (2), uf (3));
when 64 =>
Unfilter_bytes (data (i .. i + 7), uf (0 .. 7));
i := i + 8;
Out_Pixel_16 (
U16 (uf (0)) * 256 + U16 (uf (1)),
U16 (uf (2)) * 256 + U16 (uf (3)),
U16 (uf (4)) * 256 + U16 (uf (5)),
U16 (uf (6)) * 256 + U16 (uf (7))
);
when others =>
null;
end case;
when others =>
null; -- Unknown - exception already raised at header level
end case;
end if;
Inc_XY;
end loop;
-- i is between data'Last-(bytes_to_unfilter-2) and data'Last+1
reject := (data'Last + 1) - i;
if reject > 0 then
if some_trace then
Ada.Text_IO.Put ("[rj" & Integer'Image (reject) & ']');
end if;
end if;
end Output_uncompressed;
-- Out of some intelligent design, there might be an IDAT chunk
-- boundary anywhere inside the zlib compressed block...
procedure Jump_IDAT is
dummy : U32;
begin
Big_Endian (image.buffer, dummy); -- Ending chunk's CRC
-- New chunk begins here.
loop
Read_Chunk_Header (image, ch);
exit when ch.kind /= IDAT or ch.length > 0;
end loop;
if ch.kind /= IDAT then
raise error_in_image_data
with "PNG: additional data chunk must be an IDAT";
end if;
end Jump_IDAT;
---------------------------------------------------------------------
-- ** 10: Decompression ** --
-- Excerpt and simplification from UnZip.Decompress (Inflate only) --
---------------------------------------------------------------------
-- http://www.w3.org/TR/PNG/#10Compression
-- Size of sliding dictionary and circular output buffer
wsize : constant := 16#10000#;
--------------------------------------
-- Specifications of UnZ_* packages --
--------------------------------------
package UnZ_Glob is
-- I/O Buffers
-- > Sliding dictionary for unzipping, and output buffer as well
slide : Byte_Array (0 .. wsize);
slide_index : Integer := 0; -- Current Position in slide
Zip_EOF : constant Boolean := False;
adler_1 : Unsigned_32;
adler_2 : Unsigned_32;
modulus : constant := 65521;
end UnZ_Glob;
package UnZ_IO is
procedure Init_Buffers;
procedure Read_raw_byte (bt : out U8);
pragma Inline (Read_raw_byte);
package Bit_buffer is
procedure Init;
-- Read at least n bits into the bit buffer, returns the n first bits
function Read (n : Natural) return Integer;
pragma Inline (Read);
function Read_U32 (n : Natural) return Unsigned_32;
pragma Inline (Read_U32);
-- Dump n bits no longer needed from the bit buffer
procedure Dump (n : Natural);
pragma Inline (Dump);
procedure Dump_to_byte_boundary;
function Read_and_dump (n : Natural) return Integer;
pragma Inline (Read_and_dump);
function Read_and_dump_U32 (n : Natural) return Unsigned_32;
pragma Inline (Read_and_dump_U32);
end Bit_buffer;
procedure Flush (x : Natural); -- Directly from slide to output stream
procedure Flush_if_full (W : in out Integer);
pragma Inline (Flush_if_full);
procedure Copy
(distance, length : Natural;
index : in out Natural);
pragma Inline (Copy);
end UnZ_IO;
package UnZ_Meth is
procedure Inflate;
end UnZ_Meth;
------------------------------
-- Bodies of UnZ_* packages --
------------------------------
package body UnZ_IO is
procedure Init_Buffers is
begin
UnZ_Glob.slide_index := 0;
Bit_buffer.Init;
UnZ_Glob.adler_1 := 1;
UnZ_Glob.adler_2 := 0;
end Init_Buffers;
procedure Read_raw_byte (bt : out U8) is
begin
if ch.length = 0 then
-- We hit the end of a PNG 'IDAT' chunk, so we go to the next one
-- - in petto, it's strange design, but well...
-- This "feature" has taken some time (and nerves) to be addressed.
-- Incidentally, to solve the mystery, I have reprogrammed the
-- whole Huffman decoding, and looked at many other wrong places!
Jump_IDAT;
end if;
Buffering.Get_Byte (image.buffer, bt);
ch.length := ch.length - 1;
end Read_raw_byte;
package body Bit_buffer is
B : Unsigned_32;
K : Integer;
procedure Init is
begin
B := 0;
K := 0;
end Init;
procedure Need (n : Natural) is
pragma Inline (Need);
bt : U8;
begin
while K < n loop
Read_raw_byte (bt);
B := B or Shift_Left (Unsigned_32 (bt), K);
K := K + 8;
end loop;
end Need;
procedure Dump (n : Natural) is
begin
B := Shift_Right (B, n);
K := K - n;
end Dump;
procedure Dump_to_byte_boundary is
begin
Dump (K mod 8);
end Dump_to_byte_boundary;
function Read_U32 (n : Natural) return Unsigned_32 is
begin
Need (n);
return B and (Shift_Left (1, n) - 1);
end Read_U32;
function Read (n : Natural) return Integer is
begin
return Integer (Read_U32 (n));
end Read;
function Read_and_dump (n : Natural) return Integer is
res : Integer;
begin
res := Read (n);
Dump (n);
return res;
end Read_and_dump;
function Read_and_dump_U32 (n : Natural) return Unsigned_32 is
res : Unsigned_32;
begin
res := Read_U32 (n);
Dump (n);
return res;
end Read_and_dump_U32;
end Bit_buffer;
old_bytes : Natural := 0;
-- ^ How many bytes to be resent from last Inflate output?
byte_mem : Byte_Array (1 .. 8);
procedure Flush (x : Natural) is
begin
if full_trace then
Ada.Text_IO.Put ("[Flush..." & x'Image);
end if;
for slide_idx in 0 .. x - 1 loop
UnZ_Glob.adler_1 := (UnZ_Glob.adler_1 + Unsigned_32 (UnZ_Glob.slide (slide_idx))) rem UnZ_Glob.modulus;
UnZ_Glob.adler_2 := (UnZ_Glob.adler_2 + UnZ_Glob.adler_1) rem UnZ_Glob.modulus;
end loop;
if old_bytes > 0 then
declare
app : constant Byte_Array :=
byte_mem (1 .. old_bytes) & UnZ_Glob.slide (0 .. x - 1);
begin
Output_uncompressed (app, old_bytes);
-- In extreme cases (x very small), we might have some of
-- the rejected bytes from byte_mem.
if old_bytes > 0 then
byte_mem (1 .. old_bytes) := app (app'Last - (old_bytes - 1) .. app'Last);
end if;
end;
else
Output_uncompressed (UnZ_Glob.slide (0 .. x - 1), old_bytes);
if old_bytes > 0 then
byte_mem (1 .. old_bytes) := UnZ_Glob.slide (x - old_bytes .. x - 1);
end if;
end if;
if full_trace then
Ada.Text_IO.Put_Line ("finished]");
end if;
end Flush;
procedure Flush_if_full (W : in out Integer) is
begin
if W = wsize then
Flush (wsize);
W := 0;
end if;
end Flush_if_full;
----------------------------------------------------
-- Reproduction of sequences in the output slide. --
----------------------------------------------------
-- Internal:
procedure Adjust_to_Slide
(source : in out Integer;
remain : in out Natural;
part : out Integer;
index : in Integer)
is
pragma Inline (Adjust_to_Slide);
begin
source := source mod wsize;
-- source and index are now in 0..WSize-1
if source > index then
part := wsize - source;
else
part := wsize - index;
end if;
-- NB: part is in 1..WSize (part cannot be 0)
if part > remain then
part := remain;
end if;
-- Now part <= remain
remain := remain - part;
-- NB: remain cannot be < 0
end Adjust_to_Slide;
procedure Copy_range (source, index : in out Natural; amount : Positive) is
pragma Inline (Copy_range);
begin
if abs (index - source) < amount then
-- if source >= index, the effect of copy is
-- just like the non-overlapping case
for count in reverse 1 .. amount loop
UnZ_Glob.slide (index) := UnZ_Glob.slide (source);
index := index + 1;
source := source + 1;
end loop;
else -- non-overlapping -> copy slice
UnZ_Glob.slide (index .. index + amount - 1) :=
UnZ_Glob.slide (source .. source + amount - 1);
index := index + amount;
source := source + amount;
end if;
end Copy_range;
-- The copying routines:
procedure Copy (
distance, length : Natural;
index : in out Natural)
is
source, part, remain : Integer;
begin
source := index - distance;
remain := length;
loop
Adjust_to_Slide (source, remain, part, index);
Copy_range (source, index, part);
Flush_if_full (index);
exit when remain = 0;
end loop;
end Copy;
end UnZ_IO;
package body UnZ_Meth is
use GID.Decoding_PNG.Huffman;
--------[ Method: Inflate ]--------
procedure Inflate_Codes (Tl, Td : p_Table_list; Bl, Bd : Integer) is
CT : p_HufT_table; -- Current table
CT_idx : Integer; -- Current table index
length : Natural;
E : Integer; -- Table entry flag/number of extra bits
W : Integer := UnZ_Glob.slide_index;
-- More local variable for slide index
begin
if full_trace then
Ada.Text_IO.Put_Line ("Begin Inflate_Codes");
end if;
-- inflate the coded data
main_loop :
while not UnZ_Glob.Zip_EOF loop
CT := Tl.table;
CT_idx := UnZ_IO.Bit_buffer.Read (Bl);
loop
E := CT (CT_idx).extra_bits;
exit when E <= 16;
if E = invalid then
raise error_in_image_data with "PNG: invalid code in Deflate compression";
end if;
-- then it's a literal
UnZ_IO.Bit_buffer.Dump (CT (CT_idx).bits);
E := E - 16;
CT := CT (CT_idx).next_table;
CT_idx := UnZ_IO.Bit_buffer.Read (E);
end loop;
UnZ_IO.Bit_buffer.Dump (CT (CT_idx).bits);
case E is
when 16 => -- CTE.N is a Litteral
UnZ_Glob.slide (W) := U8 (CT (CT_idx).n);
W := W + 1;
UnZ_IO.Flush_if_full (W);
when 15 => -- End of block (EOB)
if full_trace then
Ada.Text_IO.Put_Line ("Exit Inflate_codes, e=15 EOB");
end if;
exit main_loop;
when others => -- We have a length/distance
-- Get length of block to copy:
length := CT (CT_idx).n + UnZ_IO.Bit_buffer.Read_and_dump (E);
-- Decode distance of block to copy:
CT := Td.table;
CT_idx := UnZ_IO.Bit_buffer.Read (Bd);
loop
E := CT (CT_idx).extra_bits;
exit when E <= 16;
if E = invalid then
raise error_in_image_data
with "PNG: invalid code in Deflate compression (LZ distance)";
end if;
UnZ_IO.Bit_buffer.Dump (CT (CT_idx).bits);
E := E - 16;
CT := CT (CT_idx).next_table;
CT_idx := UnZ_IO.Bit_buffer.Read (E);
end loop;
UnZ_IO.Bit_buffer.Dump (CT (CT_idx).bits);