chunk.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 an 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_from(strflag+'L', file.read(4))[0]
  57. except struct.error:
  58. raise EOFError from None
  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, OSError):
  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. try:
  77. self.skip()
  78. finally:
  79. self.closed = True
  80. def isatty(self):
  81. if self.closed:
  82. raise ValueError("I/O operation on closed file")
  83. return False
  84. def seek(self, pos, whence=0):
  85. """Seek to specified position into the chunk.
  86. Default position is 0 (start of chunk).
  87. If the file is not seekable, this will result in an error.
  88. """
  89. if self.closed:
  90. raise ValueError("I/O operation on closed file")
  91. if not self.seekable:
  92. raise OSError("cannot seek")
  93. if whence == 1:
  94. pos = pos + self.size_read
  95. elif whence == 2:
  96. pos = pos + self.chunksize
  97. if pos < 0 or pos > self.chunksize:
  98. raise RuntimeError
  99. self.file.seek(self.offset + pos, 0)
  100. self.size_read = pos
  101. def tell(self):
  102. if self.closed:
  103. raise ValueError("I/O operation on closed file")
  104. return self.size_read
  105. def read(self, size=-1):
  106. """Read at most size bytes from the chunk.
  107. If size is omitted or negative, read until the end
  108. of the chunk.
  109. """
  110. if self.closed:
  111. raise ValueError("I/O operation on closed file")
  112. if self.size_read >= self.chunksize:
  113. return b''
  114. if size < 0:
  115. size = self.chunksize - self.size_read
  116. if size > self.chunksize - self.size_read:
  117. size = self.chunksize - self.size_read
  118. data = self.file.read(size)
  119. self.size_read = self.size_read + len(data)
  120. if self.size_read == self.chunksize and \
  121. self.align and \
  122. (self.chunksize & 1):
  123. dummy = self.file.read(1)
  124. self.size_read = self.size_read + len(dummy)
  125. return data
  126. def skip(self):
  127. """Skip the rest of the chunk.
  128. If you are not interested in the contents of the chunk,
  129. this method should be called so that the file points to
  130. the start of the next chunk.
  131. """
  132. if self.closed:
  133. raise ValueError("I/O operation on closed file")
  134. if self.seekable:
  135. try:
  136. n = self.chunksize - self.size_read
  137. # maybe fix alignment
  138. if self.align and (self.chunksize & 1):
  139. n = n + 1
  140. self.file.seek(n, 1)
  141. self.size_read = self.size_read + n
  142. return
  143. except OSError:
  144. pass
  145. while self.size_read < self.chunksize:
  146. n = min(8192, self.chunksize - self.size_read)
  147. dummy = self.read(n)
  148. if not dummy:
  149. raise EOFError