blob: c1418be17738b2fb2acb1d8b0a2bbb93439a764c [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
105# setparams(nchannels, sampwidth, framerate, nframes, comptype, compname)
106# -- 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 Rossum3db6ebc1994-01-28 09:59:35 +0000136import __builtin__
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000137try:
138 import CL
139except ImportError:
140 pass
141
142Error = 'aifc.Error'
143
144_AIFC_version = 0xA2805140 # Version 1 of AIFF-C
145
146_skiplist = 'COMT', 'INST', 'MIDI', 'AESD', \
147 'APPL', 'NAME', 'AUTH', '(c) ', 'ANNO'
148
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000149def _read_long(file):
150 x = 0L
151 for i in range(4):
152 byte = file.read(1)
153 if byte == '':
154 raise EOFError
155 x = x*256 + ord(byte)
156 if x >= 0x80000000L:
157 x = x - 0x100000000L
158 return int(x)
159
160def _read_ulong(file):
161 x = 0L
162 for i in range(4):
163 byte = file.read(1)
164 if byte == '':
165 raise EOFError
166 x = x*256 + ord(byte)
167 return x
168
169def _read_short(file):
170 x = 0
171 for i in range(2):
172 byte = file.read(1)
173 if byte == '':
174 raise EOFError
175 x = x*256 + ord(byte)
176 if x >= 0x8000:
177 x = x - 0x10000
178 return x
179
180def _read_string(file):
181 length = ord(file.read(1))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000182 if length == 0:
183 data = ''
184 else:
185 data = file.read(length)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000186 if length & 1 == 0:
187 dummy = file.read(1)
188 return data
189
190_HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
191
192def _read_float(f): # 10 bytes
193 import math
194 expon = _read_short(f) # 2 bytes
195 sign = 1
196 if expon < 0:
197 sign = -1
198 expon = expon + 0x8000
199 himant = _read_ulong(f) # 4 bytes
200 lomant = _read_ulong(f) # 4 bytes
201 if expon == himant == lomant == 0:
202 f = 0.0
203 elif expon == 0x7FFF:
204 f = _HUGE_VAL
205 else:
206 expon = expon - 16383
207 f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63)
208 return sign * f
209
210def _write_short(f, x):
211 d, m = divmod(x, 256)
212 f.write(chr(d))
213 f.write(chr(m))
214
215def _write_long(f, x):
216 if x < 0:
217 x = x + 0x100000000L
218 data = []
219 for i in range(4):
220 d, m = divmod(x, 256)
221 data.insert(0, m)
222 x = d
223 for i in range(4):
224 f.write(chr(int(data[i])))
225
226def _write_string(f, s):
227 f.write(chr(len(s)))
228 f.write(s)
229 if len(s) & 1 == 0:
230 f.write(chr(0))
231
232def _write_float(f, x):
233 import math
234 if x < 0:
235 sign = 0x8000
236 x = x * -1
237 else:
238 sign = 0
239 if x == 0:
240 expon = 0
241 himant = 0
242 lomant = 0
243 else:
244 fmant, expon = math.frexp(x)
245 if expon > 16384 or fmant >= 1: # Infinity or NaN
246 expon = sign|0x7FFF
247 himant = 0
248 lomant = 0
249 else: # Finite
250 expon = expon + 16382
251 if expon < 0: # denormalized
252 fmant = math.ldexp(fmant, expon)
253 expon = 0
254 expon = expon | sign
255 fmant = math.ldexp(fmant, 32)
256 fsmant = math.floor(fmant)
257 himant = long(fsmant)
258 fmant = math.ldexp(fmant - fsmant, 32)
259 fsmant = math.floor(fmant)
260 lomant = long(fsmant)
261 _write_short(f, expon)
262 _write_long(f, himant)
263 _write_long(f, lomant)
264
Guido van Rossumd3166071993-05-24 14:16:22 +0000265class Chunk:
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000266 def __init__(self, file):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000267 self.file = file
268 self.chunkname = self.file.read(4)
269 if len(self.chunkname) < 4:
270 raise EOFError
271 self.chunksize = _read_long(self.file)
272 self.size_read = 0
273 self.offset = self.file.tell()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000274
275 def rewind(self):
276 self.file.seek(self.offset, 0)
277 self.size_read = 0
278
279 def setpos(self, pos):
280 if pos < 0 or pos > self.chunksize:
281 raise RuntimeError
282 self.file.seek(self.offset + pos, 0)
283 self.size_read = pos
284
285 def read(self, length):
286 if self.size_read >= self.chunksize:
287 return ''
288 if length > self.chunksize - self.size_read:
289 length = self.chunksize - self.size_read
290 data = self.file.read(length)
291 self.size_read = self.size_read + len(data)
292 return data
293
294 def skip(self):
295 try:
296 self.file.seek(self.chunksize - self.size_read, 1)
297 except RuntimeError:
298 while self.size_read < self.chunksize:
299 dummy = self.read(8192)
300 if not dummy:
301 raise EOFError
302 if self.chunksize & 1:
303 dummy = self.read(1)
304
Guido van Rossumd3166071993-05-24 14:16:22 +0000305class Aifc_read:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000306 # Variables used in this class:
307 #
308 # These variables are available to the user though appropriate
309 # methods of this class:
310 # _file -- the open file with methods read(), close(), and seek()
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000311 # set through the __init__() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000312 # _nchannels -- the number of audio channels
313 # available through the getnchannels() method
314 # _nframes -- the number of audio frames
315 # available through the getnframes() method
316 # _sampwidth -- the number of bytes per audio sample
317 # available through the getsampwidth() method
318 # _framerate -- the sampling frequency
319 # available through the getframerate() method
320 # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
321 # available through the getcomptype() method
322 # _compname -- the human-readable AIFF-C compression type
323 # available through the getcomptype() method
324 # _markers -- the marks in the audio file
325 # available through the getmarkers() and getmark()
326 # methods
327 # _soundpos -- the position in the audio stream
328 # available through the tell() method, set through the
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000329 # setpos() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000330 #
331 # These variables are used internally only:
332 # _version -- the AIFF-C version number
333 # _decomp -- the decompressor from builtin module cl
334 # _comm_chunk_read -- 1 iff the COMM chunk has been read
335 # _aifc -- 1 iff reading an AIFF-C file
336 # _ssnd_seek_needed -- 1 iff positioned correctly in audio
337 # file for readframes()
338 # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000339 # _framesize -- size of one frame in the file
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000340
341 access _file, _nchannels, _nframes, _sampwidth, _framerate, \
342 _comptype, _compname, _markers, _soundpos, _version, \
343 _decomp, _comm_chunk_read, __aifc, _ssnd_seek_needed, \
344 _ssnd_chunk, _framesize: private
345
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000346 def initfp(self, file):
347 self._file = file
348 self._version = 0
349 self._decomp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000350 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000351 self._markers = []
352 self._soundpos = 0
353 form = self._file.read(4)
354 if form != 'FORM':
355 raise Error, 'file does not start with FORM id'
356 formlength = _read_long(self._file)
357 if formlength <= 0:
358 raise Error, 'invalid FORM chunk data size'
359 formdata = self._file.read(4)
360 formlength = formlength - 4
361 if formdata == 'AIFF':
362 self._aifc = 0
363 elif formdata == 'AIFC':
364 self._aifc = 1
365 else:
366 raise Error, 'not an AIFF or AIFF-C file'
367 self._comm_chunk_read = 0
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000368 while formlength > 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000369 self._ssnd_seek_needed = 1
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000370 #DEBUG: SGI's soundfiler has a bug. There should
371 # be no need to check for EOF here.
372 try:
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000373 chunk = Chunk(self._file)
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000374 except EOFError:
375 if formlength == 8:
376 print 'Warning: FORM chunk size too large'
377 formlength = 0
378 break
379 raise EOFError # different error, raise exception
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000380 if chunk.chunkname == 'COMM':
381 self._read_comm_chunk(chunk)
382 self._comm_chunk_read = 1
383 elif chunk.chunkname == 'SSND':
384 self._ssnd_chunk = chunk
385 dummy = chunk.read(8)
386 self._ssnd_seek_needed = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000387 elif chunk.chunkname == 'FVER':
388 self._version = _read_long(chunk)
389 elif chunk.chunkname == 'MARK':
390 self._readmark(chunk)
391 elif chunk.chunkname in _skiplist:
392 pass
393 else:
394 raise Error, 'unrecognized chunk type '+chunk.chunkname
Sjoerd Mullender4150ede1993-08-26 14:12:07 +0000395 formlength = formlength - 8 - chunk.chunksize
396 if chunk.chunksize & 1:
397 formlength = formlength - 1
Sjoerd Mullender93f07401993-01-26 09:24:37 +0000398 if formlength > 0:
399 chunk.skip()
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000400 if not self._comm_chunk_read or not self._ssnd_chunk:
401 raise Error, 'COMM chunk and/or SSND chunk missing'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000402 if self._aifc and self._decomp:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000403 params = [CL.ORIGINAL_FORMAT, 0,
404 CL.BITS_PER_COMPONENT, self._sampwidth * 8,
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000405 CL.FRAME_RATE, self._framerate]
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000406 if self._nchannels == 1:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000407 params[1] = CL.MONO
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000408 elif self._nchannels == 2:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000409 params[1] = CL.STEREO_INTERLEAVED
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000410 else:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000411 raise Error, 'cannot compress more than 2 channels'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000412 self._decomp.SetParams(params)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000413
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000414 def __init__(self, f):
415 if type(f) == type(''):
Guido van Rossum3db6ebc1994-01-28 09:59:35 +0000416 f = __builtin__.open(f, 'r')
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000417 # else, assume it is an open file object already
418 self.initfp(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000419
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000420 def __del__(self):
421 if self._file:
422 self.close()
423
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000424 #
425 # User visible methods.
426 #
427 def getfp(self):
428 return self._file
429
430 def rewind(self):
431 self._ssnd_seek_needed = 1
432 self._soundpos = 0
433
434 def close(self):
435 if self._decomp:
436 self._decomp.CloseDecompressor()
437 self._decomp = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000438 self._file = None
439
440 def tell(self):
441 return self._soundpos
442
443 def getnchannels(self):
444 return self._nchannels
445
446 def getnframes(self):
447 return self._nframes
448
449 def getsampwidth(self):
450 return self._sampwidth
451
452 def getframerate(self):
453 return self._framerate
454
455 def getcomptype(self):
456 return self._comptype
457
458 def getcompname(self):
459 return self._compname
460
461## def getversion(self):
462## return self._version
463
464 def getparams(self):
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000465 return self.getnchannels(), self.getsampwidth(), \
466 self.getframerate(), self.getnframes(), \
467 self.getcomptype(), self.getcompname()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000468
469 def getmarkers(self):
470 if len(self._markers) == 0:
471 return None
472 return self._markers
473
474 def getmark(self, id):
475 for marker in self._markers:
476 if id == marker[0]:
477 return marker
478 raise Error, 'marker ' + `id` + ' does not exist'
479
480 def setpos(self, pos):
481 if pos < 0 or pos > self._nframes:
482 raise Error, 'position not in range'
483 self._soundpos = pos
484 self._ssnd_seek_needed = 1
485
486 def readframes(self, nframes):
487 if self._ssnd_seek_needed:
488 self._ssnd_chunk.rewind()
489 dummy = self._ssnd_chunk.read(8)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000490 pos = self._soundpos * self._framesize
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000491 if pos:
492 self._ssnd_chunk.setpos(pos + 8)
493 self._ssnd_seek_needed = 0
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000494 if nframes == 0:
495 return ''
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000496 data = self._ssnd_chunk.read(nframes * self._framesize)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000497 if self._convert and data:
498 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000499 self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth)
500 return data
501
502 #
503 # Internal methods.
504 #
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000505 access *: private
506
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000507 def _decomp_data(self, data):
508 dummy = self._decomp.SetParam(CL.FRAME_BUFFER_SIZE,
509 len(data) * 2)
510 return self._decomp.Decompress(len(data) / self._nchannels,
511 data)
512
513 def _ulaw2lin(self, data):
514 import audioop
515 return audioop.ulaw2lin(data, 2)
516
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000517 def _read_comm_chunk(self, chunk):
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000518 self._nchannels = _read_short(chunk)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000519 self._nframes = _read_long(chunk)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000520 self._sampwidth = (_read_short(chunk) + 7) / 8
Sjoerd Mullenderffe94901994-01-28 09:56:05 +0000521 self._framerate = int(_read_float(chunk))
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000522 self._framesize = self._nchannels * self._sampwidth
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000523 if self._aifc:
524 #DEBUG: SGI's soundeditor produces a bad size :-(
525 kludge = 0
526 if chunk.chunksize == 18:
527 kludge = 1
528 print 'Warning: bad COMM chunk size'
529 chunk.chunksize = 23
530 #DEBUG end
531 self._comptype = chunk.read(4)
532 #DEBUG start
533 if kludge:
534 length = ord(chunk.file.read(1))
535 if length & 1 == 0:
536 length = length + 1
537 chunk.chunksize = chunk.chunksize + length
538 chunk.file.seek(-1, 1)
539 #DEBUG end
540 self._compname = _read_string(chunk)
541 if self._comptype != 'NONE':
542 try:
543 import cl, CL
544 except ImportError:
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000545 if self._comptype == 'ULAW':
546 try:
547 import audioop
548 self._convert = self._ulaw2lin
549 self._framesize = self._framesize / 2
550 return
551 except ImportError:
552 pass
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000553 raise Error, 'cannot read compressed AIFF-C files'
554 if self._comptype == 'ULAW':
555 scheme = CL.G711_ULAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000556 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000557 elif self._comptype == 'ALAW':
558 scheme = CL.G711_ALAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000559 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000560 else:
561 raise Error, 'unsupported compression type'
562 self._decomp = cl.OpenDecompressor(scheme)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000563 self._convert = self._decomp_data
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000564 else:
565 self._comptype = 'NONE'
566 self._compname = 'not compressed'
567
568 def _readmark(self, chunk):
569 nmarkers = _read_short(chunk)
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000570 # Some files appear to contain invalid counts.
571 # Cope with this by testing for EOF.
572 try:
573 for i in range(nmarkers):
574 id = _read_short(chunk)
575 pos = _read_long(chunk)
576 name = _read_string(chunk)
577 self._markers.append((id, pos, name))
578 except EOFError:
579 print 'Warning: MARK chunk contains only',
580 print len(self._markers),
581 if len(self._markers) == 1: print 'marker',
582 else: print 'markers',
583 print 'instead of', nmarkers
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000584
Guido van Rossumd3166071993-05-24 14:16:22 +0000585class Aifc_write:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000586 # Variables used in this class:
587 #
588 # These variables are user settable through appropriate methods
589 # of this class:
590 # _file -- the open file with methods write(), close(), tell(), seek()
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000591 # set through the __init__() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000592 # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
593 # set through the setcomptype() or setparams() method
594 # _compname -- the human-readable AIFF-C compression type
595 # set through the setcomptype() or setparams() method
596 # _nchannels -- the number of audio channels
597 # set through the setnchannels() or setparams() method
598 # _sampwidth -- the number of bytes per audio sample
599 # set through the setsampwidth() or setparams() method
600 # _framerate -- the sampling frequency
601 # set through the setframerate() or setparams() method
602 # _nframes -- the number of audio frames written to the header
603 # set through the setnframes() or setparams() method
604 # _aifc -- whether we're writing an AIFF-C file or an AIFF file
605 # set through the aifc() method, reset through the
606 # aiff() method
607 #
608 # These variables are used internally only:
609 # _version -- the AIFF-C version number
610 # _comp -- the compressor from builtin module cl
611 # _nframeswritten -- the number of audio frames actually written
612 # _datalength -- the size of the audio samples written to the header
613 # _datawritten -- the size of the audio samples actually written
614
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000615 access _file, _comptype, _compname, _nchannels, _sampwidth, \
616 _framerate, _nframes, _aifc, _version, _comp, \
617 _nframeswritten, _datalength, _datawritten: private
618
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000619 def __init__(self, f):
620 if type(f) == type(''):
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000621 filename = f
Guido van Rossum3db6ebc1994-01-28 09:59:35 +0000622 f = __builtin__.open(f, 'w')
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000623 else:
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000624 # else, assume it is an open file object already
Guido van Rossum6ed9df21993-12-17 16:43:43 +0000625 filename = '???'
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000626 self.initfp(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000627 if filename[-5:] == '.aiff':
628 self._aifc = 0
629 else:
630 self._aifc = 1
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000631
632 def initfp(self, file):
633 self._file = file
634 self._version = _AIFC_version
635 self._comptype = 'NONE'
636 self._compname = 'not compressed'
637 self._comp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000638 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000639 self._nchannels = 0
640 self._sampwidth = 0
641 self._framerate = 0
642 self._nframes = 0
643 self._nframeswritten = 0
644 self._datawritten = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000645 self._datalength = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000646 self._markers = []
647 self._marklength = 0
648 self._aifc = 1 # AIFF-C is default
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000649
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000650 def __del__(self):
651 if self._file:
652 self.close()
653
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000654 #
655 # User visible methods.
656 #
657 def aiff(self):
658 if self._nframeswritten:
659 raise Error, 'cannot change parameters after starting to write'
660 self._aifc = 0
661
662 def aifc(self):
663 if self._nframeswritten:
664 raise Error, 'cannot change parameters after starting to write'
665 self._aifc = 1
666
667 def setnchannels(self, nchannels):
668 if self._nframeswritten:
669 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000670 if nchannels < 1:
671 raise Error, 'bad # of channels'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000672 self._nchannels = nchannels
673
674 def getnchannels(self):
675 if not self._nchannels:
676 raise Error, 'number of channels not set'
677 return self._nchannels
678
679 def setsampwidth(self, sampwidth):
680 if self._nframeswritten:
681 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000682 if sampwidth < 1 or sampwidth > 4:
683 raise Error, 'bad sample width'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000684 self._sampwidth = sampwidth
685
686 def getsampwidth(self):
687 if not self._sampwidth:
688 raise Error, 'sample width not set'
689 return self._sampwidth
690
691 def setframerate(self, framerate):
692 if self._nframeswritten:
693 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000694 if framerate <= 0:
695 raise Error, 'bad frame rate'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000696 self._framerate = framerate
697
698 def getframerate(self):
699 if not self._framerate:
700 raise Error, 'frame rate not set'
701 return self._framerate
702
703 def setnframes(self, nframes):
704 if self._nframeswritten:
705 raise Error, 'cannot change parameters after starting to write'
706 self._nframes = nframes
707
708 def getnframes(self):
709 return self._nframeswritten
710
711 def setcomptype(self, comptype, compname):
712 if self._nframeswritten:
713 raise Error, 'cannot change parameters after starting to write'
714 if comptype not in ('NONE', 'ULAW', 'ALAW'):
715 raise Error, 'unsupported compression type'
716 self._comptype = comptype
717 self._compname = compname
718
719 def getcomptype(self):
720 return self._comptype
721
722 def getcompname(self):
723 return self._compname
724
725## def setversion(self, version):
726## if self._nframeswritten:
727## raise Error, 'cannot change parameters after starting to write'
728## self._version = version
729
730 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
731 if self._nframeswritten:
732 raise Error, 'cannot change parameters after starting to write'
733 if comptype not in ('NONE', 'ULAW', 'ALAW'):
734 raise Error, 'unsupported compression type'
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000735 self.setnchannels(nchannels)
736 self.setsampwidth(sampwidth)
737 self.setframerate(framerate)
738 self.setnframes(nframes)
739 self.setcomptype(comptype, compname)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000740
741 def getparams(self):
742 if not self._nchannels or not self._sampwidth or not self._framerate:
743 raise Error, 'not all parameters set'
744 return self._nchannels, self._sampwidth, self._framerate, \
745 self._nframes, self._comptype, self._compname
746
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000747 def setmark(self, id, pos, name):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000748 if id <= 0:
749 raise Error, 'marker ID must be > 0'
750 if pos < 0:
751 raise Error, 'marker position must be >= 0'
752 if type(name) != type(''):
753 raise Error, 'marker name must be a string'
754 for i in range(len(self._markers)):
755 if id == self._markers[i][0]:
756 self._markers[i] = id, pos, name
757 return
758 self._markers.append((id, pos, name))
759
760 def getmark(self, id):
761 for marker in self._markers:
762 if id == marker[0]:
763 return marker
764 raise Error, 'marker ' + `id` + ' does not exist'
765
766 def getmarkers(self):
767 if len(self._markers) == 0:
768 return None
769 return self._markers
770
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000771 def tell(self):
772 return self._nframeswritten
773
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000774 def writeframesraw(self, data):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000775 self._ensure_header_written(len(data))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000776 nframes = len(data) / (self._sampwidth * self._nchannels)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000777 if self._convert:
778 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000779 self._file.write(data)
780 self._nframeswritten = self._nframeswritten + nframes
781 self._datawritten = self._datawritten + len(data)
782
783 def writeframes(self, data):
784 self.writeframesraw(data)
785 if self._nframeswritten != self._nframes or \
786 self._datalength != self._datawritten:
787 self._patchheader()
788
789 def close(self):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000790 self._ensure_header_written(0)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000791 if self._datawritten & 1:
792 # quick pad to even size
793 self._file.write(chr(0))
794 self._datawritten = self._datawritten + 1
795 self._writemarkers()
796 if self._nframeswritten != self._nframes or \
797 self._datalength != self._datawritten or \
798 self._marklength:
799 self._patchheader()
800 if self._comp:
801 self._comp.CloseCompressor()
802 self._comp = None
Sjoerd Mullenderfeaa7d21993-12-16 13:56:34 +0000803 self._file.flush()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000804 self._file = None
805
806 #
807 # Internal methods.
808 #
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000809 access *: private
810
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000811 def _comp_data(self, data):
812 dum = self._comp.SetParam(CL.FRAME_BUFFER_SIZE, len(data))
813 dum = self._comp.SetParam(CL.COMPRESSED_BUFFER_SIZE, len(data))
814 return self._comp.Compress(nframes, data)
815
816 def _lin2ulaw(self, data):
817 import audioop
818 return audioop.lin2ulaw(data, 2)
819
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000820 def _ensure_header_written(self, datasize):
821 if not self._nframeswritten:
822 if self._comptype in ('ULAW', 'ALAW'):
823 if not self._sampwidth:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000824 self._sampwidth = 2
825 if self._sampwidth != 2:
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000826 raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
827 if not self._nchannels:
828 raise Error, '# channels not specified'
829 if not self._sampwidth:
830 raise Error, 'sample width not specified'
831 if not self._framerate:
832 raise Error, 'sampling rate not specified'
833 self._write_header(datasize)
834
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000835 def _init_compression(self):
836 try:
837 import cl, CL
838 except ImportError:
839 if self._comptype == 'ULAW':
840 try:
841 import audioop
842 self._convert = self._lin2ulaw
843 return
844 except ImportError:
845 pass
846 raise Error, 'cannot write compressed AIFF-C files'
847 if self._comptype == 'ULAW':
848 scheme = CL.G711_ULAW
849 elif self._comptype == 'ALAW':
850 scheme = CL.G711_ALAW
851 else:
852 raise Error, 'unsupported compression type'
853 self._comp = cl.OpenCompressor(scheme)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000854 params = [CL.ORIGINAL_FORMAT, 0,
855 CL.BITS_PER_COMPONENT, self._sampwidth * 8,
856 CL.FRAME_RATE, self._framerate,
857 CL.FRAME_BUFFER_SIZE, 100,
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000858 CL.COMPRESSED_BUFFER_SIZE, 100]
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000859 if self._nchannels == 1:
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000860 params[1] = CL.MONO
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000861 elif self._nchannels == 2:
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000862 params[1] = CL.STEREO_INTERLEAVED
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000863 else:
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000864 raise Error, 'cannot compress more than 2 channels'
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000865 self._comp.SetParams(params)
866 # the compressor produces a header which we ignore
867 dummy = self._comp.Compress(0, '')
868 self._convert = self._comp_data
869
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000870 def _write_header(self, initlength):
871 if self._aifc and self._comptype != 'NONE':
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000872 self._init_compression()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000873 self._file.write('FORM')
874 if not self._nframes:
875 self._nframes = initlength / (self._nchannels * self._sampwidth)
876 self._datalength = self._nframes * self._nchannels * self._sampwidth
877 if self._datalength & 1:
878 self._datalength = self._datalength + 1
879 if self._aifc and self._comptype in ('ULAW', 'ALAW'):
880 self._datalength = self._datalength / 2
881 if self._datalength & 1:
882 self._datalength = self._datalength + 1
883 self._form_length_pos = self._file.tell()
884 commlength = self._write_form_length(self._datalength)
885 if self._aifc:
886 self._file.write('AIFC')
887 self._file.write('FVER')
888 _write_long(self._file, 4)
889 _write_long(self._file, self._version)
890 else:
891 self._file.write('AIFF')
892 self._file.write('COMM')
893 _write_long(self._file, commlength)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000894 _write_short(self._file, self._nchannels)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000895 self._nframes_pos = self._file.tell()
896 _write_long(self._file, self._nframes)
Sjoerd Mullender49c2df11994-01-06 16:35:34 +0000897 _write_short(self._file, self._sampwidth * 8)
898 _write_float(self._file, self._framerate)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000899 if self._aifc:
900 self._file.write(self._comptype)
901 _write_string(self._file, self._compname)
902 self._file.write('SSND')
903 self._ssnd_length_pos = self._file.tell()
904 _write_long(self._file, self._datalength + 8)
905 _write_long(self._file, 0)
906 _write_long(self._file, 0)
907
908 def _write_form_length(self, datalength):
909 if self._aifc:
910 commlength = 18 + 5 + len(self._compname)
911 if commlength & 1:
912 commlength = commlength + 1
913 verslength = 12
914 else:
915 commlength = 18
916 verslength = 0
917 _write_long(self._file, 4 + verslength + self._marklength + \
918 8 + commlength + 16 + datalength)
919 return commlength
920
921 def _patchheader(self):
922 curpos = self._file.tell()
923 if self._datawritten & 1:
924 datalength = self._datawritten + 1
925 self._file.write(chr(0))
926 else:
927 datalength = self._datawritten
928 if datalength == self._datalength and \
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000929 self._nframes == self._nframeswritten and \
930 self._marklength == 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000931 self._file.seek(curpos, 0)
932 return
933 self._file.seek(self._form_length_pos, 0)
934 dummy = self._write_form_length(datalength)
935 self._file.seek(self._nframes_pos, 0)
936 _write_long(self._file, self._nframeswritten)
937 self._file.seek(self._ssnd_length_pos, 0)
938 _write_long(self._file, datalength + 8)
939 self._file.seek(curpos, 0)
940 self._nframes = self._nframeswritten
941 self._datalength = datalength
942
943 def _writemarkers(self):
944 if len(self._markers) == 0:
945 return
946 self._file.write('MARK')
947 length = 2
948 for marker in self._markers:
949 id, pos, name = marker
950 length = length + len(name) + 1 + 6
951 if len(name) & 1 == 0:
952 length = length + 1
953 _write_long(self._file, length)
954 self._marklength = length + 8
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000955 _write_short(self._file, len(self._markers))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000956 for marker in self._markers:
957 id, pos, name = marker
958 _write_short(self._file, id)
959 _write_long(self._file, pos)
960 _write_string(self._file, name)
961
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000962def open(f, mode):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000963 if mode == 'r':
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000964 return Aifc_read(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000965 elif mode == 'w':
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000966 return Aifc_write(f)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000967 else:
Sjoerd Mullender2a451411993-12-20 09:36:01 +0000968 raise Error, "mode must be 'r' or 'w'"
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000969
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000970openfp = open # B/W compatibility