blob: f833e921cf1773dd1ffb279b1cf496d10626bbca [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)]
Sjoerd Mullenderfeaa7d21993-12-16 13:56:34 +0000156_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),
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000162 ( 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
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000459 self._file = None
460
461 def tell(self):
462 return self._soundpos
463
464 def getnchannels(self):
465 return self._nchannels
466
467 def getnframes(self):
468 return self._nframes
469
470 def getsampwidth(self):
471 return self._sampwidth
472
473 def getframerate(self):
474 return self._framerate
475
476 def getcomptype(self):
477 return self._comptype
478
479 def getcompname(self):
480 return self._compname
481
482## def getversion(self):
483## return self._version
484
485 def getparams(self):
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000486 return self.getnchannels(), self.getsampwidth(), \
487 self.getframerate(), self.getnframes(), \
488 self.getcomptype(), self.getcompname()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000489
490 def getmarkers(self):
491 if len(self._markers) == 0:
492 return None
493 return self._markers
494
495 def getmark(self, id):
496 for marker in self._markers:
497 if id == marker[0]:
498 return marker
499 raise Error, 'marker ' + `id` + ' does not exist'
500
501 def setpos(self, pos):
502 if pos < 0 or pos > self._nframes:
503 raise Error, 'position not in range'
504 self._soundpos = pos
505 self._ssnd_seek_needed = 1
506
507 def readframes(self, nframes):
508 if self._ssnd_seek_needed:
509 self._ssnd_chunk.rewind()
510 dummy = self._ssnd_chunk.read(8)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000511 pos = self._soundpos * self._framesize
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000512 if pos:
513 self._ssnd_chunk.setpos(pos + 8)
514 self._ssnd_seek_needed = 0
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000515 if nframes == 0:
516 return ''
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000517 data = self._ssnd_chunk.read(nframes * self._framesize)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000518 if self._convert and data:
519 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000520 self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth)
521 return data
522
523 #
524 # Internal methods.
525 #
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000526 def _decomp_data(self, data):
527 dummy = self._decomp.SetParam(CL.FRAME_BUFFER_SIZE,
528 len(data) * 2)
529 return self._decomp.Decompress(len(data) / self._nchannels,
530 data)
531
532 def _ulaw2lin(self, data):
533 import audioop
534 return audioop.ulaw2lin(data, 2)
535
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000536 def _read_comm_chunk(self, chunk):
537 nchannels = _read_short(chunk)
538 self._nchannels = _convert1(nchannels, _nchannelslist)
539 self._nframes = _read_long(chunk)
540 sampwidth = _read_short(chunk)
541 self._sampwidth = _convert1(sampwidth, _sampwidthlist)
542 framerate = _read_float(chunk)
543 self._framerate = _convert1(framerate, _frameratelist)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000544 self._framesize = self._nchannels * self._sampwidth
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000545 if self._aifc:
546 #DEBUG: SGI's soundeditor produces a bad size :-(
547 kludge = 0
548 if chunk.chunksize == 18:
549 kludge = 1
550 print 'Warning: bad COMM chunk size'
551 chunk.chunksize = 23
552 #DEBUG end
553 self._comptype = chunk.read(4)
554 #DEBUG start
555 if kludge:
556 length = ord(chunk.file.read(1))
557 if length & 1 == 0:
558 length = length + 1
559 chunk.chunksize = chunk.chunksize + length
560 chunk.file.seek(-1, 1)
561 #DEBUG end
562 self._compname = _read_string(chunk)
563 if self._comptype != 'NONE':
564 try:
565 import cl, CL
566 except ImportError:
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000567 if self._comptype == 'ULAW':
568 try:
569 import audioop
570 self._convert = self._ulaw2lin
571 self._framesize = self._framesize / 2
572 return
573 except ImportError:
574 pass
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000575 raise Error, 'cannot read compressed AIFF-C files'
576 if self._comptype == 'ULAW':
577 scheme = CL.G711_ULAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000578 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000579 elif self._comptype == 'ALAW':
580 scheme = CL.G711_ALAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000581 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000582 else:
583 raise Error, 'unsupported compression type'
584 self._decomp = cl.OpenDecompressor(scheme)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000585 self._convert = self._decomp_data
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000586 else:
587 self._comptype = 'NONE'
588 self._compname = 'not compressed'
589
590 def _readmark(self, chunk):
591 nmarkers = _read_short(chunk)
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000592 # Some files appear to contain invalid counts.
593 # Cope with this by testing for EOF.
594 try:
595 for i in range(nmarkers):
596 id = _read_short(chunk)
597 pos = _read_long(chunk)
598 name = _read_string(chunk)
599 self._markers.append((id, pos, name))
600 except EOFError:
601 print 'Warning: MARK chunk contains only',
602 print len(self._markers),
603 if len(self._markers) == 1: print 'marker',
604 else: print 'markers',
605 print 'instead of', nmarkers
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000606
Guido van Rossumd3166071993-05-24 14:16:22 +0000607class Aifc_write:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000608 # Variables used in this class:
609 #
610 # These variables are user settable through appropriate methods
611 # of this class:
612 # _file -- the open file with methods write(), close(), tell(), seek()
613 # set through the init() or initfp() method
614 # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
615 # set through the setcomptype() or setparams() method
616 # _compname -- the human-readable AIFF-C compression type
617 # set through the setcomptype() or setparams() method
618 # _nchannels -- the number of audio channels
619 # set through the setnchannels() or setparams() method
620 # _sampwidth -- the number of bytes per audio sample
621 # set through the setsampwidth() or setparams() method
622 # _framerate -- the sampling frequency
623 # set through the setframerate() or setparams() method
624 # _nframes -- the number of audio frames written to the header
625 # set through the setnframes() or setparams() method
626 # _aifc -- whether we're writing an AIFF-C file or an AIFF file
627 # set through the aifc() method, reset through the
628 # aiff() method
629 #
630 # These variables are used internally only:
631 # _version -- the AIFF-C version number
632 # _comp -- the compressor from builtin module cl
633 # _nframeswritten -- the number of audio frames actually written
634 # _datalength -- the size of the audio samples written to the header
635 # _datawritten -- the size of the audio samples actually written
636
637 def init(self, filename):
638 self = self.initfp(builtin.open(filename, 'w'))
639 if filename[-5:] == '.aiff':
640 self._aifc = 0
641 else:
642 self._aifc = 1
643 return self
644
645 def initfp(self, file):
646 self._file = file
647 self._version = _AIFC_version
648 self._comptype = 'NONE'
649 self._compname = 'not compressed'
650 self._comp = None
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000651 self._convert = None
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000652 self._nchannels = 0
653 self._sampwidth = 0
654 self._framerate = 0
655 self._nframes = 0
656 self._nframeswritten = 0
657 self._datawritten = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000658 self._datalength = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000659 self._markers = []
660 self._marklength = 0
661 self._aifc = 1 # AIFF-C is default
662 return self
663
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000664 def __del__(self):
665 if self._file:
666 self.close()
667
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000668 #
669 # User visible methods.
670 #
671 def aiff(self):
672 if self._nframeswritten:
673 raise Error, 'cannot change parameters after starting to write'
674 self._aifc = 0
675
676 def aifc(self):
677 if self._nframeswritten:
678 raise Error, 'cannot change parameters after starting to write'
679 self._aifc = 1
680
681 def setnchannels(self, nchannels):
682 if self._nframeswritten:
683 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender4ab6ff81993-02-05 13:43:44 +0000684 dummy = _convert2(nchannels, _nchannelslist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000685 self._nchannels = nchannels
686
687 def getnchannels(self):
688 if not self._nchannels:
689 raise Error, 'number of channels not set'
690 return self._nchannels
691
692 def setsampwidth(self, sampwidth):
693 if self._nframeswritten:
694 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000695 dummy = _convert2(sampwidth, _sampwidthlist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000696 self._sampwidth = sampwidth
697
698 def getsampwidth(self):
699 if not self._sampwidth:
700 raise Error, 'sample width not set'
701 return self._sampwidth
702
703 def setframerate(self, framerate):
704 if self._nframeswritten:
705 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000706 dummy = _convert2(framerate, _frameratelist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000707 self._framerate = framerate
708
709 def getframerate(self):
710 if not self._framerate:
711 raise Error, 'frame rate not set'
712 return self._framerate
713
714 def setnframes(self, nframes):
715 if self._nframeswritten:
716 raise Error, 'cannot change parameters after starting to write'
717 self._nframes = nframes
718
719 def getnframes(self):
720 return self._nframeswritten
721
722 def setcomptype(self, comptype, compname):
723 if self._nframeswritten:
724 raise Error, 'cannot change parameters after starting to write'
725 if comptype not in ('NONE', 'ULAW', 'ALAW'):
726 raise Error, 'unsupported compression type'
727 self._comptype = comptype
728 self._compname = compname
729
730 def getcomptype(self):
731 return self._comptype
732
733 def getcompname(self):
734 return self._compname
735
736## def setversion(self, version):
737## if self._nframeswritten:
738## raise Error, 'cannot change parameters after starting to write'
739## self._version = version
740
741 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
742 if self._nframeswritten:
743 raise Error, 'cannot change parameters after starting to write'
744 if comptype not in ('NONE', 'ULAW', 'ALAW'):
745 raise Error, 'unsupported compression type'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000746 dummy = _convert2(nchannels, _nchannelslist)
747 dummy = _convert2(sampwidth, _sampwidthlist)
748 dummy = _convert2(framerate, _frameratelist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000749 self._nchannels = nchannels
750 self._sampwidth = sampwidth
751 self._framerate = framerate
752 self._nframes = nframes
753 self._comptype = comptype
754 self._compname = compname
755
756 def getparams(self):
757 if not self._nchannels or not self._sampwidth or not self._framerate:
758 raise Error, 'not all parameters set'
759 return self._nchannels, self._sampwidth, self._framerate, \
760 self._nframes, self._comptype, self._compname
761
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000762 def setmark(self, id, pos, name):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000763 if id <= 0:
764 raise Error, 'marker ID must be > 0'
765 if pos < 0:
766 raise Error, 'marker position must be >= 0'
767 if type(name) != type(''):
768 raise Error, 'marker name must be a string'
769 for i in range(len(self._markers)):
770 if id == self._markers[i][0]:
771 self._markers[i] = id, pos, name
772 return
773 self._markers.append((id, pos, name))
774
775 def getmark(self, id):
776 for marker in self._markers:
777 if id == marker[0]:
778 return marker
779 raise Error, 'marker ' + `id` + ' does not exist'
780
781 def getmarkers(self):
782 if len(self._markers) == 0:
783 return None
784 return self._markers
785
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000786 def tell(self):
787 return self._nframeswritten
788
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000789 def writeframesraw(self, data):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000790 self._ensure_header_written(len(data))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000791 nframes = len(data) / (self._sampwidth * self._nchannels)
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000792 if self._convert:
793 data = self._convert(data)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000794 self._file.write(data)
795 self._nframeswritten = self._nframeswritten + nframes
796 self._datawritten = self._datawritten + len(data)
797
798 def writeframes(self, data):
799 self.writeframesraw(data)
800 if self._nframeswritten != self._nframes or \
801 self._datalength != self._datawritten:
802 self._patchheader()
803
804 def close(self):
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000805 self._ensure_header_written(0)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000806 if self._datawritten & 1:
807 # quick pad to even size
808 self._file.write(chr(0))
809 self._datawritten = self._datawritten + 1
810 self._writemarkers()
811 if self._nframeswritten != self._nframes or \
812 self._datalength != self._datawritten or \
813 self._marklength:
814 self._patchheader()
815 if self._comp:
816 self._comp.CloseCompressor()
817 self._comp = None
Sjoerd Mullenderfeaa7d21993-12-16 13:56:34 +0000818 self._file.flush()
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000819 self._file = None
820
821 #
822 # Internal methods.
823 #
Sjoerd Mullender43bf0bc1993-12-13 11:42:39 +0000824 def _comp_data(self, data):
825 dum = self._comp.SetParam(CL.FRAME_BUFFER_SIZE, len(data))
826 dum = self._comp.SetParam(CL.COMPRESSED_BUFFER_SIZE, len(data))
827 return self._comp.Compress(nframes, data)
828
829 def _lin2ulaw(self, data):
830 import audioop
831 return audioop.lin2ulaw(data, 2)
832
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000833 def _ensure_header_written(self, datasize):
834 if not self._nframeswritten:
835 if self._comptype in ('ULAW', 'ALAW'):
836 if not self._sampwidth:
837 self._sampwidth = AL.SAMPLE_16
838 if self._sampwidth != AL.SAMPLE_16:
839 raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
840 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):
849 try:
850 import cl, CL
851 except ImportError:
852 if self._comptype == 'ULAW':
853 try:
854 import audioop
855 self._convert = self._lin2ulaw
856 return
857 except ImportError:
858 pass
859 raise Error, 'cannot write compressed AIFF-C files'
860 if self._comptype == 'ULAW':
861 scheme = CL.G711_ULAW
862 elif self._comptype == 'ALAW':
863 scheme = CL.G711_ALAW
864 else:
865 raise Error, 'unsupported compression type'
866 self._comp = cl.OpenCompressor(scheme)
867 params = [CL.ORIGINAL_FORMAT, 0, \
868 CL.BITS_PER_COMPONENT, 0, \
869 CL.FRAME_RATE, self._framerate, \
870 CL.FRAME_BUFFER_SIZE, 100, \
871 CL.COMPRESSED_BUFFER_SIZE, 100]
872 if self._nchannels == AL.MONO:
873 params[1] = CL.MONO
874 else:
875 params[1] = CL.STEREO_INTERLEAVED
876 if self._sampwidth == AL.SAMPLE_8:
877 params[3] = 8
878 elif self._sampwidth == AL.SAMPLE_16:
879 params[3] = 16
880 else:
881 params[3] = 24
882 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
896 if self._aifc and self._comptype in ('ULAW', 'ALAW'):
897 self._datalength = self._datalength / 2
898 if self._datalength & 1:
899 self._datalength = self._datalength + 1
900 self._form_length_pos = self._file.tell()
901 commlength = self._write_form_length(self._datalength)
902 if self._aifc:
903 self._file.write('AIFC')
904 self._file.write('FVER')
905 _write_long(self._file, 4)
906 _write_long(self._file, self._version)
907 else:
908 self._file.write('AIFF')
909 self._file.write('COMM')
910 _write_long(self._file, commlength)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000911 _write_short(self._file, _convert2(self._nchannels, _nchannelslist))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000912 self._nframes_pos = self._file.tell()
913 _write_long(self._file, self._nframes)
914 _write_short(self._file, _convert2(self._sampwidth, _sampwidthlist))
915 _write_float(self._file, _convert2(self._framerate, _frameratelist))
916 if self._aifc:
917 self._file.write(self._comptype)
918 _write_string(self._file, self._compname)
919 self._file.write('SSND')
920 self._ssnd_length_pos = self._file.tell()
921 _write_long(self._file, self._datalength + 8)
922 _write_long(self._file, 0)
923 _write_long(self._file, 0)
924
925 def _write_form_length(self, datalength):
926 if self._aifc:
927 commlength = 18 + 5 + len(self._compname)
928 if commlength & 1:
929 commlength = commlength + 1
930 verslength = 12
931 else:
932 commlength = 18
933 verslength = 0
934 _write_long(self._file, 4 + verslength + self._marklength + \
935 8 + commlength + 16 + datalength)
936 return commlength
937
938 def _patchheader(self):
939 curpos = self._file.tell()
940 if self._datawritten & 1:
941 datalength = self._datawritten + 1
942 self._file.write(chr(0))
943 else:
944 datalength = self._datawritten
945 if datalength == self._datalength and \
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000946 self._nframes == self._nframeswritten and \
947 self._marklength == 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000948 self._file.seek(curpos, 0)
949 return
950 self._file.seek(self._form_length_pos, 0)
951 dummy = self._write_form_length(datalength)
952 self._file.seek(self._nframes_pos, 0)
953 _write_long(self._file, self._nframeswritten)
954 self._file.seek(self._ssnd_length_pos, 0)
955 _write_long(self._file, datalength + 8)
956 self._file.seek(curpos, 0)
957 self._nframes = self._nframeswritten
958 self._datalength = datalength
959
960 def _writemarkers(self):
961 if len(self._markers) == 0:
962 return
963 self._file.write('MARK')
964 length = 2
965 for marker in self._markers:
966 id, pos, name = marker
967 length = length + len(name) + 1 + 6
968 if len(name) & 1 == 0:
969 length = length + 1
970 _write_long(self._file, length)
971 self._marklength = length + 8
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000972 _write_short(self._file, len(self._markers))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000973 for marker in self._markers:
974 id, pos, name = marker
975 _write_short(self._file, id)
976 _write_long(self._file, pos)
977 _write_string(self._file, name)
978
979def open(filename, mode):
980 if mode == 'r':
981 return Aifc_read().init(filename)
982 elif mode == 'w':
983 return Aifc_write().init(filename)
984 else:
985 raise Error, 'mode must be \'r\' or \'w\''
986
987def openfp(filep, mode):
988 if mode == 'r':
989 return Aifc_read().initfp(filep)
990 elif mode == 'w':
991 return Aifc_write().initfp(filep)
992 else:
993 raise Error, 'mode must be \'r\' or \'w\''