blob: 72c1b23cd3a977f6c0b0838709672d1485b81412 [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
359 def initfp(self, file):
360 self._file = file
361 self._version = 0
362 self._decomp = None
363 self._markers = []
364 self._soundpos = 0
365 form = self._file.read(4)
366 if form != 'FORM':
367 raise Error, 'file does not start with FORM id'
368 formlength = _read_long(self._file)
369 if formlength <= 0:
370 raise Error, 'invalid FORM chunk data size'
371 formdata = self._file.read(4)
372 formlength = formlength - 4
373 if formdata == 'AIFF':
374 self._aifc = 0
375 elif formdata == 'AIFC':
376 self._aifc = 1
377 else:
378 raise Error, 'not an AIFF or AIFF-C file'
379 self._comm_chunk_read = 0
380 while 1:
381 self._ssnd_seek_needed = 1
382 try:
383 chunk = Chunk().init(self._file)
384 except EOFError:
385 raise Error, 'COMM chunk and/or SSND chunk missing'
386 formlength = formlength - 8 - chunk.chunksize
387 if chunk.chunksize & 1:
388 formlength = formlength - 1
389 if chunk.chunkname == 'COMM':
390 self._read_comm_chunk(chunk)
391 self._comm_chunk_read = 1
392 elif chunk.chunkname == 'SSND':
393 self._ssnd_chunk = chunk
394 dummy = chunk.read(8)
395 self._ssnd_seek_needed = 0
396 if formlength <= 0:
397 if not self._comm_chunk_read:
398 raise Error, 'COMM chunk missing'
399 break
400 elif chunk.chunkname == 'FVER':
401 self._version = _read_long(chunk)
402 elif chunk.chunkname == 'MARK':
403 self._readmark(chunk)
404 elif chunk.chunkname in _skiplist:
405 pass
406 else:
407 raise Error, 'unrecognized chunk type '+chunk.chunkname
408 chunk.skip()
409 if self._aifc and self._decomp:
410 params = [CL.ORIGINAL_FORMAT, 0, \
411 CL.BITS_PER_COMPONENT, 0, \
412 CL.FRAME_RATE, self._framerate]
413 if self._nchannels == AL.MONO:
414 params[1] = CL.MONO
415 else:
416 params[1] = CL.STEREO_INTERLEAVED
417 if self._sampwidth == AL.SAMPLE_8:
418 params[3] = 8
419 elif self._sampwidth == AL.SAMPLE_16:
420 params[3] = 16
421 else:
422 params[3] = 24
423 self._decomp.SetParams(params)
424 return self
425
426 def init(self, filename):
427 return self.initfp(builtin.open(filename, 'r'))
428
429 #
430 # User visible methods.
431 #
432 def getfp(self):
433 return self._file
434
435 def rewind(self):
436 self._ssnd_seek_needed = 1
437 self._soundpos = 0
438
439 def close(self):
440 if self._decomp:
441 self._decomp.CloseDecompressor()
442 self._decomp = None
443 self._file.close()
444 self._file = None
445
446 def tell(self):
447 return self._soundpos
448
449 def getnchannels(self):
450 return self._nchannels
451
452 def getnframes(self):
453 return self._nframes
454
455 def getsampwidth(self):
456 return self._sampwidth
457
458 def getframerate(self):
459 return self._framerate
460
461 def getcomptype(self):
462 return self._comptype
463
464 def getcompname(self):
465 return self._compname
466
467## def getversion(self):
468## return self._version
469
470 def getparams(self):
471 return self._nchannels, self._sampwidth, self._framerate, \
472 self._nframes, self._comptype, self._compname
473
474 def getmarkers(self):
475 if len(self._markers) == 0:
476 return None
477 return self._markers
478
479 def getmark(self, id):
480 for marker in self._markers:
481 if id == marker[0]:
482 return marker
483 raise Error, 'marker ' + `id` + ' does not exist'
484
485 def setpos(self, pos):
486 if pos < 0 or pos > self._nframes:
487 raise Error, 'position not in range'
488 self._soundpos = pos
489 self._ssnd_seek_needed = 1
490
491 def readframes(self, nframes):
492 if self._ssnd_seek_needed:
493 self._ssnd_chunk.rewind()
494 dummy = self._ssnd_chunk.read(8)
495 pos = self._soundpos * self._nchannels * self._sampwidth
496 if self._decomp:
497 if self._comptype in ('ULAW', 'ALAW'):
498 pos = pos / 2
499 if pos:
500 self._ssnd_chunk.setpos(pos + 8)
501 self._ssnd_seek_needed = 0
502 size = nframes * self._nchannels * self._sampwidth
503 if self._decomp:
504 if self._comptype in ('ULAW', 'ALAW'):
505 size = size / 2
506 data = self._ssnd_chunk.read(size)
507 if self._decomp and data:
508 params = [CL.FRAME_BUFFER_SIZE, len(data) * 2]
509 self._decomp.SetParams(params)
510 data = self._decomp.Decompress(len(data) / self._nchannels, data)
511 self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth)
512 return data
513
514 #
515 # Internal methods.
516 #
517 def _read_comm_chunk(self, chunk):
518 nchannels = _read_short(chunk)
519 self._nchannels = _convert1(nchannels, _nchannelslist)
520 self._nframes = _read_long(chunk)
521 sampwidth = _read_short(chunk)
522 self._sampwidth = _convert1(sampwidth, _sampwidthlist)
523 framerate = _read_float(chunk)
524 self._framerate = _convert1(framerate, _frameratelist)
525 if self._aifc:
526 #DEBUG: SGI's soundeditor produces a bad size :-(
527 kludge = 0
528 if chunk.chunksize == 18:
529 kludge = 1
530 print 'Warning: bad COMM chunk size'
531 chunk.chunksize = 23
532 #DEBUG end
533 self._comptype = chunk.read(4)
534 #DEBUG start
535 if kludge:
536 length = ord(chunk.file.read(1))
537 if length & 1 == 0:
538 length = length + 1
539 chunk.chunksize = chunk.chunksize + length
540 chunk.file.seek(-1, 1)
541 #DEBUG end
542 self._compname = _read_string(chunk)
543 if self._comptype != 'NONE':
544 try:
545 import cl, CL
546 except ImportError:
547 raise Error, 'cannot read compressed AIFF-C files'
548 if self._comptype == 'ULAW':
549 scheme = CL.G711_ULAW
550 elif self._comptype == 'ALAW':
551 scheme = CL.G711_ALAW
552 else:
553 raise Error, 'unsupported compression type'
554 self._decomp = cl.OpenDecompressor(scheme)
555 else:
556 self._comptype = 'NONE'
557 self._compname = 'not compressed'
558
559 def _readmark(self, chunk):
560 nmarkers = _read_short(chunk)
561 for i in range(nmarkers):
562 id = _read_short(chunk)
563 pos = _read_long(chunk)
564 name = _read_string(chunk)
565 self._markers.append((id, pos, name))
566
567class Aifc_write():
568 # Variables used in this class:
569 #
570 # These variables are user settable through appropriate methods
571 # of this class:
572 # _file -- the open file with methods write(), close(), tell(), seek()
573 # set through the init() or initfp() method
574 # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
575 # set through the setcomptype() or setparams() method
576 # _compname -- the human-readable AIFF-C compression type
577 # set through the setcomptype() or setparams() method
578 # _nchannels -- the number of audio channels
579 # set through the setnchannels() or setparams() method
580 # _sampwidth -- the number of bytes per audio sample
581 # set through the setsampwidth() or setparams() method
582 # _framerate -- the sampling frequency
583 # set through the setframerate() or setparams() method
584 # _nframes -- the number of audio frames written to the header
585 # set through the setnframes() or setparams() method
586 # _aifc -- whether we're writing an AIFF-C file or an AIFF file
587 # set through the aifc() method, reset through the
588 # aiff() method
589 #
590 # These variables are used internally only:
591 # _version -- the AIFF-C version number
592 # _comp -- the compressor from builtin module cl
593 # _nframeswritten -- the number of audio frames actually written
594 # _datalength -- the size of the audio samples written to the header
595 # _datawritten -- the size of the audio samples actually written
596
597 def init(self, filename):
598 self = self.initfp(builtin.open(filename, 'w'))
599 if filename[-5:] == '.aiff':
600 self._aifc = 0
601 else:
602 self._aifc = 1
603 return self
604
605 def initfp(self, file):
606 self._file = file
607 self._version = _AIFC_version
608 self._comptype = 'NONE'
609 self._compname = 'not compressed'
610 self._comp = None
611 self._nchannels = 0
612 self._sampwidth = 0
613 self._framerate = 0
614 self._nframes = 0
615 self._nframeswritten = 0
616 self._datawritten = 0
617 self._markers = []
618 self._marklength = 0
619 self._aifc = 1 # AIFF-C is default
620 return self
621
622 #
623 # User visible methods.
624 #
625 def aiff(self):
626 if self._nframeswritten:
627 raise Error, 'cannot change parameters after starting to write'
628 self._aifc = 0
629
630 def aifc(self):
631 if self._nframeswritten:
632 raise Error, 'cannot change parameters after starting to write'
633 self._aifc = 1
634
635 def setnchannels(self, nchannels):
636 if self._nframeswritten:
637 raise Error, 'cannot change parameters after starting to write'
638 self._nchannels = nchannels
639
640 def getnchannels(self):
641 if not self._nchannels:
642 raise Error, 'number of channels not set'
643 return self._nchannels
644
645 def setsampwidth(self, sampwidth):
646 if self._nframeswritten:
647 raise Error, 'cannot change parameters after starting to write'
648 self._sampwidth = sampwidth
649
650 def getsampwidth(self):
651 if not self._sampwidth:
652 raise Error, 'sample width not set'
653 return self._sampwidth
654
655 def setframerate(self, framerate):
656 if self._nframeswritten:
657 raise Error, 'cannot change parameters after starting to write'
658 self._framerate = framerate
659
660 def getframerate(self):
661 if not self._framerate:
662 raise Error, 'frame rate not set'
663 return self._framerate
664
665 def setnframes(self, nframes):
666 if self._nframeswritten:
667 raise Error, 'cannot change parameters after starting to write'
668 self._nframes = nframes
669
670 def getnframes(self):
671 return self._nframeswritten
672
673 def setcomptype(self, comptype, compname):
674 if self._nframeswritten:
675 raise Error, 'cannot change parameters after starting to write'
676 if comptype not in ('NONE', 'ULAW', 'ALAW'):
677 raise Error, 'unsupported compression type'
678 self._comptype = comptype
679 self._compname = compname
680
681 def getcomptype(self):
682 return self._comptype
683
684 def getcompname(self):
685 return self._compname
686
687## def setversion(self, version):
688## if self._nframeswritten:
689## raise Error, 'cannot change parameters after starting to write'
690## self._version = version
691
692 def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
693 if self._nframeswritten:
694 raise Error, 'cannot change parameters after starting to write'
695 if comptype not in ('NONE', 'ULAW', 'ALAW'):
696 raise Error, 'unsupported compression type'
697 self._nchannels = nchannels
698 self._sampwidth = sampwidth
699 self._framerate = framerate
700 self._nframes = nframes
701 self._comptype = comptype
702 self._compname = compname
703
704 def getparams(self):
705 if not self._nchannels or not self._sampwidth or not self._framerate:
706 raise Error, 'not all parameters set'
707 return self._nchannels, self._sampwidth, self._framerate, \
708 self._nframes, self._comptype, self._compname
709
710 def setmark(self, (id, pos, name)):
711 if id <= 0:
712 raise Error, 'marker ID must be > 0'
713 if pos < 0:
714 raise Error, 'marker position must be >= 0'
715 if type(name) != type(''):
716 raise Error, 'marker name must be a string'
717 for i in range(len(self._markers)):
718 if id == self._markers[i][0]:
719 self._markers[i] = id, pos, name
720 return
721 self._markers.append((id, pos, name))
722
723 def getmark(self, id):
724 for marker in self._markers:
725 if id == marker[0]:
726 return marker
727 raise Error, 'marker ' + `id` + ' does not exist'
728
729 def getmarkers(self):
730 if len(self._markers) == 0:
731 return None
732 return self._markers
733
734 def writeframesraw(self, data):
735 if not self._nframeswritten:
736 if self._comptype in ('ULAW', 'ALAW'):
737 if not self._sampwidth:
738 self._sampwidth = AL.SAMPLE_16
739 if self._sampwidth != AL.SAMPLE_16:
740 raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
741 if not self._nchannels:
742 raise Error, '# channels not specified'
743 if not self._sampwidth:
744 raise Error, 'sample width not specified'
745 if not self._framerate:
746 raise Error, 'sampling rate not specified'
747 self._write_header(len(data))
748 nframes = len(data) / (self._sampwidth * self._nchannels)
749 if self._comp:
750 params = [CL.FRAME_BUFFER_SIZE, len(data), \
751 CL.COMPRESSED_BUFFER_SIZE, len(data)]
752 self._comp.SetParams(params)
753 data = self._comp.Compress(nframes, data)
754 self._file.write(data)
755 self._nframeswritten = self._nframeswritten + nframes
756 self._datawritten = self._datawritten + len(data)
757
758 def writeframes(self, data):
759 self.writeframesraw(data)
760 if self._nframeswritten != self._nframes or \
761 self._datalength != self._datawritten:
762 self._patchheader()
763
764 def close(self):
765 if self._datawritten & 1:
766 # quick pad to even size
767 self._file.write(chr(0))
768 self._datawritten = self._datawritten + 1
769 self._writemarkers()
770 if self._nframeswritten != self._nframes or \
771 self._datalength != self._datawritten or \
772 self._marklength:
773 self._patchheader()
774 if self._comp:
775 self._comp.CloseCompressor()
776 self._comp = None
777 self._file.close()
778 self._file = None
779
780 #
781 # Internal methods.
782 #
783 def _write_header(self, initlength):
784 if self._aifc and self._comptype != 'NONE':
785 try:
786 import cl, CL
787 except ImportError:
788 raise Error, 'cannot write compressed AIFF-C files'
789 if self._comptype == 'ULAW':
790 scheme = CL.G711_ULAW
791 elif self._comptype == 'ALAW':
792 scheme = CL.G711_ALAW
793 else:
794 raise Error, 'unsupported compression type'
795 self._comp = cl.OpenCompressor(scheme)
796 params = [CL.ORIGINAL_FORMAT, 0, \
797 CL.BITS_PER_COMPONENT, 0, \
798 CL.FRAME_RATE, self._framerate]
799 if self._nchannels == AL.MONO:
800 params[1] = CL.MONO
801 else:
802 params[1] = CL.STEREO_INTERLEAVED
803 if self._sampwidth == AL.SAMPLE_8:
804 params[3] = 8
805 elif self._sampwidth == AL.SAMPLE_16:
806 params[3] = 16
807 else:
808 params[3] = 24
809 self._comp.SetParams(params)
810 self._file.write('FORM')
811 if not self._nframes:
812 self._nframes = initlength / (self._nchannels * self._sampwidth)
813 self._datalength = self._nframes * self._nchannels * self._sampwidth
814 if self._datalength & 1:
815 self._datalength = self._datalength + 1
816 if self._aifc and self._comptype in ('ULAW', 'ALAW'):
817 self._datalength = self._datalength / 2
818 if self._datalength & 1:
819 self._datalength = self._datalength + 1
820 self._form_length_pos = self._file.tell()
821 commlength = self._write_form_length(self._datalength)
822 if self._aifc:
823 self._file.write('AIFC')
824 self._file.write('FVER')
825 _write_long(self._file, 4)
826 _write_long(self._file, self._version)
827 else:
828 self._file.write('AIFF')
829 self._file.write('COMM')
830 _write_long(self._file, commlength)
831 _write_short(self._file, self._nchannels)
832 self._nframes_pos = self._file.tell()
833 _write_long(self._file, self._nframes)
834 _write_short(self._file, _convert2(self._sampwidth, _sampwidthlist))
835 _write_float(self._file, _convert2(self._framerate, _frameratelist))
836 if self._aifc:
837 self._file.write(self._comptype)
838 _write_string(self._file, self._compname)
839 self._file.write('SSND')
840 self._ssnd_length_pos = self._file.tell()
841 _write_long(self._file, self._datalength + 8)
842 _write_long(self._file, 0)
843 _write_long(self._file, 0)
844
845 def _write_form_length(self, datalength):
846 if self._aifc:
847 commlength = 18 + 5 + len(self._compname)
848 if commlength & 1:
849 commlength = commlength + 1
850 verslength = 12
851 else:
852 commlength = 18
853 verslength = 0
854 _write_long(self._file, 4 + verslength + self._marklength + \
855 8 + commlength + 16 + datalength)
856 return commlength
857
858 def _patchheader(self):
859 curpos = self._file.tell()
860 if self._datawritten & 1:
861 datalength = self._datawritten + 1
862 self._file.write(chr(0))
863 else:
864 datalength = self._datawritten
865 if datalength == self._datalength and \
866 self._nframes == self._nframeswritten:
867 self._file.seek(curpos, 0)
868 return
869 self._file.seek(self._form_length_pos, 0)
870 dummy = self._write_form_length(datalength)
871 self._file.seek(self._nframes_pos, 0)
872 _write_long(self._file, self._nframeswritten)
873 self._file.seek(self._ssnd_length_pos, 0)
874 _write_long(self._file, datalength + 8)
875 self._file.seek(curpos, 0)
876 self._nframes = self._nframeswritten
877 self._datalength = datalength
878
879 def _writemarkers(self):
880 if len(self._markers) == 0:
881 return
882 self._file.write('MARK')
883 length = 2
884 for marker in self._markers:
885 id, pos, name = marker
886 length = length + len(name) + 1 + 6
887 if len(name) & 1 == 0:
888 length = length + 1
889 _write_long(self._file, length)
890 self._marklength = length + 8
891 _write_short(len(self._file, markers))
892 for marker in self._markers:
893 id, pos, name = marker
894 _write_short(self._file, id)
895 _write_long(self._file, pos)
896 _write_string(self._file, name)
897
898def open(filename, mode):
899 if mode == 'r':
900 return Aifc_read().init(filename)
901 elif mode == 'w':
902 return Aifc_write().init(filename)
903 else:
904 raise Error, 'mode must be \'r\' or \'w\''
905
906def openfp(filep, mode):
907 if mode == 'r':
908 return Aifc_read().initfp(filep)
909 elif mode == 'w':
910 return Aifc_write().initfp(filep)
911 else:
912 raise Error, 'mode must be \'r\' or \'w\''