Debian Codegraph @

imageio/plugins/swf.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
3
4 """Read/Write SWF files.
5
6 Backend: internal
7
8 Shockwave flash (SWF) is a media format designed for rich and
9 interactive animations. This plugin makes use of this format to
10 store a series of images in a lossless format with good compression
11 (zlib). The resulting images can be shown as an animation using
12 a flash player (such as the browser).
13
14 SWF stores images in RGBA format. RGB or grayscale images are
15 automatically converted. SWF does not support meta data.
16
17 Parameters for reading
18 ----------------------
19 loop : bool
20 If True, the video will rewind as soon as a frame is requested
21 beyond the last frame. Otherwise, IndexError is raised. Default False.
22
23 Parameters for saving
24 ---------------------
25 fps : int
26 The speed to play the animation. Default 12.
27 loop : bool
28 If True, add a tag to the end of the file to play again from
29 the first frame. Most flash players will then play the movie
30 in a loop. Note that the imageio SWF Reader does not check this
31 tag. Default True.
32 html : bool
33 If the output is a file on the file system, write an html file
34 (in HTML5) that shows the animation. Default False.
35 compress : bool
36 Whether to compress the swf file. Default False. You probably don't
37 want to use this. This does not decrease the file size since
38 the images are already compressed. It will result in slower
39 read and write time. The only purpose of this feature is to
40 create compressed SWF files, so that we can test the
41 functionality to read them.
42
43 """
44
45 import os
46 import zlib
47 import logging
48 from io import BytesIO
49
50 import numpy as np
51
52 from ..core import Format, read_n_bytes, image_as_uint
53
54 logger = logging.getLogger(__name__)
55
56 _swf = None # lazily loaded in lib()
57
58
59 def load_lib():
60 global _swf
61 from . import _swf
62
63 return _swf
64
65
66 class SWFFormat(Format):
67 """See :mod:`imageio.plugins.swf`"""
68
69 def _can_read(self, request):
70 tmp = request.firstbytes[0:3].decode("ascii", "ignore")
71 if tmp in ("FWS", "CWS"):
72 return True
73
74 def _can_write(self, request):
75 if request.extension in self.extensions:
76 return True
77
78 # -- reader
79
80 class Reader(Format.Reader):
81 def _open(self, loop=False):
82 if not _swf:
83 load_lib()
84
85 self._arg_loop = bool(loop)
86
87 self._fp = self.request.get_file()
88
89 # Check file ...
90 tmp = self.request.firstbytes[0:3].decode("ascii", "ignore")
91 if tmp == "FWS":
92 pass # OK
93 elif tmp == "CWS":
94 # Compressed, we need to decompress
95 bb = self._fp.read()
96 bb = bb[:8] + zlib.decompress(bb[8:])
97 # Wrap up in a file object
98 self._fp = BytesIO(bb)
99 else:
100 raise IOError("This does not look like a valid SWF file")
101
102 # Skip first bytes. This also tests support got seeking ...
103 try:
104 self._fp.seek(8)
105 self._streaming_mode = False
106 except Exception:
107 self._streaming_mode = True
108 self._fp_read(8)
109
110 # Skip header
111 # Note that the number of frames is there, which we could
112 # potentially use, but the number of frames does not necessarily
113 # correspond to the number of images.
114 nbits = _swf.bits2int(self._fp_read(1), 5)
115 nbits = 5 + nbits * 4
116 Lrect = nbits / 8.0
117 if Lrect % 1:
118 Lrect += 1
119 Lrect = int(Lrect)
120 self._fp_read(Lrect + 3)
121
122 # Now the rest is basically tags ...
123 self._imlocs = [] # tuple (loc, sze, T, L1)
124 if not self._streaming_mode:
125 # Collect locations of frame, while skipping through the data
126 # This does not read any of the tag *data*.
127 try:
128 while True:
129 isimage, sze, T, L1 = self._read_one_tag()
130 loc = self._fp.tell()
131 if isimage:
132 # Still need to check if the format is right
133 format = ord(self._fp_read(3)[2:])
134 if format == 5: # RGB or RGBA lossless
135 self._imlocs.append((loc, sze, T, L1))
136 self._fp.seek(loc + sze) # Skip over tag
137 except IndexError:
138 pass # done reading
139
140 def _fp_read(self, n):
141 return read_n_bytes(self._fp, n)
142
143 def _close(self):
144 pass
145
146 def _get_length(self):
147 if self._streaming_mode:
148 return np.inf
149 else:
150 return len(self._imlocs)
151
152 def _get_data(self, index):
153 # Check index
154 if index < 0:
155 raise IndexError("Index in swf file must be > 0")
156 if not self._streaming_mode:
157 if self._arg_loop and self._imlocs:
158 index = index % len(self._imlocs)
159 if index >= len(self._imlocs):
160 raise IndexError("Index out of bounds")
161
162 if self._streaming_mode:
163 # Walk over tags until we find an image
164 while True:
165 isimage, sze, T, L1 = self._read_one_tag()
166 bb = self._fp_read(sze) # always read data
167 if isimage:
168 im = _swf.read_pixels(bb, 0, T, L1) # can be None
169 if im is not None:
170 return im, {}
171
172 else:
173 # Go to corresponding location, read data, and convert to image
174 loc, sze, T, L1 = self._imlocs[index]
175 self._fp.seek(loc)
176 bb = self._fp_read(sze)
177 # Read_pixels should return ndarry, since we checked format
178 im = _swf.read_pixels(bb, 0, T, L1)
179 return im, {}
180
181 def _read_one_tag(self):
182 """
183 Return (True, loc, size, T, L1) if an image that we can read.
184 Return (False, loc, size, T, L1) if any other tag.
185 """
186
187 # Get head
188 head = self._fp_read(6)
189 if not head: # pragma: no cover
190 raise IndexError("Reached end of swf movie")
191
192 # Determine type and length
193 T, L1, L2 = _swf.get_type_and_len(head)
194 if not L2: # pragma: no cover
195 raise RuntimeError("Invalid tag length, could not proceed")
196
197 # Read data
198 isimage = False
199 sze = L2 - 6
200 # bb = self._fp_read(L2 - 6)
201
202 # Parse tag
203 if T == 0:
204 raise IndexError("Reached end of swf movie")
205 elif T in [20, 36]:
206 isimage = True
207 # im = _swf.read_pixels(bb, 0, T, L1) # can be None
208 elif T in [6, 21, 35, 90]: # pragma: no cover
209 logger.warning("Ignoring JPEG image: cannot read JPEG.")
210 else:
211 pass # Not an image tag
212
213 # Done. Return image. Can be None
214 # return im
215 return isimage, sze, T, L1
216
217 def _get_meta_data(self, index):
218 return {} # This format does not support meta data
219
220 # -- writer
221
222 class Writer(Format.Writer):
223 def _open(self, fps=12, loop=True, html=False, compress=False):
224 if not _swf:
225 load_lib()
226
227 self._arg_fps = int(fps)
228 self._arg_loop = bool(loop)
229 self._arg_html = bool(html)
230 self._arg_compress = bool(compress)
231
232 self._fp = self.request.get_file()
233 self._framecounter = 0
234 self._framesize = (100, 100)
235
236 # For compress, we use an in-memory file object
237 if self._arg_compress:
238 self._fp_real = self._fp
239 self._fp = BytesIO()
240
241 def _close(self):
242 self._complete()
243 # Get size of (uncompressed) file
244 sze = self._fp.tell()
245 # set nframes, this is in the potentially compressed region
246 self._fp.seek(self._location_to_save_nframes)
247 self._fp.write(_swf.int2uint16(self._framecounter))
248 # Compress body?
249 if self._arg_compress:
250 bb = self._fp.getvalue()
251 self._fp = self._fp_real
252 self._fp.write(bb[:8])
253 self._fp.write(zlib.compress(bb[8:]))
254 sze = self._fp.tell() # renew sze value
255 # set size
256 self._fp.seek(4)
257 self._fp.write(_swf.int2uint32(sze))
258 self._fp = None # Disable
259
260 # Write html?
261 if self._arg_html and os.path.isfile(self.request.filename):
262 dirname, fname = os.path.split(self.request.filename)
263 filename = os.path.join(dirname, fname[:-4] + ".html")
264 w, h = self._framesize
265 html = HTML % (fname, w, h, fname)
266 with open(filename, "wb") as f:
267 f.write(html.encode("utf-8"))
268
269 def _write_header(self, framesize, fps):
270 self._framesize = framesize
271 # Called as soon as we know framesize; when we get first frame
272 bb = b""
273 bb += "FC"[self._arg_compress].encode("ascii")
274 bb += "WS".encode("ascii") # signature bytes
275 bb += _swf.int2uint8(8) # version
276 bb += "0000".encode("ascii") # FileLength (leave open for now)
277 bb += (
278 _swf.Tag().make_rect_record(0, framesize[0], 0, framesize[1]).tobytes()
279 )
280 bb += _swf.int2uint8(0) + _swf.int2uint8(fps) # FrameRate
281 self._location_to_save_nframes = len(bb)
282 bb += "00".encode("ascii") # nframes (leave open for now)
283 self._fp.write(bb)
284
285 # Write some initial tags
286 taglist = _swf.FileAttributesTag(), _swf.SetBackgroundTag(0, 0, 0)
287 for tag in taglist:
288 self._fp.write(tag.get_tag())
289
290 def _complete(self):
291 # What if no images were saved?
292 if not self._framecounter:
293 self._write_header((10, 10), self._arg_fps)
294 # Write stop tag if we do not loop
295 if not self._arg_loop:
296 self._fp.write(_swf.DoActionTag("stop").get_tag())
297 # finish with end tag
298 self._fp.write("\x00\x00".encode("ascii"))
299
300 def _append_data(self, im, meta):
301 # Correct shape and type
302 if im.ndim == 3 and im.shape[-1] == 1:
303 im = im[:, :, 0]
304 im = image_as_uint(im, bitdepth=8)
305 # Get frame size
306 wh = im.shape[1], im.shape[0]
307 # Write header on first frame
308 isfirstframe = False
309 if self._framecounter == 0:
310 isfirstframe = True
311 self._write_header(wh, self._arg_fps)
312 # Create tags
313 bm = _swf.BitmapTag(im)
314 sh = _swf.ShapeTag(bm.id, (0, 0), wh)
315 po = _swf.PlaceObjectTag(1, sh.id, move=(not isfirstframe))
316 sf = _swf.ShowFrameTag()
317 # Write tags
318 for tag in [bm, sh, po, sf]:
319 self._fp.write(tag.get_tag())
320 self._framecounter += 1
321
322 def set_meta_data(self, meta):
323 pass
324
325
326 HTML = """
327 <!DOCTYPE html>
328 <html>
329 <head>
330 <title>Show Flash animation %s</title>
331 </head>
332 <body>
333 <embed width="%i" height="%i" src="%s">
334 </html>
335 """