-
Notifications
You must be signed in to change notification settings - Fork 10
/
PNGEncoder2.hx
1559 lines (1319 loc) · 70.6 KB
/
PNGEncoder2.hx
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
/*
Copyright (c) 2008, Adobe Systems Incorporated
Copyright (c) 2011, Pimm Hogeling and Edo Rivai
Copyright (c) 2011-2015, Cameron Desrochers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.display.Stage;
import flash.errors.Error;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.ProgressEvent;
import flash.geom.Rectangle;
import flash.Lib;
import flash.Memory;
import flash.system.ApplicationDomain;
import flash.system.System;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.Timer;
import flash.Vector;
import DeflateStream;
class PNGKeywords
{
public static var TITLE = "Title"; // Short (one line) title or caption for image
public static var AUTHOR = "Author"; // Name of image's creator
public static var DESCRIPTION = "Description"; // Description of image (possibly long)
public static var COPYRIGHT = "Copyright"; // Copyright notice
public static var CREATION_TIME = "Creation Time"; // Time of original image creation
public static var SOFTWARE = "Software"; // Software used to create the image
public static var DISCLAIMER = "Disclaimer"; // Legal disclaimer
public static var WARNING = "Warning"; // Warning of nature of content
public static var SOURCE = "Source"; // Device used to create the image
public static var COMMENT = "Comment"; // Miscellaneous comment
}
// Separate public interface from private implementation because all
// members appear as public in SWC
class PNGEncoder2 extends EventDispatcher
{
// For internal use only. Do not access.
private var __impl : PNGEncoder2Impl;
public static var level : CompressionLevel;
// Provide both HaXe and AS3 properties to access the PNG result for reading
@:protected private inline function get_png() { return __impl.png; }
@:protected public var png(get_png, null) : ByteArray;
@:getter(png) private function flGetPng() { return get_png(); }
// Provide both HaXe and AS3 properties to access the target FPS (read/write)
@:protected private inline function get_targetFPS() { return __impl.targetFPS; }
@:protected private inline function set_targetFPS(fps : Int) { return __impl.targetFPS = fps; }
@:protected public var targetFPS(get_targetFPS, set_targetFPS) : Int;
@:getter(targetFPS) private function flGetTargetFPS() { return get_targetFPS(); }
@:setter(targetFPS) private function flSetTargetFPS(fps : Int) { set_targetFPS(fps); }
/**
* Creates a PNG image from the specified BitmapData.
* If the BitmapData's transparent property is true, then a 32-bit
* PNG (i.e. with alpha) is generated, otherwise a (generally smaller)
* 24-bit PNG is generated.
* Highly optimized for speed.
*
* @param image The BitmapData that will be converted into the PNG format.
* @return a ByteArray representing the PNG encoded image data.
* @playerversion Flash 10
*/
public static function encode(image : BitmapData) : ByteArray
{
PNGEncoder2Impl.level = level;
return PNGEncoder2Impl.encode(image, null);
}
/**
* Creates a PNG image from the specified BitmapData and metadata.
* If the BitmapData's transparent property is true, then a 32-bit
* PNG (i.e. with alpha) is generated, otherwise a (generally smaller)
* 24-bit PNG is generated.
* Highly optimized for speed.
*
* @param image The BitmapData that will be converted into the PNG format.
* @param metadata An object that will be treated as key-value pairs of keyword-value metadata.
* @return a ByteArray representing the PNG encoded image data.
* @playerversion Flash 10
*/
public static function encodeWithMetadata(image : BitmapData, metadata : Dynamic) : ByteArray
{
PNGEncoder2Impl.level = level;
return PNGEncoder2Impl.encode(image, metadata);
}
/**
* Creates a PNG image from the specified BitmapData without blocking.
* If the BitmapData's transparent property is true, then a 32-bit
* PNG (i.e. with alpha) is generated, otherwise a (generally smaller)
* 24-bit PNG is generated.
* Highly optimized for speed.
*
* @param image The BitmapData that will be converted into the PNG format.
* @return a PNGEncoder2 object that dispatches COMPLETE and PROGRESS events.
* The encoder object allows the targetFPS to be set, and has a 'png'
* property to access the encoded data once the COMPLETE event has fired.
* @playerversion Flash 10
*/
public static function encodeAsync(image : BitmapData) : PNGEncoder2
{
return new PNGEncoder2(image, null);
}
/**
* Creates a PNG image from the specified BitmapData and metadata,
* without blocking.
* If the BitmapData's transparent property is true, then a 32-bit
* PNG (i.e. with alpha) is generated, otherwise a (generally smaller)
* 24-bit PNG is generated.
* Highly optimized for speed.
*
* @param image The BitmapData that will be converted into the PNG format.
* @param metadata An object that will be treated as key-value pairs of keyword-value metadata.
* @return a PNGEncoder2 object that dispatches COMPLETE and PROGRESS events.
* The encoder object allows the targetFPS to be set, and has a 'png'
* property to access the encoded data once the COMPLETE event has fired.
* @playerversion Flash 10
*/
public static function encodeAsyncWithMetadata(image : BitmapData, metadata : Dynamic) : PNGEncoder2
{
return new PNGEncoder2(image, metadata);
}
#if DECODER
/**
* Provides a simple, synchronous (but fast) decoder for image files
* created using PNGEncoder2 (though not, alas, arbitrary PNGs).
*
* @param pngBytes The raw bytes of the PNG encoded image data.
* @return A BitmapData representing the decoded image.
* @playerversion Flash 10
*/
public static inline function decode(pngBytes : ByteArray) : BitmapData
{
return PNGEncoder2Impl.decode(pngBytes);
}
#end
/**
* Clears any long-term cached memory (e.g. CRC tables) in order
* to reduce memory usage. This is only needed in resource-constrained
* environments; it's faster to leave the cache intact between
* encodings.
*/
public static function freeCachedMemory()
{
PNGEncoder2Impl.freeCachedMemory();
}
private inline function new(image : BitmapData, metadata : Dynamic)
{
super();
PNGEncoder2Impl.level = level;
__impl = new PNGEncoder2Impl(image, this, metadata);
}
}
// The actual implementation of all PNG functionality (completely refactored
// and improved (by Cameron) from the HaXe port of the original AS3 version --
// new features include fast performance, 24- and 32-bit PNG support, the
// Paeth filter, and adaptive asynchronous encoding)
@:protected private class PNGEncoder2Impl
{
// Domain memory (aka "fast memory") layout:
// 0: CRC table (256 4-byte entries)
// 1024: Deflate stream (fixed) scratch memory
// CHUNK_START: Compressed image data to be written to the next chunk in the output
// After chunk: Additional scratch memory used to construct the chunk
private static inline var CRC_TABLE_END = 256 * 4;
private static inline var DEFLATE_SCRATCH = CRC_TABLE_END;
private static inline var CHUNK_START = DEFLATE_SCRATCH + DeflateStream.SCRATCH_MEMORY_SIZE;
private static inline var FRAME_AVG_SMOOTH_COUNT = 4; // Number of frames to calculate averages from. Must be power of 2
private static inline var FIRST_UPDATE_PIXELS = 20 * 1024; // Encode this many pixels right away on the first frame
private static inline var MIN_PIXELS_PER_UPDATE = 20 * 1024; // Always compress at least this many pixels per chunk
private static var data : ByteArray; // The select()ed working memory
private static var sprite : Sprite; // Used purely to listen to ENTER_FRAME events
private static var encoding = false; // Keeps track of global state, to ensure only one PNG can be encoded at once
private static var region : Rectangle; // Re-used rectangle for async update function (avoids per-frame allocation)
private static var pendingAsyncEncodings : Vector<PNGEncoder2Impl> = new Vector<PNGEncoder2Impl>();
// FAST compression level is default
public static var level : CompressionLevel;
//
// Asynchronous encoder member variables:
//
public var png : ByteArray; // The resulting PNG output for the asynchronous encoder
public var targetFPS : Int; // The desired number of frames-per-second during asynchronous encoding (will attempt to achieve this)
private var img : BitmapData; // The input image
private var dispatcher : IEventDispatcher; // The dispatcher to use for dispatching PROGRESS and COMPLETE events
private var deflateStream : DeflateStream; // To compress each chunk's data
private var currentY : Int; // The current scanline in the input image (tracks progress)
private var msPerFrame : Vector<Int>; // Keeps track of last FRAME_AVG_SMOOTH_COUNT measures of milliseconds between sequential frame
private var msPerFrameIndex : Int; // Index into msPerFrame at which to store next measure
private var msPerLine : Vector<Float>; // Keeps track of last FRAME_AVG_SMOOTH_COUNT measures (one per chunk) of average milliseconds to process a single line
private var msPerLineIndex : Int; // Index into msPerLine at which to store next measure
private var updatesPerFrame : Vector<Int>; // Keeps track of last FRAME_AVG_SMOOTH_COUNT measures of the number of updates (i.e. chunks) that can be processed per frame (generally just one except at very low frame rates)
private var updatesPerFrameIndex : Int; // Index into updatesPerFrame at which to store next measure
private var updates : Int; // Total number of updates (i.e. chunks) done *since the last frame was entered*
private var lastFrameStart : Int; // Lib.getTimer() value. Used to calculate millisecond delta between two frames
private var step : Int; // Number of scanlines to process during the next update (in order to approximate targetFPS, but without wasting cycles)
private var done : Bool; // Whether there's any more scanlines to process or not
private var metadata : Dynamic; // Treated as key-value pairs of tEXt/iTXt metadata
private var frameCount : Int; // Total number of frames that have elapsed so far during the encoding
public static inline function encode(img : BitmapData, metadata : Dynamic) : ByteArray
{
// Save current domain memory and restore it after, to avoid
// conflicts with other components using domain memory
var oldFastMem = ApplicationDomain.currentDomain.domainMemory;
var png = beginEncoding(img, metadata);
// Initialize stream for IDAT chunks
var deflateStream = DeflateStream.createEx(level, DEFLATE_SCRATCH, CHUNK_START, true);
writeIDATChunk(img, 0, img.height, deflateStream, png);
endEncoding(png);
deflateStream = null; // Just in case this helps the garbage collector...
Memory.select(oldFastMem);
return png;
}
#if DECODER
public static inline function decode(pngBytes : ByteArray) : BitmapData
{
//var start = Lib.getTimer();
// Assumes valid PNG created by PNGEncoder2 -- only the most basic error checking is done!
var failed = false;
if (pngBytes.length < 16) {
failed = true;
}
if (!failed && (pngBytes.readInt() != 0x89504e47 || pngBytes.readInt() != 0x0D0A1A0A)) {
failed = true;
}
//trace("Basic prelude: " + (Lib.getTimer() - start) + "ms");
//start = Lib.getTimer();
var bmp : BitmapData = null;
if (!failed) {
// Extract the dimensions, bit depth, and all the IDAT chunks
var width = -1;
var height = -1;
var transparent = false;
var idatData = new ByteArray();
var chunkLength = pngBytes.readUnsignedInt();
var chunkType = pngBytes.readUnsignedInt();
if (chunkType != 0x49484452 /* IHDR */) {
failed = true;
}
while (chunkType != 0x49454E44 /* IEND */) {
if (chunkType == 0x49484452 /* IHDR */) {
if (chunkLength != 13) {
failed = true;
}
width = pngBytes.readInt();
height = pngBytes.readInt();
++pngBytes.position; // Ignore bit depth (constant)
transparent = pngBytes.readUnsignedByte() == 6;
pngBytes.position += 3; // Ignore other options (constant)
// Resize to maximum length to avoid too many resizes when there's lots of chunks
idatData.length = transparent ? (height * width * 4 + height) : (height * width * 3 + height);
}
else if (chunkType == 0x49444154 /* IDAT */) {
pngBytes.readBytes(idatData, idatData.position, chunkLength);
idatData.position += chunkLength;
}
else {
pngBytes.position += chunkLength;
}
pngBytes.position += 4; // Ignore CRC-32 of chunk
chunkLength = pngBytes.readUnsignedInt();
chunkType = pngBytes.readUnsignedInt();
}
//trace("Chunk parsing & copying: " + (Lib.getTimer() - start) + "ms");
if (width == 0 || height == 0) {
bmp = new BitmapData(width, height, transparent, 0x00FFFFFF);
}
else if (!failed) {
// Decompress the data (is this as fast as it could be? Seems a tad
// slower than I was expecting... but still relatively quick, I suppose)
//start = Lib.getTimer();
idatData.uncompress();
//trace("uncompress(): " + (Lib.getTimer() - start) + "ms");
//start = Lib.getTimer();
// Reverse the Paeth filter (and add in alpha values if the PNG was non-transparent,
// otherwise move the alpha byte from the end to the beginning).
// Note: PNG is RGB(A), Flash wants ARGB, and get/setI32 are little-endian.
var oldFastMem = ApplicationDomain.currentDomain.domainMemory;
var addr = 0;
if (transparent) {
// Since the uncompressed data is > than the final bitmap size,
// we can undo the filter in-place
var destAddr : Int = 0;
Memory.select(idatData);
// First line
++addr; // Skip filter byte (it's always sub for the first line)
Memory.setI32(destAddr, rotl8(Memory.getI32(addr))); // first pixel
var widthBy4 = width * 4;
var endAddr = destAddr + widthBy4;
addr += 4;
destAddr += 4;
var endAddr64 = destAddr + ((widthBy4 - 1) & 0xFFFFFFC0);
while (destAddr != endAddr64) {
Memory.setI32(destAddr, byteAdd4(rotl8(Memory.getI32(addr)), Memory.getI32(destAddr - 4)));
Memory.setI32(destAddr + 4, byteAdd4(rotl8(Memory.getI32(addr + 4)), Memory.getI32(destAddr)));
Memory.setI32(destAddr + 8, byteAdd4(rotl8(Memory.getI32(addr + 8)), Memory.getI32(destAddr + 4)));
Memory.setI32(destAddr + 12, byteAdd4(rotl8(Memory.getI32(addr + 12)), Memory.getI32(destAddr + 8)));
Memory.setI32(destAddr + 16, byteAdd4(rotl8(Memory.getI32(addr + 16)), Memory.getI32(destAddr + 12)));
Memory.setI32(destAddr + 20, byteAdd4(rotl8(Memory.getI32(addr + 20)), Memory.getI32(destAddr + 16)));
Memory.setI32(destAddr + 24, byteAdd4(rotl8(Memory.getI32(addr + 24)), Memory.getI32(destAddr + 20)));
Memory.setI32(destAddr + 28, byteAdd4(rotl8(Memory.getI32(addr + 28)), Memory.getI32(destAddr + 24)));
Memory.setI32(destAddr + 32, byteAdd4(rotl8(Memory.getI32(addr + 32)), Memory.getI32(destAddr + 28)));
Memory.setI32(destAddr + 36, byteAdd4(rotl8(Memory.getI32(addr + 36)), Memory.getI32(destAddr + 32)));
Memory.setI32(destAddr + 40, byteAdd4(rotl8(Memory.getI32(addr + 40)), Memory.getI32(destAddr + 36)));
Memory.setI32(destAddr + 44, byteAdd4(rotl8(Memory.getI32(addr + 44)), Memory.getI32(destAddr + 40)));
Memory.setI32(destAddr + 48, byteAdd4(rotl8(Memory.getI32(addr + 48)), Memory.getI32(destAddr + 44)));
Memory.setI32(destAddr + 52, byteAdd4(rotl8(Memory.getI32(addr + 52)), Memory.getI32(destAddr + 48)));
Memory.setI32(destAddr + 56, byteAdd4(rotl8(Memory.getI32(addr + 56)), Memory.getI32(destAddr + 52)));
Memory.setI32(destAddr + 60, byteAdd4(rotl8(Memory.getI32(addr + 60)), Memory.getI32(destAddr + 56)));
addr += 64;
destAddr += 64;
}
while (destAddr != endAddr) {
Memory.setI32(destAddr, byteAdd4(rotl8(Memory.getI32(addr)), Memory.getI32(destAddr - 4)));
addr += 4;
destAddr += 4;
}
// Other lines:
for (i in 1 ... height) {
++addr; // Skip filter byte (always Paeth here)
// Do first pixel (4 bytes) manually (formula is different)
Memory.setI32(destAddr, byteAdd4(rotl8(Memory.getI32(addr)), Memory.getI32(destAddr - widthBy4)));
endAddr = destAddr + widthBy4;
addr += 4;
destAddr += 4;
endAddr64 = destAddr + ((widthBy4 - 1) & 0xFFFFFFC0);
while (destAddr != endAddr64) {
Memory.setI32(destAddr, byteAdd4(rotl8(Memory.getI32(addr)), paethPredictor4(Memory.getI32(destAddr - 4), Memory.getI32(destAddr - widthBy4), Memory.getI32(destAddr - 4 - widthBy4))));
Memory.setI32(destAddr + 4, byteAdd4(rotl8(Memory.getI32(addr + 4)), paethPredictor4(Memory.getI32(destAddr ), Memory.getI32(destAddr + 4 - widthBy4), Memory.getI32(destAddr - widthBy4))));
Memory.setI32(destAddr + 8, byteAdd4(rotl8(Memory.getI32(addr + 8)), paethPredictor4(Memory.getI32(destAddr + 4), Memory.getI32(destAddr + 8 - widthBy4), Memory.getI32(destAddr + 4 - widthBy4))));
Memory.setI32(destAddr + 12, byteAdd4(rotl8(Memory.getI32(addr + 12)), paethPredictor4(Memory.getI32(destAddr + 8), Memory.getI32(destAddr + 12 - widthBy4), Memory.getI32(destAddr + 8 - widthBy4))));
Memory.setI32(destAddr + 16, byteAdd4(rotl8(Memory.getI32(addr + 16)), paethPredictor4(Memory.getI32(destAddr + 12), Memory.getI32(destAddr + 16 - widthBy4), Memory.getI32(destAddr + 12 - widthBy4))));
Memory.setI32(destAddr + 20, byteAdd4(rotl8(Memory.getI32(addr + 20)), paethPredictor4(Memory.getI32(destAddr + 16), Memory.getI32(destAddr + 20 - widthBy4), Memory.getI32(destAddr + 16 - widthBy4))));
Memory.setI32(destAddr + 24, byteAdd4(rotl8(Memory.getI32(addr + 24)), paethPredictor4(Memory.getI32(destAddr + 20), Memory.getI32(destAddr + 24 - widthBy4), Memory.getI32(destAddr + 20 - widthBy4))));
Memory.setI32(destAddr + 28, byteAdd4(rotl8(Memory.getI32(addr + 28)), paethPredictor4(Memory.getI32(destAddr + 24), Memory.getI32(destAddr + 28 - widthBy4), Memory.getI32(destAddr + 24 - widthBy4))));
Memory.setI32(destAddr + 32, byteAdd4(rotl8(Memory.getI32(addr + 32)), paethPredictor4(Memory.getI32(destAddr + 28), Memory.getI32(destAddr + 32 - widthBy4), Memory.getI32(destAddr + 28 - widthBy4))));
Memory.setI32(destAddr + 36, byteAdd4(rotl8(Memory.getI32(addr + 36)), paethPredictor4(Memory.getI32(destAddr + 32), Memory.getI32(destAddr + 36 - widthBy4), Memory.getI32(destAddr + 32 - widthBy4))));
Memory.setI32(destAddr + 40, byteAdd4(rotl8(Memory.getI32(addr + 40)), paethPredictor4(Memory.getI32(destAddr + 36), Memory.getI32(destAddr + 40 - widthBy4), Memory.getI32(destAddr + 36 - widthBy4))));
Memory.setI32(destAddr + 44, byteAdd4(rotl8(Memory.getI32(addr + 44)), paethPredictor4(Memory.getI32(destAddr + 40), Memory.getI32(destAddr + 44 - widthBy4), Memory.getI32(destAddr + 40 - widthBy4))));
Memory.setI32(destAddr + 48, byteAdd4(rotl8(Memory.getI32(addr + 48)), paethPredictor4(Memory.getI32(destAddr + 44), Memory.getI32(destAddr + 48 - widthBy4), Memory.getI32(destAddr + 44 - widthBy4))));
Memory.setI32(destAddr + 52, byteAdd4(rotl8(Memory.getI32(addr + 52)), paethPredictor4(Memory.getI32(destAddr + 48), Memory.getI32(destAddr + 52 - widthBy4), Memory.getI32(destAddr + 48 - widthBy4))));
Memory.setI32(destAddr + 56, byteAdd4(rotl8(Memory.getI32(addr + 56)), paethPredictor4(Memory.getI32(destAddr + 52), Memory.getI32(destAddr + 56 - widthBy4), Memory.getI32(destAddr + 52 - widthBy4))));
Memory.setI32(destAddr + 60, byteAdd4(rotl8(Memory.getI32(addr + 60)), paethPredictor4(Memory.getI32(destAddr + 56), Memory.getI32(destAddr + 60 - widthBy4), Memory.getI32(destAddr + 56 - widthBy4))));
addr += 64;
destAddr += 64;
}
while (destAddr != endAddr) {
Memory.setI32(destAddr, byteAdd4(rotl8(Memory.getI32(addr)), paethPredictor4(Memory.getI32(destAddr - 4), Memory.getI32(destAddr - widthBy4), Memory.getI32(destAddr - 4 - widthBy4))));
addr += 4;
destAddr += 4;
}
}
//trace("Reverse filters (32-bit): " + (Lib.getTimer() - start) + "ms");
// Copy into a BitmapData!
Memory.select(oldFastMem);
idatData.position = 0;
bmp = new BitmapData(width, height, transparent, 0x00FFFFFF);
bmp.setPixels(new Rectangle(0, 0, width, height), idatData);
}
else { // 24-bit
//var start = Lib.getTimer();
var destStart = idatData.length;
var destAddr : Int = destStart;
// Since Flash wants ARGB (4-byte) values for each pixel,
// we can't decode on-place :-(
idatData.length = idatData.length + width * height * 4;
Memory.select(idatData);
// First line
++addr; // Skip filter byte (it's always sub for the first line)
// First pixel has different formula
Memory.setI16(destAddr, Memory.getByte(addr) << 8);
Memory.setByte(destAddr + 2, Memory.getByte(addr + 1));
Memory.setByte(destAddr + 3, Memory.getByte(addr + 2));
var widthBy4 = width * 4;
var endAddr = destAddr + widthBy4;
addr += 3;
destAddr += 4;
var endAddr64 = destAddr + ((widthBy4 - 1) & 0xFFFFFFC0);
// Rest of first line
--addr; // Offset addr by one so that when reading 32-bit little-endian RGB value,
// we can read a random byte in the alpha (XRGB) which is OK because it's
// ignored (but we do it to get the RGB offset properly)
while (destAddr != endAddr64) {
Memory.setI32(destAddr, byteAdd4(Memory.getI32(addr), Memory.getI32(destAddr - 4)));
Memory.setI32(destAddr + 4, byteAdd4(Memory.getI32(addr + 3), Memory.getI32(destAddr)));
Memory.setI32(destAddr + 8, byteAdd4(Memory.getI32(addr + 6), Memory.getI32(destAddr + 4)));
Memory.setI32(destAddr + 12, byteAdd4(Memory.getI32(addr + 9), Memory.getI32(destAddr + 8)));
Memory.setI32(destAddr + 16, byteAdd4(Memory.getI32(addr + 12), Memory.getI32(destAddr + 12)));
Memory.setI32(destAddr + 20, byteAdd4(Memory.getI32(addr + 15), Memory.getI32(destAddr + 16)));
Memory.setI32(destAddr + 24, byteAdd4(Memory.getI32(addr + 18), Memory.getI32(destAddr + 20)));
Memory.setI32(destAddr + 28, byteAdd4(Memory.getI32(addr + 21), Memory.getI32(destAddr + 24)));
Memory.setI32(destAddr + 32, byteAdd4(Memory.getI32(addr + 24), Memory.getI32(destAddr + 28)));
Memory.setI32(destAddr + 36, byteAdd4(Memory.getI32(addr + 27), Memory.getI32(destAddr + 32)));
Memory.setI32(destAddr + 40, byteAdd4(Memory.getI32(addr + 30), Memory.getI32(destAddr + 36)));
Memory.setI32(destAddr + 44, byteAdd4(Memory.getI32(addr + 33), Memory.getI32(destAddr + 40)));
Memory.setI32(destAddr + 48, byteAdd4(Memory.getI32(addr + 36), Memory.getI32(destAddr + 44)));
Memory.setI32(destAddr + 52, byteAdd4(Memory.getI32(addr + 39), Memory.getI32(destAddr + 48)));
Memory.setI32(destAddr + 56, byteAdd4(Memory.getI32(addr + 42), Memory.getI32(destAddr + 52)));
Memory.setI32(destAddr + 60, byteAdd4(Memory.getI32(addr + 45), Memory.getI32(destAddr + 56)));
addr += 48;
destAddr += 64;
}
while (destAddr != endAddr) {
Memory.setI32(destAddr, byteAdd4(Memory.getI32(addr), Memory.getI32(destAddr - 4)));
addr += 3;
destAddr += 4;
}
++addr; // Un-offset addr
// Remaining lines:
for (i in 1 ... height) {
++addr; // Skip filter byte, always Paeth here
// Do first pixel manually (formula is different)
Memory.setI16(destAddr, (Memory.getByte(addr) + Memory.getByte(destAddr + 1 - widthBy4)) << 8);
Memory.setByte(destAddr + 2, Memory.getByte(addr + 1) + Memory.getByte(destAddr + 2 - widthBy4));
Memory.setByte(destAddr + 3, Memory.getByte(addr + 2) + Memory.getByte(destAddr + 3 - widthBy4));
endAddr = destAddr + widthBy4;
addr += 3;
destAddr += 4;
endAddr64 = destAddr + ((widthBy4 - 1) & 0xFFFFFFC0);
--addr;
while (destAddr != endAddr64) {
Memory.setI32(destAddr, byteAdd4(Memory.getI32(addr), paethPredictor3Hi(Memory.getI32(destAddr - 4), Memory.getI32(destAddr - widthBy4), Memory.getI32(destAddr - 4 - widthBy4))));
Memory.setI32(destAddr + 4, byteAdd4(Memory.getI32(addr + 3), paethPredictor3Hi(Memory.getI32(destAddr), Memory.getI32(destAddr + 4 - widthBy4), Memory.getI32(destAddr - widthBy4))));
Memory.setI32(destAddr + 8, byteAdd4(Memory.getI32(addr + 6), paethPredictor3Hi(Memory.getI32(destAddr + 4), Memory.getI32(destAddr + 8 - widthBy4), Memory.getI32(destAddr + 4 - widthBy4))));
Memory.setI32(destAddr + 12, byteAdd4(Memory.getI32(addr + 9), paethPredictor3Hi(Memory.getI32(destAddr + 8), Memory.getI32(destAddr + 12 - widthBy4), Memory.getI32(destAddr + 8 - widthBy4))));
Memory.setI32(destAddr + 16, byteAdd4(Memory.getI32(addr + 12), paethPredictor3Hi(Memory.getI32(destAddr + 12), Memory.getI32(destAddr + 16 - widthBy4), Memory.getI32(destAddr + 12 - widthBy4))));
Memory.setI32(destAddr + 20, byteAdd4(Memory.getI32(addr + 15), paethPredictor3Hi(Memory.getI32(destAddr + 16), Memory.getI32(destAddr + 20 - widthBy4), Memory.getI32(destAddr + 16 - widthBy4))));
Memory.setI32(destAddr + 24, byteAdd4(Memory.getI32(addr + 18), paethPredictor3Hi(Memory.getI32(destAddr + 20), Memory.getI32(destAddr + 24 - widthBy4), Memory.getI32(destAddr + 20 - widthBy4))));
Memory.setI32(destAddr + 28, byteAdd4(Memory.getI32(addr + 21), paethPredictor3Hi(Memory.getI32(destAddr + 24), Memory.getI32(destAddr + 28 - widthBy4), Memory.getI32(destAddr + 24 - widthBy4))));
Memory.setI32(destAddr + 32, byteAdd4(Memory.getI32(addr + 24), paethPredictor3Hi(Memory.getI32(destAddr + 28), Memory.getI32(destAddr + 32 - widthBy4), Memory.getI32(destAddr + 28 - widthBy4))));
Memory.setI32(destAddr + 36, byteAdd4(Memory.getI32(addr + 27), paethPredictor3Hi(Memory.getI32(destAddr + 32), Memory.getI32(destAddr + 36 - widthBy4), Memory.getI32(destAddr + 32 - widthBy4))));
Memory.setI32(destAddr + 40, byteAdd4(Memory.getI32(addr + 30), paethPredictor3Hi(Memory.getI32(destAddr + 36), Memory.getI32(destAddr + 40 - widthBy4), Memory.getI32(destAddr + 36 - widthBy4))));
Memory.setI32(destAddr + 44, byteAdd4(Memory.getI32(addr + 33), paethPredictor3Hi(Memory.getI32(destAddr + 40), Memory.getI32(destAddr + 44 - widthBy4), Memory.getI32(destAddr + 40 - widthBy4))));
Memory.setI32(destAddr + 48, byteAdd4(Memory.getI32(addr + 36), paethPredictor3Hi(Memory.getI32(destAddr + 44), Memory.getI32(destAddr + 48 - widthBy4), Memory.getI32(destAddr + 44 - widthBy4))));
Memory.setI32(destAddr + 52, byteAdd4(Memory.getI32(addr + 39), paethPredictor3Hi(Memory.getI32(destAddr + 48), Memory.getI32(destAddr + 52 - widthBy4), Memory.getI32(destAddr + 48 - widthBy4))));
Memory.setI32(destAddr + 56, byteAdd4(Memory.getI32(addr + 42), paethPredictor3Hi(Memory.getI32(destAddr + 52), Memory.getI32(destAddr + 56 - widthBy4), Memory.getI32(destAddr + 52 - widthBy4))));
Memory.setI32(destAddr + 60, byteAdd4(Memory.getI32(addr + 45), paethPredictor3Hi(Memory.getI32(destAddr + 56), Memory.getI32(destAddr + 60 - widthBy4), Memory.getI32(destAddr + 56 - widthBy4))));
addr += 48;
destAddr += 64;
}
while (destAddr != endAddr) {
Memory.setI32(destAddr, byteAdd4(Memory.getI32(addr), paethPredictor3Hi(Memory.getI32(destAddr - 4), Memory.getI32(destAddr - widthBy4), Memory.getI32(destAddr - 4 - widthBy4))));
addr += 3;
destAddr += 4;
}
++addr;
}
//trace("Reverse filters (32-bit): " + (Lib.getTimer() - start) + "ms");
// Copy into a BitmapData!
Memory.select(oldFastMem);
idatData.position = destStart;
bmp = new BitmapData(width, height, transparent, 0x00FFFFFF);
bmp.setPixels(new Rectangle(0, 0, width, height), idatData);
}
}
}
return bmp;
}
private static inline function rotl8(x : Int) { return (x << 8) | (x >>> 24); }
private static inline function byteAdd4(a : UInt, b : UInt)
{
return (((a & 0xFF00FF00) + (b & 0xFF00FF00)) & 0xFF00FF00) | (((a & 0x00FF00FF) + (b & 0x00FF00FF)) & 0x00FF00FF);
}
private static inline function paethPredictor3Hi(a : Int, b : Int, c : Int)
{
var pa = abs((b & 0x0000FF00) - (c & 0x0000FF00));
var pb = abs((a & 0x0000FF00) - (c & 0x0000FF00));
var pc = abs((a & 0x0000FF00) + (b & 0x0000FF00) - ((c << 1) & 0x0001FE00));
var notACond = (((pb - pa) | (pc - pa)) >> 31) & 0x0000FF00;
var notBCond = ((pc - pb) >> 31) & 0x0000FF00;
pa = abs((b & 0x00FF0000) - (c & 0x00FF0000));
pb = abs((a & 0x00FF0000) - (c & 0x00FF0000));
pc = abs((a & 0x00FF0000) + (b & 0x00FF0000) - ((c << 1) & 0x01FE0000));
notACond |= (((pb - pa) | (pc - pa)) >> 31) & 0x00FF0000;
notBCond |= ((pc - pb) >> 31) & 0x00FF0000;
pa = abs(((b >> 8) & 0x00FF0000) - ((c >> 8) & 0x00FF0000));
pb = abs(((a >> 8) & 0x00FF0000) - ((c >> 8) & 0x00FF0000));
pc = abs(((a >> 8) & 0x00FF0000) + ((b >> 8) & 0x00FF0000) - ((c >> 7) & 0x01FE0000));
notACond |= (((pb - pa) | (pc - pa)) >> 31) & 0xFF000000;
notBCond |= ((pc - pb) >> 31) & 0xFF000000;
//return pa <= pb && pa <= pc ? a : (pb <= pc ? b : c);
return (a & ~notACond) | (b & notACond & ~notBCond) | (c & notACond & notBCond);
}
#end
private static inline function beginEncoding(img : BitmapData, metadata : Dynamic) : ByteArray
{
if (encoding) {
throw new Error("Only one PNG can be encoded at once (are you encoding asynchronously while attempting to encode another PNG synchronously?)");
// This limitation is in place to make the implementation simpler;
// there is only one domain memory chunk across all PNG encoding
// (because it contains cached values like the CRC table).
}
encoding = true;
if (level == null) {
// Use default if no level explicitly specified
#if (FAST_ONLY || !(FAST_ONLY || NORMAL_ONLY || GOOD_ONLY))
level = FAST;
#elseif NORMAL_ONLY
level = NORMAL;
#elseif GOOD_ONLY
level = GOOD;
#end
}
// Data will be select()ed for use with fast memory
// The first 256 * 4 bytes are the CRC table
// Inner chunk data is appended to the CRC table, starting at CHUNK_START
initialize(); // Sets up data var & CRC table
// Create output byte array
var png:ByteArray = new ByteArray();
writePNGSignature(png);
writeIHDRChunk(img, png);
writeMetadataChunks(metadata, png);
return png;
}
private static inline function endEncoding(png : ByteArray)
{
writeIENDChunk(png);
encoding = false;
png.position = 0;
}
public inline function new(image : BitmapData, dispatcher : IEventDispatcher, metadata : Dynamic)
{
targetFPS = 20; // Default, can be overridden
_new(image, dispatcher, metadata); // Constructors are slow -- delegate to function
}
private function _new(image : BitmapData, dispatcher : IEventDispatcher, metadata : Dynamic)
{
fastNew(image, dispatcher, metadata);
}
//private static var __frame : Int;
//private static function staticEnterFrame(e : Event) { ++__frame; }
private inline function fastNew(image : BitmapData, dispatcher : IEventDispatcher, metadata : Dynamic)
{
img = image;
this.dispatcher = dispatcher;
this.metadata = metadata;
if (encoding) {
// Add to queue for later!
pendingAsyncEncodings.push(this);
}
else {
lastFrameStart = Lib.getTimer();
// Preserve current domain memory so that we can leave it as we found
// it once we've finished using it
var oldFastMem = ApplicationDomain.currentDomain.domainMemory;
png = beginEncoding(img, metadata);
currentY = 0;
frameCount = 0;
done = false;
msPerFrame = new Vector<Int>(FRAME_AVG_SMOOTH_COUNT, true);
msPerFrameIndex = 0;
msPerLine = new Vector<Float>(FRAME_AVG_SMOOTH_COUNT, true);
msPerLineIndex = 0;
updatesPerFrame = new Vector<Int>(FRAME_AVG_SMOOTH_COUNT, true);
updatesPerFrameIndex = 0;
// Note that this effectively freezes the compression level for the
// duration of the encoding (even if the static level member changes)
deflateStream = DeflateStream.createEx(level, DEFLATE_SCRATCH, CHUNK_START, true);
//if (!sprite.hasEventListener(Event.ENTER_FRAME)) {
// sprite.addEventListener(Event.ENTER_FRAME, staticEnterFrame);
//}
//trace("Async encoding began on frame " + __frame);
// Get notified of new frames
sprite.addEventListener(Event.ENTER_FRAME, onEnterFrame);
// We write data in chunks (one per update), starting with one
// chunk right now in order to gather some statistics up front
// to make an informed estimate for the next update's step size.
// Note that small images may be entirely encoded in this step,
// but we don't dispatch any events until the next update in
// order to give the client an opportunity to attach event listeners.
if (img.width > 0 && img.height > 0) {
// Determine proper start step
var startTime = Lib.getTimer();
// Write first ~20K pixels to see how fast it is
var height = Math.ceil(Math.min(FIRST_UPDATE_PIXELS / img.width, img.height));
writeIDATChunk(img, 0, height, deflateStream, png);
var endTime = Lib.getTimer();
updateMsPerLine(endTime - startTime, height);
// Use unmeasured FPS as guestimate to seed msPerFrame
var fps = Lib.current == null || Lib.current.stage == null ? 24 : Lib.current.stage.frameRate;
updateMsPerFrame(Std.int(1.0 / fps * 1000));
updateUpdatesPerFrame(1);
updateStep();
currentY = height;
}
else {
// A dimension is 0
step = img.height;
}
updates = 0;
Memory.select(oldFastMem); // Play nice!
}
}
// Updates the msPerLine vector with a new measure
private inline function updateMsPerLine(ms : Int, lines : Int)
{
if (lines != 0) {
if (ms <= 0) {
// Can occasionally happen because timer resolution on Windows is limited to 10ms
ms = 5; // Guess!
}
msPerLine[msPerLineIndex] = ms * 1.0 / lines;
msPerLineIndex = (msPerLineIndex + 1) & (FRAME_AVG_SMOOTH_COUNT - 1); // Cheap modulus
}
}
// Updates the msPerFrame vector with a new measure
private inline function updateMsPerFrame(ms : Int)
{
msPerFrame[msPerFrameIndex] = ms;
msPerFrameIndex = (msPerFrameIndex + 1) & (FRAME_AVG_SMOOTH_COUNT - 1); // Cheap modulus
}
// Updates the updatesPerFrame vector with a new measure
private inline function updateUpdatesPerFrame(updates : Int)
{
updatesPerFrame[updatesPerFrameIndex] = updates;
updatesPerFrameIndex = (updatesPerFrameIndex + 1) & (FRAME_AVG_SMOOTH_COUNT - 1);
}
// Makes an informed estimate of how many scanlines should be processed during
// the next update, and sets the "step" member variable to that value
private inline function updateStep()
{
// Updates are always executing as fast as possible in order to saturate the
// event loop/render cycle (aka the "elastic racetrack": see http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/)
// So, instead of changing the update frequency, we predict the best number of
// scanlines to process (the "step") during the next update based on past evidence
// of how long it takes to process one scanline. We monitor the FPS to determine
// how closely we're approaching the targetFPS, and thus which direction we should
// adjust towards. We push against the targetFPS as much as possible in order to
// saturate the AVM2's cycle and so minimize idling time and maximize encoding speed).
// Data: We have the last FRAME_AVG_SMOOTH_COUNT measurements of various
// statistics that we can use to calculate moving averages
var avgMsPerFrame = 0.0;
var count = 0;
for (ms in msPerFrame) {
if (ms > 0) { // Discount measurements of 0 (can happen with imprecise platform timers)
avgMsPerFrame += ms;
++count;
}
}
if (count != 0) { // Make sure we have sufficient data
avgMsPerFrame /= count;
// Check our current empirical FPS against the target
// (with 15% leeway in favour of a slightly slower FPS)
var targetMs = 1000.0 / targetFPS;
if (avgMsPerFrame > targetMs * 1.15) {
// Too slow, pull back a bit
targetMs -= avgMsPerFrame - targetMs; // Error delta
}
var avgUpdatesPerFrame = 0.0;
count = 0;
for (ups in updatesPerFrame) {
if (ups > 0) {
avgUpdatesPerFrame += ups;
++count;
}
}
if (count != 0) {
avgUpdatesPerFrame /= count;
var avgMsPerLine = 0.0;
count = 0;
for (ms in msPerLine) {
if (ms > 0) {
avgMsPerLine += ms;
++count;
}
}
if (count != 0) {
avgMsPerLine /= count;
// Calculate step; must include at least MIN_PIXELS_PER_FRAME, and must be >= 1
// In dimensional analysis, the estimate works out to:
// ? scanlinesPerUpdate = scanlinesPerMs * targetMsPerFrame * framesPerUpdate
step = Math.ceil(Math.max(targetMs / avgMsPerLine / avgUpdatesPerFrame, MIN_PIXELS_PER_UPDATE / img.width));
}
else {
step = Math.ceil(MIN_PIXELS_PER_UPDATE / img.width);
}
}
else {
step = Math.ceil(MIN_PIXELS_PER_UPDATE / img.width);
}
}
else { // Not enough data, just use bare minimum for step
step = Math.ceil(MIN_PIXELS_PER_UPDATE / img.width);
}
}
private function onEnterFrame(e : Event)
{
updateFrameInfo();
update();
}
private inline function updateFrameInfo()
{
if (!done) {
++frameCount;
var now = Lib.getTimer();
updateMsPerFrame(now - lastFrameStart);
lastFrameStart = now;
updateUpdatesPerFrame(updates);
updates = 0;
}
}
private inline function update()
{
// Need to check if we've finished or not since it's possible (if we're
// attached to a timer) for a timer event to be dispatched before we stop
// it, but get processed after we've finished (e.g. if there's two timer
// events in the event queue and the first one finishes the work, the second
// will still cause this function to be entered since it was generated
// before we stopped the timer).
if (!done) {
var start = Lib.getTimer();
++updates;
// Play nice with others, and preserve the domain memory
var oldFastMem = ApplicationDomain.currentDomain.domainMemory;
Memory.select(data);
// Queue events (dispatched at end) instead of dispatching them inline
// because during a call to dispatchEvent *other* pending events
// might be dispatched too, possibly resulting in this method being
// called again in a re-entrant fashion (which doesn't play nicely
// with storing/retrieving oldFastMem).
var progressEvent : ProgressEvent = null;
var completeEvent : Event = null;
var bytesPerPixel = img.transparent ? 4 : 3;
var totalBytes = bytesPerPixel * img.width * img.height;
if (currentY >= img.height) {
// Finished encoding the entire image in the initial setup
progressEvent = new ProgressEvent(ProgressEvent.PROGRESS, false, false, totalBytes, totalBytes);
completeEvent = finalize();
}
else {
var next = Std.int(Math.min(currentY + step, img.height));
writeIDATChunk(img, currentY, next, deflateStream, png);
currentY = next;
var currentBytes = bytesPerPixel * img.width * currentY;
progressEvent = new ProgressEvent(ProgressEvent.PROGRESS, false, false, currentBytes, totalBytes);
completeEvent = finalize();
updateMsPerLine(Lib.getTimer() - start, step);
updateStep();
}
Memory.select(oldFastMem);
// With `done` stable and domain memory properly set, we can now safely
// handle re-entrancy (thank goodness Flash is single threaded or this
// would be even more of a nightmare)
if (progressEvent != null) {
dispatcher.dispatchEvent(progressEvent);
progressEvent = null;
}
if (completeEvent != null) {
dispatcher.dispatchEvent(completeEvent);
completeEvent = null;
}
if (done) {
//trace("Async encoding finished on frame " + __frame + " (targetFPS was " + targetFPS + ")");
// Clear some references to give the garbage collector an easier time
dispatcher = null; // This removes a circular reference, which might save a mark-and-sweep step
img = null;
deflateStream = null;
msPerFrame = null;
msPerLine = null;
updatesPerFrame = null;
if (!encoding && pendingAsyncEncodings.length > 0) {
// Need to check `encoding` just in case someone started encoding another PNG
// in the async COMPLETED event handler
var next = pendingAsyncEncodings.shift();
next._new(next.img, next.dispatcher, next.metadata);
}
}
}
}
// Only finalizes the encoding if there's nothing left to encode
private inline function finalize() : Event
{
var result : Event = null;
if (currentY >= img.height) {
done = true;
sprite.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
endEncoding(png);
result = new Event(Event.COMPLETE);
//trace("Async completed over " + frameCount + " frame(s)");
}
return result;
}
private static inline function writePNGSignature(png : ByteArray)
{
// See PNG spec for details
png.writeUnsignedInt(0x89504e47);
png.writeUnsignedInt(0x0D0A1A0A);
}
private static inline function writeIHDRChunk(img : BitmapData, png : ByteArray)
{
var chunkLength = 13; // 13-byte header
data.length = Std.int(Math.max(CHUNK_START + chunkLength, ApplicationDomain.MIN_DOMAIN_MEMORY_LENGTH));
Memory.select(data);
writeI32BE(CHUNK_START, img.width);
writeI32BE(CHUNK_START + 4, img.height);
Memory.setByte(CHUNK_START + 8, 8); // Bit depth
if (img.transparent) {
Memory.setByte(CHUNK_START + 9, 6); // RGBA colour type
}
else {
Memory.setByte(CHUNK_START + 9, 2); // RGB colour type
}
Memory.setByte(CHUNK_START + 10, 0); // Compression method (always 0 -> zlib)
Memory.setByte(CHUNK_START + 11, 0); // Filter method (always 0)
Memory.setByte(CHUNK_START + 12, 0); // No interlacing
writeChunk(png, 0x49484452, chunkLength);
}
private static function writeMetadataChunks(metadata : Dynamic, png : ByteArray)
{
if (metadata != null) {
var chunkData = new ByteArray();
Memory.select(data);