-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlime.py
More file actions
256 lines (192 loc) · 6.66 KB
/
lime.py
File metadata and controls
256 lines (192 loc) · 6.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#! /usr/bin/python
# LIME Copyright (C) 2011 Matthew Thompson, Nick Thompson
#
# This file is part of LIME.
#
# LIME is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# LIME is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LIME. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import struct
import wave
from StringIO import StringIO
# UI elements
from Tkinter import Tk
from tkFileDialog import askopenfilename
PREFIX = ''
class Chunk(object):
def __init__(self, file, datacallback=None, debug=False):
self.debug = debug
self.datacallback = datacallback
self.name = file.read(4)
self.size = struct.unpack('<I', file.read(4))[0]
if debug:
print PREFIX + "\nRead: " + self.name + " size " + str(self.size)
self.data = []
self.children = []
self.header = None
if self.name == 'LIST':
self.header = file.read(4)
self.read_children(file, self.size)
elif datacallback:
datacallback(self, file)
else:
file.seek(self.size, 1)
def read_children(self, file, stop):
start = file.tell()
global PREFIX
PREFIX += "\t"
while file.tell() < stop - start:
self.children.append(Chunk(file, self.datacallback, self.debug))
PREFIX = PREFIX[:-1]
def __repr__(self):
return "Chunk %s (size %d) (%d children)" % (
self.name, self.size, len(self.children)
)
class RIFF(object):
def __init__(self, file, datacallback=None, debug=False):
assert file.read(4) == 'RIFF'
self.size = struct.unpack('<I', file.read(4))[0] # total file size
self.name = file.read(4) # should be 'OMNI'
assert self.name == 'OMNI'
self.children = []
while file.tell() < self.size + 4:
self.children.append(Chunk(file, datacallback, debug))
def read_cstring(file):
s = StringIO()
c = ''
while c != '\0':
s.write(c)
c = file.read(1)
return s.getvalue()
def attacher(self, file):
"""Attaches blob data to the chunk in string form."""
self.data = StringIO(file.read(self.size))
def dumper(self, file):
global NUM
blob = file.read(self.size)
if blob.find(' WAV') != -1:
listbegin = blob.find('LIST')
idblock = StringIO(blob[:listbegin])
idblock.seek(15, 1)
name = read_cstring(idblock)
blob = StringIO(blob[listbegin:])
audiolist = Chunk(blob, attacher)
try:
process_audio(name, audiolist.children)
# It ran into some non-audio data
except Exception:
print "Skipping...\n"
def process_header(chunk):
data = chunk.data
data.seek(18, 1)
bitrate1 = struct.unpack('<H', data.read(2))[0]
data.seek(2, 1)
bitrate2 = struct.unpack('<H', data.read(2))[0]
data.seek(2, 1)
idk = struct.unpack('<H', data.read(2))[0]
bits = struct.unpack('<H', data.read(2))[0]
print "\nAudio format might be %dHz or %dHz, with %d bits\n" % (
bitrate1, bitrate2, bits)
return {'sampwidth': bits / 8, 'channels': 1, 'framerate': bitrate1}
def process_audio(name, chunks):
junk = 0
valid = 0
head = chunks[0]
wavinfo = process_header(head)
# Change the working directory to extract_path
# so everything will extract to that location
os.chdir(extract_path)
print "\nWriting %s.wav\n" % name
out = wave.open("%s.wav" % name, 'wb')
out.setnchannels(wavinfo['channels'])
out.setframerate(wavinfo['framerate'])
out.setsampwidth(wavinfo['sampwidth'])
for chunk in chunks[1:]:
if chunk.name == 'MxCh':
valid += 1
chunk.data.seek(14, 0)
out.writeframes(chunk.data.read())
else:
junk += 1
out.close()
print "stats: %d valid, %d junk" % (valid, junk)
def FolPath(filename):
'''Sets the extraction path for the SI archive.
Works for both absolute and relative paths'''
# The folder name to extract the files to
foldername = os.path.dirname(sys.argv[0])
# The base filename (minus .SI)
basefilename = os.path.basename(filename[:-3])
# The complete location to extract the files to
extract_path = os.path.join(foldername, basefilename)
# If the folder does not exists, make it
if not os.path.exists(extract_path):
os.mkdir(extract_path)
# Send back the path
return extract_path
def main():
'''Simple GUI'''
print "\nWelcome to LIME\n"
# SI archive label
fileformat = [("SI Archive", "*.SI")]
# Draw (then withdraw) the root Tk window
root = Tk()
root.withdraw()
# Overwrite root display settings
root.overrideredirect(True)
root.geometry('0x0+0+0')
# Show window again, lift it so it can receive the focus
# Otherwise, it is behind the console window
root.deiconify()
root.lift()
root.focus_force()
# Select the SI archive
filename = askopenfilename(
parent=root,
title="Select a LEGO Island SI Archive",
defaultextension=".SI",
filetypes=fileformat
)
# The user clicked the cancel button
if not filename:
# Give focus back to console window
root.destroy()
raw_input('''\nCould not find an SI Archive to extract!
Press Enter to close LIME.\n''')
raise SystemExit
# The user selected an archive
else:
# Give focus back to console window
root.destroy()
# Display intro text
print "\nReading {0}".format(filename)
print "\n{0}\n".format("-" * 40)
# Run process to get the extraction path
global extract_path
extract_path = FolPath(filename)
# Send archive to extractor
RIFF(open(filename, 'rb'), dumper, debug=True)
if __name__ == "__main__":
try:
filename = sys.argv[1]
# Run process to get the extraction path
extract_path = FolPath(filename)
# Display intro text
print "\nReading {0}".format(filename)
print "\n{0}\n".format("-" * 40)
# Send archive to extractor
RIFF(open(filename, 'rb'), dumper, debug=True)
# The command-line argument was not invoked, open file dialog
except IndexError:
main()