blob: ee1f8f05c9683f0785bb9a94cda79ae4e1b6e462 [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')
58# or
59# f = aifc.openfp(filep, 'r')
60# where file is the name of a file and filep is an open file pointer.
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +000061# The open file pointer must have methods read(), seek(), and close().
62# In some types of audio files, if the setpos() method is not used,
63# the seek() method is not necessary.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000064#
65# This returns an instance of a class with the following public methods:
66# getnchannels() -- returns number of audio channels (1 for
67# mono, 2 for stereo)
68# getsampwidth() -- returns sample width in bytes
69# getframerate() -- returns sampling frequency
70# getnframes() -- returns number of audio frames
71# getcomptype() -- returns compression type ('NONE' for AIFF files)
72# getcompname() -- returns human-readable version of
73# compression type ('not compressed' for AIFF files)
74# getparams() -- returns a tuple consisting of all of the
75# above in the above order
76# getmarkers() -- get the list of marks in the audio file or None
77# if there are no marks
78# getmark(id) -- get mark with the specified id (raises an error
79# if the mark does not exist)
80# readframes(n) -- returns at most n frames of audio
81# rewind() -- rewind to the beginning of the audio stream
82# setpos(pos) -- seek to the specified position
83# tell() -- return the current position
Guido van Rossum17ed1ae1993-06-01 13:21:04 +000084# close() -- close the instance (make it unusable)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000085# The position returned by tell(), the position given to setpos() and
86# the position of marks are all compatible and have nothing to do with
87# the actual postion in the file.
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +000088# The close() method is called automatically when the class instance
89# is destroyed.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +000090#
91# Writing AIFF files:
92# f = aifc.open(file, 'w')
93# or
94# f = aifc.openfp(filep, 'w')
95# where file is the name of a file and filep is an open file pointer.
96# The open file pointer must have methods write(), tell(), seek(), and
97# close().
98#
99# This returns an instance of a class with the following public methods:
100# aiff() -- create an AIFF file (AIFF-C default)
101# aifc() -- create an AIFF-C file
102# setnchannels(n) -- set the number of channels
103# setsampwidth(n) -- set the sample width
104# setframerate(n) -- set the frame rate
105# setnframes(n) -- set the number of frames
106# setcomptype(type, name)
107# -- set the compression type and the
108# human-readable compression type
109# setparams(nchannels, sampwidth, framerate, nframes, comptype, compname)
110# -- set all parameters at once
111# setmark(id, pos, name)
112# -- add specified mark to the list of marks
113# tell() -- return current position in output file (useful
114# in combination with setmark())
115# writeframesraw(data)
116# -- write audio frames without pathing up the
117# file header
118# writeframes(data)
119# -- write audio frames and patch up the file header
120# close() -- patch up the file header and close the
121# output file
122# You should set the parameters before the first writeframesraw or
123# writeframes. The total number of frames does not need to be set,
124# but when it is set to the correct value, the header does not have to
125# be patched up.
126# It is best to first set all parameters, perhaps possibly the
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000127# compression type, and then write audio frames using writeframesraw.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000128# When all frames have been written, either call writeframes('') or
129# close() to patch up the sizes in the header.
130# Marks can be added anytime. If there are any marks, ypu must call
131# close() after all frames have been written.
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000132# The close() method is called automatically when the class instance
133# is destroyed.
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000134#
135# When a file is opened with the extension '.aiff', an AIFF file is
136# written, otherwise an AIFF-C file is written. This default can be
137# changed by calling aiff() or aifc() before the first writeframes or
138# writeframesraw.
139
140import builtin
141import AL
142try:
143 import CL
144except ImportError:
145 pass
146
147Error = 'aifc.Error'
148
149_AIFC_version = 0xA2805140 # Version 1 of AIFF-C
150
151_skiplist = 'COMT', 'INST', 'MIDI', 'AESD', \
152 'APPL', 'NAME', 'AUTH', '(c) ', 'ANNO'
153
154_nchannelslist = [(1, AL.MONO), (2, AL.STEREO)]
155_sampwidthlist = [(8, AL.SAMPLE_8), (16, AL.SAMPLE_16), (24, AL.SAMPLE_24)]
156_frameratelist = [(48000, AL.RATE_48000), \
157 (44100, AL.RATE_44100), \
158 (32000, AL.RATE_32000), \
159 (22050, AL.RATE_22050), \
160 (16000, AL.RATE_16000), \
161 (11025, AL.RATE_11025), \
162 ( 8000, AL.RATE_8000)]
163
164def _convert1(value, list):
165 for t in list:
166 if value == t[0]:
167 return t[1]
168 raise Error, 'unknown parameter value'
169
170def _convert2(value, list):
171 for t in list:
172 if value == t[1]:
173 return t[0]
174 raise Error, 'unknown parameter value'
175
176def _read_long(file):
177 x = 0L
178 for i in range(4):
179 byte = file.read(1)
180 if byte == '':
181 raise EOFError
182 x = x*256 + ord(byte)
183 if x >= 0x80000000L:
184 x = x - 0x100000000L
185 return int(x)
186
187def _read_ulong(file):
188 x = 0L
189 for i in range(4):
190 byte = file.read(1)
191 if byte == '':
192 raise EOFError
193 x = x*256 + ord(byte)
194 return x
195
196def _read_short(file):
197 x = 0
198 for i in range(2):
199 byte = file.read(1)
200 if byte == '':
201 raise EOFError
202 x = x*256 + ord(byte)
203 if x >= 0x8000:
204 x = x - 0x10000
205 return x
206
207def _read_string(file):
208 length = ord(file.read(1))
209 data = file.read(length)
210 if length & 1 == 0:
211 dummy = file.read(1)
212 return data
213
214_HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
215
216def _read_float(f): # 10 bytes
217 import math
218 expon = _read_short(f) # 2 bytes
219 sign = 1
220 if expon < 0:
221 sign = -1
222 expon = expon + 0x8000
223 himant = _read_ulong(f) # 4 bytes
224 lomant = _read_ulong(f) # 4 bytes
225 if expon == himant == lomant == 0:
226 f = 0.0
227 elif expon == 0x7FFF:
228 f = _HUGE_VAL
229 else:
230 expon = expon - 16383
231 f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63)
232 return sign * f
233
234def _write_short(f, x):
235 d, m = divmod(x, 256)
236 f.write(chr(d))
237 f.write(chr(m))
238
239def _write_long(f, x):
240 if x < 0:
241 x = x + 0x100000000L
242 data = []
243 for i in range(4):
244 d, m = divmod(x, 256)
245 data.insert(0, m)
246 x = d
247 for i in range(4):
248 f.write(chr(int(data[i])))
249
250def _write_string(f, s):
251 f.write(chr(len(s)))
252 f.write(s)
253 if len(s) & 1 == 0:
254 f.write(chr(0))
255
256def _write_float(f, x):
257 import math
258 if x < 0:
259 sign = 0x8000
260 x = x * -1
261 else:
262 sign = 0
263 if x == 0:
264 expon = 0
265 himant = 0
266 lomant = 0
267 else:
268 fmant, expon = math.frexp(x)
269 if expon > 16384 or fmant >= 1: # Infinity or NaN
270 expon = sign|0x7FFF
271 himant = 0
272 lomant = 0
273 else: # Finite
274 expon = expon + 16382
275 if expon < 0: # denormalized
276 fmant = math.ldexp(fmant, expon)
277 expon = 0
278 expon = expon | sign
279 fmant = math.ldexp(fmant, 32)
280 fsmant = math.floor(fmant)
281 himant = long(fsmant)
282 fmant = math.ldexp(fmant - fsmant, 32)
283 fsmant = math.floor(fmant)
284 lomant = long(fsmant)
285 _write_short(f, expon)
286 _write_long(f, himant)
287 _write_long(f, lomant)
288
Guido van Rossumd3166071993-05-24 14:16:22 +0000289class Chunk:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000290 def init(self, file):
291 self.file = file
292 self.chunkname = self.file.read(4)
293 if len(self.chunkname) < 4:
294 raise EOFError
295 self.chunksize = _read_long(self.file)
296 self.size_read = 0
297 self.offset = self.file.tell()
298 return self
299
300 def rewind(self):
301 self.file.seek(self.offset, 0)
302 self.size_read = 0
303
304 def setpos(self, pos):
305 if pos < 0 or pos > self.chunksize:
306 raise RuntimeError
307 self.file.seek(self.offset + pos, 0)
308 self.size_read = pos
309
310 def read(self, length):
311 if self.size_read >= self.chunksize:
312 return ''
313 if length > self.chunksize - self.size_read:
314 length = self.chunksize - self.size_read
315 data = self.file.read(length)
316 self.size_read = self.size_read + len(data)
317 return data
318
319 def skip(self):
320 try:
321 self.file.seek(self.chunksize - self.size_read, 1)
322 except RuntimeError:
323 while self.size_read < self.chunksize:
324 dummy = self.read(8192)
325 if not dummy:
326 raise EOFError
327 if self.chunksize & 1:
328 dummy = self.read(1)
329
Guido van Rossumd3166071993-05-24 14:16:22 +0000330class Aifc_read:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000331 # Variables used in this class:
332 #
333 # These variables are available to the user though appropriate
334 # methods of this class:
335 # _file -- the open file with methods read(), close(), and seek()
336 # set through the init() ir initfp() method
337 # _nchannels -- the number of audio channels
338 # available through the getnchannels() method
339 # _nframes -- the number of audio frames
340 # available through the getnframes() method
341 # _sampwidth -- the number of bytes per audio sample
342 # available through the getsampwidth() method
343 # _framerate -- the sampling frequency
344 # available through the getframerate() method
345 # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
346 # available through the getcomptype() method
347 # _compname -- the human-readable AIFF-C compression type
348 # available through the getcomptype() method
349 # _markers -- the marks in the audio file
350 # available through the getmarkers() and getmark()
351 # methods
352 # _soundpos -- the position in the audio stream
353 # available through the tell() method, set through the
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000354 # setpos() method
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000355 #
356 # These variables are used internally only:
357 # _version -- the AIFF-C version number
358 # _decomp -- the decompressor from builtin module cl
359 # _comm_chunk_read -- 1 iff the COMM chunk has been read
360 # _aifc -- 1 iff reading an AIFF-C file
361 # _ssnd_seek_needed -- 1 iff positioned correctly in audio
362 # file for readframes()
363 # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000364 # _framesize -- size of one frame in the file
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000365 def initfp(self, file):
366 self._file = file
367 self._version = 0
368 self._decomp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000369 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000370 self._markers = []
371 self._soundpos = 0
372 form = self._file.read(4)
373 if form != 'FORM':
374 raise Error, 'file does not start with FORM id'
375 formlength = _read_long(self._file)
376 if formlength <= 0:
377 raise Error, 'invalid FORM chunk data size'
378 formdata = self._file.read(4)
379 formlength = formlength - 4
380 if formdata == 'AIFF':
381 self._aifc = 0
382 elif formdata == 'AIFC':
383 self._aifc = 1
384 else:
385 raise Error, 'not an AIFF or AIFF-C file'
386 self._comm_chunk_read = 0
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000387 while formlength > 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000388 self._ssnd_seek_needed = 1
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000389 #DEBUG: SGI's soundfiler has a bug. There should
390 # be no need to check for EOF here.
391 try:
392 chunk = Chunk().init(self._file)
393 except EOFError:
394 if formlength == 8:
395 print 'Warning: FORM chunk size too large'
396 formlength = 0
397 break
398 raise EOFError # different error, raise exception
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000399 if chunk.chunkname == 'COMM':
400 self._read_comm_chunk(chunk)
401 self._comm_chunk_read = 1
402 elif chunk.chunkname == 'SSND':
403 self._ssnd_chunk = chunk
404 dummy = chunk.read(8)
405 self._ssnd_seek_needed = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000406 elif chunk.chunkname == 'FVER':
407 self._version = _read_long(chunk)
408 elif chunk.chunkname == 'MARK':
409 self._readmark(chunk)
410 elif chunk.chunkname in _skiplist:
411 pass
412 else:
413 raise Error, 'unrecognized chunk type '+chunk.chunkname
Sjoerd Mullender4150ede1993-08-26 14:12:07 +0000414 formlength = formlength - 8 - chunk.chunksize
415 if chunk.chunksize & 1:
416 formlength = formlength - 1
Sjoerd Mullender93f07401993-01-26 09:24:37 +0000417 if formlength > 0:
418 chunk.skip()
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000419 if not self._comm_chunk_read or not self._ssnd_chunk:
420 raise Error, 'COMM chunk and/or SSND chunk missing'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000421 if self._aifc and self._decomp:
422 params = [CL.ORIGINAL_FORMAT, 0, \
423 CL.BITS_PER_COMPONENT, 0, \
424 CL.FRAME_RATE, self._framerate]
425 if self._nchannels == AL.MONO:
426 params[1] = CL.MONO
427 else:
428 params[1] = CL.STEREO_INTERLEAVED
429 if self._sampwidth == AL.SAMPLE_8:
430 params[3] = 8
431 elif self._sampwidth == AL.SAMPLE_16:
432 params[3] = 16
433 else:
434 params[3] = 24
435 self._decomp.SetParams(params)
436 return self
437
438 def init(self, filename):
439 return self.initfp(builtin.open(filename, 'r'))
440
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000441 def __del__(self):
442 if self._file:
443 self.close()
444
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000445 #
446 # User visible methods.
447 #
448 def getfp(self):
449 return self._file
450
451 def rewind(self):
452 self._ssnd_seek_needed = 1
453 self._soundpos = 0
454
455 def close(self):
456 if self._decomp:
457 self._decomp.CloseDecompressor()
458 self._decomp = None
459 self._file.close()
460 self._file = None
461
462 def tell(self):
463 return self._soundpos
464
465 def getnchannels(self):
466 return self._nchannels
467
468 def getnframes(self):
469 return self._nframes
470
471 def getsampwidth(self):
472 return self._sampwidth
473
474 def getframerate(self):
475 return self._framerate
476
477 def getcomptype(self):
478 return self._comptype
479
480 def getcompname(self):
481 return self._compname
482
483## def getversion(self):
484## return self._version
485
486 def getparams(self):
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000487 return self.getnchannels(), self.getsampwidth(), \
488 self.getframerate(), self.getnframes(), \
489 self.getcomptype(), self.getcompname()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000490
491 def getmarkers(self):
492 if len(self._markers) == 0:
493 return None
494 return self._markers
495
496 def getmark(self, id):
497 for marker in self._markers:
498 if id == marker[0]:
499 return marker
500 raise Error, 'marker ' + `id` + ' does not exist'
501
502 def setpos(self, pos):
503 if pos < 0 or pos > self._nframes:
504 raise Error, 'position not in range'
505 self._soundpos = pos
506 self._ssnd_seek_needed = 1
507
508 def readframes(self, nframes):
509 if self._ssnd_seek_needed:
510 self._ssnd_chunk.rewind()
511 dummy = self._ssnd_chunk.read(8)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000512 pos = self._soundpos * self._framesize
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000513 if pos:
514 self._ssnd_chunk.setpos(pos + 8)
515 self._ssnd_seek_needed = 0
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000516 if nframes == 0:
517 return ''
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000518 data = self._ssnd_chunk.read(nframes * self._framesize)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000519 if self._convert and data:
520 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000521 self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth)
522 return data
523
524 #
525 # Internal methods.
526 #
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000527 def _decomp_data(self, data):
528 dummy = self._decomp.SetParam(CL.FRAME_BUFFER_SIZE,
529 len(data) * 2)
530 return self._decomp.Decompress(len(data) / self._nchannels,
531 data)
532
533 def _ulaw2lin(self, data):
534 import audioop
535 return audioop.ulaw2lin(data, 2)
536
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000537 def _read_comm_chunk(self, chunk):
538 nchannels = _read_short(chunk)
539 self._nchannels = _convert1(nchannels, _nchannelslist)
540 self._nframes = _read_long(chunk)
541 sampwidth = _read_short(chunk)
542 self._sampwidth = _convert1(sampwidth, _sampwidthlist)
543 framerate = _read_float(chunk)
544 self._framerate = _convert1(framerate, _frameratelist)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000545 self._framesize = self._nchannels * self._sampwidth
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000546 if self._aifc:
547 #DEBUG: SGI's soundeditor produces a bad size :-(
548 kludge = 0
549 if chunk.chunksize == 18:
550 kludge = 1
551 print 'Warning: bad COMM chunk size'
552 chunk.chunksize = 23
553 #DEBUG end
554 self._comptype = chunk.read(4)
555 #DEBUG start
556 if kludge:
557 length = ord(chunk.file.read(1))
558 if length & 1 == 0:
559 length = length + 1
560 chunk.chunksize = chunk.chunksize + length
561 chunk.file.seek(-1, 1)
562 #DEBUG end
563 self._compname = _read_string(chunk)
564 if self._comptype != 'NONE':
565 try:
566 import cl, CL
567 except ImportError:
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000568 if self._comptype == 'ULAW':
569 try:
570 import audioop
571 self._convert = self._ulaw2lin
572 self._framesize = self._framesize / 2
573 return
574 except ImportError:
575 pass
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000576 raise Error, 'cannot read compressed AIFF-C files'
577 if self._comptype == 'ULAW':
578 scheme = CL.G711_ULAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000579 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000580 elif self._comptype == 'ALAW':
581 scheme = CL.G711_ALAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000582 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000583 else:
584 raise Error, 'unsupported compression type'
585 self._decomp = cl.OpenDecompressor(scheme)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000586 self._convert = self._decomp_data
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000587 else:
588 self._comptype = 'NONE'
589 self._compname = 'not compressed'
590
591 def _readmark(self, chunk):
592 nmarkers = _read_short(chunk)
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000593 # Some files appear to contain invalid counts.
594 # Cope with this by testing for EOF.
595 try:
596 for i in range(nmarkers):
597 id = _read_short(chunk)
598 pos = _read_long(chunk)
599 name = _read_string(chunk)
600 self._markers.append((id, pos, name))
601 except EOFError:
602 print 'Warning: MARK chunk contains only',
603 print len(self._markers),
604 if len(self._markers) == 1: print 'marker',
605 else: print 'markers',
606 print 'instead of', nmarkers
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000607
Guido van Rossumd3166071993-05-24 14:16:22 +0000608class Aifc_write:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000609 # Variables used in this class:
610 #
611 # These variables are user settable through appropriate methods
612 # of this class:
613 # _file -- the open file with methods write(), close(), tell(), seek()
614 # set through the init() or initfp() method
615 # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
616 # set through the setcomptype() or setparams() method
617 # _compname -- the human-readable AIFF-C compression type
618 # set through the setcomptype() or setparams() method
619 # _nchannels -- the number of audio channels
620 # set through the setnchannels() or setparams() method
621 # _sampwidth -- the number of bytes per audio sample
622 # set through the setsampwidth() or setparams() method
623 # _framerate -- the sampling frequency
624 # set through the setframerate() or setparams() method
625 # _nframes -- the number of audio frames written to the header
626 # set through the setnframes() or setparams() method
627 # _aifc -- whether we're writing an AIFF-C file or an AIFF file
628 # set through the aifc() method, reset through the
629 # aiff() method
630 #
631 # These variables are used internally only:
632 # _version -- the AIFF-C version number
633 # _comp -- the compressor from builtin module cl
634 # _nframeswritten -- the number of audio frames actually written
635 # _datalength -- the size of the audio samples written to the header
636 # _datawritten -- the size of the audio samples actually written
637
638 def init(self, filename):
639 self = self.initfp(builtin.open(filename, 'w'))
640 if filename[-5:] == '.aiff':
641 self._aifc = 0
642 else:
643 self._aifc = 1
644 return self
645
646 def initfp(self, file):
647 self._file = file
648 self._version = _AIFC_version
649 self._comptype = 'NONE'
650 self._compname = 'not compressed'
651 self._comp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000652 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000653 self._nchannels = 0
654 self._sampwidth = 0
655 self._framerate = 0
656 self._nframes = 0
657 self._nframeswritten = 0
658 self._datawritten = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000659 self._datalength = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000660 self._markers = []
661 self._marklength = 0
662 self._aifc = 1 # AIFF-C is default
663 return self
664
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000665 def __del__(self):
666 if self._file:
667 self.close()
668
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000669 #
670 # User visible methods.
671 #
672 def aiff(self):
673 if self._nframeswritten:
674 raise Error, 'cannot change parameters after starting to write'
675 self._aifc = 0
676
677 def aifc(self):
678 if self._nframeswritten:
679 raise Error, 'cannot change parameters after starting to write'
680 self._aifc = 1
681
682 def setnchannels(self, nchannels):
683 if self._nframeswritten:
684 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender4ab6ff81993-02-05 13:43:44 +0000685 dummy = _convert2(nchannels, _nchannelslist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000686 self._nchannels = nchannels
687
688 def getnchannels(self):
689 if not self._nchannels:
690 raise Error, 'number of channels not set'
691 return self._nchannels
692
693 def setsampwidth(self, sampwidth):
694 if self._nframeswritten:
695 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000696 dummy = _convert2(sampwidth, _sampwidthlist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000697 self._sampwidth = sampwidth
698
699 def getsampwidth(self):
700 if not self._sampwidth:
701 raise Error, 'sample width not set'
702 return self._sampwidth
703
704 def setframerate(self, framerate):
705 if self._nframeswritten:
706 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000707 dummy = _convert2(framerate, _frameratelist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000708 self._framerate = framerate
709
710 def getframerate(self):
711 if not self._framerate:
712 raise Error, 'frame rate not set'
713 return self._framerate
714
715 def setnframes(self, nframes):
716 if self._nframeswritten:
717 raise Error, 'cannot change parameters after starting to write'
718 self._nframes = nframes
719
720 def getnframes(self):
721 return self._nframeswritten
722
723 def setcomptype(self, comptype, compname):
724 if self._nframeswritten:
725 raise Error, 'cannot change parameters after starting to write'
726 if comptype not in ('NONE', 'ULAW', 'ALAW'):
727 raise Error, 'unsupported compression type'
728 self._comptype = comptype
729 self._compname = compname
730
731 def getcomptype(self):
732 return self._comptype
733
734 def getcompname(self):
735 return self._compname
736
737## def setversion(self, version):
738## if self._nframeswritten:
739## raise Error, 'cannot change parameters after starting to write'
740## self._version = version
741
742 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
743 if self._nframeswritten:
744 raise Error, 'cannot change parameters after starting to write'
745 if comptype not in ('NONE', 'ULAW', 'ALAW'):
746 raise Error, 'unsupported compression type'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000747 dummy = _convert2(nchannels, _nchannelslist)
748 dummy = _convert2(sampwidth, _sampwidthlist)
749 dummy = _convert2(framerate, _frameratelist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000750 self._nchannels = nchannels
751 self._sampwidth = sampwidth
752 self._framerate = framerate
753 self._nframes = nframes
754 self._comptype = comptype
755 self._compname = compname
756
757 def getparams(self):
758 if not self._nchannels or not self._sampwidth or not self._framerate:
759 raise Error, 'not all parameters set'
760 return self._nchannels, self._sampwidth, self._framerate, \
761 self._nframes, self._comptype, self._compname
762
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000763 def setmark(self, id, pos, name):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000764 if id <= 0:
765 raise Error, 'marker ID must be > 0'
766 if pos < 0:
767 raise Error, 'marker position must be >= 0'
768 if type(name) != type(''):
769 raise Error, 'marker name must be a string'
770 for i in range(len(self._markers)):
771 if id == self._markers[i][0]:
772 self._markers[i] = id, pos, name
773 return
774 self._markers.append((id, pos, name))
775
776 def getmark(self, id):
777 for marker in self._markers:
778 if id == marker[0]:
779 return marker
780 raise Error, 'marker ' + `id` + ' does not exist'
781
782 def getmarkers(self):
783 if len(self._markers) == 0:
784 return None
785 return self._markers
786
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000787 def tell(self):
788 return self._nframeswritten
789
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000790 def writeframesraw(self, data):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000791 self._ensure_header_written(len(data))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000792 nframes = len(data) / (self._sampwidth * self._nchannels)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000793 if self._convert:
794 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000795 self._file.write(data)
796 self._nframeswritten = self._nframeswritten + nframes
797 self._datawritten = self._datawritten + len(data)
798
799 def writeframes(self, data):
800 self.writeframesraw(data)
801 if self._nframeswritten != self._nframes or \
802 self._datalength != self._datawritten:
803 self._patchheader()
804
805 def close(self):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000806 self._ensure_header_written(0)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000807 if self._datawritten & 1:
808 # quick pad to even size
809 self._file.write(chr(0))
810 self._datawritten = self._datawritten + 1
811 self._writemarkers()
812 if self._nframeswritten != self._nframes or \
813 self._datalength != self._datawritten or \
814 self._marklength:
815 self._patchheader()
816 if self._comp:
817 self._comp.CloseCompressor()
818 self._comp = None
819 self._file.close()
820 self._file = None
821
822 #
823 # Internal methods.
824 #
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000825 def _comp_data(self, data):
826 dum = self._comp.SetParam(CL.FRAME_BUFFER_SIZE, len(data))
827 dum = self._comp.SetParam(CL.COMPRESSED_BUFFER_SIZE, len(data))
828 return self._comp.Compress(nframes, data)
829
830 def _lin2ulaw(self, data):
831 import audioop
832 return audioop.lin2ulaw(data, 2)
833
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000834 def _ensure_header_written(self, datasize):
835 if not self._nframeswritten:
836 if self._comptype in ('ULAW', 'ALAW'):
837 if not self._sampwidth:
838 self._sampwidth = AL.SAMPLE_16
839 if self._sampwidth != AL.SAMPLE_16:
840 raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
841 if not self._nchannels:
842 raise Error, '# channels not specified'
843 if not self._sampwidth:
844 raise Error, 'sample width not specified'
845 if not self._framerate:
846 raise Error, 'sampling rate not specified'
847 self._write_header(datasize)
848
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000849 def _init_compression(self):
850 try:
851 import cl, CL
852 except ImportError:
853 if self._comptype == 'ULAW':
854 try:
855 import audioop
856 self._convert = self._lin2ulaw
857 return
858 except ImportError:
859 pass
860 raise Error, 'cannot write compressed AIFF-C files'
861 if self._comptype == 'ULAW':
862 scheme = CL.G711_ULAW
863 elif self._comptype == 'ALAW':
864 scheme = CL.G711_ALAW
865 else:
866 raise Error, 'unsupported compression type'
867 self._comp = cl.OpenCompressor(scheme)
868 params = [CL.ORIGINAL_FORMAT, 0, \
869 CL.BITS_PER_COMPONENT, 0, \
870 CL.FRAME_RATE, self._framerate, \
871 CL.FRAME_BUFFER_SIZE, 100, \
872 CL.COMPRESSED_BUFFER_SIZE, 100]
873 if self._nchannels == AL.MONO:
874 params[1] = CL.MONO
875 else:
876 params[1] = CL.STEREO_INTERLEAVED
877 if self._sampwidth == AL.SAMPLE_8:
878 params[3] = 8
879 elif self._sampwidth == AL.SAMPLE_16:
880 params[3] = 16
881 else:
882 params[3] = 24
883 self._comp.SetParams(params)
884 # the compressor produces a header which we ignore
885 dummy = self._comp.Compress(0, '')
886 self._convert = self._comp_data
887
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000888 def _write_header(self, initlength):
889 if self._aifc and self._comptype != 'NONE':
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000890 self._init_compression()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000891 self._file.write('FORM')
892 if not self._nframes:
893 self._nframes = initlength / (self._nchannels * self._sampwidth)
894 self._datalength = self._nframes * self._nchannels * self._sampwidth
895 if self._datalength & 1:
896 self._datalength = self._datalength + 1
897 if self._aifc and self._comptype in ('ULAW', 'ALAW'):
898 self._datalength = self._datalength / 2
899 if self._datalength & 1:
900 self._datalength = self._datalength + 1
901 self._form_length_pos = self._file.tell()
902 commlength = self._write_form_length(self._datalength)
903 if self._aifc:
904 self._file.write('AIFC')
905 self._file.write('FVER')
906 _write_long(self._file, 4)
907 _write_long(self._file, self._version)
908 else:
909 self._file.write('AIFF')
910 self._file.write('COMM')
911 _write_long(self._file, commlength)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000912 _write_short(self._file, _convert2(self._nchannels, _nchannelslist))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000913 self._nframes_pos = self._file.tell()
914 _write_long(self._file, self._nframes)
915 _write_short(self._file, _convert2(self._sampwidth, _sampwidthlist))
916 _write_float(self._file, _convert2(self._framerate, _frameratelist))
917 if self._aifc:
918 self._file.write(self._comptype)
919 _write_string(self._file, self._compname)
920 self._file.write('SSND')
921 self._ssnd_length_pos = self._file.tell()
922 _write_long(self._file, self._datalength + 8)
923 _write_long(self._file, 0)
924 _write_long(self._file, 0)
925
926 def _write_form_length(self, datalength):
927 if self._aifc:
928 commlength = 18 + 5 + len(self._compname)
929 if commlength & 1:
930 commlength = commlength + 1
931 verslength = 12
932 else:
933 commlength = 18
934 verslength = 0
935 _write_long(self._file, 4 + verslength + self._marklength + \
936 8 + commlength + 16 + datalength)
937 return commlength
938
939 def _patchheader(self):
940 curpos = self._file.tell()
941 if self._datawritten & 1:
942 datalength = self._datawritten + 1
943 self._file.write(chr(0))
944 else:
945 datalength = self._datawritten
946 if datalength == self._datalength and \
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000947 self._nframes == self._nframeswritten and \
948 self._marklength == 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000949 self._file.seek(curpos, 0)
950 return
951 self._file.seek(self._form_length_pos, 0)
952 dummy = self._write_form_length(datalength)
953 self._file.seek(self._nframes_pos, 0)
954 _write_long(self._file, self._nframeswritten)
955 self._file.seek(self._ssnd_length_pos, 0)
956 _write_long(self._file, datalength + 8)
957 self._file.seek(curpos, 0)
958 self._nframes = self._nframeswritten
959 self._datalength = datalength
960
961 def _writemarkers(self):
962 if len(self._markers) == 0:
963 return
964 self._file.write('MARK')
965 length = 2
966 for marker in self._markers:
967 id, pos, name = marker
968 length = length + len(name) + 1 + 6
969 if len(name) & 1 == 0:
970 length = length + 1
971 _write_long(self._file, length)
972 self._marklength = length + 8
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000973 _write_short(self._file, len(self._markers))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000974 for marker in self._markers:
975 id, pos, name = marker
976 _write_short(self._file, id)
977 _write_long(self._file, pos)
978 _write_string(self._file, name)
979
980def open(filename, mode):
981 if mode == 'r':
982 return Aifc_read().init(filename)
983 elif mode == 'w':
984 return Aifc_write().init(filename)
985 else:
986 raise Error, 'mode must be \'r\' or \'w\''
987
988def openfp(filep, mode):
989 if mode == 'r':
990 return Aifc_read().initfp(filep)
991 elif mode == 'w':
992 return Aifc_write().initfp(filep)
993 else:
994 raise Error, 'mode must be \'r\' or \'w\''