-
Notifications
You must be signed in to change notification settings - Fork 12
/
bgragifformat.pas
1238 lines (1091 loc) · 36 KB
/
bgragifformat.pas
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
{ ***************************************************************************
* *
* This file is part of BGRABitmap library which is distributed under the *
* modified LGPL. *
* *
* See the file COPYING.modifiedLGPL.txt, included in this distribution, *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
************************* BGRABitmap library ******************************
- Drawing routines with transparency and antialiasing with Lazarus.
Offers also various transforms.
- These routines allow to manipulate 32bit images in BGRA format or RGBA
format (depending on the platform).
- This code is under modified LGPL (see COPYING.modifiedLGPL.txt).
This means that you can link this library inside your programs for any purpose.
Only the included part of the code must remain LGPL.
- If you make some improvements to this library, please notify here:
http://www.lazarus.freepascal.org/index.php/topic,12037.0.html
********************* Contact : Circular at operamail.com *******************
******************************* CONTRIBUTOR(S) ******************************
- Edivando S. Santos Brasil | [email protected]
(Compatibility with FPC ($Mode objfpc/delphi) and delphi VCL 11/2018)
***************************** END CONTRIBUTOR(S) *****************************}
Unit BGRAGifFormat;
{$i bgrabitmap.inc}{$H+}
{.$POINTERMATH ON}
interface
uses
Classes, SysUtils, BGRATypes,{$IFNDEF FPC}Types, GraphType,{$ENDIF} BGRAGraphics, BGRABitmap, BGRABitmapTypes,
BGRAPalette;
type
//what to do when finishing a frame and starting the next one
TDisposeMode = (dmNone, //undefined value
dmKeep, //keep the changes done by the frame
dmErase, //clear everything after the frame
dmRestore); //restore to how it was before the frame
//one image in the array
TGifSubImage = record
Image: TBGRABitmap; //image to draw at the beggining of the frame
Position: TPoint; //relative position of the image in the frame
DelayMs: integer; //time in milliseconds to wait before going to next frame
DisposeMode: TDisposeMode; //what do do when going to next frame
HasLocalPalette: boolean; //the image has its own palette
end;
TGifSubImageArray = array of TGifSubImage;
TGIFSignature = packed array[1..6] of AnsiChar; //'GIF87a' or 'GIF89a'
TGIFScreenDescriptor = packed record
Width, Height: BGRAWord;
flags, //screen bit depth = ((flags shr 4) and 7) + 1
//palette bit depth = (flags and 7) + 1
BackgroundColorIndex, //index of background color in global palette
AspectRatio64 : byte; //0 if not specified, otherwise aspect ratio is (AspectRatio64 + 15) / 64
end;
TGIFImageDescriptor = packed record
x, y, Width, Height: BGRAWord;
flags: byte;
end;
TGIFImageDescriptorWithHeader = packed record
ImageIntroducer: byte;
Image: TGIFImageDescriptor;
end;
TGIFExtensionBlock = packed record
FunctionCode: byte;
end;
TGIFGraphicControlExtension = packed record
flags: byte;
DelayHundredthSec: BGRAWord;
TransparentColorIndex: byte;
end;
TGIFGraphicControlExtensionWithHeader = packed record
ExtensionIntroducer: byte;
FunctionCode: byte;
BlockSize: byte;
GraphicControl: TGIFGraphicControlExtension;
BlockTerminator: byte;
end;
TPackedRGBTriple = packed record
r, g, b: byte;
end;
TGIFData = record
Width, Height: integer;
AspectRatio: single;
BackgroundColor: TColor;
LoopCount: BGRAWord;
Images: {$IFDEF BDS}TGifSubImageArray{$ELSE}array of TGifSubImage{$ENDIF};
end;
{ EColorQuantizerMissing }
EColorQuantizerMissing = class(Exception)
constructor Create; overload;
constructor Create(AMessage: string); overload;
end;
const
GIFScreenDescriptor_GlobalColorTableFlag = $80; //global palette is present
GIFScreenDescriptor_GlobalColorSortFlag = $08; //global palette colors are sorted by importance
GIFImageIntroducer = $2c;
GIFExtensionIntroducer = $21;
GIFBlockTerminator = $00;
GIFFileTerminator = $3B;
GIFGraphicControlExtension_TransparentFlag = $01; //transparent color index is provided
GIFGraphicControlExtension_UserInputFlag = $02; //wait for user input at this frame (ignored)
GIFGraphicControlExtension_FunctionCode = $f9;
GIFGraphicControlExtension_DisposeModeShift = 2;
GIFImageDescriptor_LocalColorTableFlag = $80; //local palette is present
GIFImageDescriptor_InterlacedFlag = $40; //image data is interlaced
GIFImageDescriptor_LocalColorSortFlag = $20; //local palette colors are sorted by importance
GIFInterlacedStart: array[1..4] of BGRALongInt = (0, 4, 2, 1);
GIFInterlacedStep: array[1..4] of BGRALongInt = (8, 8, 4, 2);
GIFCodeTableSize = 4096;
NetscapeApplicationIdentifier = 'NETSCAPE2.0';
NetscapeSubBlockIdLoopCount = 1;
NetscapeSubBlockIdBuffering = 2;
function CeilLn2(AValue: Integer): integer;
function BGRAToPackedRgbTriple(color: TBGRAPixel): TPackedRGBTriple;
function PackedRgbTribleToBGRA(rgb: TPackedRGBTriple): TBGRAPixel;
function GIFLoadFromStream(stream: TStream; MaxImageCount: integer = maxLongint): TGIFData;
procedure GIFSaveToStream(AData: TGifData; Stream: TStream; AQuantizerFactory: TBGRAColorQuantizerAny;
ADitheringAlgorithm: TDitheringAlgorithm);
procedure GIFDecodeLZW(AStream: TStream; AImage: TBGRACustomBitmap;
const APalette: ArrayOfTBGRAPixel; transcolorIndex: integer;
interlaced: boolean);
//Encode an image supplied as an sequence of bytes, from left to right and top to bottom.
//Adapted from the work of Udo Schmal, http://www.gocher.me/FPWriteGIF
procedure GIFEncodeLZW(AStream: TStream; AImageData: PByte;
AImageWidth, AImageHeight: integer; ABitDepth: byte);
implementation
function PackedRgbTribleToBGRA(rgb: TPackedRGBTriple): TBGRAPixel;
begin
Result.red := rgb.r;
Result.green := rgb.g;
Result.blue := rgb.b;
Result.alpha := 255;
end;
function BGRAToPackedRgbTriple(color: TBGRAPixel): TPackedRGBTriple;
begin
result.r := color.red;
result.g := color.green;
result.b := color.blue;
end;
function CeilLn2(AValue: Integer): integer;
var comp: integer;
begin
result := 0;
comp := 1;
while (comp < AValue) and (result < 30) do
begin
inc(result);
comp := comp shl 1;
end;
end;
procedure GIFDecodeLZW(AStream: TStream; AImage: TBGRACustomBitmap;
const APalette: ArrayOfTBGRAPixel; transcolorIndex: integer;
interlaced: boolean);
var
xd, yd: BGRALongInt;
type
Pstr = ^Tstr;
Tstr = record
prefix: Pstr;
suffix: BGRALongInt;
end;
Pstrtab = ^Tstrtab;
Tstrtab = array[0..GIFCodeTableSize-1] of Tstr;
var
strtab: Pstrtab;
oldcode, curcode, clearcode, endcode: BGRALongInt;
codesize, codelen, codemask: BGRALongInt;
stridx: BGRALongInt;
bitbuf, bitsinbuf: BGRALongInt;
bytbuf: packed array[0..255] of byte;
bytinbuf, bytbufidx: byte;
endofsrc: boolean;
xcnt, ycnt, ystep, pass: BGRALongInt;
pdest: PBGRAPixel;
procedure InitStringTable;
var
i: BGRALongInt;
begin
new(strtab);
clearcode := 1 shl codesize;
endcode := clearcode + 1;
stridx := endcode + 1;
codelen := codesize + 1;
codemask := (1 shl codelen) - 1;
for i := 0 to clearcode - 1 do
begin
strtab^[i].prefix := nil;
strtab^[i].suffix := i;
end;
for i := clearcode to GIFCodeTableSize-1 do
begin
strtab^[i].prefix := nil;
strtab^[i].suffix := 0;
end;
end;
procedure ClearStringTable;
var
i: BGRALongInt;
begin
clearcode := 1 shl codesize;
endcode := clearcode + 1;
stridx := endcode + 1;
codelen := codesize + 1;
codemask := (1 shl codelen) - 1;
for i := clearcode to GIFCodeTableSize-1 do
begin
strtab^[i].prefix := nil;
strtab^[i].suffix := 0;
end;
end;
procedure DoneStringTable;
begin
dispose(strtab);
end;
function GetNextCode: BGRALongInt;
begin
while (bitsinbuf < codelen) do
begin
if (bytinbuf = 0) then
begin
if AStream.Read(bytinbuf, 1) <> 1 then
raise exception.Create('Unexpected end of stream');
if (bytinbuf = 0) then
begin
endofsrc := True;
result := endcode;
exit;
end;
AStream.Read(bytbuf, bytinbuf);
bytbufidx := 0;
end;
bitbuf := bitbuf or (BGRALongInt(byte(bytbuf[bytbufidx])) shl bitsinbuf);
Inc(bytbufidx);
Dec(bytinbuf);
Inc(bitsinbuf, 8);
end;
Result := bitbuf and codemask;
bitbuf := bitbuf shr codelen;
Dec(bitsinbuf, codelen);
//write(inttostr(result)+'@'+inttostr(codelen)+' ');
end;
procedure AddStr2Tab(prefix: Pstr; suffix: BGRALongInt);
begin
if stridx >= GIFCodeTableSize then exit;
strtab^[stridx].prefix := prefix;
strtab^[stridx].suffix := suffix;
Inc(stridx);
case stridx of
0..1: codelen := 1;
2..3: codelen := 2;
4..7: codelen := 3;
8..15: codelen := 4;
16..31: codelen := 5;
32..63: codelen := 6;
64..127: codelen := 7;
128..255: codelen := 8;
256..511: codelen := 9;
512..1023: codelen := 10;
1024..2047: codelen := 11;
2048..4096: codelen := 12;
end;
codemask := (1 shl codelen) - 1;
end;
function Code2Str(code: BGRALongInt): Pstr;
begin
Result := addr(strtab^[code]);
end;
procedure WriteStr(s: Pstr);
var
colorIndex: integer;
begin
if (s^.prefix <> nil) then
WriteStr(s^.prefix);
if (ycnt >= yd) then
begin
if interlaced then
begin
while ycnt >= yd do
begin
if pass >= 5 then exit;
Inc(pass);
ycnt := GIFInterlacedStart[pass];
ystep := GIFInterlacedStep[pass];
end;
end else exit;
end;
colorIndex := s^.suffix;
if xcnt = 0 then pdest := AImage.ScanLine[ycnt];
if (colorIndex <> transcolorIndex) and (colorIndex >= 0) and
(colorIndex < length(APalette)) then
pdest^ := APalette[colorIndex];
Inc(xcnt);
inc(pdest);
if (xcnt >= xd) then
begin
pdest := nil;
xcnt := 0;
Inc(ycnt, ystep);
if not interlaced then
if (ycnt >= yd) then
begin
Inc(pass);
end;
end;
end;
function firstchar(s: Pstr): byte;
begin
while (s^.prefix <> nil) do
s := s^.prefix;
Result := s^.suffix;
end;
begin
endofsrc := False;
xd := AImage.Width;
yd := AImage.Height;
xcnt := 0;
pdest := nil;
if interlaced then
begin
pass := 1;
ycnt := GIFInterlacedStart[pass];
ystep := GIFInterlacedStep[pass];
end
else
begin
pass := 4;
ycnt := 0;
ystep := 1;
end;
oldcode := 0;
bitbuf := 0;
bitsinbuf := 0;
bytinbuf := 0;
bytbufidx := 0;
codesize := 0;
AStream.Read(codesize, 1);
InitStringTable;
curcode := getnextcode;
//Write('Reading ');
while (curcode <> endcode) and (pass < 5) and not endofsrc do
begin
if (curcode = clearcode) then
begin
ClearStringTable;
repeat
curcode := getnextcode;
until (curcode <> clearcode);
if (curcode = endcode) then
break;
WriteStr(code2str(curcode));
oldcode := curcode;
end
else
begin
if (curcode < stridx) then
begin
WriteStr(Code2Str(curcode));
AddStr2Tab(Code2Str(oldcode), firstchar(Code2Str(curcode)));
oldcode := curcode;
end
else
begin
if (curcode > stridx) then
begin
//write('!Invalid! ');
break;
end;
AddStr2Tab(Code2Str(oldcode), firstchar(Code2Str(oldcode)));
WriteStr(Code2Str(stridx - 1));
oldcode := curcode;
end;
end;
curcode := getnextcode;
end;
DoneStringTable;
//Writeln;
if not endofsrc then
begin
bytinbuf:= 0;
AStream.ReadBuffer(bytinbuf, 1);
if bytinbuf <> 0 then
raise exception.Create('Invalid GIF format: expecting block terminator');
end;
end;
//Encode an image supplied as an sequence of bytes, from left to right and top to bottom.
//Adapted from the work of Udo Schmal, http://www.gocher.me/FPWriteGIF
procedure GIFEncodeLZW(AStream: TStream; AImageData: PByte;
AImageWidth, AImageHeight: integer; ABitDepth: byte);
var //input position
PInput, PInputEnd: PByte;
// get the next pixel from the bitmap
function ReadValue: byte;
begin
result := PInput^;
Inc(PInput);
end;
var // GIF buffer can be up to 255 bytes long
OutputBufferSize: BGRANativeInt;
OutputBuffer: packed array[0..255] of byte;
procedure FlushByteOutput;
begin
if OutputBufferSize > 0 then
begin
OutputBuffer[0] := OutputBufferSize;
AStream.WriteBuffer(OutputBuffer, OutputBufferSize+1);
OutputBufferSize := 0;
end;
end;
procedure OutputByte(AValue: byte);
begin
if OutputBufferSize = 255 then FlushByteOutput;
inc(OutputBufferSize);
OutputBuffer[OutputBufferSize] := AValue;
end;
type TCode = BGRAWord;
var
BitBuffer : BGRADWord; // steady stream of bit output
BitBufferLen : Byte; // number of bits in buffer
CurCodeSize : byte; // current code size
// save the code in the output data stream
procedure WriteCode(Code: TCode);
begin
//Write(IntToStr(Code)+'@'+IntToStr(CurCodeSize)+' ');
// append code to bit buffer
BitBuffer := BitBuffer or (Code shl BitBufferLen);
BitBufferLen := BitBufferLen + CurCodeSize;
// output whole bytes
while BitBufferLen >= 8 do
begin
OutputByte(BitBuffer and $ff);
BitBuffer := BitBuffer shr 8;
BitBufferLen := BitBufferLen -8;
end;
end;
procedure CloseBitOutput;
begin
// write out the rest of the bit string
// and add padding bits if necessary
while BitBufferLen > 0 do
begin
OutputByte(BitBuffer and $ff);
BitBuffer := BitBuffer shr 8;
if BitBufferLen >= 8 then
BitBufferLen := BitBufferLen -8
else
BitBufferLen := 0;
end;
end;
type
PCodeTableEntry = ^TCodeTableEntry;
TCodeTableEntry = packed record
Prefix: TCode;
LongerFirst, LongerLast: TCode;
Suffix, Padding: Byte;
NextWithPrefix: TCode;
end;
var
ClearCode : TCode; // reset decode params
EndStreamCode : TCode; // last code in input stream
FirstCodeSlot : TCode; // first slot when table is empty
NextCodeSlot : TCode; // next slot to be used
PEntry: PCodeTableEntry;
CodeTable: array of TCodeTableEntry;
CurrentCode : TCode; // code representing current string
procedure DoClearCode;
var
i: BGRAWord;
begin
for i := 0 to (1 shl ABitDepth)-1 do
with CodeTable[i] do
begin
LongerFirst:= 0;
LongerLast:= 0;
end;
WriteCode(ClearCode);
CurCodeSize := ABitDepth + 1;
NextCodeSlot := FirstCodeSlot;
end;
var
CurValue: Byte;
i: TCode;
found: boolean; // decoded string in prefix table?
begin
if ABitDepth > 8 then
raise exception.Create('Maximum bit depth is 8');
//output
AStream.WriteByte(ABitDepth);
ClearCode := 1 shl ABitDepth;
EndStreamCode := ClearCode + 1;
FirstCodeSlot := ClearCode + 2;
CurCodeSize := ABitDepth + 1;
OutputBufferSize := 0;
BitBuffer := 0;
BitBufferLen := 0;
//input
PInput := AImageData;
PInputEnd := AImageData + BGRAPtrInt(AImageWidth)*AImageHeight;
setlength(CodeTable, GIFCodeTableSize);
DoClearCode;
//write('Writing ');
while PInput < PInputEnd do
begin
CurrentCode := ReadValue;
if CurrentCode >= ClearCode then
raise exception.Create('Internal error');
//try to match the longest string
while PInput < PInputEnd do
begin
CurValue := ReadValue;
found := false;
i := CodeTable[CurrentCode].LongerFirst;
while i <> 0 do
begin
PEntry := @CodeTable[i];
if PEntry^.Suffix = CurValue then
begin
found := true;
CurrentCode := i;
break;
end;
i := PEntry^.NextWithPrefix;
end;
if not found then
begin
PEntry := @CodeTable[CurrentCode];
if PEntry^.LongerFirst = 0 then
begin
//store the first and last code being longer
PEntry^.LongerFirst := NextCodeSlot;
PEntry^.LongerLast := NextCodeSlot;
end else
begin
//link next entry having the same prefix
CodeTable[PEntry^.LongerLast].NextWithPrefix:= NextCodeSlot;
PEntry^.LongerLast := NextCodeSlot;
end;
// add new encode table entry
PEntry := @CodeTable[NextCodeSlot];
PEntry^.Prefix := CurrentCode;
PEntry^.Suffix := CurValue;
PEntry^.LongerFirst := 0;
PEntry^.LongerLast := 0;
PEntry^.NextWithPrefix := 0;
inc(NextCodeSlot);
Dec(PInput);
break;
end;
end;
// write the code of the longest entry found
WriteCode(CurrentCode);
if NextCodeSlot >= GIFCodeTableSize then
DoClearCode
else if NextCodeSlot > 1 shl CurCodeSize then
inc(CurCodeSize);
end;
WriteCode(EndStreamCode);
CloseBitOutput;
FlushByteOutput;
AStream.WriteByte(0); //GIF block terminator
//Writeln;
end;
function GIFLoadFromStream(stream: TStream; MaxImageCount: integer = maxLongint): TGIFData;
procedure DumpData;
var
Count: byte;
begin
repeat
Count := 0;
stream.Read(Count, 1);
stream.position := stream.position + Count;
until (Count = 0) or (stream.position >= stream.size);
end;
function ReadString: Ansistring;
var Count: byte;
begin
Count := 0;
stream.Read(Count, 1);
setlength(result, Count);
if Count > 0 then
stream.ReadBuffer(result[1], length(result));
end;
var
NbImages: integer;
GIFSignature: TGIFSignature;
GIFScreenDescriptor: TGIFScreenDescriptor;
GIFBlockID: {$IFDEF FPC}Char{$ELSE}AnsiChar{$ENDIF};
GIFImageDescriptor: TGIFImageDescriptor;
globalPalette: ArrayOfTBGRAPixel;
localPalette: ArrayOfTBGRAPixel;
transcolorIndex: integer;
DelayMs: integer;
disposeMode: TDisposeMode;
procedure LoadGlobalPalette;
var
NbEntries, i: integer;
rgb: TPackedRGBTriple;
begin
NbEntries := 1 shl (GIFScreenDescriptor.flags and $07 + 1);
setlength(globalPalette, NbEntries);
for i := 0 to NbEntries - 1 do
begin
stream.ReadBuffer({%H-}rgb, 3);
globalPalette[i] := PackedRgbTribleToBGRA(rgb);
end;
end;
procedure LoadLocalPalette;
var
NbEntries, i: integer;
rgb: TPackedRGBTriple;
begin
NbEntries := 1 shl (GIFImageDescriptor.flags and $07 + 1);
setlength(localPalette, NbEntries);
for i := 0 to NbEntries - 1 do
begin
stream.ReadBuffer({%H-}rgb, 3);
localPalette[i] := PackedRgbTribleToBGRA(rgb);
end;
end;
procedure LoadImage;
var
imgWidth, imgHeight: integer;
img: TBGRABitmap;
Interlaced: boolean;
palette: ArrayOfTBGRAPixel;
begin
stream.Read(GIFImageDescriptor, sizeof(GIFImageDescriptor));
{$IFNDEF BDS}GIFImageDescriptor.Width := LEtoN(GIFImageDescriptor.Width);{$ENDIF}
{$IFNDEF BDS}GIFImageDescriptor.Height := LEtoN(GIFImageDescriptor.Height);{$ENDIF}
{$IFNDEF BDS}GIFImageDescriptor.x := LEtoN(GIFImageDescriptor.x);{$ENDIF}
{$IFNDEF BDS}GIFImageDescriptor.y := LEtoN(GIFImageDescriptor.y);{$ENDIF}
if (GIFImageDescriptor.flags and GIFImageDescriptor_LocalColorTableFlag =
GIFImageDescriptor_LocalColorTableFlag) then
LoadLocalPalette
else
localPalette := nil;
if localPalette <> nil then
palette := localPalette
else
palette := globalPalette;
imgWidth := GIFImageDescriptor.Width;
imgHeight := GIFImageDescriptor.Height;
if length(result.Images) <= NbImages then
setlength(result.Images, length(result.Images) * 2 + 1);
img := TBGRABitmap.Create(imgWidth, imgHeight);
img.Fill(BGRAPixelTransparent);
result.Images[NbImages].Image := img;
result.Images[NbImages].Position := point(GIFImageDescriptor.x, GIFImageDescriptor.y);
result.Images[NbImages].DelayMs := DelayMs;
result.Images[NbImages].DisposeMode := disposeMode;
result.Images[NbImages].HasLocalPalette := localPalette <> nil;
Inc(NbImages);
Interlaced := GIFImageDescriptor.flags and GIFImageDescriptor_InterlacedFlag =
GIFImageDescriptor_InterlacedFlag;
GIFDecodeLZW(stream, img, palette, transcolorIndex, Interlaced);
end;
procedure ReadExtension;
var
GIFExtensionBlock: TGIFExtensionBlock;
GIFGraphicControlExtension: TGIFGraphicControlExtension;
mincount, Count, SubBlockId: byte;
app: String;
begin
stream.ReadBuffer({%H-}GIFExtensionBlock, sizeof(GIFExtensionBlock));
case GIFExtensionBlock.FunctionCode of
$F9: //graphic control extension
begin
Count := 0;
stream.Read(Count, 1);
if Count < sizeof(GIFGraphicControlExtension) then
mincount := 0
else
begin
mincount := sizeof(GIFGraphicControlExtension);
stream.ReadBuffer({%H-}GIFGraphicControlExtension, mincount);
{$IFNDEF BDS}GIFGraphicControlExtension.DelayHundredthSec := LEtoN(GIFGraphicControlExtension.DelayHundredthSec);{$ENDIF}
if GIFGraphicControlExtension.flags and
GIFGraphicControlExtension_TransparentFlag =
GIFGraphicControlExtension_TransparentFlag then
transcolorIndex := GIFGraphicControlExtension.TransparentColorIndex
else
transcolorIndex := -1;
if GIFGraphicControlExtension.DelayHundredthSec <> 0 then
DelayMs := GIFGraphicControlExtension.DelayHundredthSec * 10;
DisposeMode := TDisposeMode((GIFGraphicControlExtension.flags shr GIFGraphicControlExtension_DisposeModeShift) and 7);
end;
stream.Position := Stream.Position + Count - mincount;
DumpData;
end;
$ff: //application extension
begin
app := ReadString;
if app <> '' then
begin
if app = NetscapeApplicationIdentifier then
begin
repeat
Count := 0;
stream.Read(Count,1);
if Count = 0 then break;
stream.ReadBuffer({%H-}SubBlockId,1);
Dec(Count);
if (SubBlockId = NetscapeSubBlockIdLoopCount) and (Count >= 2) then
begin
stream.ReadBuffer(result.LoopCount, 2);
dec(Count,2);
{$IFNDEF BDS}result.LoopCount := LEtoN(result.LoopCount);{$ENDIF}
if result.LoopCount > 0 then inc(result.LoopCount);
end;
stream.Position:= stream.Position+Count;
until false;
end else
DumpData;
end;
end
else
begin
DumpData;
end;
end;
end;
begin
result.Width := 0;
result.Height := 0;
result.BackgroundColor := clNone;
result.Images := nil;
result.AspectRatio := 1;
result.LoopCount := 1;
if stream = nil then exit;
NbImages := 0;
transcolorIndex := -1;
DelayMs := 100;
disposeMode := dmErase;
FillChar({%H-}GIFSignature,sizeof(GIFSignature),0);
stream.Read(GIFSignature, sizeof(GIFSignature));
if (GIFSignature[1] = 'G') and (GIFSignature[2] = 'I') and (GIFSignature[3] = 'F') then
begin
stream.ReadBuffer({%H-}GIFScreenDescriptor, sizeof(GIFScreenDescriptor));
{$IFNDEF BDS}GIFScreenDescriptor.Width := LEtoN(GIFScreenDescriptor.Width);{$ENDIF}
{$IFNDEF BDS}GIFScreenDescriptor.Height := LEtoN(GIFScreenDescriptor.Height);{$ENDIF}
result.Width := GIFScreenDescriptor.Width;
result.Height := GIFScreenDescriptor.Height;
if GIFScreenDescriptor.AspectRatio64 = 0 then
result.AspectRatio:= 1
else
result.AspectRatio:= (GIFScreenDescriptor.AspectRatio64+15)/64;
if (GIFScreenDescriptor.flags and GIFScreenDescriptor_GlobalColorTableFlag =
GIFScreenDescriptor_GlobalColorTableFlag) then
begin
LoadGlobalPalette;
if GIFScreenDescriptor.BackgroundColorIndex < length(globalPalette) then
result.BackgroundColor :=
BGRAToColor(globalPalette[GIFScreenDescriptor.BackgroundColorIndex]);
end;
repeat
stream.ReadBuffer({%H-}GIFBlockID, sizeof(GIFBlockID));
case GIFBlockID of
';': ;
',': begin
if NbImages >= MaxImageCount then break;
LoadImage;
end;
'!': ReadExtension;
else
begin
raise Exception.Create('TBGRAAnimatedGif: unexpected block type');
break;
end;
end;
until (GIFBlockID = ';') or (stream.Position >= stream.size);
end
else
raise Exception.Create('TBGRAAnimatedGif: invalid header');
setlength(result.Images, NbImages);
end;
procedure GIFSaveToStream(AData: TGifData; Stream: TStream; AQuantizerFactory: TBGRAColorQuantizerAny;
ADitheringAlgorithm: TDitheringAlgorithm);
var
signature: TGIFSignature;
screenDescriptor: TGIFScreenDescriptor;
globalPalette: TBGRAPalette;
globalQuantizer: TBGRACustomColorQuantizer;
globalTranspIndex: integer;
procedure AddColorsToPalette(AImage: TBGRACustomBitmap; APalette: TBGRAPalette);
var n: integer;
p: PBGRAPixel;
c: TBGRAPixel;
begin
p := AImage.Data;
for n := AImage.NbPixels-1 downto 0 do
begin
if p^.alpha < 255 then //transparent color will be needed to dither properly
APalette.AddColor(BGRAPixelTransparent);
if p^.alpha > 0 then //color may be needed to dither properly
begin
c := p^;
c.alpha := 255;
APalette.AddColor(c);
end;
inc(p);
end;
end;
function ImageCount: integer;
begin
result := length(AData.Images);
end;
function NeedGlobalPalette: boolean;
var i: integer;
begin
for i := 0 to ImageCount-1 do
if not AData.Images[i].HasLocalPalette then
begin
result := true;
exit;
end;
end;
function IndexOfGlobalColor(AColor: TBGRAPixel): integer;
begin
if Assigned(globalQuantizer) then
result := globalQuantizer.ReducedPalette.FindNearestColorIndex(AColor)
else
result := globalPalette.IndexOfColor(AColor);
end;
procedure MakeGlobalPalette;
var i: integer;
indexed: TBGRAIndexedPalette;
bitDepth: integer;
begin
globalPalette := TBGRAPalette.Create;
for i := 0 to ImageCount-1 do
if not AData.Images[i].HasLocalPalette then
AddColorsToPalette(AData.Images[i].Image, globalPalette);
if AData.BackgroundColor <> clNone then
globalPalette.AddColor(ColorToBGRA(ColorToRGB(AData.BackgroundColor)));
if globalPalette.Count > 256 then
begin
if Assigned(AQuantizerFactory) then
begin
globalQuantizer:= AQuantizerFactory.Create(globalPalette, False, 256);
globalPalette.Free;
globalPalette := TBGRAIndexedPalette.Create(globalQuantizer.ReducedPalette);
end
else
begin
globalPalette.Free;
raise EColorQuantizerMissing.Create;
end;
end else
begin
indexed := TBGRAIndexedPalette.Create(globalPalette);
globalPalette.Free;
globalPalette := indexed;
end;
globalTranspIndex:= globalPalette.IndexOfColor(BGRAPixelTransparent);
if AData.BackgroundColor <> clNone then
screenDescriptor.BackgroundColorIndex:= IndexOfGlobalColor(ColorToBGRA(ColorToRGB(AData.BackgroundColor))) and 255;
bitDepth := CeilLn2(globalPalette.Count);
if bitDepth > 8 then bitDepth:= 8;
if bitDepth < 1 then bitDepth:= 1;
screenDescriptor.flags := screenDescriptor.flags or GIFScreenDescriptor_GlobalColorTableFlag;
screenDescriptor.flags := screenDescriptor.flags or (bitDepth-1);
end;
procedure WritePalette(pal: TBGRAPalette; bitDepth: integer);
var i: integer;
numberToWrite,numberFromPal: Integer;
rgbs: ^TPackedRGBTriple;
black: TPackedRGBTriple;
begin
if not Assigned(pal) then exit;
numberToWrite:= 1 shl bitDepth;
numberFromPal := pal.Count;
if numberFromPal > numberToWrite then numberFromPal:= numberToWrite;
getmem(rgbs, numberToWrite*sizeof(TPackedRGBTriple));
try
for i := 0 to numberFromPal-1 do
rgbs[i] := BGRAToPackedRgbTriple(pal.Color[i]);
black := BGRAToPackedRgbTriple(ColorToBGRA(clBlack));
for i := numberFromPal to numberToWrite-1 do
rgbs[i] := black;
Stream.WriteBuffer(rgbs^,sizeof(TPackedRGBTriple)*numberToWrite);