/
GIFPlayer.as
296 lines (257 loc) · 8.16 KB
/
GIFPlayer.as
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
/************************************************************************
* Copyright 2010-2011 Worlize Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***********************************************************************/
package com.worlize.gif
{
import com.worlize.gif.constants.DisposalType;
import com.worlize.gif.events.AsyncDecodeErrorEvent;
import com.worlize.gif.events.GIFDecoderEvent;
import com.worlize.gif.events.GIFPlayerEvent;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import flash.utils.Timer;
[Event(name="complete",type="com.worlize.gif.events.GIFPlayerEvent")]
[Event(name="frameRendered",type="com.worlize.gif.events.GIFPlayerEvent")]
[Event(name="asyncDecodeError",type="com.worlize.gif.events.AsyncDecodeErrorEvent")]
public class GIFPlayer extends Bitmap
{
[Bindable]
public var autoPlay:Boolean;
[Bindable]
public var enableFrameSkipping:Boolean = false;
private var wasPlaying:Boolean = false;
private var minFrameDelay:Number;
private var useSmoothing:Boolean = false;
private var lastQuantizationError:Number = 0;
private var gifDecoder:GIFDecoder;
private var timer:Timer = new Timer(0, 0);
private var currentLoop:uint;
private var _loopCount:uint;
private var _currentFrame:int = -1;
private var _frameCount:uint = 0;
private var _frames:Vector.<GIFFrame>;
private var _ready:Boolean = false;
private var _imageWidth:Number;
private var _imageHeight:Number;
public function GIFPlayer(autoPlay:Boolean = true) {
this.autoPlay = autoPlay;
if (stage) {
initMinFrameDelay();
}
addEventListener(Event.ADDED_TO_STAGE, initMinFrameDelay);
timer.addEventListener(TimerEvent.TIMER, handleTimer);
addEventListener(Event.REMOVED_FROM_STAGE, handleRemovedFromStage);
}
protected function handleRemovedFromStage(event:Event):void {
wasPlaying = playing;
stop();
addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
}
protected function handleAddedToStage(event:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
if (wasPlaying) {
play();
}
}
override public function set smoothing(newValue:Boolean):void {
if (useSmoothing !== newValue) {
useSmoothing = newValue;
super.smoothing = newValue;
}
}
private function initMinFrameDelay(event:Event=null):void {
// stage.frameRate = 60;
minFrameDelay = 1000 / stage.frameRate;
}
public function loadBytes(data:ByteArray):void {
reset();
gifDecoder.decodeBytes(data);
}
public function reset():void {
stop();
setReady(false);
unloadDecoder();
dispose();
initDecoder();
}
protected function initDecoder():void {
gifDecoder = new GIFDecoder();
gifDecoder.addEventListener(GIFDecoderEvent.DECODE_COMPLETE, handleDecodeComplete);
gifDecoder.addEventListener(AsyncDecodeErrorEvent.ASYNC_DECODE_ERROR, handleAsyncDecodeError);
}
protected function unloadDecoder():void {
if (gifDecoder) {
gifDecoder.removeEventListener(GIFDecoderEvent.DECODE_COMPLETE, handleDecodeComplete);
gifDecoder.removeEventListener(AsyncDecodeErrorEvent.ASYNC_DECODE_ERROR, handleAsyncDecodeError);
gifDecoder = null;
}
}
protected function handleDecodeComplete(event:GIFDecoderEvent):void {
// trace("Decode complete. Total decoding time: " + gifDecoder.totalDecodeTime + " Blocking decode time: " + gifDecoder.blockingDecodeTime);
currentLoop = 0;
_loopCount = gifDecoder.loopCount;
_frames = gifDecoder.frames;
_frameCount = _frames.length;
_currentFrame = -1;
_imageWidth = gifDecoder.width;
_imageHeight = gifDecoder.height;
gifDecoder.cleanup();
unloadDecoder();
setReady(true);
dispatchEvent(new Event('totalFramesChange'));
dispatchEvent(new GIFPlayerEvent(GIFPlayerEvent.COMPLETE));
if (stage) {
if (autoPlay) {
gotoAndPlay(1);
}
else {
gotoAndStop(1);
}
}
}
private function handleTimer(event:TimerEvent):void {
step();
}
public function gotoAndPlay(requestedIndex:uint):void {
lastQuantizationError = 0;
goto(requestedIndex-1);
play();
}
public function gotoAndStop(requestedIndex:uint):void {
stop();
lastQuantizationError = 0;
goto(requestedIndex-1);
}
public function play():void {
if (_frameCount <= 0) {
throw new Error("Nothing to play");
}
// single-frame file, nothing to play but we can
// render the first frame.
if (_frameCount === 1) {
goto(0);
}
else {
timer.start();
lastQuantizationError = 0;
}
}
public function stop():void {
if (timer.running) {
timer.stop();
}
}
private function quantizeFrameDelay(input:Number, increment:Number):Number {
var adjustedInput:Number = input + lastQuantizationError;
var output:Number = Math.round((adjustedInput)/increment)*increment;
lastQuantizationError = adjustedInput - output;
return output;
}
private function step():void {
if (_currentFrame + 1 >= _frameCount) {
currentLoop ++;
if (_loopCount === 0 || currentLoop < _loopCount) {
goto(0);
}
else {
stop();
}
}
else {
goto(_currentFrame + 1);
}
}
// This private API function uses zero-based indices, while the public
// facing API uses one-based indices
private function goto(requestedIndex:uint):void {
if (requestedIndex >= _frameCount || requestedIndex < 0) {
throw new RangeError("The requested frame is out of bounds.");
}
if (requestedIndex === _currentFrame) {
return;
}
// Store current frame index
_currentFrame = requestedIndex;
var requestedDelay:Number = (currentFrameObject.delayMs === 0) ? 100 : currentFrameObject.delayMs;
var delay:Number = Math.round(quantizeFrameDelay(requestedDelay, minFrameDelay));
delay = Math.max(delay - minFrameDelay/2, 0);
timer.delay = delay;
if (delay === 0 && enableFrameSkipping) {
// skip the frame
step();
return;
}
// Update the display
bitmapData = currentFrameObject.bitmapData;
if (useSmoothing) {
super.smoothing = true;
}
var renderedEvent:GIFPlayerEvent = new GIFPlayerEvent(GIFPlayerEvent.FRAME_RENDERED);
renderedEvent.frameIndex = _currentFrame;
dispatchEvent(renderedEvent);
}
public function dispose():void {
if (_frames === null) { return; }
for (var i:int = 0; i < _frames.length; i ++) {
_frames[i].bitmapData.dispose();
}
}
public function get playing():Boolean {
return timer.running;
}
[Bindable(event="frameRendered")]
public function get currentFrame():uint {
return _currentFrame+1;
}
[Bindable(event="totalFramesChange")]
public function get totalFrames():uint {
return _frameCount;
}
[Bindable(event="readyChange")]
public function get ready():Boolean {
return _ready;
}
protected function setReady(newValue:Boolean):void {
if (_ready !== newValue) {
_ready = newValue;
dispatchEvent(new Event("readyChange"));
}
}
public function get loopCount():uint {
return _loopCount;
}
protected function get currentFrameObject():GIFFrame {
return _frames[_currentFrame];
}
protected function get previousFrameObject():GIFFrame {
if (_currentFrame === 0) { return null; }
return _frames[_currentFrame-1];
}
protected function handleAsyncDecodeError(event:AsyncDecodeErrorEvent):void {
dispatchEvent(event.clone());
}
override public function get width():Number {
return _imageWidth;
}
override public function get height():Number {
return _imageHeight;
}
}
}