blob: 08e4d208a2ac1850483a04792f4e0f7a0764c064 [file] [log] [blame]
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +00001# Stuff to parse Sun and NeXT audio files.
2#
3# An audio consists of a header followed by the data. The structure
4# of the header is as follows.
5#
6# +---------------+
7# | magic word |
8# +---------------+
9# | header size |
10# +---------------+
11# | data size |
12# +---------------+
13# | encoding |
14# +---------------+
15# | sample rate |
16# +---------------+
17# | # of channels |
18# +---------------+
19# | info |
20# | |
21# +---------------+
22#
23# The magic word consists of the 4 characters '.snd'. Apart from the
24# info field, all header fields are 4 bytes in size. They are all
25# 32-bit unsigned integers encoded in big-endian byte order.
26#
27# The header size really gives the start of the data.
28# The data size is the physical size of the data. From the other
29# parameter the number of frames can be calculated.
30# The encoding gives the way in which audio samples are encoded.
31# Possible values are listed below.
32# The info field currently consists of an ASCII string giving a
33# human-readable description of the audio file. The info field is
34# padded with NUL bytes to the header size.
35#
36# Usage.
37#
38# Reading audio files:
39# f = au.open(file, 'r')
40# or
41# f = au.openfp(filep, 'r')
42# where file is the name of a file and filep is an open file pointer.
43# The open file pointer must have methods read(), seek(), and close().
44# When the setpos() and rewind() methods are not used, the seek()
45# method is not necessary.
46#
47# This returns an instance of a class with the following public methods:
48# getnchannels() -- returns number of audio channels (1 for
49# mono, 2 for stereo)
50# getsampwidth() -- returns sample width in bytes
51# getframerate() -- returns sampling frequency
52# getnframes() -- returns number of audio frames
53# getcomptype() -- returns compression type ('NONE' for AIFF files)
54# getcompname() -- returns human-readable version of
55# compression type ('not compressed' for AIFF files)
56# getparams() -- returns a tuple consisting of all of the
57# above in the above order
58# getmarkers() -- returns None (for compatibility with the
59# aifc module)
60# getmark(id) -- raises an error since the mark does not
61# exist (for compatibility with the aifc module)
62# readframes(n) -- returns at most n frames of audio
63# rewind() -- rewind to the beginning of the audio stream
64# setpos(pos) -- seek to the specified position
65# tell() -- return the current position
66# close() -- close the instance (make it unusable)
67# The position returned by tell() and the position given to setpos()
68# are compatible and have nothing to do with the actual postion in the
69# file.
70# The close() method is called automatically when the class instance
71# is destroyed.
72#
73# Writing audio files:
74# f = au.open(file, 'w')
75# or
76# f = au.openfp(filep, 'w')
77# where file is the name of a file and filep is an open file pointer.
78# The open file pointer must have methods write(), tell(), seek(), and
79# close().
80#
81# This returns an instance of a class with the following public methods:
82# setnchannels(n) -- set the number of channels
83# setsampwidth(n) -- set the sample width
84# setframerate(n) -- set the frame rate
85# setnframes(n) -- set the number of frames
86# setcomptype(type, name)
87# -- set the compression type and the
88# human-readable compression type
89# setparams(nchannels, sampwidth, framerate, nframes, comptype, compname)
90# -- set all parameters at once
91# tell() -- return current position in output file
92# writeframesraw(data)
93# -- write audio frames without pathing up the
94# file header
95# writeframes(data)
96# -- write audio frames and patch up the file header
97# close() -- patch up the file header and close the
98# output file
99# You should set the parameters before the first writeframesraw or
100# writeframes. The total number of frames does not need to be set,
101# but when it is set to the correct value, the header does not have to
102# be patched up.
103# It is best to first set all parameters, perhaps possibly the
104# compression type, and then write audio frames using writeframesraw.
105# When all frames have been written, either call writeframes('') or
106# close() to patch up the sizes in the header.
107# The close() method is called automatically when the class instance
108# is destroyed.
109
110# from <multimedia/audio_filehdr.h>
111AUDIO_FILE_MAGIC = 0x2e736e64
112AUDIO_FILE_ENCODING_MULAW_8 = 1
113AUDIO_FILE_ENCODING_LINEAR_8 = 2
114AUDIO_FILE_ENCODING_LINEAR_16 = 3
115AUDIO_FILE_ENCODING_LINEAR_24 = 4
116AUDIO_FILE_ENCODING_LINEAR_32 = 5
117AUDIO_FILE_ENCODING_FLOAT = 6
118AUDIO_FILE_ENCODING_DOUBLE = 7
119AUDIO_FILE_ENCODING_ADPCM_G721 = 23
120AUDIO_FILE_ENCODING_ADPCM_G722 = 24
121AUDIO_FILE_ENCODING_ADPCM_G723_3 = 25
122AUDIO_FILE_ENCODING_ADPCM_G723_5 = 26
123AUDIO_FILE_ENCODING_ALAW_8 = 27
124
125# from <multimedia/audio_hdr.h>
126AUDIO_UNKNOWN_SIZE = 0xFFFFFFFFL # ((unsigned)(~0))
127
128_simple_encodings = [AUDIO_FILE_ENCODING_MULAW_8,
129 AUDIO_FILE_ENCODING_LINEAR_8,
130 AUDIO_FILE_ENCODING_LINEAR_16,
131 AUDIO_FILE_ENCODING_LINEAR_24,
132 AUDIO_FILE_ENCODING_LINEAR_32,
133 AUDIO_FILE_ENCODING_ALAW_8]
134
135def _read_u32(file):
136 x = 0L
137 for i in range(4):
138 byte = file.read(1)
139 if byte == '':
140 raise EOFError
141 x = x*256 + ord(byte)
142 return x
143
144def _write_u32(file, x):
145 data = []
146 for i in range(4):
147 d, m = divmod(x, 256)
148 data.insert(0, m)
149 x = d
150 for i in range(4):
151 file.write(chr(int(data[i])))
152
153class Au_read:
154 def initfp(self, file):
155 self._file = file
156 self._soundpos = 0
157 magic = int(_read_u32(file))
158 if magic != AUDIO_FILE_MAGIC:
159 raise Error, 'bad magic number'
160 self._hdr_size = int(_read_u32(file))
161 if self._hdr_size < 24:
162 raise Error, 'header size too small'
163 if self._hdr_size > 100:
164 raise Error, 'header size rediculously large'
165 self._data_size = _read_u32(file)
166 if self._data_size != AUDIO_UNKNOWN_SIZE:
167 self._data_size = int(self._data_size)
168 self._encoding = int(_read_u32(file))
169 if self._encoding not in _simple_encodings:
170 raise Error, 'encoding not (yet) supported'
171 if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8,
172 AUDIO_FILE_ENCODING_LINEAR_8,
173 AUDIO_FILE_ENCODING_ALAW_8):
174 self._sampwidth = 2
175 self._framesize = 1
176 elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_16:
177 self._framesize = self._sampwidth = 2
178 elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_24:
179 self._framesize = self._sampwidth = 3
180 elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32:
181 self._framesize = self._sampwidth = 4
182 else:
183 raise Error, 'unknown encoding'
184 self._framerate = int(_read_u32(file))
185 self._nchannels = int(_read_u32(file))
186 self._framesize = self._framesize * self._nchannels
187 if self._hdr_size > 24:
188 self._info = file.read(self._hdr_size - 24)
189 for i in range(len(self._info)):
190 if self._info[i] == '\0':
191 self._info = self._info[:i]
192 break
193 else:
194 self._info = ''
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000195
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000196 def __init__(self, f):
197 if type(f) == type(''):
198 import builtin
199 f = builtin.open(f, 'r')
200 self.initfp(f)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000201
202 def __del__(self):
203 if self._file:
204 self.close()
205
206 def getfp(self):
207 return self._file
208
209 def getnchannels(self):
210 return self._nchannels
211
212 def getsampwidth(self):
213 return self._sampwidth
214
215 def getframerate(self):
216 return self._framerate
217
218 def getnframes(self):
219 if self._data_size == AUDIO_UNKNOWN_SIZE:
220 return AUDIO_UNKNOWN_SIZE
221 if self._encoding in _simple_encodings:
222 return self._data_size / self._framesize
223 return 0 # XXX--must do some arithmetic here
224
225 def getcomptype(self):
226 if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
227 return 'ULAW'
228 elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8:
229 return 'ALAW'
230 else:
231 return 'NONE'
232
233 def getcompname(self):
234 if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
235 return 'CCITT G.711 u-law'
236 elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8:
237 return 'CCITT G.711 A-law'
238 else:
239 return 'not compressed'
240
241 def getparams(self):
242 return self.getnchannels(), self.getsampwidth(), \
243 self.getframerate(), self.getnframes(), \
244 self.getcomptype(), self.getcompname()
245
246 def getmarkers(self):
247 return None
248
249 def getmark(self, id):
250 raise Error, 'no marks'
251
252 def readframes(self, nframes):
253 if self._encoding in _simple_encodings:
254 if nframes == AUDIO_UNKNOWN_SIZE:
255 data = self._file.read()
256 else:
257 data = self._file.read(nframes * self._sampwidth * self._nchannels)
258 if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
259 import audioop
260 data = audioop.ulaw2lin(data, self._sampwidth)
261 return data
262 return None # XXX--not implemented yet
263
264 def rewind(self):
265 self._soundpos = 0
266 self._file.seek(self._hdr_size)
267
268 def tell(self):
269 return self._soundpos
270
271 def setpos(self, pos):
272 if pos < 0 or pos > self.getnframes():
273 raise Error, 'position not in range'
274 self._file.seek(pos * self._framesize + self._hdr_size)
275 self._soundpos = pos
276
277 def close(self):
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000278 self._file = None
279
280class Au_write:
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000281 def __init__(self, f):
282 if type(f) == type(''):
283 import builtin
284 f = builtin.open(f, 'w')
285 self.initfp(f)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000286
287 def initfp(self, file):
288 self._file = file
289 self._framerate = 0
290 self._nchannels = 0
291 self._sampwidth = 0
292 self._framesize = 0
293 self._nframes = AUDIO_UNKNOWN_SIZE
294 self._nframeswritten = 0
295 self._datawritten = 0
296 self._datalength = 0
297 self._info = ''
298 self._comptype = 'ULAW' # default is U-law
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000299
300 def __del__(self):
301 if self._file:
302 self.close()
303
304 def setnchannels(self, nchannels):
305 if self._nframeswritten:
306 raise Error, 'cannot change parameters after starting to write'
307 if nchannels not in (1, 2, 4):
308 raise Error, 'only 1, 2, or 4 channels supported'
309 self._nchannels = nchannels
310
311 def getnchannels(self):
312 if not self._nchannels:
313 raise Error, 'number of channels not set'
314 return self._nchannels
315
316 def setsampwidth(self, sampwidth):
317 if self._nframeswritten:
318 raise Error, 'cannot change parameters after starting to write'
319 if sampwidth not in (1, 2, 4):
320 raise Error, 'bad sample width'
321 self._sampwidth = sampwidth
322
323 def getsampwidth(self):
324 if not self._framerate:
325 raise Error, 'sample width not specified'
326 return self._sampwidth
327
328 def setframerate(self, framerate):
329 if self._nframeswritten:
330 raise Error, 'cannot change parameters after starting to write'
331 self._framerate = framerate
332
333 def getframerate(self):
334 if not self._framerate:
335 raise Error, 'frame rate not set'
336 return self._framerate
337
338 def setnframes(self, nframes):
339 if self._nframeswritten:
340 raise Error, 'cannot change parameters after starting to write'
341 if nframes < 0:
342 raise Error, '# of frames cannot be negative'
343 self._nframes = nframes
344
345 def getnframes(self):
346 return self._nframeswritten
347
348 def setcomptype(self, type, name):
349 if type in ('NONE', 'ULAW'):
350 self._comptype = type
351 else:
352 raise Error, 'unknown compression type'
353
354 def getcomptype(self):
355 return self._comptype
356
357 def getcompname(self):
358 if self._comptype == 'ULAW':
359 return 'CCITT G.711 u-law'
360 elif self._comptype == 'ALAW':
361 return 'CCITT G.711 A-law'
362 else:
363 return 'not compressed'
364
365 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
366 self.setnchannels(nchannels)
367 self.setsampwidth(sampwidth)
368 self.setframerate(framerate)
369 self.setnframes(nframes)
370 self.setcomptype(comptype, compname)
371
372 def getparams(self):
373 return self.getnchannels(), self.getsampwidth(), \
374 self.getframerate(), self.getnframes(), \
375 self.getcomptype(), self.getcompname()
376
377 def tell(self):
378 return self._nframeswritten
379
380 def writeframesraw(self, data):
381 self._ensure_header_written()
382 nframes = len(data) / self._framesize
383 if self._comptype == 'ULAW':
384 import audioop
385 data = audioop.lin2ulaw(data, self._sampwidth)
386 self._file.write(data)
387 self._nframeswritten = self._nframeswritten + nframes
388 self._datawritten = self._datawritten + len(data)
389
390 def writeframes(self, data):
391 self.writeframesraw(data)
392 if self._nframeswritten != self._nframes or \
393 self._datalength != self._datawritten:
394 self._patchheader()
395
396 def close(self):
397 self._ensure_header_written()
398 if self._nframeswritten != self._nframes or \
399 self._datalength != self._datawritten:
400 self._patchheader()
Sjoerd Mullenderad7324c1993-12-16 14:02:44 +0000401 self._file.flush()
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000402 self._file = None
403
404 #
405 # private methods
406 #
407 def _ensure_header_written(self):
408 if not self._nframeswritten:
409 if not self._nchannels:
410 raise Error, '# of channels not specified'
411 if not self._sampwidth:
412 raise Error, 'sample width not specified'
413 if not self._framerate:
414 raise Error, 'frame rate not specified'
415 self._write_header()
416
417 def _write_header(self):
418 if self._comptype == 'NONE':
419 if self._sampwidth == 1:
420 encoding = AUDIO_FILE_ENCODING_LINEAR_8
421 self._framesize = 1
422 elif self._sampwidth == 2:
423 encoding = AUDIO_FILE_ENCODING_LINEAR_16
424 self._framesize = 2
425 elif self._sampwidth == 4:
426 encoding = AUDIO_FILE_ENCODING_LINEAR_32
427 self._framesize = 4
428 else:
429 raise Error, 'internal error'
430 elif self._comptype == 'ULAW':
431 encoding = AUDIO_FILE_ENCODING_MULAW_8
432 self._framesize = 1
433 else:
434 raise Error, 'internal error'
435 self._framesize = self._framesize * self._nchannels
436 _write_u32(self._file, AUDIO_FILE_MAGIC)
437 header_size = 25 + len(self._info)
438 header_size = (header_size + 7) & ~7
439 _write_u32(self._file, header_size)
440 if self._nframes == AUDIO_UNKNOWN_SIZE:
441 length = AUDIO_UNKNOWN_SIZE
442 else:
443 length = self._nframes * self._framesize
444 _write_u32(self._file, length)
445 self._datalength = length
446 _write_u32(self._file, encoding)
447 _write_u32(self._file, self._framerate)
448 _write_u32(self._file, self._nchannels)
449 self._file.write(self._info)
450 self._file.write('\0'*(header_size - len(self._info) - 24))
451
452 def _patchheader(self):
453 self._file.seek(8)
454 _write_u32(self._file, self._datawritten)
455 self._datalength = self._datawritten
456 self._file.seek(0, 2)
457
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000458def open(f, mode):
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000459 if mode == 'r':
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000460 return Au_read(f)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000461 elif mode == 'w':
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000462 return Au_write(f)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000463 else:
464 raise Error, "mode must be 'r' or 'w'"
465
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000466openfp = open