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 # This code was taken from https://github.com/almarklein/visvis/blob/master/vvmovie/images2swf.py
4
5 # styletest: ignore E261
6
7 """
8 Provides a function (write_swf) to store a series of numpy arrays in an
9 SWF movie, that can be played on a wide range of OS's.
10
11 In desperation of wanting to share animated images, and then lacking a good
12 writer for animated gif or .avi, I decided to look into SWF. This format
13 is very well documented.
14
15 This is a pure python module to create an SWF file that shows a series
16 of images. The images are stored using the DEFLATE algorithm (same as
17 PNG and ZIP and which is included in the standard Python distribution).
18 As this compression algorithm is much more effective than that used in
19 GIF images, we obtain better quality (24 bit colors + alpha channel)
20 while still producesing smaller files (a test showed ~75%). Although
21 SWF also allows for JPEG compression, doing so would probably require
22 a third party library for the JPEG encoding/decoding, we could
23 perhaps do this via Pillow or freeimage.
24
25 sources and tools:
26
27 - SWF on wikipedia
28 - Adobes "SWF File Format Specification" version 10
29 (http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v10.pdf)
30 - swftools (swfdump in specific) for debugging
31 - iwisoft swf2avi can be used to convert swf to avi/mpg/flv with really
32 good quality, while file size is reduced with factors 20-100.
33 A good program in my opinion. The free version has the limitation
34 of a watermark in the upper left corner.
35
36 """
37
38 import os
39 import zlib
40 import time # noqa
41 import logging
42
43 import numpy as np
44
45 logger = logging.getLogger(__name__)
46
47 # todo: use Pillow to support reading JPEG images from SWF?
48
49
50 # Base functions and classes
51
52
53 class BitArray:
54 """Dynamic array of bits that automatically resizes
55 with factors of two.
56 Append bits using .append() or +=
57 You can reverse bits using .reverse()
58 """
59
60 def __init__(self, initvalue=None):
61 self.data = np.zeros((16,), dtype=np.uint8)
62 self._len = 0
63 if initvalue is not None:
64 self.append(initvalue)
65
66 def __len__(self):
67 return self._len # self.data.shape[0]
68
69 def __repr__(self):
70 return self.data[: self._len].tobytes().decode("ascii")
71
72 def _checkSize(self):
73 # check length... grow if necessary
74 arraylen = self.data.shape[0]
75 if self._len >= arraylen:
76 tmp = np.zeros((arraylen * 2,), dtype=np.uint8)
77 tmp[: self._len] = self.data[: self._len]
78 self.data = tmp
79
80 def __add__(self, value):
81 self.append(value)
82 return self
83
84 def append(self, bits):
85 # check input
86 if isinstance(bits, BitArray):
87 bits = str(bits)
88 if isinstance(bits, int): # pragma: no cover - we dont use it
89 bits = str(bits)
90 if not isinstance(bits, str): # pragma: no cover
91 raise ValueError("Append bits as strings or integers!")
92
93 # add bits
94 for bit in bits:
95 self.data[self._len] = ord(bit)
96 self._len += 1
97 self._checkSize()
98
99 def reverse(self):
100 """In-place reverse."""
101 tmp = self.data[: self._len].copy()
102 self.data[: self._len] = tmp[::-1]
103
104 def tobytes(self):
105 """Convert to bytes. If necessary,
106 zeros are padded to the end (right side).
107 """
108 bits = str(self)
109
110 # determine number of bytes
111 nbytes = 0
112 while nbytes * 8 < len(bits):
113 nbytes += 1
114 # pad
115 bits = bits.ljust(nbytes * 8, "0")
116
117 # go from bits to bytes
118 bb = bytes()
119 for i in range(nbytes):
120 tmp = int(bits[i * 8 : (i + 1) * 8], 2)
121 bb += int2uint8(tmp)
122
123 # done
124 return bb
125
126
127 def int2uint32(i):
128 return int(i).to_bytes(4, "little")
129
130
131 def int2uint16(i):
132 return int(i).to_bytes(2, "little")
133
134
135 def int2uint8(i):
136 return int(i).to_bytes(1, "little")
137
138
139 def int2bits(i, n=None):
140 """convert int to a string of bits (0's and 1's in a string),
141 pad to n elements. Convert back using int(ss,2)."""
142 ii = i
143
144 # make bits
145 bb = BitArray()
146 while ii > 0:
147 bb += str(ii % 2)
148 ii = ii >> 1
149 bb.reverse()
150
151 # justify
152 if n is not None:
153 if len(bb) > n: # pragma: no cover
154 raise ValueError("int2bits fail: len larger than padlength.")
155 bb = str(bb).rjust(n, "0")
156
157 # done
158 return BitArray(bb)
159
160
161 def bits2int(bb, n=8):
162 # Init
163 value = ""
164
165 # Get value in bits
166 for i in range(len(bb)):
167 b = bb[i : i + 1]
168 tmp = bin(ord(b))[2:]
169 # value += tmp.rjust(8,'0')
170 value = tmp.rjust(8, "0") + value
171
172 # Make decimal
173 return int(value[:n], 2)
174
175
176 def get_type_and_len(bb):
177 """bb should be 6 bytes at least
178 Return (type, length, length_of_full_tag)
179 """
180 # Init
181 value = ""
182
183 # Get first 16 bits
184 for i in range(2):
185 b = bb[i : i + 1]
186 tmp = bin(ord(b))[2:]
187 # value += tmp.rjust(8,'0')
188 value = tmp.rjust(8, "0") + value
189
190 # Get type and length
191 type = int(value[:10], 2)
192 L = int(value[10:], 2)
193 L2 = L + 2
194
195 # Long tag header?
196 if L == 63: # '111111'
197 value = ""
198 for i in range(2, 6):
199 b = bb[i : i + 1] # becomes a single-byte bytes()
200 tmp = bin(ord(b))[2:]
201 # value += tmp.rjust(8,'0')
202 value = tmp.rjust(8, "0") + value
203 L = int(value, 2)
204 L2 = L + 6
205
206 # Done
207 return type, L, L2
208
209
210 def signedint2bits(i, n=None):
211 """convert signed int to a string of bits (0's and 1's in a string),
212 pad to n elements. Negative numbers are stored in 2's complement bit
213 patterns, thus positive numbers always start with a 0.
214 """
215
216 # negative number?
217 ii = i
218 if i < 0:
219 # A negative number, -n, is represented as the bitwise opposite of
220 ii = abs(ii) - 1 # the positive-zero number n-1.
221
222 # make bits
223 bb = BitArray()
224 while ii > 0:
225 bb += str(ii % 2)
226 ii = ii >> 1
227 bb.reverse()
228
229 # justify
230 bb = "0" + str(bb) # always need the sign bit in front
231 if n is not None:
232 if len(bb) > n: # pragma: no cover
233 raise ValueError("signedint2bits fail: len larger than padlength.")
234 bb = bb.rjust(n, "0")
235
236 # was it negative? (then opposite bits)
237 if i < 0:
238 bb = bb.replace("0", "x").replace("1", "0").replace("x", "1")
239
240 # done
241 return BitArray(bb)
242
243
244 def twits2bits(arr):
245 """Given a few (signed) numbers, store them
246 as compactly as possible in the wat specifief by the swf format.
247 The numbers are multiplied by 20, assuming they
248 are twits.
249 Can be used to make the RECT record.
250 """
251
252 # first determine length using non justified bit strings
253 maxlen = 1
254 for i in arr:
255 tmp = len(signedint2bits(i * 20))
256 if tmp > maxlen:
257 maxlen = tmp
258
259 # build array
260 bits = int2bits(maxlen, 5)
261 for i in arr:
262 bits += signedint2bits(i * 20, maxlen)
263
264 return bits
265
266
267 def floats2bits(arr):
268 """Given a few (signed) numbers, convert them to bits,
269 stored as FB (float bit values). We always use 16.16.
270 Negative numbers are not (yet) possible, because I don't
271 know how the're implemented (ambiguity).
272 """
273 bits = int2bits(31, 5) # 32 does not fit in 5 bits!
274 for i in arr:
275 if i < 0: # pragma: no cover
276 raise ValueError("Dit not implement negative floats!")
277 i1 = int(i)
278 i2 = i - i1
279 bits += int2bits(i1, 15)
280 bits += int2bits(i2 * 2**16, 16)
281 return bits
282
283
284 # Base Tag
285
286
287 class Tag:
288 def __init__(self):
289 self.bytes = bytes()
290 self.tagtype = -1
291
292 def process_tag(self):
293 """Implement this to create the tag."""
294 raise NotImplementedError()
295
296 def get_tag(self):
297 """Calls processTag and attaches the header."""
298 self.process_tag()
299
300 # tag to binary
301 bits = int2bits(self.tagtype, 10)
302
303 # complete header uint16 thing
304 bits += "1" * 6 # = 63 = 0x3f
305 # make uint16
306 bb = int2uint16(int(str(bits), 2))
307
308 # now add 32bit length descriptor
309 bb += int2uint32(len(self.bytes))
310
311 # done, attach and return
312 bb += self.bytes
313 return bb
314
315 def make_rect_record(self, xmin, xmax, ymin, ymax):
316 """Simply uses makeCompactArray to produce
317 a RECT Record."""
318 return twits2bits([xmin, xmax, ymin, ymax])
319
320 def make_matrix_record(self, scale_xy=None, rot_xy=None, trans_xy=None):
321 # empty matrix?
322 if scale_xy is None and rot_xy is None and trans_xy is None:
323 return "0" * 8
324
325 # init
326 bits = BitArray()
327
328 # scale
329 if scale_xy:
330 bits += "1"
331 bits += floats2bits([scale_xy[0], scale_xy[1]])
332 else:
333 bits += "0"
334
335 # rotation
336 if rot_xy:
337 bits += "1"
338 bits += floats2bits([rot_xy[0], rot_xy[1]])
339 else:
340 bits += "0"
341
342 # translation (no flag here)
343 if trans_xy:
344 bits += twits2bits([trans_xy[0], trans_xy[1]])
345 else:
346 bits += twits2bits([0, 0])
347
348 # done
349 return bits
350
351
352 # Control tags
353
354
355 class ControlTag(Tag):
356 def __init__(self):
357 Tag.__init__(self)
358
359
360 class FileAttributesTag(ControlTag):
361 def __init__(self):
362 ControlTag.__init__(self)
363 self.tagtype = 69
364
365 def process_tag(self):
366 self.bytes = "\x00".encode("ascii") * (1 + 3)
367
368
369 class ShowFrameTag(ControlTag):
370 def __init__(self):
371 ControlTag.__init__(self)
372 self.tagtype = 1
373
374 def process_tag(self):
375 self.bytes = bytes()
376
377
378 class SetBackgroundTag(ControlTag):
379 """Set the color in 0-255, or 0-1 (if floats given)."""
380
381 def __init__(self, *rgb):
382 self.tagtype = 9
383 if len(rgb) == 1:
384 rgb = rgb[0]
385 self.rgb = rgb
386
387 def process_tag(self):
388 bb = bytes()
389 for i in range(3):
390 clr = self.rgb[i]
391 if isinstance(clr, float): # pragma: no cover - not used
392 clr = clr * 255
393 bb += int2uint8(clr)
394 self.bytes = bb
395
396
397 class DoActionTag(Tag):
398 def __init__(self, action="stop"):
399 Tag.__init__(self)
400 self.tagtype = 12
401 self.actions = [action]
402
403 def append(self, action): # pragma: no cover - not used
404 self.actions.append(action)
405
406 def process_tag(self):
407 bb = bytes()
408
409 for action in self.actions:
410 action = action.lower()
411 if action == "stop":
412 bb += "\x07".encode("ascii")
413 elif action == "play": # pragma: no cover - not used
414 bb += "\x06".encode("ascii")
415 else: # pragma: no cover
416 logger.warning("unknown action: %s" % action)
417
418 bb += int2uint8(0)
419 self.bytes = bb
420
421
422 # Definition tags
423 class DefinitionTag(Tag):
424 counter = 0 # to give automatically id's
425
426 def __init__(self):
427 Tag.__init__(self)
428 DefinitionTag.counter += 1
429 self.id = DefinitionTag.counter # id in dictionary
430
431
432 class BitmapTag(DefinitionTag):
433 def __init__(self, im):
434 DefinitionTag.__init__(self)
435 self.tagtype = 36 # DefineBitsLossless2
436
437 # convert image (note that format is ARGB)
438 # even a grayscale image is stored in ARGB, nevertheless,
439 # the fabilous deflate compression will make it that not much
440 # more data is required for storing (25% or so, and less than 10%
441 # when storing RGB as ARGB).
442
443 if len(im.shape) == 3:
444 if im.shape[2] in [3, 4]:
445 tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
446 for i in range(3):
447 tmp[:, :, i + 1] = im[:, :, i]
448 if im.shape[2] == 4:
449 tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is
450 else: # pragma: no cover
451 raise ValueError("Invalid shape to be an image.")
452
453 elif len(im.shape) == 2:
454 tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255
455 for i in range(3):
456 tmp[:, :, i + 1] = im[:, :]
457 else: # pragma: no cover
458 raise ValueError("Invalid shape to be an image.")
459
460 # we changed the image to uint8 4 channels.
461 # now compress!
462 self._data = zlib.compress(tmp.tobytes(), zlib.DEFLATED)
463 self.imshape = im.shape
464
465 def process_tag(self):
466 # build tag
467 bb = bytes()
468 bb += int2uint16(self.id) # CharacterID
469 bb += int2uint8(5) # BitmapFormat
470 bb += int2uint16(self.imshape[1]) # BitmapWidth
471 bb += int2uint16(self.imshape[0]) # BitmapHeight
472 bb += self._data # ZlibBitmapData
473
474 self.bytes = bb
475
476
477 class PlaceObjectTag(ControlTag):
478 def __init__(self, depth, idToPlace=None, xy=(0, 0), move=False):
479 ControlTag.__init__(self)
480 self.tagtype = 26
481 self.depth = depth
482 self.idToPlace = idToPlace
483 self.xy = xy
484 self.move = move
485
486 def process_tag(self):
487 # retrieve stuff
488 depth = self.depth
489 xy = self.xy
490 id = self.idToPlace
491
492 # build PlaceObject2
493 bb = bytes()
494 if self.move:
495 bb += "\x07".encode("ascii")
496 else:
497 # (8 bit flags): 4:matrix, 2:character, 1:move
498 bb += "\x06".encode("ascii")
499 bb += int2uint16(depth) # Depth
500 bb += int2uint16(id) # character id
501 bb += self.make_matrix_record(trans_xy=xy).tobytes() # MATRIX record
502 self.bytes = bb
503
504
505 class ShapeTag(DefinitionTag):
506 def __init__(self, bitmapId, xy, wh):
507 DefinitionTag.__init__(self)
508 self.tagtype = 2
509 self.bitmapId = bitmapId
510 self.xy = xy
511 self.wh = wh
512
513 def process_tag(self):
514 """Returns a defineshape tag. with a bitmap fill"""
515
516 bb = bytes()
517 bb += int2uint16(self.id)
518 xy, wh = self.xy, self.wh
519 tmp = self.make_rect_record(xy[0], wh[0], xy[1], wh[1]) # ShapeBounds
520 bb += tmp.tobytes()
521
522 # make SHAPEWITHSTYLE structure
523
524 # first entry: FILLSTYLEARRAY with in it a single fill style
525 bb += int2uint8(1) # FillStyleCount
526 bb += "\x41".encode("ascii") # FillStyleType (0x41 or 0x43 unsmoothed)
527 bb += int2uint16(self.bitmapId) # BitmapId
528 # bb += '\x00' # BitmapMatrix (empty matrix with leftover bits filled)
529 bb += self.make_matrix_record(scale_xy=(20, 20)).tobytes()
530
531 # # first entry: FILLSTYLEARRAY with in it a single fill style
532 # bb += int2uint8(1) # FillStyleCount
533 # bb += '\x00' # solid fill
534 # bb += '\x00\x00\xff' # color
535
536 # second entry: LINESTYLEARRAY with a single line style
537 bb += int2uint8(0) # LineStyleCount
538 # bb += int2uint16(0*20) # Width
539 # bb += '\x00\xff\x00' # Color
540
541 # third and fourth entry: NumFillBits and NumLineBits (4 bits each)
542 # I each give them four bits, so 16 styles possible.
543 bb += "\x44".encode("ascii")
544
545 self.bytes = bb
546
547 # last entries: SHAPERECORDs ... (individual shape records not aligned)
548 # STYLECHANGERECORD
549 bits = BitArray()
550 bits += self.make_style_change_record(0, 1, moveTo=(self.wh[0], self.wh[1]))
551 # STRAIGHTEDGERECORD 4x
552 bits += self.make_straight_edge_record(-self.wh[0], 0)
553 bits += self.make_straight_edge_record(0, -self.wh[1])
554 bits += self.make_straight_edge_record(self.wh[0], 0)
555 bits += self.make_straight_edge_record(0, self.wh[1])
556
557 # ENDSHAPRECORD
558 bits += self.make_end_shape_record()
559
560 self.bytes += bits.tobytes()
561
562 # done
563 # self.bytes = bb
564
565 def make_style_change_record(self, lineStyle=None, fillStyle=None, moveTo=None):
566 # first 6 flags
567 # Note that we use FillStyle1. If we don't flash (at least 8) does not
568 # recognize the frames properly when importing to library.
569
570 bits = BitArray()
571 bits += "0" # TypeFlag (not an edge record)
572 bits += "0" # StateNewStyles (only for DefineShape2 and Defineshape3)
573 if lineStyle:
574 bits += "1" # StateLineStyle
575 else:
576 bits += "0"
577 if fillStyle:
578 bits += "1" # StateFillStyle1
579 else:
580 bits += "0"
581 bits += "0" # StateFillStyle0
582 if moveTo:
583 bits += "1" # StateMoveTo
584 else:
585 bits += "0"
586
587 # give information
588 # todo: nbits for fillStyle and lineStyle is hard coded.
589
590 if moveTo:
591 bits += twits2bits([moveTo[0], moveTo[1]])
592 if fillStyle:
593 bits += int2bits(fillStyle, 4)
594 if lineStyle:
595 bits += int2bits(lineStyle, 4)
596
597 return bits
598
599 def make_straight_edge_record(self, *dxdy):
600 if len(dxdy) == 1:
601 dxdy = dxdy[0]
602
603 # determine required number of bits
604 xbits = signedint2bits(dxdy[0] * 20)
605 ybits = signedint2bits(dxdy[1] * 20)
606 nbits = max([len(xbits), len(ybits)])
607
608 bits = BitArray()
609 bits += "11" # TypeFlag and StraightFlag
610 bits += int2bits(nbits - 2, 4)
611 bits += "1" # GeneralLineFlag
612 bits += signedint2bits(dxdy[0] * 20, nbits)
613 bits += signedint2bits(dxdy[1] * 20, nbits)
614
615 # note: I do not make use of vertical/horizontal only lines...
616
617 return bits
618
619 def make_end_shape_record(self):
620 bits = BitArray()
621 bits += "0" # TypeFlag: no edge
622 bits += "0" * 5 # EndOfShape
623 return bits
624
625
626 def read_pixels(bb, i, tagType, L1):
627 """With pf's seed after the recordheader, reads the pixeldata."""
628
629 # Get info
630 charId = bb[i : i + 2] # noqa
631 i += 2
632 format = ord(bb[i : i + 1])
633 i += 1
634 width = bits2int(bb[i : i + 2], 16)
635 i += 2
636 height = bits2int(bb[i : i + 2], 16)
637 i += 2
638
639 # If we can, get pixeldata and make numpy array
640 if format != 5:
641 logger.warning("Can only read 24bit or 32bit RGB(A) lossless images.")
642 else:
643 # Read byte data
644 offset = 2 + 1 + 2 + 2 # all the info bits
645 bb2 = bb[i : i + (L1 - offset)]
646
647 # Decompress and make numpy array
648 data = zlib.decompress(bb2)
649 a = np.frombuffer(data, dtype=np.uint8)
650
651 # Set shape
652 if tagType == 20:
653 # DefineBitsLossless - RGB data
654 try:
655 a = a.reshape(height, width, 3)
656 except Exception:
657 # Byte align stuff might cause troubles
658 logger.warning("Cannot read image due to byte alignment")
659 if tagType == 36:
660 # DefineBitsLossless2 - ARGB data
661 a = a.reshape(height, width, 4)
662 # Swap alpha channel to make RGBA
663 b = a
664 a = np.zeros_like(a)
665 a[:, :, 0] = b[:, :, 1]
666 a[:, :, 1] = b[:, :, 2]
667 a[:, :, 2] = b[:, :, 3]
668 a[:, :, 3] = b[:, :, 0]
669
670 return a
671
672
673 # Last few functions
674
675
676 # These are the original public functions, we don't use them, but we
677 # keep it so that in principle this module can be used stand-alone.
678
679
680 def checkImages(images): # pragma: no cover
681 """checkImages(images)
682 Check numpy images and correct intensity range etc.
683 The same for all movie formats.
684 """
685 # Init results
686 images2 = []
687
688 for im in images:
689 if isinstance(im, np.ndarray):
690 # Check and convert dtype
691 if im.dtype == np.uint8:
692 images2.append(im) # Ok
693 elif im.dtype in [np.float32, np.float64]:
694 theMax = im.max()
695 if 128 < theMax < 300:
696 pass # assume 0:255
697 else:
698 im = im.copy()
699 im[im < 0] = 0
700 im[im > 1] = 1
701 im *= 255
702 images2.append(im.astype(np.uint8))
703 else:
704 im = im.astype(np.uint8)
705 images2.append(im)
706 # Check size
707 if im.ndim == 2:
708 pass # ok
709 elif im.ndim == 3:
710 if im.shape[2] not in [3, 4]:
711 raise ValueError("This array can not represent an image.")
712 else:
713 raise ValueError("This array can not represent an image.")
714 else:
715 raise ValueError("Invalid image type: " + str(type(im)))
716
717 # Done
718 return images2
719
720
721 def build_file(
722 fp, taglist, nframes=1, framesize=(500, 500), fps=10, version=8
723 ): # pragma: no cover
724 """Give the given file (as bytes) a header."""
725
726 # compose header
727 bb = bytes()
728 bb += "F".encode("ascii") # uncompressed
729 bb += "WS".encode("ascii") # signature bytes
730 bb += int2uint8(version) # version
731 bb += "0000".encode("ascii") # FileLength (leave open for now)
732 bb += Tag().make_rect_record(0, framesize[0], 0, framesize[1]).tobytes()
733 bb += int2uint8(0) + int2uint8(fps) # FrameRate
734 bb += int2uint16(nframes)
735 fp.write(bb)
736
737 # produce all tags
738 for tag in taglist:
739 fp.write(tag.get_tag())
740
741 # finish with end tag
742 fp.write("\x00\x00".encode("ascii"))
743
744 # set size
745 sze = fp.tell()
746 fp.seek(4)
747 fp.write(int2uint32(sze))
748
749
750 def write_swf(filename, images, duration=0.1, repeat=True): # pragma: no cover
751 """Write an swf-file from the specified images. If repeat is False,
752 the movie is finished with a stop action. Duration may also
753 be a list with durations for each frame (note that the duration
754 for each frame is always an integer amount of the minimum duration.)
755
756 Images should be a list consisting numpy arrays with values between
757 0 and 255 for integer types, and between 0 and 1 for float types.
758
759 """
760
761 # Check images
762 images2 = checkImages(images)
763
764 # Init
765 taglist = [FileAttributesTag(), SetBackgroundTag(0, 0, 0)]
766
767 # Check duration
768 if hasattr(duration, "__len__"):
769 if len(duration) == len(images2):
770 duration = [d for d in duration]
771 else:
772 raise ValueError("len(duration) doesn't match amount of images.")
773 else:
774 duration = [duration for im in images2]
775
776 # Build delays list
777 minDuration = float(min(duration))
778 delays = [round(d / minDuration) for d in duration]
779 delays = [max(1, int(d)) for d in delays]
780
781 # Get FPS
782 fps = 1.0 / minDuration
783
784 # Produce series of tags for each image
785 # t0 = time.time()
786 nframes = 0
787 for im in images2:
788 bm = BitmapTag(im)
789 wh = (im.shape[1], im.shape[0])
790 sh = ShapeTag(bm.id, (0, 0), wh)
791 po = PlaceObjectTag(1, sh.id, move=nframes > 0)
792 taglist.extend([bm, sh, po])
793 for i in range(delays[nframes]):
794 taglist.append(ShowFrameTag())
795 nframes += 1
796
797 if not repeat:
798 taglist.append(DoActionTag("stop"))
799
800 # Build file
801 # t1 = time.time()
802 fp = open(filename, "wb")
803 try:
804 build_file(fp, taglist, nframes=nframes, framesize=wh, fps=fps)
805 except Exception:
806 raise
807 finally:
808 fp.close()
809 # t2 = time.time()
810
811 # logger.warning("Writing SWF took %1.2f and %1.2f seconds" % (t1-t0, t2-t1) )
812
813
814 def read_swf(filename): # pragma: no cover
815 """Read all images from an SWF (shockwave flash) file. Returns a list
816 of numpy arrays.
817
818 Limitation: only read the PNG encoded images (not the JPG encoded ones).
819 """
820
821 # Check whether it exists
822 if not os.path.isfile(filename):
823 raise IOError("File not found: " + str(filename))
824
825 # Init images
826 images = []
827
828 # Open file and read all
829 fp = open(filename, "rb")
830 bb = fp.read()
831
832 try:
833 # Check opening tag
834 tmp = bb[0:3].decode("ascii", "ignore")
835 if tmp.upper() == "FWS":
836 pass # ok
837 elif tmp.upper() == "CWS":
838 # Decompress movie
839 bb = bb[:8] + zlib.decompress(bb[8:])
840 else:
841 raise IOError("Not a valid SWF file: " + str(filename))
842
843 # Set filepointer at first tag (skipping framesize RECT and two uin16's
844 i = 8
845 nbits = bits2int(bb[i : i + 1], 5) # skip FrameSize
846 nbits = 5 + nbits * 4
847 Lrect = nbits / 8.0
848 if Lrect % 1:
849 Lrect += 1
850 Lrect = int(Lrect)
851 i += Lrect + 4
852
853 # Iterate over the tags
854 counter = 0
855 while True:
856 counter += 1
857
858 # Get tag header
859 head = bb[i : i + 6]
860 if not head:
861 break # Done (we missed end tag)
862
863 # Determine type and length
864 T, L1, L2 = get_type_and_len(head)
865 if not L2:
866 logger.warning("Invalid tag length, could not proceed")
867 break
868 # logger.warning(T, L2)
869
870 # Read image if we can
871 if T in [20, 36]:
872 im = read_pixels(bb, i + 6, T, L1)
873 if im is not None:
874 images.append(im)
875 elif T in [6, 21, 35, 90]:
876 logger.warning("Ignoring JPEG image: cannot read JPEG.")
877 else:
878 pass # Not an image tag
879
880 # Detect end tag
881 if T == 0:
882 break
883
884 # Next tag!
885 i += L2
886
887 finally:
888 fp.close()
889
890 # Done
891 return images
892
893
894 # Backward compatibility; same public names as when this was images2swf.
895 writeSwf = write_swf
896 readSwf = read_swf