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