blob: 6c19dea98dc75540007d7e845b9ccdb5e2c960fd [file] [log] [blame]
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +00001# Stuff to parse AIFF-C and AIFF files.
2#
3# Unless explicitly stated otherwise, the description below is true
4# both for AIFF-C files and AIFF files.
5#
6# An AIFF-C file has the following structure.
7#
8# +-----------------+
9# | FORM |
10# +-----------------+
11# | <size> |
12# +----+------------+
13# | | AIFC |
14# | +------------+
15# | | <chunks> |
16# | | . |
17# | | . |
18# | | . |
19# +----+------------+
20#
21# An AIFF file has the string "AIFF" instead of "AIFC".
22#
23# A chunk consists of an identifier (4 bytes) followed by a size (4 bytes,
24# big endian order), followed by the data. The size field does not include
25# the size of the 8 byte header.
26#
27# The following chunk types are recognized.
28#
29# FVER
30# <version number of AIFF-C defining document> (AIFF-C only).
31# MARK
32# <# of markers> (2 bytes)
33# list of markers:
34# <marker ID> (2 bytes, must be > 0)
35# <position> (4 bytes)
36# <marker name> ("pstring")
37# COMM
38# <# of channels> (2 bytes)
39# <# of sound frames> (4 bytes)
40# <size of the samples> (2 bytes)
41# <sampling frequency> (10 bytes, IEEE 80-bit extended
42# floating point)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +000043# in AIFF-C files only:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000044# <compression type> (4 bytes)
45# <human-readable version of compression type> ("pstring")
46# SSND
47# <offset> (4 bytes, not used by this program)
48# <blocksize> (4 bytes, not used by this program)
49# <sound data>
50#
51# A pstring consists of 1 byte length, a string of characters, and 0 or 1
52# byte pad to make the total length even.
53#
54# Usage.
55#
56# Reading AIFF files:
57# f = aifc.open(file, 'r')
Sjoerd Mullender2a451411993-12-20 09:36:01 +000058# where file is either the name of a file or an open file pointer.
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +000059# The open file pointer must have methods read(), seek(), and close().
60# In some types of audio files, if the setpos() method is not used,
61# the seek() method is not necessary.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000062#
63# This returns an instance of a class with the following public methods:
64# getnchannels() -- returns number of audio channels (1 for
65# mono, 2 for stereo)
66# getsampwidth() -- returns sample width in bytes
67# getframerate() -- returns sampling frequency
68# getnframes() -- returns number of audio frames
69# getcomptype() -- returns compression type ('NONE' for AIFF files)
70# getcompname() -- returns human-readable version of
71# compression type ('not compressed' for AIFF files)
72# getparams() -- returns a tuple consisting of all of the
73# above in the above order
74# getmarkers() -- get the list of marks in the audio file or None
75# if there are no marks
76# getmark(id) -- get mark with the specified id (raises an error
77# if the mark does not exist)
78# readframes(n) -- returns at most n frames of audio
79# rewind() -- rewind to the beginning of the audio stream
80# setpos(pos) -- seek to the specified position
81# tell() -- return the current position
Guido van Rossum17ed1ae1993-06-01 13:21:04 +000082# close() -- close the instance (make it unusable)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000083# The position returned by tell(), the position given to setpos() and
84# the position of marks are all compatible and have nothing to do with
85# the actual postion in the file.
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +000086# The close() method is called automatically when the class instance
87# is destroyed.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000088#
89# Writing AIFF files:
90# f = aifc.open(file, 'w')
Sjoerd Mullender2a451411993-12-20 09:36:01 +000091# where file is either the name of a file or an open file pointer.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000092# The open file pointer must have methods write(), tell(), seek(), and
93# close().
94#
95# This returns an instance of a class with the following public methods:
96# aiff() -- create an AIFF file (AIFF-C default)
97# aifc() -- create an AIFF-C file
98# setnchannels(n) -- set the number of channels
99# setsampwidth(n) -- set the sample width
100# setframerate(n) -- set the frame rate
101# setnframes(n) -- set the number of frames
102# setcomptype(type, name)
103# -- set the compression type and the
104# human-readable compression type
Guido van Rossumbb189db1998-04-23 21:40:02 +0000105# setparams(tuple)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000106# -- set all parameters at once
107# setmark(id, pos, name)
108# -- add specified mark to the list of marks
109# tell() -- return current position in output file (useful
110# in combination with setmark())
111# writeframesraw(data)
112# -- write audio frames without pathing up the
113# file header
114# writeframes(data)
115# -- write audio frames and patch up the file header
116# close() -- patch up the file header and close the
117# output file
118# You should set the parameters before the first writeframesraw or
119# writeframes. The total number of frames does not need to be set,
120# but when it is set to the correct value, the header does not have to
121# be patched up.
122# It is best to first set all parameters, perhaps possibly the
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000123# compression type, and then write audio frames using writeframesraw.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000124# When all frames have been written, either call writeframes('') or
125# close() to patch up the sizes in the header.
126# Marks can be added anytime. If there are any marks, ypu must call
127# close() after all frames have been written.
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000128# The close() method is called automatically when the class instance
129# is destroyed.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000130#
131# When a file is opened with the extension '.aiff', an AIFF file is
132# written, otherwise an AIFF-C file is written. This default can be
133# changed by calling aiff() or aifc() before the first writeframes or
134# writeframesraw.
135
Guido van Rossum36bb1811996-12-31 05:57:34 +0000136import struct
Guido van Rossum3db6ebc1994-01-28 09:59:35 +0000137import __builtin__
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000138
139Error = 'aifc.Error'
140
141_AIFC_version = 0xA2805140 # Version 1 of AIFF-C
142
143_skiplist = 'COMT', 'INST', 'MIDI', 'AESD', \
144 'APPL', 'NAME', 'AUTH', '(c) ', 'ANNO'
145
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000146def _read_long(file):
Guido van Rossum36bb1811996-12-31 05:57:34 +0000147 try:
148 return struct.unpack('>l', file.read(4))[0]
149 except struct.error:
150 raise EOFError
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000151
152def _read_ulong(file):
Guido van Rossum36bb1811996-12-31 05:57:34 +0000153 try:
154 return struct.unpack('>L', file.read(4))[0]
155 except struct.error:
156 raise EOFError
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000157
158def _read_short(file):
Guido van Rossum36bb1811996-12-31 05:57:34 +0000159 try:
160 return struct.unpack('>h', file.read(2))[0]
161 except struct.error:
162 raise EOFError
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000163
164def _read_string(file):
165 length = ord(file.read(1))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000166 if length == 0:
167 data = ''
168 else:
169 data = file.read(length)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000170 if length & 1 == 0:
171 dummy = file.read(1)
172 return data
173
174_HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
175
176def _read_float(f): # 10 bytes
177 import math
178 expon = _read_short(f) # 2 bytes
179 sign = 1
180 if expon < 0:
181 sign = -1
182 expon = expon + 0x8000
183 himant = _read_ulong(f) # 4 bytes
184 lomant = _read_ulong(f) # 4 bytes
185 if expon == himant == lomant == 0:
186 f = 0.0
187 elif expon == 0x7FFF:
188 f = _HUGE_VAL
189 else:
190 expon = expon - 16383
191 f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63)
192 return sign * f
193
194def _write_short(f, x):
Guido van Rossum36bb1811996-12-31 05:57:34 +0000195 f.write(struct.pack('>h', x))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000196
197def _write_long(f, x):
Guido van Rossumafe3ebf1997-01-11 19:21:09 +0000198 f.write(struct.pack('>L', x))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000199
200def _write_string(f, s):
201 f.write(chr(len(s)))
202 f.write(s)
203 if len(s) & 1 == 0:
204 f.write(chr(0))
205
206def _write_float(f, x):
207 import math
208 if x < 0:
209 sign = 0x8000
210 x = x * -1
211 else:
212 sign = 0
213 if x == 0:
214 expon = 0
215 himant = 0
216 lomant = 0
217 else:
218 fmant, expon = math.frexp(x)
219 if expon > 16384 or fmant >= 1: # Infinity or NaN
220 expon = sign|0x7FFF
221 himant = 0
222 lomant = 0
223 else: # Finite
224 expon = expon + 16382
225 if expon < 0: # denormalized
226 fmant = math.ldexp(fmant, expon)
227 expon = 0
228 expon = expon | sign
229 fmant = math.ldexp(fmant, 32)
230 fsmant = math.floor(fmant)
231 himant = long(fsmant)
232 fmant = math.ldexp(fmant - fsmant, 32)
233 fsmant = math.floor(fmant)
234 lomant = long(fsmant)
235 _write_short(f, expon)
236 _write_long(f, himant)
237 _write_long(f, lomant)
238
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000239from chunk import Chunk
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000240
Guido van Rossumd3166071993-05-24 14:16:22 +0000241class Aifc_read:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000242 # Variables used in this class:
243 #
244 # These variables are available to the user though appropriate
245 # methods of this class:
246 # _file -- the open file with methods read(), close(), and seek()
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000247 # set through the __init__() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000248 # _nchannels -- the number of audio channels
249 # available through the getnchannels() method
250 # _nframes -- the number of audio frames
251 # available through the getnframes() method
252 # _sampwidth -- the number of bytes per audio sample
253 # available through the getsampwidth() method
254 # _framerate -- the sampling frequency
255 # available through the getframerate() method
256 # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
257 # available through the getcomptype() method
258 # _compname -- the human-readable AIFF-C compression type
259 # available through the getcomptype() method
260 # _markers -- the marks in the audio file
261 # available through the getmarkers() and getmark()
262 # methods
263 # _soundpos -- the position in the audio stream
264 # available through the tell() method, set through the
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000265 # setpos() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000266 #
267 # These variables are used internally only:
268 # _version -- the AIFF-C version number
269 # _decomp -- the decompressor from builtin module cl
270 # _comm_chunk_read -- 1 iff the COMM chunk has been read
271 # _aifc -- 1 iff reading an AIFF-C file
272 # _ssnd_seek_needed -- 1 iff positioned correctly in audio
273 # file for readframes()
274 # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000275 # _framesize -- size of one frame in the file
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000276
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000277 def initfp(self, file):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000278 self._version = 0
279 self._decomp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000280 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000281 self._markers = []
282 self._soundpos = 0
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000283 self._file = Chunk(file)
284 if self._file.getname() != 'FORM':
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000285 raise Error, 'file does not start with FORM id'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000286 formdata = self._file.read(4)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000287 if formdata == 'AIFF':
288 self._aifc = 0
289 elif formdata == 'AIFC':
290 self._aifc = 1
291 else:
292 raise Error, 'not an AIFF or AIFF-C file'
293 self._comm_chunk_read = 0
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000294 while 1:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000295 self._ssnd_seek_needed = 1
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000296 try:
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000297 chunk = Chunk(self._file)
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000298 except EOFError:
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000299 break
300 chunkname = chunk.getname()
301 if chunkname == 'COMM':
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000302 self._read_comm_chunk(chunk)
303 self._comm_chunk_read = 1
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000304 elif chunkname == 'SSND':
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000305 self._ssnd_chunk = chunk
306 dummy = chunk.read(8)
307 self._ssnd_seek_needed = 0
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000308 elif chunkname == 'FVER':
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000309 self._version = _read_long(chunk)
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000310 elif chunkname == 'MARK':
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000311 self._readmark(chunk)
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000312 elif chunkname in _skiplist:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000313 pass
314 else:
315 raise Error, 'unrecognized chunk type '+chunk.chunkname
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000316 chunk.skip()
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000317 if not self._comm_chunk_read or not self._ssnd_chunk:
318 raise Error, 'COMM chunk and/or SSND chunk missing'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000319 if self._aifc and self._decomp:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000320 import cl
321 params = [cl.ORIGINAL_FORMAT, 0,
322 cl.BITS_PER_COMPONENT, self._sampwidth * 8,
323 cl.FRAME_RATE, self._framerate]
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000324 if self._nchannels == 1:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000325 params[1] = cl.MONO
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000326 elif self._nchannels == 2:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000327 params[1] = cl.STEREO_INTERLEAVED
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000328 else:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000329 raise Error, 'cannot compress more than 2 channels'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000330 self._decomp.SetParams(params)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000331
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000332 def __init__(self, f):
333 if type(f) == type(''):
Guido van Rossume174c151994-09-16 10:55:53 +0000334 f = __builtin__.open(f, 'rb')
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000335 # else, assume it is an open file object already
336 self.initfp(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000337
338 #
339 # User visible methods.
340 #
341 def getfp(self):
342 return self._file
343
344 def rewind(self):
345 self._ssnd_seek_needed = 1
346 self._soundpos = 0
347
348 def close(self):
349 if self._decomp:
350 self._decomp.CloseDecompressor()
351 self._decomp = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000352 self._file = None
353
354 def tell(self):
355 return self._soundpos
356
357 def getnchannels(self):
358 return self._nchannels
359
360 def getnframes(self):
361 return self._nframes
362
363 def getsampwidth(self):
364 return self._sampwidth
365
366 def getframerate(self):
367 return self._framerate
368
369 def getcomptype(self):
370 return self._comptype
371
372 def getcompname(self):
373 return self._compname
374
375## def getversion(self):
376## return self._version
377
378 def getparams(self):
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000379 return self.getnchannels(), self.getsampwidth(), \
380 self.getframerate(), self.getnframes(), \
381 self.getcomptype(), self.getcompname()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000382
383 def getmarkers(self):
384 if len(self._markers) == 0:
385 return None
386 return self._markers
387
388 def getmark(self, id):
389 for marker in self._markers:
390 if id == marker[0]:
391 return marker
392 raise Error, 'marker ' + `id` + ' does not exist'
393
394 def setpos(self, pos):
395 if pos < 0 or pos > self._nframes:
396 raise Error, 'position not in range'
397 self._soundpos = pos
398 self._ssnd_seek_needed = 1
399
400 def readframes(self, nframes):
401 if self._ssnd_seek_needed:
Guido van Rossum8ea7bb81999-06-09 13:32:28 +0000402 self._ssnd_chunk.seek(0)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000403 dummy = self._ssnd_chunk.read(8)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000404 pos = self._soundpos * self._framesize
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000405 if pos:
406 self._ssnd_chunk.setpos(pos + 8)
407 self._ssnd_seek_needed = 0
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000408 if nframes == 0:
409 return ''
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000410 data = self._ssnd_chunk.read(nframes * self._framesize)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000411 if self._convert and data:
412 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000413 self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth)
414 return data
415
416 #
417 # Internal methods.
418 #
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000419
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000420 def _decomp_data(self, data):
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000421 import cl
422 dummy = self._decomp.SetParam(cl.FRAME_BUFFER_SIZE,
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000423 len(data) * 2)
424 return self._decomp.Decompress(len(data) / self._nchannels,
425 data)
426
427 def _ulaw2lin(self, data):
428 import audioop
429 return audioop.ulaw2lin(data, 2)
430
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000431 def _adpcm2lin(self, data):
432 import audioop
433 if not hasattr(self, '_adpcmstate'):
434 # first time
435 self._adpcmstate = None
436 data, self._adpcmstate = audioop.adpcm2lin(data, 2,
437 self._adpcmstate)
438 return data
439
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000440 def _read_comm_chunk(self, chunk):
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000441 self._nchannels = _read_short(chunk)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000442 self._nframes = _read_long(chunk)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000443 self._sampwidth = (_read_short(chunk) + 7) / 8
Sjoerd Mullenderffe94901994-01-28 09:56:05 +0000444 self._framerate = int(_read_float(chunk))
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000445 self._framesize = self._nchannels * self._sampwidth
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000446 if self._aifc:
447 #DEBUG: SGI's soundeditor produces a bad size :-(
448 kludge = 0
449 if chunk.chunksize == 18:
450 kludge = 1
451 print 'Warning: bad COMM chunk size'
452 chunk.chunksize = 23
453 #DEBUG end
454 self._comptype = chunk.read(4)
455 #DEBUG start
456 if kludge:
457 length = ord(chunk.file.read(1))
458 if length & 1 == 0:
459 length = length + 1
460 chunk.chunksize = chunk.chunksize + length
461 chunk.file.seek(-1, 1)
462 #DEBUG end
463 self._compname = _read_string(chunk)
464 if self._comptype != 'NONE':
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000465 if self._comptype == 'G722':
466 try:
467 import audioop
468 except ImportError:
469 pass
470 else:
471 self._convert = self._adpcm2lin
472 self._framesize = self._framesize / 4
473 return
474 # for ULAW and ALAW try Compression Library
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000475 try:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000476 import cl
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000477 except ImportError:
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000478 if self._comptype == 'ULAW':
479 try:
480 import audioop
481 self._convert = self._ulaw2lin
482 self._framesize = self._framesize / 2
483 return
484 except ImportError:
485 pass
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000486 raise Error, 'cannot read compressed AIFF-C files'
487 if self._comptype == 'ULAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000488 scheme = cl.G711_ULAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000489 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000490 elif self._comptype == 'ALAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000491 scheme = cl.G711_ALAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000492 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000493 else:
494 raise Error, 'unsupported compression type'
495 self._decomp = cl.OpenDecompressor(scheme)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000496 self._convert = self._decomp_data
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000497 else:
498 self._comptype = 'NONE'
499 self._compname = 'not compressed'
500
501 def _readmark(self, chunk):
502 nmarkers = _read_short(chunk)
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000503 # Some files appear to contain invalid counts.
504 # Cope with this by testing for EOF.
505 try:
506 for i in range(nmarkers):
507 id = _read_short(chunk)
508 pos = _read_long(chunk)
509 name = _read_string(chunk)
Sjoerd Mullenderebea8961994-10-03 10:21:06 +0000510 if pos or name:
511 # some files appear to have
512 # dummy markers consisting of
513 # a position 0 and name ''
514 self._markers.append((id, pos, name))
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000515 except EOFError:
516 print 'Warning: MARK chunk contains only',
517 print len(self._markers),
518 if len(self._markers) == 1: print 'marker',
519 else: print 'markers',
520 print 'instead of', nmarkers
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000521
Guido van Rossumd3166071993-05-24 14:16:22 +0000522class Aifc_write:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000523 # Variables used in this class:
524 #
525 # These variables are user settable through appropriate methods
526 # of this class:
527 # _file -- the open file with methods write(), close(), tell(), seek()
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000528 # set through the __init__() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000529 # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
530 # set through the setcomptype() or setparams() method
531 # _compname -- the human-readable AIFF-C compression type
532 # set through the setcomptype() or setparams() method
533 # _nchannels -- the number of audio channels
534 # set through the setnchannels() or setparams() method
535 # _sampwidth -- the number of bytes per audio sample
536 # set through the setsampwidth() or setparams() method
537 # _framerate -- the sampling frequency
538 # set through the setframerate() or setparams() method
539 # _nframes -- the number of audio frames written to the header
540 # set through the setnframes() or setparams() method
541 # _aifc -- whether we're writing an AIFF-C file or an AIFF file
542 # set through the aifc() method, reset through the
543 # aiff() method
544 #
545 # These variables are used internally only:
546 # _version -- the AIFF-C version number
547 # _comp -- the compressor from builtin module cl
548 # _nframeswritten -- the number of audio frames actually written
549 # _datalength -- the size of the audio samples written to the header
550 # _datawritten -- the size of the audio samples actually written
551
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000552 def __init__(self, f):
553 if type(f) == type(''):
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000554 filename = f
Guido van Rossume174c151994-09-16 10:55:53 +0000555 f = __builtin__.open(f, 'wb')
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000556 else:
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000557 # else, assume it is an open file object already
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000558 filename = '???'
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000559 self.initfp(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000560 if filename[-5:] == '.aiff':
561 self._aifc = 0
562 else:
563 self._aifc = 1
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000564
565 def initfp(self, file):
566 self._file = file
567 self._version = _AIFC_version
568 self._comptype = 'NONE'
569 self._compname = 'not compressed'
570 self._comp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000571 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000572 self._nchannels = 0
573 self._sampwidth = 0
574 self._framerate = 0
575 self._nframes = 0
576 self._nframeswritten = 0
577 self._datawritten = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000578 self._datalength = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000579 self._markers = []
580 self._marklength = 0
581 self._aifc = 1 # AIFF-C is default
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000582
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000583 def __del__(self):
584 if self._file:
585 self.close()
586
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000587 #
588 # User visible methods.
589 #
590 def aiff(self):
591 if self._nframeswritten:
592 raise Error, 'cannot change parameters after starting to write'
593 self._aifc = 0
594
595 def aifc(self):
596 if self._nframeswritten:
597 raise Error, 'cannot change parameters after starting to write'
598 self._aifc = 1
599
600 def setnchannels(self, nchannels):
601 if self._nframeswritten:
602 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000603 if nchannels < 1:
604 raise Error, 'bad # of channels'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000605 self._nchannels = nchannels
606
607 def getnchannels(self):
608 if not self._nchannels:
609 raise Error, 'number of channels not set'
610 return self._nchannels
611
612 def setsampwidth(self, sampwidth):
613 if self._nframeswritten:
614 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000615 if sampwidth < 1 or sampwidth > 4:
616 raise Error, 'bad sample width'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000617 self._sampwidth = sampwidth
618
619 def getsampwidth(self):
620 if not self._sampwidth:
621 raise Error, 'sample width not set'
622 return self._sampwidth
623
624 def setframerate(self, framerate):
625 if self._nframeswritten:
626 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000627 if framerate <= 0:
628 raise Error, 'bad frame rate'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000629 self._framerate = framerate
630
631 def getframerate(self):
632 if not self._framerate:
633 raise Error, 'frame rate not set'
634 return self._framerate
635
636 def setnframes(self, nframes):
637 if self._nframeswritten:
638 raise Error, 'cannot change parameters after starting to write'
639 self._nframes = nframes
640
641 def getnframes(self):
642 return self._nframeswritten
643
644 def setcomptype(self, comptype, compname):
645 if self._nframeswritten:
646 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000647 if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000648 raise Error, 'unsupported compression type'
649 self._comptype = comptype
650 self._compname = compname
651
652 def getcomptype(self):
653 return self._comptype
654
655 def getcompname(self):
656 return self._compname
657
658## def setversion(self, version):
659## if self._nframeswritten:
660## raise Error, 'cannot change parameters after starting to write'
661## self._version = version
662
663 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
664 if self._nframeswritten:
665 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000666 if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000667 raise Error, 'unsupported compression type'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000668 self.setnchannels(nchannels)
669 self.setsampwidth(sampwidth)
670 self.setframerate(framerate)
671 self.setnframes(nframes)
672 self.setcomptype(comptype, compname)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000673
674 def getparams(self):
675 if not self._nchannels or not self._sampwidth or not self._framerate:
676 raise Error, 'not all parameters set'
677 return self._nchannels, self._sampwidth, self._framerate, \
678 self._nframes, self._comptype, self._compname
679
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000680 def setmark(self, id, pos, name):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000681 if id <= 0:
682 raise Error, 'marker ID must be > 0'
683 if pos < 0:
684 raise Error, 'marker position must be >= 0'
685 if type(name) != type(''):
686 raise Error, 'marker name must be a string'
687 for i in range(len(self._markers)):
688 if id == self._markers[i][0]:
689 self._markers[i] = id, pos, name
690 return
691 self._markers.append((id, pos, name))
692
693 def getmark(self, id):
694 for marker in self._markers:
695 if id == marker[0]:
696 return marker
697 raise Error, 'marker ' + `id` + ' does not exist'
698
699 def getmarkers(self):
700 if len(self._markers) == 0:
701 return None
702 return self._markers
703
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000704 def tell(self):
705 return self._nframeswritten
706
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000707 def writeframesraw(self, data):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000708 self._ensure_header_written(len(data))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000709 nframes = len(data) / (self._sampwidth * self._nchannels)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000710 if self._convert:
711 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000712 self._file.write(data)
713 self._nframeswritten = self._nframeswritten + nframes
714 self._datawritten = self._datawritten + len(data)
715
716 def writeframes(self, data):
717 self.writeframesraw(data)
718 if self._nframeswritten != self._nframes or \
719 self._datalength != self._datawritten:
720 self._patchheader()
721
722 def close(self):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000723 self._ensure_header_written(0)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000724 if self._datawritten & 1:
725 # quick pad to even size
726 self._file.write(chr(0))
727 self._datawritten = self._datawritten + 1
728 self._writemarkers()
729 if self._nframeswritten != self._nframes or \
730 self._datalength != self._datawritten or \
731 self._marklength:
732 self._patchheader()
733 if self._comp:
734 self._comp.CloseCompressor()
735 self._comp = None
Sjoerd Mullenderfeaa7d21993-12-16 13:56:34 +0000736 self._file.flush()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000737 self._file = None
738
739 #
740 # Internal methods.
741 #
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000742
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000743 def _comp_data(self, data):
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000744 import cl
745 dum = self._comp.SetParam(cl.FRAME_BUFFER_SIZE, len(data))
746 dum = self._comp.SetParam(cl.COMPRESSED_BUFFER_SIZE, len(data))
Guido van Rossum5c071fa1999-05-03 18:02:44 +0000747 return self._comp.Compress(self._nframes, data)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000748
749 def _lin2ulaw(self, data):
750 import audioop
751 return audioop.lin2ulaw(data, 2)
752
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000753 def _lin2adpcm(self, data):
754 import audioop
755 if not hasattr(self, '_adpcmstate'):
756 self._adpcmstate = None
757 data, self._adpcmstate = audioop.lin2adpcm(data, 2,
758 self._adpcmstate)
759 return data
760
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000761 def _ensure_header_written(self, datasize):
762 if not self._nframeswritten:
763 if self._comptype in ('ULAW', 'ALAW'):
764 if not self._sampwidth:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000765 self._sampwidth = 2
766 if self._sampwidth != 2:
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000767 raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000768 if self._comptype == 'G722':
769 if not self._sampwidth:
770 self._sampwidth = 2
771 if self._sampwidth != 2:
772 raise Error, 'sample width must be 2 when compressing with G7.22 (ADPCM)'
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000773 if not self._nchannels:
774 raise Error, '# channels not specified'
775 if not self._sampwidth:
776 raise Error, 'sample width not specified'
777 if not self._framerate:
778 raise Error, 'sampling rate not specified'
779 self._write_header(datasize)
780
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000781 def _init_compression(self):
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000782 if self._comptype == 'G722':
783 import audioop
784 self._convert = self._lin2adpcm
785 return
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000786 try:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000787 import cl
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000788 except ImportError:
789 if self._comptype == 'ULAW':
790 try:
791 import audioop
792 self._convert = self._lin2ulaw
793 return
794 except ImportError:
795 pass
796 raise Error, 'cannot write compressed AIFF-C files'
797 if self._comptype == 'ULAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000798 scheme = cl.G711_ULAW
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000799 elif self._comptype == 'ALAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000800 scheme = cl.G711_ALAW
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000801 else:
802 raise Error, 'unsupported compression type'
803 self._comp = cl.OpenCompressor(scheme)
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000804 params = [cl.ORIGINAL_FORMAT, 0,
805 cl.BITS_PER_COMPONENT, self._sampwidth * 8,
806 cl.FRAME_RATE, self._framerate,
807 cl.FRAME_BUFFER_SIZE, 100,
808 cl.COMPRESSED_BUFFER_SIZE, 100]
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000809 if self._nchannels == 1:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000810 params[1] = cl.MONO
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000811 elif self._nchannels == 2:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000812 params[1] = cl.STEREO_INTERLEAVED
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000813 else:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000814 raise Error, 'cannot compress more than 2 channels'
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000815 self._comp.SetParams(params)
816 # the compressor produces a header which we ignore
817 dummy = self._comp.Compress(0, '')
818 self._convert = self._comp_data
819
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000820 def _write_header(self, initlength):
821 if self._aifc and self._comptype != 'NONE':
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000822 self._init_compression()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000823 self._file.write('FORM')
824 if not self._nframes:
825 self._nframes = initlength / (self._nchannels * self._sampwidth)
826 self._datalength = self._nframes * self._nchannels * self._sampwidth
827 if self._datalength & 1:
828 self._datalength = self._datalength + 1
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000829 if self._aifc:
830 if self._comptype in ('ULAW', 'ALAW'):
831 self._datalength = self._datalength / 2
832 if self._datalength & 1:
833 self._datalength = self._datalength + 1
834 elif self._comptype == 'G722':
835 self._datalength = (self._datalength + 3) / 4
836 if self._datalength & 1:
837 self._datalength = self._datalength + 1
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000838 self._form_length_pos = self._file.tell()
839 commlength = self._write_form_length(self._datalength)
840 if self._aifc:
841 self._file.write('AIFC')
842 self._file.write('FVER')
843 _write_long(self._file, 4)
844 _write_long(self._file, self._version)
845 else:
846 self._file.write('AIFF')
847 self._file.write('COMM')
848 _write_long(self._file, commlength)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000849 _write_short(self._file, self._nchannels)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000850 self._nframes_pos = self._file.tell()
851 _write_long(self._file, self._nframes)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000852 _write_short(self._file, self._sampwidth * 8)
853 _write_float(self._file, self._framerate)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000854 if self._aifc:
855 self._file.write(self._comptype)
856 _write_string(self._file, self._compname)
857 self._file.write('SSND')
858 self._ssnd_length_pos = self._file.tell()
859 _write_long(self._file, self._datalength + 8)
860 _write_long(self._file, 0)
861 _write_long(self._file, 0)
862
863 def _write_form_length(self, datalength):
864 if self._aifc:
865 commlength = 18 + 5 + len(self._compname)
866 if commlength & 1:
867 commlength = commlength + 1
868 verslength = 12
869 else:
870 commlength = 18
871 verslength = 0
872 _write_long(self._file, 4 + verslength + self._marklength + \
873 8 + commlength + 16 + datalength)
874 return commlength
875
876 def _patchheader(self):
877 curpos = self._file.tell()
878 if self._datawritten & 1:
879 datalength = self._datawritten + 1
880 self._file.write(chr(0))
881 else:
882 datalength = self._datawritten
883 if datalength == self._datalength and \
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000884 self._nframes == self._nframeswritten and \
885 self._marklength == 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000886 self._file.seek(curpos, 0)
887 return
888 self._file.seek(self._form_length_pos, 0)
889 dummy = self._write_form_length(datalength)
890 self._file.seek(self._nframes_pos, 0)
891 _write_long(self._file, self._nframeswritten)
892 self._file.seek(self._ssnd_length_pos, 0)
893 _write_long(self._file, datalength + 8)
894 self._file.seek(curpos, 0)
895 self._nframes = self._nframeswritten
896 self._datalength = datalength
897
898 def _writemarkers(self):
899 if len(self._markers) == 0:
900 return
901 self._file.write('MARK')
902 length = 2
903 for marker in self._markers:
904 id, pos, name = marker
905 length = length + len(name) + 1 + 6
906 if len(name) & 1 == 0:
907 length = length + 1
908 _write_long(self._file, length)
909 self._marklength = length + 8
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000910 _write_short(self._file, len(self._markers))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000911 for marker in self._markers:
912 id, pos, name = marker
913 _write_short(self._file, id)
914 _write_long(self._file, pos)
915 _write_string(self._file, name)
916
Fred Drake43161351999-06-22 21:23:23 +0000917def open(f, mode=None):
918 if mode is None:
919 if hasattr(f, 'mode'):
920 mode = f.mode
921 else:
922 mode = 'rb'
923 if mode in ('r', 'rb'):
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000924 return Aifc_read(f)
Fred Drake43161351999-06-22 21:23:23 +0000925 elif mode in ('w', 'wb'):
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000926 return Aifc_write(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000927 else:
Fred Drake43161351999-06-22 21:23:23 +0000928 raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000929
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000930openfp = open # B/W compatibility
Guido van Rossum36bb1811996-12-31 05:57:34 +0000931
932if __name__ == '__main__':
933 import sys
934 if not sys.argv[1:]:
935 sys.argv.append('/usr/demos/data/audio/bach.aiff')
936 fn = sys.argv[1]
937 f = open(fn, 'r')
938 print "Reading", fn
939 print "nchannels =", f.getnchannels()
940 print "nframes =", f.getnframes()
941 print "sampwidth =", f.getsampwidth()
942 print "framerate =", f.getframerate()
943 print "comptype =", f.getcomptype()
944 print "compname =", f.getcompname()
945 if sys.argv[2:]:
946 gn = sys.argv[2]
947 print "Writing", gn
948 g = open(gn, 'w')
949 g.setparams(f.getparams())
950 while 1:
951 data = f.readframes(1024)
952 if not data:
953 break
954 g.writeframes(data)
955 g.close()
956 f.close()
957 print "Done."