Debian Codegraph @

contrib/aseprite_codec/aseprite.py

raw symbols SCIP
1 """Decoder for Aseprite animation files in .ase or .aseprite format.
2 """
3
4 import io
5 import zlib
6 import struct
7
8 from pyglet.image import ImageData, Animation, AnimationFrame
9 from pyglet.image.codecs import ImageDecoder, ImageDecodeException
10
11
12 # Documentation for the Aseprite format can be found here:
13 # https://raw.githubusercontent.com/aseprite/aseprite/master/docs/ase-file-specs.md
14
15
16 BYTE = "B"
17 WORD = "H"
18 SHORT = "h"
19 DWORD = "I"
20
21 BLEND_MODES = {0: 'Normal',
22 1: 'Multiply',
23 2: 'Screen',
24 3: 'Overlay',
25 4: 'Darken',
26 5: 'Lighten',
27 6: 'Color Dodge',
28 7: 'Color Burn',
29 8: 'Hard Light',
30 9: 'Soft Light',
31 10: 'Difference',
32 11: 'Exclusion',
33 12: 'Hue',
34 13: 'Saturation',
35 14: 'Color',
36 15: 'Luminosity'}
37
38 PALETTE_DICT = {}
39 PALETTE_INDEX = 0
40
41
42 def _unpack(fmt, file):
43 """Unpack little endian bytes from a file-like object. """
44 size = struct.calcsize(fmt)
45 data = file.read(size)
46 if len(data) < size:
47 raise ImageDecodeException('Unexpected EOF')
48 return struct.unpack("<" + fmt, data)[0]
49
50
51 def _chunked_iter(seq, size):
52 return (seq[pos:pos + size] for pos in range(0, len(seq), size))
53
54
55 #########################################
56 # Class for Aseprite compliant header
57 #########################################
58
59 class AsepriteHeader:
60 def __init__(self, file):
61 self.file_size = _unpack(DWORD, file)
62 self.magic_number = hex(_unpack(WORD, file))
63 self.num_frames = _unpack(WORD, file)
64 self.width = _unpack(WORD, file)
65 self.height = _unpack(WORD, file)
66 self.color_depth = _unpack(WORD, file)
67 self.flags = _unpack(DWORD, file)
68 self.speed = _unpack(WORD, file)
69 self._zero = _unpack(DWORD, file)
70 self._zero = _unpack(DWORD, file)
71 self.palette_index = _unpack(BYTE, file)
72 self._ignore = _unpack(BYTE * 3, file)
73 self.number_of_colors = _unpack(WORD, file)
74 self._zero = _unpack(BYTE * 94, file)
75
76
77 #########################################
78 # Class for Aseprite animation frames
79 #########################################
80
81 class Frame(object):
82 def __init__(self, num_chunks, duration, header, data):
83 self.num_chunks = num_chunks
84 self.duration = duration
85 self.color_depth = header.color_depth
86 self.width = header.width
87 self.height = header.height
88 self._data = data
89 self.chunks = self._parse_chunks()
90 self.cels = [c for c in self.chunks if type(c) == CelChunk]
91 self.layers = [c for c in self.chunks if type(c) == LayerChunk]
92
93 def _parse_chunks(self):
94 fileobj = io.BytesIO(self._data)
95 chunks = []
96 for chunk in range(self.num_chunks):
97 chunk_size = _unpack(DWORD, fileobj)
98 chunk_type = format(_unpack(WORD, fileobj), "#06x")
99 header_size = struct.calcsize(DWORD + WORD)
100 chunk_data = fileobj.read(chunk_size - header_size)
101 if chunk_type in ("0x0004", "0x0011", "0x2016"):
102 chunks.append(DeprecatedChunk(chunk_size, chunk_type, chunk_data))
103 elif chunk_type == "0x2004":
104 chunks.append(LayerChunk(chunk_size, chunk_type, chunk_data))
105 elif chunk_type == "0x2005":
106 chunks.append(CelChunk(chunk_size, chunk_type, chunk_data))
107 elif chunk_type == "0x2017":
108 chunks.append(PathChunk(chunk_size, chunk_type, chunk_data))
109 elif chunk_type == "0x2018":
110 chunks.append(FrameTagsChunk(chunk_size, chunk_type, chunk_data))
111 elif chunk_type == "0x2019":
112 palette_chunk = PaletteChunk(chunk_size, chunk_type, chunk_data)
113 chunks.append(palette_chunk)
114 global PALETTE_DICT
115 PALETTE_DICT = palette_chunk.palette_dict.copy()
116 elif chunk_type == "0x2020":
117 chunks.append(UserDataChunk(chunk_size, chunk_type, chunk_data))
118 return chunks
119
120 def _pad_pixels(self, cel):
121 """For cels that don't fill the entire frame, pad with zeros."""
122 fileobj = io.BytesIO(cel.pixel_data)
123
124 padding = b'\x00\x00\x00\x00'
125 top_pad = padding * (self.width * cel.y_pos)
126 left_pad = padding * cel.x_pos
127 right_pad = padding * (self.width - cel.x_pos - cel.width)
128 bottom_pad = padding * (self.width * (self.height - cel.height - cel.y_pos))
129 line_size = cel.width * 4 # (RGBA)
130
131 pixel_array = top_pad
132 for i in range(cel.height):
133 pixel_array += (left_pad + fileobj.read(line_size) + right_pad)
134 pixel_array += bottom_pad
135
136 return pixel_array
137
138 @staticmethod
139 def _blend_pixels(bottom, top, mode):
140 # Iterate over the arrays in chunks of 4 (RGBA):
141 bottom_iter = _chunked_iter(bottom, 4)
142 top_iter = _chunked_iter(top, 4)
143
144 if mode == 'Normal':
145 final_array = []
146 # If RGBA values are > 0, use the top pixel.
147 for bottom_pixel, top_pixel in zip(bottom_iter, top_iter):
148 if any(top_pixel) > 0: # Any of R, G, B, A > 0
149 final_array.extend(top_pixel)
150 else:
151 final_array.extend(bottom_pixel)
152 return bytes(final_array)
153
154 # TODO: implement additional blend modes
155 else:
156 raise ImageDecodeException("Unsupported blend mode: '{}'".format(mode))
157
158 def _convert_to_rgba(self, cel):
159 if self.color_depth == 8:
160 global PALETTE_INDEX
161 pixel_array = []
162 for pixel in cel.pixel_data:
163 if pixel == PALETTE_INDEX:
164 pixel_array.extend([0, 0, 0, 0])
165 else:
166 pixel_array.extend(PALETTE_DICT[pixel])
167 cel.pixel_data = bytes(pixel_array)
168 return cel
169
170 elif self.color_depth == 16:
171 greyscale_iter = _chunked_iter(cel.pixel_data, 2)
172 pixel_array = []
173 for pixel in greyscale_iter:
174 rgba = (pixel[0] * 3) + pixel[1]
175 pixel_array.append(rgba)
176 cel.pixel_data = bytes(pixel_array)
177 return cel
178
179 else:
180 return cel
181
182 def get_pixel_array(self, layers):
183 # Start off with an empty RGBA base:
184 pixel_array = bytes(4 * self.width * self.height)
185
186 # Blend each layer's cel data one-by-one:
187 for cel in self.cels:
188 cel = self._convert_to_rgba(cel)
189 padded_pixels = self._pad_pixels(cel)
190 blend_mode = BLEND_MODES[layers[cel.layer_index].blend_mode]
191 pixel_array = self._blend_pixels(pixel_array, padded_pixels, blend_mode)
192
193 return pixel_array
194
195
196 #########################################
197 # Aseprite Chunk type definitions
198 #########################################
199
200 class Chunk:
201 def __init__(self, size, chunk_type):
202 self.size = size
203 self.chunk_type = chunk_type
204
205
206 class LayerChunk(Chunk):
207 def __init__(self, size, chunk_type, data):
208 super().__init__(size, chunk_type)
209 fileobj = io.BytesIO(data)
210 self.flags = _unpack(WORD, fileobj)
211 self.layer_type = _unpack(WORD, fileobj)
212 self.child_level = _unpack(WORD, fileobj)
213 _ignored_width = _unpack(WORD, fileobj)
214 _ignored_height = _unpack(WORD, fileobj)
215 self.blend_mode = _unpack(WORD, fileobj)
216 self.opacity = _unpack(BYTE, fileobj)
217 _zero_unused = _unpack(BYTE * 3, fileobj)
218 name_length = _unpack(WORD, fileobj)
219 self.name = fileobj.read(name_length)
220 if hasattr(self.name, "decode"):
221 self.name = self.name.decode('utf8')
222
223
224 class CelChunk(Chunk):
225 def __init__(self, size, chunk_type, data):
226 super().__init__(size, chunk_type)
227 fileobj = io.BytesIO(data)
228 self.layer_index = _unpack(WORD, fileobj)
229 self.x_pos = _unpack(SHORT, fileobj)
230 self.y_pos = _unpack(SHORT, fileobj)
231 self.opacity_level = _unpack(BYTE, fileobj)
232 self.cel_type = _unpack(WORD, fileobj)
233 _zero_unused = _unpack(BYTE * 7, fileobj)
234 if self.cel_type == 0:
235 self.width = _unpack(WORD, fileobj)
236 self.height = _unpack(WORD, fileobj)
237 self.pixel_data = fileobj.read()
238 elif self.cel_type == 1:
239 self.frame_position = _unpack(WORD, fileobj)
240 elif self.cel_type == 2:
241 self.width = _unpack(WORD, fileobj)
242 self.height = _unpack(WORD, fileobj)
243 self.pixel_data = zlib.decompress(fileobj.read())
244
245
246 class PathChunk(Chunk):
247 def __init__(self, size, chunk_type, data):
248 super().__init__(size, chunk_type)
249
250
251 class FrameTagsChunk(Chunk):
252 def __init__(self, size, chunk_type, data):
253 super().__init__(size, chunk_type)
254 # TODO: unpack this data.
255
256
257 class PaletteChunk(Chunk):
258 def __init__(self, size, chunk_type, data):
259 super().__init__(size, chunk_type)
260 fileobj = io.BytesIO(data)
261 self.palette_size = _unpack(DWORD, fileobj)
262 self.first_color_index = _unpack(DWORD, fileobj)
263 self.last_color_index = _unpack(DWORD, fileobj)
264 _zero = _unpack(BYTE * 8, fileobj)
265 self.palette_dict = {}
266 if _unpack(WORD, fileobj) == 1: # color has name
267 size = 7
268 else:
269 size = 6
270 for index in range(self.first_color_index, self.last_color_index+1):
271 rgba_data = fileobj.read(size)
272 # Ignore the palette names, as they aren't needed:
273 r, g, b, a = struct.unpack('<BBBB', rgba_data[:4])
274 self.palette_dict[index] = r, g, b, a
275
276
277 class UserDataChunk(Chunk):
278 def __init__(self, size, chunk_type, data):
279 super().__init__(size, chunk_type)
280 # TODO: unpack this data.
281
282
283 class DeprecatedChunk(Chunk):
284 def __init__(self, size, chunk_type, data):
285 super().__init__(size, chunk_type)
286
287
288 #########################################
289 # Image Decoder class definition
290 #########################################
291
292 class AsepriteImageDecoder(ImageDecoder):
293 def get_file_extensions(self):
294 return ['.ase', '.aseprite']
295
296 def get_animation_file_extensions(self):
297 return ['.ase', '.aseprite']
298
299 def decode(self, filename, file):
300 header, frames, layers, pitch = self._parse_file(filename, file)
301 pixel_data = frames[0].get_pixel_array(layers=layers)
302 return ImageData(header.width, header.height, 'RGBA', pixel_data, -pitch)
303
304 def decode_animation(self, file, filename):
305 header, frames, layers, pitch = self._parse_file(file, filename)
306 animation_frames = []
307 for frame in frames:
308 pixel_data = frame.get_pixel_array(layers=layers)
309 image = ImageData(header.width, header.height, 'RGBA', pixel_data, -pitch)
310 animation_frames.append(AnimationFrame(image, frame.duration/1000.0))
311 return Animation(animation_frames)
312
313 @staticmethod
314 def _parse_file(filename, file):
315 if not file:
316 file = open(filename, 'rb')
317
318 header = AsepriteHeader(file)
319 if header.magic_number != '0xa5e0':
320 raise ImageDecodeException("Does not appear to be a valid ASEprite file.")
321
322 if header.color_depth not in (8, 16, 32):
323 raise ImageDecodeException("Invalid color depth.")
324
325 global PALETTE_INDEX
326 PALETTE_INDEX = header.palette_index
327
328 frames = []
329 for _ in range(header.num_frames):
330 frame_size = _unpack(DWORD, file)
331 magic_number = hex(_unpack(WORD, file))
332 if magic_number != '0xf1fa':
333 raise ImageDecodeException("Malformed frame. File may be corrupted.")
334 num_chunks = _unpack(WORD, file)
335 duration = _unpack(WORD, file)
336 _zero = _unpack(BYTE * 6, file)
337 header_size = struct.calcsize(DWORD + WORD * 3 + BYTE * 6)
338 data = file.read(frame_size - header_size)
339 frames.append(Frame(num_chunks, duration, header, data))
340
341 # Layers chunk is in the first frame:
342 layers = frames[0].layers
343 pitch = len('RGBA') * header.width
344
345 file.close()
346
347 return header, frames, layers, pitch
348
349
350 def get_decoders():
351 return [AsepriteImageDecoder()]
352
353
354 def get_encoders():
355 return []