/Lib/chunk.py

http://unladen-swallow.googlecode.com/ · Python · 167 lines · 90 code · 12 blank · 65 comment · 33 complexity · 6de2072a26d020150cdee0bb183fe649 MD5 · raw file

  1. """Simple class to read IFF chunks.
  2. An IFF chunk (used in formats such as AIFF, TIFF, RMFF (RealMedia File
  3. Format)) has the following structure:
  4. +----------------+
  5. | ID (4 bytes) |
  6. +----------------+
  7. | size (4 bytes) |
  8. +----------------+
  9. | data |
  10. | ... |
  11. +----------------+
  12. The ID is a 4-byte string which identifies the type of chunk.
  13. The size field (a 32-bit value, encoded using big-endian byte order)
  14. gives the size of the whole chunk, including the 8-byte header.
  15. Usually an IFF-type file consists of one or more chunks. The proposed
  16. usage of the Chunk class defined here is to instantiate an instance at
  17. the start of each chunk and read from the instance until it reaches
  18. the end, after which a new instance can be instantiated. At the end
  19. of the file, creating a new instance will fail with a EOFError
  20. exception.
  21. Usage:
  22. while True:
  23. try:
  24. chunk = Chunk(file)
  25. except EOFError:
  26. break
  27. chunktype = chunk.getname()
  28. while True:
  29. data = chunk.read(nbytes)
  30. if not data:
  31. pass
  32. # do something with data
  33. The interface is file-like. The implemented methods are:
  34. read, close, seek, tell, isatty.
  35. Extra methods are: skip() (called by close, skips to the end of the chunk),
  36. getname() (returns the name (ID) of the chunk)
  37. The __init__ method has one required argument, a file-like object
  38. (including a chunk instance), and one optional argument, a flag which
  39. specifies whether or not chunks are aligned on 2-byte boundaries. The
  40. default is 1, i.e. aligned.
  41. """
  42. class Chunk:
  43. def __init__(self, file, align=True, bigendian=True, inclheader=False):
  44. import struct
  45. self.closed = False
  46. self.align = align # whether to align to word (2-byte) boundaries
  47. if bigendian:
  48. strflag = '>'
  49. else:
  50. strflag = '<'
  51. self.file = file
  52. self.chunkname = file.read(4)
  53. if len(self.chunkname) < 4:
  54. raise EOFError
  55. try:
  56. self.chunksize = struct.unpack(strflag+'L', file.read(4))[0]
  57. except struct.error:
  58. raise EOFError
  59. if inclheader:
  60. self.chunksize = self.chunksize - 8 # subtract header
  61. self.size_read = 0
  62. try:
  63. self.offset = self.file.tell()
  64. except (AttributeError, IOError):
  65. self.seekable = False
  66. else:
  67. self.seekable = True
  68. def getname(self):
  69. """Return the name (ID) of the current chunk."""
  70. return self.chunkname
  71. def getsize(self):
  72. """Return the size of the current chunk."""
  73. return self.chunksize
  74. def close(self):
  75. if not self.closed:
  76. self.skip()
  77. self.closed = True
  78. def isatty(self):
  79. if self.closed:
  80. raise ValueError, "I/O operation on closed file"
  81. return False
  82. def seek(self, pos, whence=0):
  83. """Seek to specified position into the chunk.
  84. Default position is 0 (start of chunk).
  85. If the file is not seekable, this will result in an error.
  86. """
  87. if self.closed:
  88. raise ValueError, "I/O operation on closed file"
  89. if not self.seekable:
  90. raise IOError, "cannot seek"
  91. if whence == 1:
  92. pos = pos + self.size_read
  93. elif whence == 2:
  94. pos = pos + self.chunksize
  95. if pos < 0 or pos > self.chunksize:
  96. raise RuntimeError
  97. self.file.seek(self.offset + pos, 0)
  98. self.size_read = pos
  99. def tell(self):
  100. if self.closed:
  101. raise ValueError, "I/O operation on closed file"
  102. return self.size_read
  103. def read(self, size=-1):
  104. """Read at most size bytes from the chunk.
  105. If size is omitted or negative, read until the end
  106. of the chunk.
  107. """
  108. if self.closed:
  109. raise ValueError, "I/O operation on closed file"
  110. if self.size_read >= self.chunksize:
  111. return ''
  112. if size < 0:
  113. size = self.chunksize - self.size_read
  114. if size > self.chunksize - self.size_read:
  115. size = self.chunksize - self.size_read
  116. data = self.file.read(size)
  117. self.size_read = self.size_read + len(data)
  118. if self.size_read == self.chunksize and \
  119. self.align and \
  120. (self.chunksize & 1):
  121. dummy = self.file.read(1)
  122. self.size_read = self.size_read + len(dummy)
  123. return data
  124. def skip(self):
  125. """Skip the rest of the chunk.
  126. If you are not interested in the contents of the chunk,
  127. this method should be called so that the file points to
  128. the start of the next chunk.
  129. """
  130. if self.closed:
  131. raise ValueError, "I/O operation on closed file"
  132. if self.seekable:
  133. try:
  134. n = self.chunksize - self.size_read
  135. # maybe fix alignment
  136. if self.align and (self.chunksize & 1):
  137. n = n + 1
  138. self.file.seek(n, 1)
  139. self.size_read = self.size_read + n
  140. return
  141. except IOError:
  142. pass
  143. while self.size_read < self.chunksize:
  144. n = min(8192, self.chunksize - self.size_read)
  145. dummy = self.read(n)
  146. if not dummy:
  147. raise EOFError