home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Lib / aifc.py < prev    next >
Text File  |  1994-02-15  |  28KB  |  968 lines

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