def __init__(self, source): '''Construct a `StaticSource` for the data in `source`. :Parameters: `source` : `Source` The source to read and decode audio and video data from. ''' source = source._get_queue_source() if source.video_format: raise NotImplementedError( 'Static sources not supported for video yet.') self.audio_format = source.audio_format if not self.audio_format: return # Arbitrary: number of bytes to request at a time. buffer_size = 1 << 20 # 1 MB # Naive implementation. Driver-specific implementations may override # to load static audio data into device (or at least driver) memory. data = BytesIO() while True: audio_data = source.get_audio_data(buffer_size) if not audio_data: break data.write(audio_data.get_string_data()) self._data = data.getvalue() self._duration = len(self._data) / \ float(self.audio_format.bytes_per_second)
def __init__(self, data, audio_format): '''Construct a memory source over the given data buffer. ''' self._file = BytesIO(data) self._max_offset = len(data) self.audio_format = audio_format self._duration = len(data) / float(audio_format.bytes_per_second)
class StaticMemorySource(StaticSource): """ Helper class for default implementation of :class:`.StaticSource`. Do not use directly. This class is used internally by pyglet. Args: data (AudioData): The audio data. audio_format (AudioFormat): The audio format. """ def __init__(self, data, audio_format): """Construct a memory source over the given data buffer.""" self._file = BytesIO(data) self._max_offset = len(data) self.audio_format = audio_format self._duration = len(data) / float(audio_format.bytes_per_second) def seek(self, timestamp): """Seek to given timestamp. Args: timestamp (float): Time where to seek in the source. """ offset = int(timestamp * self.audio_format.bytes_per_second) # Align to sample if self.audio_format.bytes_per_sample == 2: offset &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: offset &= 0xfffffffc self._file.seek(offset) def get_audio_data(self, bytes, compensation_time=0.0): """Get next packet of audio data. Args: bytes (int): Maximum number of bytes of data to return. compensation_time (float): Not used in this class. Returns: :class:`.AudioData`: Next packet of audio data, or ``None`` if there is no (more) data. """ offset = self._file.tell() timestamp = float(offset) / self.audio_format.bytes_per_second # Align to sample size if self.audio_format.bytes_per_sample == 2: bytes &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: bytes &= 0xfffffffc data = self._file.read(bytes) if not len(data): return None duration = float(len(data)) / self.audio_format.bytes_per_second return AudioData(data, len(data), timestamp, duration, [])
def _parse_chunks(self): fileobj = BytesIO(self._data) chunks = [] for chunk in range(self.num_chunks): chunk_size = _unpack(DWORD, fileobj) chunk_type = format(_unpack(WORD, fileobj), "#06x") header_size = struct.calcsize(DWORD + WORD) chunk_data = fileobj.read(chunk_size - header_size) if chunk_type in ("0x0004", "0x0011", "0x2016"): chunks.append(DeprecatedChunk(chunk_size, chunk_type, chunk_data)) elif chunk_type == "0x2004": chunks.append(LayerChunk(chunk_size, chunk_type, chunk_data)) elif chunk_type == "0x2005": chunks.append(CelChunk(chunk_size, chunk_type, chunk_data)) elif chunk_type == "0x2017": chunks.append(PathChunk(chunk_size, chunk_type, chunk_data)) elif chunk_type == "0x2018": chunks.append(FrameTagsChunk(chunk_size, chunk_type, chunk_data)) elif chunk_type == "0x2019": palette_chunk = PaletteChunk(chunk_size, chunk_type, chunk_data) chunks.append(palette_chunk) global PALETTE_DICT PALETTE_DICT = palette_chunk.palette_dict.copy() elif chunk_type == "0x2020": chunks.append(UserDataChunk(chunk_size, chunk_type, chunk_data)) return chunks
def __init__(self, source): source = source._get_queue_source() if source.video_format: raise NotImplementedError( 'Static sources not supported for video yet.') self.audio_format = source.audio_format if not self.audio_format: self._data = None self._duration = 0. return # Arbitrary: number of bytes to request at a time. buffer_size = 1 << 20 # 1 MB # Naive implementation. Driver-specific implementations may override # to load static audio data into device (or at least driver) memory. data = BytesIO() while True: audio_data = source.get_audio_data(buffer_size) if not audio_data: break data.write(audio_data.get_string_data()) self._data = data.getvalue() self._duration = (len(self._data) / float(self.audio_format.bytes_per_second))
def load_texture(self): if self.texture_file: self.texture_file = join(dirname(__file__), self.texture_file) self.original_texture = image.load(self.texture_file).texture file = BytesIO() self.original_texture.save(self.texture_file, file, encoder=self.encoder) file.seek(0) self.saved_texture = image.load(self.texture_file, file).texture
def __init__(self, size, chunk_type, data): super(LayerChunk, self).__init__(size, chunk_type) fileobj = BytesIO(data) self.flags = _unpack(WORD, fileobj) self.layer_type = _unpack(WORD, fileobj) self.child_level = _unpack(WORD, fileobj) _ignored_width = _unpack(WORD, fileobj) _ignored_height = _unpack(WORD, fileobj) self.blend_mode = _unpack(WORD, fileobj) self.opacity = _unpack(BYTE, fileobj) _zero_unused = _unpack(BYTE * 3, fileobj) name_length = _unpack(WORD, fileobj) self.name = fileobj.read(name_length) if hasattr(self.name, "decode"): self.name = self.name.decode('utf8')
def open(self, filename, mode='rb'): if self.dir: path = self.dir + '/' + filename else: path = filename text = self.zip.read(path) return BytesIO(text)
def __init__(self, size, chunk_type, data): super(PaletteChunk, self).__init__(size, chunk_type) fileobj = BytesIO(data) self.palette_size = _unpack(DWORD, fileobj) self.first_color_index = _unpack(DWORD, fileobj) self.last_color_index = _unpack(DWORD, fileobj) _zero = _unpack(BYTE * 8, fileobj) self.palette_dict = {} if _unpack(WORD, fileobj) == 1: # color has name size = 7 else: size = 6 for index in range(self.first_color_index, self.last_color_index+1): rgba_data = fileobj.read(size) # Ignore the palette names, as they aren't needed: r, g, b, a = struct.unpack('<BBBB', rgba_data[:4]) self.palette_dict[index] = r, g, b, a
def _pad_pixels(self, cel): """For cels that dont fill the entire frame, pad with zeros.""" fileobj = BytesIO(cel.pixel_data) padding = b'\x00\x00\x00\x00' top_pad = bytes(padding) * (self.width * cel.y_pos) left_pad = bytes(padding) * cel.x_pos right_pad = bytes(padding) * (self.width - cel.x_pos - cel.width) bottom_pad = bytes(padding) * (self.width * (self.height - cel.height - cel.y_pos)) line_size = cel.width * len(padding) pixel_array = top_pad for i in range(cel.height): pixel_array += (left_pad + fileobj.read(line_size) + right_pad) pixel_array += bottom_pad return pixel_array
def load_texture(self): print('Drawing scene...') self.window.set_visible() self.window.dispatch_events() self.draw() print('Saving depth image...') img = image.get_buffer_manager().get_depth_buffer() file = BytesIO() img.save('buffer.png', file) print('Loading depth image as texture...') file.seek(0) self.saved_texture = image.load('buffer.png', file) print('Done.') self.window.set_visible(False)
def open(self, filename, mode='rb'): if self.dir: path = self.dir + '/' + filename else: path = filename forward_slash_path = path.replace(os.sep, '/') # zip can only handle forward slashes text = self.zip.read(forward_slash_path) return BytesIO(text)
def __init__(self, size, chunk_type, data): super(CelChunk, self).__init__(size, chunk_type) fileobj = BytesIO(data) self.layer_index = _unpack(WORD, fileobj) self.x_pos = _unpack(SIGNED_WORD, fileobj) self.y_pos = _unpack(SIGNED_WORD, fileobj) self.opacity_level = _unpack(BYTE, fileobj) self.cel_type = _unpack(WORD, fileobj) _zero_unused = _unpack(BYTE * 7, fileobj) if self.cel_type == 0: self.width = _unpack(WORD, fileobj) self.height = _unpack(WORD, fileobj) self.pixel_data = fileobj.read() elif self.cel_type == 1: self.frame_position = _unpack(WORD, fileobj) elif self.cel_type == 2: self.width = _unpack(WORD, fileobj) self.height = _unpack(WORD, fileobj) self.pixel_data = zlib.decompress(fileobj.read())
class StaticMemorySource(StaticSource): """Helper class for default implementation of `StaticSource`. Do not use directly.""" def __init__(self, data, audio_format): """Construct a memory source over the given data buffer. """ self._file = BytesIO(data) self._max_offset = len(data) self.audio_format = audio_format self._duration = len(data) / float(audio_format.bytes_per_second) def seek(self, timestamp): offset = int(timestamp * self.audio_format.bytes_per_second) # Align to sample if self.audio_format.bytes_per_sample == 2: offset &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: offset &= 0xfffffffc self._file.seek(offset) def get_audio_data(self, bytes_): offset = self._file.tell() timestamp = float(offset) / self.audio_format.bytes_per_second # Align to sample size if self.audio_format.bytes_per_sample == 2: bytes_ &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: bytes_ &= 0xfffffffc data = self._file.read(bytes_) if not len(data): return None duration = float(len(data)) / self.audio_format.bytes_per_second return AudioData(data, len(data), timestamp, duration, list())
def load(filename, file=None, decoder=None, batch=None): """Load a 3D model from a file. :Parameters: `filename` : str Used to guess the model format, and to load the file if `file` is unspecified. `file` : file-like object or None Source of model data in any supported format. `decoder` : ModelDecoder or None If unspecified, all decoders that are registered for the filename extension are tried. An exception is raised if no codecs are registered for the file extension, or if decoding fails. `batch` : Batch or None An optional Batch instance to add this model to. :rtype: :py:mod:`~pyglet.model.Model` """ if not file: file = open(filename, 'rb') if not hasattr(file, 'seek'): file = BytesIO(file.read()) try: if decoder: return decoder.decode(file, filename, batch) else: first_exception = None for decoder in get_decoders(filename): try: model = decoder.decode(file, filename, batch) return model except ModelDecodeException as e: if (not first_exception or first_exception.exception_priority < e.exception_priority): first_exception = e file.seek(0) if not first_exception: raise ModelDecodeException( 'No decoders are available for this model format.') raise first_exception finally: file.close()
def _get_stream(self, path): if zipfile.is_zipfile(path): return path elif not os.path.exists(path + '.001'): return None else: with open(path + '.001', 'rb') as volume: bytes_ = bytes(volume.read()) volume_index = 2 while os.path.exists(path + '.{0:0>3}'.format(volume_index)): with open(path + '.{0:0>3}'.format(volume_index), 'rb') as volume: bytes_ += bytes(volume.read()) volume_index += 1 zip_stream = BytesIO(bytes_) if zipfile.is_zipfile(zip_stream): return zip_stream else: return None
def load(filename, file=None, decoder=None, batch=None): """Load a 3D model from a file. :Parameters: `filename` : str Used to guess the model format, and to load the file if `file` is unspecified. `file` : file-like object or None Source of model data in any supported format. `decoder` : ModelDecoder or None If unspecified, all decoders that are registered for the filename extension are tried. If none succeed, the exception from the first decoder is raised. `batch` : Batch or None An optional Batch instance to add this model to. :rtype: Model """ if not file: file = open(filename, 'rb') if not hasattr(file, 'seek'): file = BytesIO(file.read()) try: if decoder: return decoder.decode(file, filename, batch) else: first_exception = None for decoder in _codecs.get_decoders(filename): try: model = decoder.decode(file, filename, batch) return model except _codecs.ModelDecodeException as e: if (not first_exception or first_exception.exception_priority < e.exception_priority): first_exception = e file.seek(0) if not first_exception: raise _codecs.ModelDecodeException('No decoders are available' 'for this model format.') raise first_exception finally: file.close()
def __init__(self, file): if not hasattr(file, 'seek'): file = BytesIO(file.read()) super(RIFFFile, self).__init__(file, 0)