aifc.py 33 KB

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