blob: 4e919d44f93adfdda0cef7b08f40ba1d6e4150b8 [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)
43# if AIFF-C files only:
44# <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.
61# The open file pointer must have methods read(), seek(), and
62# close(). In some types of audio files, if the setpos() method is
63# not used, the seek() method is not necessary.
64#
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
84# The position returned by tell(), the position given to setpos() and
85# the position of marks are all compatible and have nothing to do with
86# the actual postion in the file.
87#
88# Writing AIFF files:
89# f = aifc.open(file, 'w')
90# or
91# f = aifc.openfp(filep, 'w')
92# where file is the name of a file and filep is an open file pointer.
93# The open file pointer must have methods write(), tell(), seek(), and
94# close().
95#
96# This returns an instance of a class with the following public methods:
97# aiff() -- create an AIFF file (AIFF-C default)
98# aifc() -- create an AIFF-C file
99# setnchannels(n) -- set the number of channels
100# setsampwidth(n) -- set the sample width
101# setframerate(n) -- set the frame rate
102# setnframes(n) -- set the number of frames
103# setcomptype(type, name)
104# -- set the compression type and the
105# human-readable compression type
106# setparams(nchannels, sampwidth, framerate, nframes, comptype, compname)
107# -- set all parameters at once
108# setmark(id, pos, name)
109# -- add specified mark to the list of marks
110# tell() -- return current position in output file (useful
111# in combination with setmark())
112# writeframesraw(data)
113# -- write audio frames without pathing up the
114# file header
115# writeframes(data)
116# -- write audio frames and patch up the file header
117# close() -- patch up the file header and close the
118# output file
119# You should set the parameters before the first writeframesraw or
120# writeframes. The total number of frames does not need to be set,
121# but when it is set to the correct value, the header does not have to
122# be patched up.
123# It is best to first set all parameters, perhaps possibly the
124# compression type, and the write audio frames using writeframesraw.
125# When all frames have been written, either call writeframes('') or
126# close() to patch up the sizes in the header.
127# Marks can be added anytime. If there are any marks, ypu must call
128# close() after all frames have been written.
129#
130# When a file is opened with the extension '.aiff', an AIFF file is
131# written, otherwise an AIFF-C file is written. This default can be
132# changed by calling aiff() or aifc() before the first writeframes or
133# writeframesraw.
134
135import builtin
136import AL
137try:
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
149_nchannelslist = [(1, AL.MONO), (2, AL.STEREO)]
150_sampwidthlist = [(8, AL.SAMPLE_8), (16, AL.SAMPLE_16), (24, AL.SAMPLE_24)]
151_frameratelist = [(48000, AL.RATE_48000), \
152 (44100, AL.RATE_44100), \
153 (32000, AL.RATE_32000), \
154 (22050, AL.RATE_22050), \
155 (16000, AL.RATE_16000), \
156 (11025, AL.RATE_11025), \
157 ( 8000, AL.RATE_8000)]
158
159def _convert1(value, list):
160 for t in list:
161 if value == t[0]:
162 return t[1]
163 raise Error, 'unknown parameter value'
164
165def _convert2(value, list):
166 for t in list:
167 if value == t[1]:
168 return t[0]
169 raise Error, 'unknown parameter value'
170
171def _read_long(file):
172 x = 0L
173 for i in range(4):
174 byte = file.read(1)
175 if byte == '':
176 raise EOFError
177 x = x*256 + ord(byte)
178 if x >= 0x80000000L:
179 x = x - 0x100000000L
180 return int(x)
181
182def _read_ulong(file):
183 x = 0L
184 for i in range(4):
185 byte = file.read(1)
186 if byte == '':
187 raise EOFError
188 x = x*256 + ord(byte)
189 return x
190
191def _read_short(file):
192 x = 0
193 for i in range(2):
194 byte = file.read(1)
195 if byte == '':
196 raise EOFError
197 x = x*256 + ord(byte)
198 if x >= 0x8000:
199 x = x - 0x10000
200 return x
201
202def _read_string(file):
203 length = ord(file.read(1))
204 data = file.read(length)
205 if length & 1 == 0:
206 dummy = file.read(1)
207 return data
208
209_HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
210
211def _read_float(f): # 10 bytes
212 import math
213 expon = _read_short(f) # 2 bytes
214 sign = 1
215 if expon < 0:
216 sign = -1
217 expon = expon + 0x8000
218 himant = _read_ulong(f) # 4 bytes
219 lomant = _read_ulong(f) # 4 bytes
220 if expon == himant == lomant == 0:
221 f = 0.0
222 elif expon == 0x7FFF:
223 f = _HUGE_VAL
224 else:
225 expon = expon - 16383
226 f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63)
227 return sign * f
228
229def _write_short(f, x):
230 d, m = divmod(x, 256)
231 f.write(chr(d))
232 f.write(chr(m))
233
234def _write_long(f, x):
235 if x < 0:
236 x = x + 0x100000000L
237 data = []
238 for i in range(4):
239 d, m = divmod(x, 256)
240 data.insert(0, m)
241 x = d
242 for i in range(4):
243 f.write(chr(int(data[i])))
244
245def _write_string(f, s):
246 f.write(chr(len(s)))
247 f.write(s)
248 if len(s) & 1 == 0:
249 f.write(chr(0))
250
251def _write_float(f, x):
252 import math
253 if x < 0:
254 sign = 0x8000
255 x = x * -1
256 else:
257 sign = 0
258 if x == 0:
259 expon = 0
260 himant = 0
261 lomant = 0
262 else:
263 fmant, expon = math.frexp(x)
264 if expon > 16384 or fmant >= 1: # Infinity or NaN
265 expon = sign|0x7FFF
266 himant = 0
267 lomant = 0
268 else: # Finite
269 expon = expon + 16382
270 if expon < 0: # denormalized
271 fmant = math.ldexp(fmant, expon)
272 expon = 0
273 expon = expon | sign
274 fmant = math.ldexp(fmant, 32)
275 fsmant = math.floor(fmant)
276 himant = long(fsmant)
277 fmant = math.ldexp(fmant - fsmant, 32)
278 fsmant = math.floor(fmant)
279 lomant = long(fsmant)
280 _write_short(f, expon)
281 _write_long(f, himant)
282 _write_long(f, lomant)
283
284class Chunk():
285 def init(self, file):
286 self.file = file
287 self.chunkname = self.file.read(4)
288 if len(self.chunkname) < 4:
289 raise EOFError
290 self.chunksize = _read_long(self.file)
291 self.size_read = 0
292 self.offset = self.file.tell()
293 return self
294
295 def rewind(self):
296 self.file.seek(self.offset, 0)
297 self.size_read = 0
298
299 def setpos(self, pos):
300 if pos < 0 or pos > self.chunksize:
301 raise RuntimeError
302 self.file.seek(self.offset + pos, 0)
303 self.size_read = pos
304
305 def read(self, length):
306 if self.size_read >= self.chunksize:
307 return ''
308 if length > self.chunksize - self.size_read:
309 length = self.chunksize - self.size_read
310 data = self.file.read(length)
311 self.size_read = self.size_read + len(data)
312 return data
313
314 def skip(self):
315 try:
316 self.file.seek(self.chunksize - self.size_read, 1)
317 except RuntimeError:
318 while self.size_read < self.chunksize:
319 dummy = self.read(8192)
320 if not dummy:
321 raise EOFError
322 if self.chunksize & 1:
323 dummy = self.read(1)
324
325class Aifc_read():
326 # Variables used in this class:
327 #
328 # These variables are available to the user though appropriate
329 # methods of this class:
330 # _file -- the open file with methods read(), close(), and seek()
331 # set through the init() ir initfp() method
332 # _nchannels -- the number of audio channels
333 # available through the getnchannels() method
334 # _nframes -- the number of audio frames
335 # available through the getnframes() method
336 # _sampwidth -- the number of bytes per audio sample
337 # available through the getsampwidth() method
338 # _framerate -- the sampling frequency
339 # available through the getframerate() method
340 # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
341 # available through the getcomptype() method
342 # _compname -- the human-readable AIFF-C compression type
343 # available through the getcomptype() method
344 # _markers -- the marks in the audio file
345 # available through the getmarkers() and getmark()
346 # methods
347 # _soundpos -- the position in the audio stream
348 # available through the tell() method, set through the
349 # tell() method
350 #
351 # These variables are used internally only:
352 # _version -- the AIFF-C version number
353 # _decomp -- the decompressor from builtin module cl
354 # _comm_chunk_read -- 1 iff the COMM chunk has been read
355 # _aifc -- 1 iff reading an AIFF-C file
356 # _ssnd_seek_needed -- 1 iff positioned correctly in audio
357 # file for readframes()
358 # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000359 # _framesize -- size of one frame in the file
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000360 def initfp(self, file):
361 self._file = file
362 self._version = 0
363 self._decomp = None
364 self._markers = []
365 self._soundpos = 0
366 form = self._file.read(4)
367 if form != 'FORM':
368 raise Error, 'file does not start with FORM id'
369 formlength = _read_long(self._file)
370 if formlength <= 0:
371 raise Error, 'invalid FORM chunk data size'
372 formdata = self._file.read(4)
373 formlength = formlength - 4
374 if formdata == 'AIFF':
375 self._aifc = 0
376 elif formdata == 'AIFC':
377 self._aifc = 1
378 else:
379 raise Error, 'not an AIFF or AIFF-C file'
380 self._comm_chunk_read = 0
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000381 while formlength > 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000382 self._ssnd_seek_needed = 1
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000383 #DEBUG: SGI's soundfiler has a bug. There should
384 # be no need to check for EOF here.
385 try:
386 chunk = Chunk().init(self._file)
387 except EOFError:
388 if formlength == 8:
389 print 'Warning: FORM chunk size too large'
390 formlength = 0
391 break
392 raise EOFError # different error, raise exception
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000393 formlength = formlength - 8 - chunk.chunksize
394 if chunk.chunksize & 1:
395 formlength = formlength - 1
396 if chunk.chunkname == 'COMM':
397 self._read_comm_chunk(chunk)
398 self._comm_chunk_read = 1
399 elif chunk.chunkname == 'SSND':
400 self._ssnd_chunk = chunk
401 dummy = chunk.read(8)
402 self._ssnd_seek_needed = 0
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000403 elif chunk.chunkname == 'FVER':
404 self._version = _read_long(chunk)
405 elif chunk.chunkname == 'MARK':
406 self._readmark(chunk)
407 elif chunk.chunkname in _skiplist:
408 pass
409 else:
410 raise Error, 'unrecognized chunk type '+chunk.chunkname
Sjoerd Mullender93f07401993-01-26 09:24:37 +0000411 if formlength > 0:
412 chunk.skip()
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000413 if not self._comm_chunk_read or not self._ssnd_chunk:
414 raise Error, 'COMM chunk and/or SSND chunk missing'
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000415 if self._aifc and self._decomp:
416 params = [CL.ORIGINAL_FORMAT, 0, \
417 CL.BITS_PER_COMPONENT, 0, \
418 CL.FRAME_RATE, self._framerate]
419 if self._nchannels == AL.MONO:
420 params[1] = CL.MONO
421 else:
422 params[1] = CL.STEREO_INTERLEAVED
423 if self._sampwidth == AL.SAMPLE_8:
424 params[3] = 8
425 elif self._sampwidth == AL.SAMPLE_16:
426 params[3] = 16
427 else:
428 params[3] = 24
429 self._decomp.SetParams(params)
430 return self
431
432 def init(self, filename):
433 return self.initfp(builtin.open(filename, 'r'))
434
435 #
436 # User visible methods.
437 #
438 def getfp(self):
439 return self._file
440
441 def rewind(self):
442 self._ssnd_seek_needed = 1
443 self._soundpos = 0
444
445 def close(self):
446 if self._decomp:
447 self._decomp.CloseDecompressor()
448 self._decomp = None
449 self._file.close()
450 self._file = None
451
452 def tell(self):
453 return self._soundpos
454
455 def getnchannels(self):
456 return self._nchannels
457
458 def getnframes(self):
459 return self._nframes
460
461 def getsampwidth(self):
462 return self._sampwidth
463
464 def getframerate(self):
465 return self._framerate
466
467 def getcomptype(self):
468 return self._comptype
469
470 def getcompname(self):
471 return self._compname
472
473## def getversion(self):
474## return self._version
475
476 def getparams(self):
477 return self._nchannels, self._sampwidth, self._framerate, \
478 self._nframes, self._comptype, self._compname
479
480 def getmarkers(self):
481 if len(self._markers) == 0:
482 return None
483 return self._markers
484
485 def getmark(self, id):
486 for marker in self._markers:
487 if id == marker[0]:
488 return marker
489 raise Error, 'marker ' + `id` + ' does not exist'
490
491 def setpos(self, pos):
492 if pos < 0 or pos > self._nframes:
493 raise Error, 'position not in range'
494 self._soundpos = pos
495 self._ssnd_seek_needed = 1
496
497 def readframes(self, nframes):
498 if self._ssnd_seek_needed:
499 self._ssnd_chunk.rewind()
500 dummy = self._ssnd_chunk.read(8)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000501 pos = self._soundpos * self._framesize
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000502 if pos:
503 self._ssnd_chunk.setpos(pos + 8)
504 self._ssnd_seek_needed = 0
Sjoerd Mullender8d733a01993-01-29 12:01:00 +0000505 if nframes == 0:
506 return ''
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000507 data = self._ssnd_chunk.read(nframes * self._framesize)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000508 if self._decomp and data:
Sjoerd Mullender4ab6ff81993-02-05 13:43:44 +0000509 dummy = self._decomp.SetParam(CL.FRAME_BUFFER_SIZE, \
510 len(data) * 2)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000511 data = self._decomp.Decompress(len(data) / self._nchannels, data)
512 self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth)
513 return data
514
515 #
516 # Internal methods.
517 #
518 def _read_comm_chunk(self, chunk):
519 nchannels = _read_short(chunk)
520 self._nchannels = _convert1(nchannels, _nchannelslist)
521 self._nframes = _read_long(chunk)
522 sampwidth = _read_short(chunk)
523 self._sampwidth = _convert1(sampwidth, _sampwidthlist)
524 framerate = _read_float(chunk)
525 self._framerate = _convert1(framerate, _frameratelist)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000526 self._framesize = self._nchannels * self._sampwidth
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000527 if self._aifc:
528 #DEBUG: SGI's soundeditor produces a bad size :-(
529 kludge = 0
530 if chunk.chunksize == 18:
531 kludge = 1
532 print 'Warning: bad COMM chunk size'
533 chunk.chunksize = 23
534 #DEBUG end
535 self._comptype = chunk.read(4)
536 #DEBUG start
537 if kludge:
538 length = ord(chunk.file.read(1))
539 if length & 1 == 0:
540 length = length + 1
541 chunk.chunksize = chunk.chunksize + length
542 chunk.file.seek(-1, 1)
543 #DEBUG end
544 self._compname = _read_string(chunk)
545 if self._comptype != 'NONE':
546 try:
547 import cl, CL
548 except ImportError:
549 raise Error, 'cannot read compressed AIFF-C files'
550 if self._comptype == 'ULAW':
551 scheme = CL.G711_ULAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000552 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000553 elif self._comptype == 'ALAW':
554 scheme = CL.G711_ALAW
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000555 self._framesize = self._framesize / 2
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000556 else:
557 raise Error, 'unsupported compression type'
558 self._decomp = cl.OpenDecompressor(scheme)
559 else:
560 self._comptype = 'NONE'
561 self._compname = 'not compressed'
562
563 def _readmark(self, chunk):
564 nmarkers = _read_short(chunk)
565 for i in range(nmarkers):
566 id = _read_short(chunk)
567 pos = _read_long(chunk)
568 name = _read_string(chunk)
569 self._markers.append((id, pos, name))
570
571class Aifc_write():
572 # Variables used in this class:
573 #
574 # These variables are user settable through appropriate methods
575 # of this class:
576 # _file -- the open file with methods write(), close(), tell(), seek()
577 # set through the init() or initfp() method
578 # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
579 # set through the setcomptype() or setparams() method
580 # _compname -- the human-readable AIFF-C compression type
581 # set through the setcomptype() or setparams() method
582 # _nchannels -- the number of audio channels
583 # set through the setnchannels() or setparams() method
584 # _sampwidth -- the number of bytes per audio sample
585 # set through the setsampwidth() or setparams() method
586 # _framerate -- the sampling frequency
587 # set through the setframerate() or setparams() method
588 # _nframes -- the number of audio frames written to the header
589 # set through the setnframes() or setparams() method
590 # _aifc -- whether we're writing an AIFF-C file or an AIFF file
591 # set through the aifc() method, reset through the
592 # aiff() method
593 #
594 # These variables are used internally only:
595 # _version -- the AIFF-C version number
596 # _comp -- the compressor from builtin module cl
597 # _nframeswritten -- the number of audio frames actually written
598 # _datalength -- the size of the audio samples written to the header
599 # _datawritten -- the size of the audio samples actually written
600
601 def init(self, filename):
602 self = self.initfp(builtin.open(filename, 'w'))
603 if filename[-5:] == '.aiff':
604 self._aifc = 0
605 else:
606 self._aifc = 1
607 return self
608
609 def initfp(self, file):
610 self._file = file
611 self._version = _AIFC_version
612 self._comptype = 'NONE'
613 self._compname = 'not compressed'
614 self._comp = None
615 self._nchannels = 0
616 self._sampwidth = 0
617 self._framerate = 0
618 self._nframes = 0
619 self._nframeswritten = 0
620 self._datawritten = 0
621 self._markers = []
622 self._marklength = 0
623 self._aifc = 1 # AIFF-C is default
624 return self
625
626 #
627 # User visible methods.
628 #
629 def aiff(self):
630 if self._nframeswritten:
631 raise Error, 'cannot change parameters after starting to write'
632 self._aifc = 0
633
634 def aifc(self):
635 if self._nframeswritten:
636 raise Error, 'cannot change parameters after starting to write'
637 self._aifc = 1
638
639 def setnchannels(self, nchannels):
640 if self._nframeswritten:
641 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender4ab6ff81993-02-05 13:43:44 +0000642 dummy = _convert2(nchannels, _nchannelslist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000643 self._nchannels = nchannels
644
645 def getnchannels(self):
646 if not self._nchannels:
647 raise Error, 'number of channels not set'
648 return self._nchannels
649
650 def setsampwidth(self, sampwidth):
651 if self._nframeswritten:
652 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000653 dummy = _convert2(sampwidth, _sampwidthlist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000654 self._sampwidth = sampwidth
655
656 def getsampwidth(self):
657 if not self._sampwidth:
658 raise Error, 'sample width not set'
659 return self._sampwidth
660
661 def setframerate(self, framerate):
662 if self._nframeswritten:
663 raise Error, 'cannot change parameters after starting to write'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000664 dummy = _convert2(framerate, _frameratelist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000665 self._framerate = framerate
666
667 def getframerate(self):
668 if not self._framerate:
669 raise Error, 'frame rate not set'
670 return self._framerate
671
672 def setnframes(self, nframes):
673 if self._nframeswritten:
674 raise Error, 'cannot change parameters after starting to write'
675 self._nframes = nframes
676
677 def getnframes(self):
678 return self._nframeswritten
679
680 def setcomptype(self, comptype, compname):
681 if self._nframeswritten:
682 raise Error, 'cannot change parameters after starting to write'
683 if comptype not in ('NONE', 'ULAW', 'ALAW'):
684 raise Error, 'unsupported compression type'
685 self._comptype = comptype
686 self._compname = compname
687
688 def getcomptype(self):
689 return self._comptype
690
691 def getcompname(self):
692 return self._compname
693
694## def setversion(self, version):
695## if self._nframeswritten:
696## raise Error, 'cannot change parameters after starting to write'
697## self._version = version
698
699 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
700 if self._nframeswritten:
701 raise Error, 'cannot change parameters after starting to write'
702 if comptype not in ('NONE', 'ULAW', 'ALAW'):
703 raise Error, 'unsupported compression type'
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000704 dummy = _convert2(nchannels, _nchannelslist)
705 dummy = _convert2(sampwidth, _sampwidthlist)
706 dummy = _convert2(framerate, _frameratelist)
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000707 self._nchannels = nchannels
708 self._sampwidth = sampwidth
709 self._framerate = framerate
710 self._nframes = nframes
711 self._comptype = comptype
712 self._compname = compname
713
714 def getparams(self):
715 if not self._nchannels or not self._sampwidth or not self._framerate:
716 raise Error, 'not all parameters set'
717 return self._nchannels, self._sampwidth, self._framerate, \
718 self._nframes, self._comptype, self._compname
719
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000720 def setmark(self, id, pos, name):
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000721 if id <= 0:
722 raise Error, 'marker ID must be > 0'
723 if pos < 0:
724 raise Error, 'marker position must be >= 0'
725 if type(name) != type(''):
726 raise Error, 'marker name must be a string'
727 for i in range(len(self._markers)):
728 if id == self._markers[i][0]:
729 self._markers[i] = id, pos, name
730 return
731 self._markers.append((id, pos, name))
732
733 def getmark(self, id):
734 for marker in self._markers:
735 if id == marker[0]:
736 return marker
737 raise Error, 'marker ' + `id` + ' does not exist'
738
739 def getmarkers(self):
740 if len(self._markers) == 0:
741 return None
742 return self._markers
743
744 def writeframesraw(self, data):
745 if not self._nframeswritten:
746 if self._comptype in ('ULAW', 'ALAW'):
747 if not self._sampwidth:
748 self._sampwidth = AL.SAMPLE_16
749 if self._sampwidth != AL.SAMPLE_16:
750 raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
751 if not self._nchannels:
752 raise Error, '# channels not specified'
753 if not self._sampwidth:
754 raise Error, 'sample width not specified'
755 if not self._framerate:
756 raise Error, 'sampling rate not specified'
757 self._write_header(len(data))
758 nframes = len(data) / (self._sampwidth * self._nchannels)
759 if self._comp:
Sjoerd Mullender4ab6ff81993-02-05 13:43:44 +0000760 dummy = self._comp.SetParam(CL.FRAME_BUFFER_SIZE, \
761 len(data))
762 dummy = self._comp.SetParam(CL.COMPRESSED_BUFFER_SIZE,\
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000763 len(data))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000764 data = self._comp.Compress(nframes, data)
765 self._file.write(data)
766 self._nframeswritten = self._nframeswritten + nframes
767 self._datawritten = self._datawritten + len(data)
768
769 def writeframes(self, data):
770 self.writeframesraw(data)
771 if self._nframeswritten != self._nframes or \
772 self._datalength != self._datawritten:
773 self._patchheader()
774
775 def close(self):
776 if self._datawritten & 1:
777 # quick pad to even size
778 self._file.write(chr(0))
779 self._datawritten = self._datawritten + 1
780 self._writemarkers()
781 if self._nframeswritten != self._nframes or \
782 self._datalength != self._datawritten or \
783 self._marklength:
784 self._patchheader()
785 if self._comp:
786 self._comp.CloseCompressor()
787 self._comp = None
788 self._file.close()
789 self._file = None
790
791 #
792 # Internal methods.
793 #
794 def _write_header(self, initlength):
795 if self._aifc and self._comptype != 'NONE':
796 try:
797 import cl, CL
798 except ImportError:
799 raise Error, 'cannot write compressed AIFF-C files'
800 if self._comptype == 'ULAW':
801 scheme = CL.G711_ULAW
802 elif self._comptype == 'ALAW':
803 scheme = CL.G711_ALAW
804 else:
805 raise Error, 'unsupported compression type'
806 self._comp = cl.OpenCompressor(scheme)
807 params = [CL.ORIGINAL_FORMAT, 0, \
808 CL.BITS_PER_COMPONENT, 0, \
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000809 CL.FRAME_RATE, self._framerate, \
810 CL.FRAME_BUFFER_SIZE, 100, \
811 CL.COMPRESSED_BUFFER_SIZE, 100]
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000812 if self._nchannels == AL.MONO:
813 params[1] = CL.MONO
814 else:
815 params[1] = CL.STEREO_INTERLEAVED
816 if self._sampwidth == AL.SAMPLE_8:
817 params[3] = 8
818 elif self._sampwidth == AL.SAMPLE_16:
819 params[3] = 16
820 else:
821 params[3] = 24
822 self._comp.SetParams(params)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000823 # the compressor produces a header which we ignore
824 dummy = self._comp.Compress(0, '')
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000825 self._file.write('FORM')
826 if not self._nframes:
827 self._nframes = initlength / (self._nchannels * self._sampwidth)
828 self._datalength = self._nframes * self._nchannels * self._sampwidth
829 if self._datalength & 1:
830 self._datalength = self._datalength + 1
831 if self._aifc and self._comptype in ('ULAW', 'ALAW'):
832 self._datalength = self._datalength / 2
833 if self._datalength & 1:
834 self._datalength = self._datalength + 1
835 self._form_length_pos = self._file.tell()
836 commlength = self._write_form_length(self._datalength)
837 if self._aifc:
838 self._file.write('AIFC')
839 self._file.write('FVER')
840 _write_long(self._file, 4)
841 _write_long(self._file, self._version)
842 else:
843 self._file.write('AIFF')
844 self._file.write('COMM')
845 _write_long(self._file, commlength)
Sjoerd Mullender3a997271993-02-04 16:43:28 +0000846 _write_short(self._file, _convert2(self._nchannels, _nchannelslist))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000847 self._nframes_pos = self._file.tell()
848 _write_long(self._file, self._nframes)
849 _write_short(self._file, _convert2(self._sampwidth, _sampwidthlist))
850 _write_float(self._file, _convert2(self._framerate, _frameratelist))
851 if self._aifc:
852 self._file.write(self._comptype)
853 _write_string(self._file, self._compname)
854 self._file.write('SSND')
855 self._ssnd_length_pos = self._file.tell()
856 _write_long(self._file, self._datalength + 8)
857 _write_long(self._file, 0)
858 _write_long(self._file, 0)
859
860 def _write_form_length(self, datalength):
861 if self._aifc:
862 commlength = 18 + 5 + len(self._compname)
863 if commlength & 1:
864 commlength = commlength + 1
865 verslength = 12
866 else:
867 commlength = 18
868 verslength = 0
869 _write_long(self._file, 4 + verslength + self._marklength + \
870 8 + commlength + 16 + datalength)
871 return commlength
872
873 def _patchheader(self):
874 curpos = self._file.tell()
875 if self._datawritten & 1:
876 datalength = self._datawritten + 1
877 self._file.write(chr(0))
878 else:
879 datalength = self._datawritten
880 if datalength == self._datalength and \
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000881 self._nframes == self._nframeswritten and \
882 self._marklength == 0:
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000883 self._file.seek(curpos, 0)
884 return
885 self._file.seek(self._form_length_pos, 0)
886 dummy = self._write_form_length(datalength)
887 self._file.seek(self._nframes_pos, 0)
888 _write_long(self._file, self._nframeswritten)
889 self._file.seek(self._ssnd_length_pos, 0)
890 _write_long(self._file, datalength + 8)
891 self._file.seek(curpos, 0)
892 self._nframes = self._nframeswritten
893 self._datalength = datalength
894
895 def _writemarkers(self):
896 if len(self._markers) == 0:
897 return
898 self._file.write('MARK')
899 length = 2
900 for marker in self._markers:
901 id, pos, name = marker
902 length = length + len(name) + 1 + 6
903 if len(name) & 1 == 0:
904 length = length + 1
905 _write_long(self._file, length)
906 self._marklength = length + 8
Sjoerd Mullender7564a641993-01-22 14:26:28 +0000907 _write_short(self._file, len(self._markers))
Sjoerd Mullendereeabe7e1993-01-22 12:53:11 +0000908 for marker in self._markers:
909 id, pos, name = marker
910 _write_short(self._file, id)
911 _write_long(self._file, pos)
912 _write_string(self._file, name)
913
914def open(filename, mode):
915 if mode == 'r':
916 return Aifc_read().init(filename)
917 elif mode == 'w':
918 return Aifc_write().init(filename)
919 else:
920 raise Error, 'mode must be \'r\' or \'w\''
921
922def openfp(filep, mode):
923 if mode == 'r':
924 return Aifc_read().initfp(filep)
925 elif mode == 'w':
926 return Aifc_write().initfp(filep)
927 else:
928 raise Error, 'mode must be \'r\' or \'w\''