blob: cd414c0618c2bc870d851da444d29f087bb596cd [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 Rossumd3166071993-05-24 14:16:22 +0000239class Chunk:
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000240 def __init__(self, file):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000241 self.file = file
242 self.chunkname = self.file.read(4)
243 if len(self.chunkname) < 4:
244 raise EOFError
245 self.chunksize = _read_long(self.file)
246 self.size_read = 0
247 self.offset = self.file.tell()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000248
249 def rewind(self):
250 self.file.seek(self.offset, 0)
251 self.size_read = 0
252
253 def setpos(self, pos):
254 if pos < 0 or pos > self.chunksize:
255 raise RuntimeError
256 self.file.seek(self.offset + pos, 0)
257 self.size_read = pos
258
259 def read(self, length):
260 if self.size_read >= self.chunksize:
261 return ''
262 if length > self.chunksize - self.size_read:
263 length = self.chunksize - self.size_read
264 data = self.file.read(length)
265 self.size_read = self.size_read + len(data)
266 return data
267
268 def skip(self):
269 try:
270 self.file.seek(self.chunksize - self.size_read, 1)
271 except RuntimeError:
272 while self.size_read < self.chunksize:
273 dummy = self.read(8192)
274 if not dummy:
275 raise EOFError
276 if self.chunksize & 1:
277 dummy = self.read(1)
278
Guido van Rossumd3166071993-05-24 14:16:22 +0000279class Aifc_read:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000280 # Variables used in this class:
281 #
282 # These variables are available to the user though appropriate
283 # methods of this class:
284 # _file -- the open file with methods read(), close(), and seek()
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000285 # set through the __init__() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000286 # _nchannels -- the number of audio channels
287 # available through the getnchannels() method
288 # _nframes -- the number of audio frames
289 # available through the getnframes() method
290 # _sampwidth -- the number of bytes per audio sample
291 # available through the getsampwidth() method
292 # _framerate -- the sampling frequency
293 # available through the getframerate() method
294 # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
295 # available through the getcomptype() method
296 # _compname -- the human-readable AIFF-C compression type
297 # available through the getcomptype() method
298 # _markers -- the marks in the audio file
299 # available through the getmarkers() and getmark()
300 # methods
301 # _soundpos -- the position in the audio stream
302 # available through the tell() method, set through the
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000303 # setpos() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000304 #
305 # These variables are used internally only:
306 # _version -- the AIFF-C version number
307 # _decomp -- the decompressor from builtin module cl
308 # _comm_chunk_read -- 1 iff the COMM chunk has been read
309 # _aifc -- 1 iff reading an AIFF-C file
310 # _ssnd_seek_needed -- 1 iff positioned correctly in audio
311 # file for readframes()
312 # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000313 # _framesize -- size of one frame in the file
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000314
Guido van Rossumd7abed31996-08-20 20:40:07 +0000315## if 0: access _file, _nchannels, _nframes, _sampwidth, _framerate, \
316## _comptype, _compname, _markers, _soundpos, _version, \
317## _decomp, _comm_chunk_read, __aifc, _ssnd_seek_needed, \
318## _ssnd_chunk, _framesize: private
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000319
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000320 def initfp(self, file):
321 self._file = file
322 self._version = 0
323 self._decomp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000324 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000325 self._markers = []
326 self._soundpos = 0
327 form = self._file.read(4)
328 if form != 'FORM':
329 raise Error, 'file does not start with FORM id'
330 formlength = _read_long(self._file)
331 if formlength <= 0:
332 raise Error, 'invalid FORM chunk data size'
333 formdata = self._file.read(4)
334 formlength = formlength - 4
335 if formdata == 'AIFF':
336 self._aifc = 0
337 elif formdata == 'AIFC':
338 self._aifc = 1
339 else:
340 raise Error, 'not an AIFF or AIFF-C file'
341 self._comm_chunk_read = 0
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000342 while formlength > 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000343 self._ssnd_seek_needed = 1
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000344 #DEBUG: SGI's soundfiler has a bug. There should
345 # be no need to check for EOF here.
346 try:
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000347 chunk = Chunk(self._file)
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000348 except EOFError:
349 if formlength == 8:
350 print 'Warning: FORM chunk size too large'
351 formlength = 0
352 break
353 raise EOFError # different error, raise exception
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000354 if chunk.chunkname == 'COMM':
355 self._read_comm_chunk(chunk)
356 self._comm_chunk_read = 1
357 elif chunk.chunkname == 'SSND':
358 self._ssnd_chunk = chunk
359 dummy = chunk.read(8)
360 self._ssnd_seek_needed = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000361 elif chunk.chunkname == 'FVER':
362 self._version = _read_long(chunk)
363 elif chunk.chunkname == 'MARK':
364 self._readmark(chunk)
365 elif chunk.chunkname in _skiplist:
366 pass
367 else:
368 raise Error, 'unrecognized chunk type '+chunk.chunkname
Sjoerd Mullender4150ede1993-08-26 14:12:07 +0000369 formlength = formlength - 8 - chunk.chunksize
370 if chunk.chunksize & 1:
371 formlength = formlength - 1
Sjoerd Mullender93f07401993-01-26 09:24:37 +0000372 if formlength > 0:
373 chunk.skip()
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000374 if not self._comm_chunk_read or not self._ssnd_chunk:
375 raise Error, 'COMM chunk and/or SSND chunk missing'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000376 if self._aifc and self._decomp:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000377 import cl
378 params = [cl.ORIGINAL_FORMAT, 0,
379 cl.BITS_PER_COMPONENT, self._sampwidth * 8,
380 cl.FRAME_RATE, self._framerate]
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000381 if self._nchannels == 1:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000382 params[1] = cl.MONO
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000383 elif self._nchannels == 2:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000384 params[1] = cl.STEREO_INTERLEAVED
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000385 else:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000386 raise Error, 'cannot compress more than 2 channels'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000387 self._decomp.SetParams(params)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000388
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000389 def __init__(self, f):
390 if type(f) == type(''):
Guido van Rossume174c151994-09-16 10:55:53 +0000391 f = __builtin__.open(f, 'rb')
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000392 # else, assume it is an open file object already
393 self.initfp(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000394
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000395 def __del__(self):
396 if self._file:
397 self.close()
398
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000399 #
400 # User visible methods.
401 #
402 def getfp(self):
403 return self._file
404
405 def rewind(self):
406 self._ssnd_seek_needed = 1
407 self._soundpos = 0
408
409 def close(self):
410 if self._decomp:
411 self._decomp.CloseDecompressor()
412 self._decomp = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000413 self._file = None
414
415 def tell(self):
416 return self._soundpos
417
418 def getnchannels(self):
419 return self._nchannels
420
421 def getnframes(self):
422 return self._nframes
423
424 def getsampwidth(self):
425 return self._sampwidth
426
427 def getframerate(self):
428 return self._framerate
429
430 def getcomptype(self):
431 return self._comptype
432
433 def getcompname(self):
434 return self._compname
435
436## def getversion(self):
437## return self._version
438
439 def getparams(self):
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000440 return self.getnchannels(), self.getsampwidth(), \
441 self.getframerate(), self.getnframes(), \
442 self.getcomptype(), self.getcompname()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000443
444 def getmarkers(self):
445 if len(self._markers) == 0:
446 return None
447 return self._markers
448
449 def getmark(self, id):
450 for marker in self._markers:
451 if id == marker[0]:
452 return marker
453 raise Error, 'marker ' + `id` + ' does not exist'
454
455 def setpos(self, pos):
456 if pos < 0 or pos > self._nframes:
457 raise Error, 'position not in range'
458 self._soundpos = pos
459 self._ssnd_seek_needed = 1
460
461 def readframes(self, nframes):
462 if self._ssnd_seek_needed:
463 self._ssnd_chunk.rewind()
464 dummy = self._ssnd_chunk.read(8)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000465 pos = self._soundpos * self._framesize
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000466 if pos:
467 self._ssnd_chunk.setpos(pos + 8)
468 self._ssnd_seek_needed = 0
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000469 if nframes == 0:
470 return ''
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000471 data = self._ssnd_chunk.read(nframes * self._framesize)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000472 if self._convert and data:
473 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000474 self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth)
475 return data
476
477 #
478 # Internal methods.
479 #
Guido van Rossumd7abed31996-08-20 20:40:07 +0000480## if 0: access *: private
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000481
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000482 def _decomp_data(self, data):
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000483 import cl
484 dummy = self._decomp.SetParam(cl.FRAME_BUFFER_SIZE,
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000485 len(data) * 2)
486 return self._decomp.Decompress(len(data) / self._nchannels,
487 data)
488
489 def _ulaw2lin(self, data):
490 import audioop
491 return audioop.ulaw2lin(data, 2)
492
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000493 def _adpcm2lin(self, data):
494 import audioop
495 if not hasattr(self, '_adpcmstate'):
496 # first time
497 self._adpcmstate = None
498 data, self._adpcmstate = audioop.adpcm2lin(data, 2,
499 self._adpcmstate)
500 return data
501
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000502 def _read_comm_chunk(self, chunk):
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000503 self._nchannels = _read_short(chunk)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000504 self._nframes = _read_long(chunk)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000505 self._sampwidth = (_read_short(chunk) + 7) / 8
Sjoerd Mullenderffe94901994-01-28 09:56:05 +0000506 self._framerate = int(_read_float(chunk))
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000507 self._framesize = self._nchannels * self._sampwidth
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000508 if self._aifc:
509 #DEBUG: SGI's soundeditor produces a bad size :-(
510 kludge = 0
511 if chunk.chunksize == 18:
512 kludge = 1
513 print 'Warning: bad COMM chunk size'
514 chunk.chunksize = 23
515 #DEBUG end
516 self._comptype = chunk.read(4)
517 #DEBUG start
518 if kludge:
519 length = ord(chunk.file.read(1))
520 if length & 1 == 0:
521 length = length + 1
522 chunk.chunksize = chunk.chunksize + length
523 chunk.file.seek(-1, 1)
524 #DEBUG end
525 self._compname = _read_string(chunk)
526 if self._comptype != 'NONE':
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000527 if self._comptype == 'G722':
528 try:
529 import audioop
530 except ImportError:
531 pass
532 else:
533 self._convert = self._adpcm2lin
534 self._framesize = self._framesize / 4
535 return
536 # for ULAW and ALAW try Compression Library
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000537 try:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000538 import cl
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000539 except ImportError:
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000540 if self._comptype == 'ULAW':
541 try:
542 import audioop
543 self._convert = self._ulaw2lin
544 self._framesize = self._framesize / 2
545 return
546 except ImportError:
547 pass
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000548 raise Error, 'cannot read compressed AIFF-C files'
549 if self._comptype == 'ULAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000550 scheme = cl.G711_ULAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000551 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000552 elif self._comptype == 'ALAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000553 scheme = cl.G711_ALAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000554 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000555 else:
556 raise Error, 'unsupported compression type'
557 self._decomp = cl.OpenDecompressor(scheme)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000558 self._convert = self._decomp_data
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000559 else:
560 self._comptype = 'NONE'
561 self._compname = 'not compressed'
562
563 def _readmark(self, chunk):
564 nmarkers = _read_short(chunk)
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000565 # Some files appear to contain invalid counts.
566 # Cope with this by testing for EOF.
567 try:
568 for i in range(nmarkers):
569 id = _read_short(chunk)
570 pos = _read_long(chunk)
571 name = _read_string(chunk)
Sjoerd Mullenderebea8961994-10-03 10:21:06 +0000572 if pos or name:
573 # some files appear to have
574 # dummy markers consisting of
575 # a position 0 and name ''
576 self._markers.append((id, pos, name))
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000577 except EOFError:
578 print 'Warning: MARK chunk contains only',
579 print len(self._markers),
580 if len(self._markers) == 1: print 'marker',
581 else: print 'markers',
582 print 'instead of', nmarkers
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000583
Guido van Rossumd3166071993-05-24 14:16:22 +0000584class Aifc_write:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000585 # Variables used in this class:
586 #
587 # These variables are user settable through appropriate methods
588 # of this class:
589 # _file -- the open file with methods write(), close(), tell(), seek()
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000590 # set through the __init__() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000591 # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
592 # set through the setcomptype() or setparams() method
593 # _compname -- the human-readable AIFF-C compression type
594 # set through the setcomptype() or setparams() method
595 # _nchannels -- the number of audio channels
596 # set through the setnchannels() or setparams() method
597 # _sampwidth -- the number of bytes per audio sample
598 # set through the setsampwidth() or setparams() method
599 # _framerate -- the sampling frequency
600 # set through the setframerate() or setparams() method
601 # _nframes -- the number of audio frames written to the header
602 # set through the setnframes() or setparams() method
603 # _aifc -- whether we're writing an AIFF-C file or an AIFF file
604 # set through the aifc() method, reset through the
605 # aiff() method
606 #
607 # These variables are used internally only:
608 # _version -- the AIFF-C version number
609 # _comp -- the compressor from builtin module cl
610 # _nframeswritten -- the number of audio frames actually written
611 # _datalength -- the size of the audio samples written to the header
612 # _datawritten -- the size of the audio samples actually written
613
Guido van Rossumd7abed31996-08-20 20:40:07 +0000614## if 0: access _file, _comptype, _compname, _nchannels, _sampwidth, \
615## _framerate, _nframes, _aifc, _version, _comp, \
616## _nframeswritten, _datalength, _datawritten: private
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000617
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000618 def __init__(self, f):
619 if type(f) == type(''):
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000620 filename = f
Guido van Rossume174c151994-09-16 10:55:53 +0000621 f = __builtin__.open(f, 'wb')
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000622 else:
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000623 # else, assume it is an open file object already
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000624 filename = '???'
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000625 self.initfp(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000626 if filename[-5:] == '.aiff':
627 self._aifc = 0
628 else:
629 self._aifc = 1
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000630
631 def initfp(self, file):
632 self._file = file
633 self._version = _AIFC_version
634 self._comptype = 'NONE'
635 self._compname = 'not compressed'
636 self._comp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000637 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000638 self._nchannels = 0
639 self._sampwidth = 0
640 self._framerate = 0
641 self._nframes = 0
642 self._nframeswritten = 0
643 self._datawritten = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000644 self._datalength = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000645 self._markers = []
646 self._marklength = 0
647 self._aifc = 1 # AIFF-C is default
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000648
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000649 def __del__(self):
650 if self._file:
651 self.close()
652
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000653 #
654 # User visible methods.
655 #
656 def aiff(self):
657 if self._nframeswritten:
658 raise Error, 'cannot change parameters after starting to write'
659 self._aifc = 0
660
661 def aifc(self):
662 if self._nframeswritten:
663 raise Error, 'cannot change parameters after starting to write'
664 self._aifc = 1
665
666 def setnchannels(self, nchannels):
667 if self._nframeswritten:
668 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000669 if nchannels < 1:
670 raise Error, 'bad # of channels'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000671 self._nchannels = nchannels
672
673 def getnchannels(self):
674 if not self._nchannels:
675 raise Error, 'number of channels not set'
676 return self._nchannels
677
678 def setsampwidth(self, sampwidth):
679 if self._nframeswritten:
680 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000681 if sampwidth < 1 or sampwidth > 4:
682 raise Error, 'bad sample width'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000683 self._sampwidth = sampwidth
684
685 def getsampwidth(self):
686 if not self._sampwidth:
687 raise Error, 'sample width not set'
688 return self._sampwidth
689
690 def setframerate(self, framerate):
691 if self._nframeswritten:
692 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000693 if framerate <= 0:
694 raise Error, 'bad frame rate'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000695 self._framerate = framerate
696
697 def getframerate(self):
698 if not self._framerate:
699 raise Error, 'frame rate not set'
700 return self._framerate
701
702 def setnframes(self, nframes):
703 if self._nframeswritten:
704 raise Error, 'cannot change parameters after starting to write'
705 self._nframes = nframes
706
707 def getnframes(self):
708 return self._nframeswritten
709
710 def setcomptype(self, comptype, compname):
711 if self._nframeswritten:
712 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000713 if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000714 raise Error, 'unsupported compression type'
715 self._comptype = comptype
716 self._compname = compname
717
718 def getcomptype(self):
719 return self._comptype
720
721 def getcompname(self):
722 return self._compname
723
724## def setversion(self, version):
725## if self._nframeswritten:
726## raise Error, 'cannot change parameters after starting to write'
727## self._version = version
728
729 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
730 if self._nframeswritten:
731 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000732 if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000733 raise Error, 'unsupported compression type'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000734 self.setnchannels(nchannels)
735 self.setsampwidth(sampwidth)
736 self.setframerate(framerate)
737 self.setnframes(nframes)
738 self.setcomptype(comptype, compname)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000739
740 def getparams(self):
741 if not self._nchannels or not self._sampwidth or not self._framerate:
742 raise Error, 'not all parameters set'
743 return self._nchannels, self._sampwidth, self._framerate, \
744 self._nframes, self._comptype, self._compname
745
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000746 def setmark(self, id, pos, name):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000747 if id <= 0:
748 raise Error, 'marker ID must be > 0'
749 if pos < 0:
750 raise Error, 'marker position must be >= 0'
751 if type(name) != type(''):
752 raise Error, 'marker name must be a string'
753 for i in range(len(self._markers)):
754 if id == self._markers[i][0]:
755 self._markers[i] = id, pos, name
756 return
757 self._markers.append((id, pos, name))
758
759 def getmark(self, id):
760 for marker in self._markers:
761 if id == marker[0]:
762 return marker
763 raise Error, 'marker ' + `id` + ' does not exist'
764
765 def getmarkers(self):
766 if len(self._markers) == 0:
767 return None
768 return self._markers
769
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000770 def tell(self):
771 return self._nframeswritten
772
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000773 def writeframesraw(self, data):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000774 self._ensure_header_written(len(data))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000775 nframes = len(data) / (self._sampwidth * self._nchannels)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000776 if self._convert:
777 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000778 self._file.write(data)
779 self._nframeswritten = self._nframeswritten + nframes
780 self._datawritten = self._datawritten + len(data)
781
782 def writeframes(self, data):
783 self.writeframesraw(data)
784 if self._nframeswritten != self._nframes or \
785 self._datalength != self._datawritten:
786 self._patchheader()
787
788 def close(self):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000789 self._ensure_header_written(0)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000790 if self._datawritten & 1:
791 # quick pad to even size
792 self._file.write(chr(0))
793 self._datawritten = self._datawritten + 1
794 self._writemarkers()
795 if self._nframeswritten != self._nframes or \
796 self._datalength != self._datawritten or \
797 self._marklength:
798 self._patchheader()
799 if self._comp:
800 self._comp.CloseCompressor()
801 self._comp = None
Sjoerd Mullenderfeaa7d21993-12-16 13:56:34 +0000802 self._file.flush()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000803 self._file = None
804
805 #
806 # Internal methods.
807 #
Guido van Rossumd7abed31996-08-20 20:40:07 +0000808## if 0: access *: private
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000809
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000810 def _comp_data(self, data):
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000811 import cl
812 dum = self._comp.SetParam(cl.FRAME_BUFFER_SIZE, len(data))
813 dum = self._comp.SetParam(cl.COMPRESSED_BUFFER_SIZE, len(data))
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000814 return self._comp.Compress(nframes, data)
815
816 def _lin2ulaw(self, data):
817 import audioop
818 return audioop.lin2ulaw(data, 2)
819
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000820 def _lin2adpcm(self, data):
821 import audioop
822 if not hasattr(self, '_adpcmstate'):
823 self._adpcmstate = None
824 data, self._adpcmstate = audioop.lin2adpcm(data, 2,
825 self._adpcmstate)
826 return data
827
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000828 def _ensure_header_written(self, datasize):
829 if not self._nframeswritten:
830 if self._comptype in ('ULAW', 'ALAW'):
831 if not self._sampwidth:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000832 self._sampwidth = 2
833 if self._sampwidth != 2:
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000834 raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000835 if self._comptype == 'G722':
836 if not self._sampwidth:
837 self._sampwidth = 2
838 if self._sampwidth != 2:
839 raise Error, 'sample width must be 2 when compressing with G7.22 (ADPCM)'
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000840 if not self._nchannels:
841 raise Error, '# channels not specified'
842 if not self._sampwidth:
843 raise Error, 'sample width not specified'
844 if not self._framerate:
845 raise Error, 'sampling rate not specified'
846 self._write_header(datasize)
847
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000848 def _init_compression(self):
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000849 if self._comptype == 'G722':
850 import audioop
851 self._convert = self._lin2adpcm
852 return
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000853 try:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000854 import cl
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000855 except ImportError:
856 if self._comptype == 'ULAW':
857 try:
858 import audioop
859 self._convert = self._lin2ulaw
860 return
861 except ImportError:
862 pass
863 raise Error, 'cannot write compressed AIFF-C files'
864 if self._comptype == 'ULAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000865 scheme = cl.G711_ULAW
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000866 elif self._comptype == 'ALAW':
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000867 scheme = cl.G711_ALAW
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000868 else:
869 raise Error, 'unsupported compression type'
870 self._comp = cl.OpenCompressor(scheme)
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000871 params = [cl.ORIGINAL_FORMAT, 0,
872 cl.BITS_PER_COMPONENT, self._sampwidth * 8,
873 cl.FRAME_RATE, self._framerate,
874 cl.FRAME_BUFFER_SIZE, 100,
875 cl.COMPRESSED_BUFFER_SIZE, 100]
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000876 if self._nchannels == 1:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000877 params[1] = cl.MONO
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000878 elif self._nchannels == 2:
Guido van Rossum2c2f7311998-08-07 15:28:23 +0000879 params[1] = cl.STEREO_INTERLEAVED
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000880 else:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000881 raise Error, 'cannot compress more than 2 channels'
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000882 self._comp.SetParams(params)
883 # the compressor produces a header which we ignore
884 dummy = self._comp.Compress(0, '')
885 self._convert = self._comp_data
886
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000887 def _write_header(self, initlength):
888 if self._aifc and self._comptype != 'NONE':
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000889 self._init_compression()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000890 self._file.write('FORM')
891 if not self._nframes:
892 self._nframes = initlength / (self._nchannels * self._sampwidth)
893 self._datalength = self._nframes * self._nchannels * self._sampwidth
894 if self._datalength & 1:
895 self._datalength = self._datalength + 1
Sjoerd Mullender1f057541994-09-06 16:17:51 +0000896 if self._aifc:
897 if self._comptype in ('ULAW', 'ALAW'):
898 self._datalength = self._datalength / 2
899 if self._datalength & 1:
900 self._datalength = self._datalength + 1
901 elif self._comptype == 'G722':
902 self._datalength = (self._datalength + 3) / 4
903 if self._datalength & 1:
904 self._datalength = self._datalength + 1
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000905 self._form_length_pos = self._file.tell()
906 commlength = self._write_form_length(self._datalength)
907 if self._aifc:
908 self._file.write('AIFC')
909 self._file.write('FVER')
910 _write_long(self._file, 4)
911 _write_long(self._file, self._version)
912 else:
913 self._file.write('AIFF')
914 self._file.write('COMM')
915 _write_long(self._file, commlength)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000916 _write_short(self._file, self._nchannels)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000917 self._nframes_pos = self._file.tell()
918 _write_long(self._file, self._nframes)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000919 _write_short(self._file, self._sampwidth * 8)
920 _write_float(self._file, self._framerate)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000921 if self._aifc:
922 self._file.write(self._comptype)
923 _write_string(self._file, self._compname)
924 self._file.write('SSND')
925 self._ssnd_length_pos = self._file.tell()
926 _write_long(self._file, self._datalength + 8)
927 _write_long(self._file, 0)
928 _write_long(self._file, 0)
929
930 def _write_form_length(self, datalength):
931 if self._aifc:
932 commlength = 18 + 5 + len(self._compname)
933 if commlength & 1:
934 commlength = commlength + 1
935 verslength = 12
936 else:
937 commlength = 18
938 verslength = 0
939 _write_long(self._file, 4 + verslength + self._marklength + \
940 8 + commlength + 16 + datalength)
941 return commlength
942
943 def _patchheader(self):
944 curpos = self._file.tell()
945 if self._datawritten & 1:
946 datalength = self._datawritten + 1
947 self._file.write(chr(0))
948 else:
949 datalength = self._datawritten
950 if datalength == self._datalength and \
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000951 self._nframes == self._nframeswritten and \
952 self._marklength == 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000953 self._file.seek(curpos, 0)
954 return
955 self._file.seek(self._form_length_pos, 0)
956 dummy = self._write_form_length(datalength)
957 self._file.seek(self._nframes_pos, 0)
958 _write_long(self._file, self._nframeswritten)
959 self._file.seek(self._ssnd_length_pos, 0)
960 _write_long(self._file, datalength + 8)
961 self._file.seek(curpos, 0)
962 self._nframes = self._nframeswritten
963 self._datalength = datalength
964
965 def _writemarkers(self):
966 if len(self._markers) == 0:
967 return
968 self._file.write('MARK')
969 length = 2
970 for marker in self._markers:
971 id, pos, name = marker
972 length = length + len(name) + 1 + 6
973 if len(name) & 1 == 0:
974 length = length + 1
975 _write_long(self._file, length)
976 self._marklength = length + 8
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000977 _write_short(self._file, len(self._markers))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000978 for marker in self._markers:
979 id, pos, name = marker
980 _write_short(self._file, id)
981 _write_long(self._file, pos)
982 _write_string(self._file, name)
983
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000984def open(f, mode):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000985 if mode == 'r':
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000986 return Aifc_read(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000987 elif mode == 'w':
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000988 return Aifc_write(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000989 else:
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000990 raise Error, "mode must be 'r' or 'w'"
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000991
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000992openfp = open # B/W compatibility
Guido van Rossum36bb1811996-12-31 05:57:34 +0000993
994if __name__ == '__main__':
995 import sys
996 if not sys.argv[1:]:
997 sys.argv.append('/usr/demos/data/audio/bach.aiff')
998 fn = sys.argv[1]
999 f = open(fn, 'r')
1000 print "Reading", fn
1001 print "nchannels =", f.getnchannels()
1002 print "nframes =", f.getnframes()
1003 print "sampwidth =", f.getsampwidth()
1004 print "framerate =", f.getframerate()
1005 print "comptype =", f.getcomptype()
1006 print "compname =", f.getcompname()
1007 if sys.argv[2:]:
1008 gn = sys.argv[2]
1009 print "Writing", gn
1010 g = open(gn, 'w')
1011 g.setparams(f.getparams())
1012 while 1:
1013 data = f.readframes(1024)
1014 if not data:
1015 break
1016 g.writeframes(data)
1017 g.close()
1018 f.close()
1019 print "Done."