aifc.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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, you 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. def _read_long(file):
  129. try:
  130. return struct.unpack('>l', file.read(4))[0]
  131. except struct.error:
  132. raise EOFError
  133. def _read_ulong(file):
  134. try:
  135. return struct.unpack('>L', file.read(4))[0]
  136. except struct.error:
  137. raise EOFError
  138. def _read_short(file):
  139. try:
  140. return struct.unpack('>h', file.read(2))[0]
  141. except struct.error:
  142. raise EOFError
  143. def _read_ushort(file):
  144. try:
  145. return struct.unpack('>H', file.read(2))[0]
  146. except struct.error:
  147. raise EOFError
  148. def _read_string(file):
  149. length = ord(file.read(1))
  150. if length == 0:
  151. data = ''
  152. else:
  153. data = file.read(length)
  154. if length & 1 == 0:
  155. dummy = file.read(1)
  156. return data
  157. _HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
  158. def _read_float(f): # 10 bytes
  159. expon = _read_short(f) # 2 bytes
  160. sign = 1
  161. if expon < 0:
  162. sign = -1
  163. expon = expon + 0x8000
  164. himant = _read_ulong(f) # 4 bytes
  165. lomant = _read_ulong(f) # 4 bytes
  166. if expon == himant == lomant == 0:
  167. f = 0.0
  168. elif expon == 0x7FFF:
  169. f = _HUGE_VAL
  170. else:
  171. expon = expon - 16383
  172. f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63)
  173. return sign * f
  174. def _write_short(f, x):
  175. f.write(struct.pack('>h', x))
  176. def _write_ushort(f, x):
  177. f.write(struct.pack('>H', x))
  178. def _write_long(f, x):
  179. f.write(struct.pack('>l', x))
  180. def _write_ulong(f, x):
  181. f.write(struct.pack('>L', x))
  182. def _write_string(f, s):
  183. if len(s) > 255:
  184. raise ValueError("string exceeds maximum pstring length")
  185. f.write(struct.pack('B', len(s)))
  186. f.write(s)
  187. if len(s) & 1 == 0:
  188. f.write(chr(0))
  189. def _write_float(f, x):
  190. import math
  191. if x < 0:
  192. sign = 0x8000
  193. x = x * -1
  194. else:
  195. sign = 0
  196. if x == 0:
  197. expon = 0
  198. himant = 0
  199. lomant = 0
  200. else:
  201. fmant, expon = math.frexp(x)
  202. if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN
  203. expon = sign|0x7FFF
  204. himant = 0
  205. lomant = 0
  206. else: # Finite
  207. expon = expon + 16382
  208. if expon < 0: # denormalized
  209. fmant = math.ldexp(fmant, expon)
  210. expon = 0
  211. expon = expon | sign
  212. fmant = math.ldexp(fmant, 32)
  213. fsmant = math.floor(fmant)
  214. himant = long(fsmant)
  215. fmant = math.ldexp(fmant - fsmant, 32)
  216. fsmant = math.floor(fmant)
  217. lomant = long(fsmant)
  218. _write_ushort(f, expon)
  219. _write_ulong(f, himant)
  220. _write_ulong(f, lomant)
  221. from chunk import Chunk
  222. class Aifc_read:
  223. # Variables used in this class:
  224. #
  225. # These variables are available to the user though appropriate
  226. # methods of this class:
  227. # _file -- the open file with methods read(), close(), and seek()
  228. # set through the __init__() method
  229. # _nchannels -- the number of audio channels
  230. # available through the getnchannels() method
  231. # _nframes -- the number of audio frames
  232. # available through the getnframes() method
  233. # _sampwidth -- the number of bytes per audio sample
  234. # available through the getsampwidth() method
  235. # _framerate -- the sampling frequency
  236. # available through the getframerate() method
  237. # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
  238. # available through the getcomptype() method
  239. # _compname -- the human-readable AIFF-C compression type
  240. # available through the getcomptype() method
  241. # _markers -- the marks in the audio file
  242. # available through the getmarkers() and getmark()
  243. # methods
  244. # _soundpos -- the position in the audio stream
  245. # available through the tell() method, set through the
  246. # setpos() method
  247. #
  248. # These variables are used internally only:
  249. # _version -- the AIFF-C version number
  250. # _decomp -- the decompressor from builtin module cl
  251. # _comm_chunk_read -- 1 iff the COMM chunk has been read
  252. # _aifc -- 1 iff reading an AIFF-C file
  253. # _ssnd_seek_needed -- 1 iff positioned correctly in audio
  254. # file for readframes()
  255. # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
  256. # _framesize -- size of one frame in the file
  257. def initfp(self, file):
  258. self._version = 0
  259. self._decomp = None
  260. self._convert = None
  261. self._markers = []
  262. self._soundpos = 0
  263. self._file = file
  264. chunk = Chunk(file)
  265. if chunk.getname() != 'FORM':
  266. raise Error, 'file does not start with FORM id'
  267. formdata = chunk.read(4)
  268. if formdata == 'AIFF':
  269. self._aifc = 0
  270. elif formdata == 'AIFC':
  271. self._aifc = 1
  272. else:
  273. raise Error, 'not an AIFF or AIFF-C file'
  274. self._comm_chunk_read = 0
  275. while 1:
  276. self._ssnd_seek_needed = 1
  277. try:
  278. chunk = Chunk(self._file)
  279. except EOFError:
  280. break
  281. chunkname = chunk.getname()
  282. if chunkname == 'COMM':
  283. self._read_comm_chunk(chunk)
  284. self._comm_chunk_read = 1
  285. elif chunkname == 'SSND':
  286. self._ssnd_chunk = chunk
  287. dummy = chunk.read(8)
  288. self._ssnd_seek_needed = 0
  289. elif chunkname == 'FVER':
  290. self._version = _read_ulong(chunk)
  291. elif chunkname == 'MARK':
  292. self._readmark(chunk)
  293. chunk.skip()
  294. if not self._comm_chunk_read or not self._ssnd_chunk:
  295. raise Error, 'COMM chunk and/or SSND chunk missing'
  296. if self._aifc and self._decomp:
  297. import cl
  298. params = [cl.ORIGINAL_FORMAT, 0,
  299. cl.BITS_PER_COMPONENT, self._sampwidth * 8,
  300. cl.FRAME_RATE, self._framerate]
  301. if self._nchannels == 1:
  302. params[1] = cl.MONO
  303. elif self._nchannels == 2:
  304. params[1] = cl.STEREO_INTERLEAVED
  305. else:
  306. raise Error, 'cannot compress more than 2 channels'
  307. self._decomp.SetParams(params)
  308. def __init__(self, f):
  309. if type(f) == type(''):
  310. f = __builtin__.open(f, 'rb')
  311. # else, assume it is an open file object already
  312. self.initfp(f)
  313. #
  314. # User visible methods.
  315. #
  316. def getfp(self):
  317. return self._file
  318. def rewind(self):
  319. self._ssnd_seek_needed = 1
  320. self._soundpos = 0
  321. def close(self):
  322. decomp = self._decomp
  323. try:
  324. if decomp:
  325. self._decomp = None
  326. decomp.CloseDecompressor()
  327. finally:
  328. self._file.close()
  329. def tell(self):
  330. return self._soundpos
  331. def getnchannels(self):
  332. return self._nchannels
  333. def getnframes(self):
  334. return self._nframes
  335. def getsampwidth(self):
  336. return self._sampwidth
  337. def getframerate(self):
  338. return self._framerate
  339. def getcomptype(self):
  340. return self._comptype
  341. def getcompname(self):
  342. return self._compname
  343. ## def getversion(self):
  344. ## return self._version
  345. def getparams(self):
  346. return self.getnchannels(), self.getsampwidth(), \
  347. self.getframerate(), self.getnframes(), \
  348. self.getcomptype(), self.getcompname()
  349. def getmarkers(self):
  350. if len(self._markers) == 0:
  351. return None
  352. return self._markers
  353. def getmark(self, id):
  354. for marker in self._markers:
  355. if id == marker[0]:
  356. return marker
  357. raise Error, 'marker %r does not exist' % (id,)
  358. def setpos(self, pos):
  359. if pos < 0 or pos > self._nframes:
  360. raise Error, 'position not in range'
  361. self._soundpos = pos
  362. self._ssnd_seek_needed = 1
  363. def readframes(self, nframes):
  364. if self._ssnd_seek_needed:
  365. self._ssnd_chunk.seek(0)
  366. dummy = self._ssnd_chunk.read(8)
  367. pos = self._soundpos * self._framesize
  368. if pos:
  369. self._ssnd_chunk.seek(pos + 8)
  370. self._ssnd_seek_needed = 0
  371. if nframes == 0:
  372. return ''
  373. data = self._ssnd_chunk.read(nframes * self._framesize)
  374. if self._convert and data:
  375. data = self._convert(data)
  376. self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
  377. return data
  378. #
  379. # Internal methods.
  380. #
  381. def _decomp_data(self, data):
  382. import cl
  383. dummy = self._decomp.SetParam(cl.FRAME_BUFFER_SIZE,
  384. len(data) * 2)
  385. return self._decomp.Decompress(len(data) // self._nchannels,
  386. data)
  387. def _ulaw2lin(self, data):
  388. import audioop
  389. return audioop.ulaw2lin(data, 2)
  390. def _adpcm2lin(self, data):
  391. import audioop
  392. if not hasattr(self, '_adpcmstate'):
  393. # first time
  394. self._adpcmstate = None
  395. data, self._adpcmstate = audioop.adpcm2lin(data, 2,
  396. self._adpcmstate)
  397. return data
  398. def _read_comm_chunk(self, chunk):
  399. self._nchannels = _read_short(chunk)
  400. self._nframes = _read_long(chunk)
  401. self._sampwidth = (_read_short(chunk) + 7) // 8
  402. self._framerate = int(_read_float(chunk))
  403. self._framesize = self._nchannels * self._sampwidth
  404. if self._aifc:
  405. #DEBUG: SGI's soundeditor produces a bad size :-(
  406. kludge = 0
  407. if chunk.chunksize == 18:
  408. kludge = 1
  409. print 'Warning: bad COMM chunk size'
  410. chunk.chunksize = 23
  411. #DEBUG end
  412. self._comptype = chunk.read(4)
  413. #DEBUG start
  414. if kludge:
  415. length = ord(chunk.file.read(1))
  416. if length & 1 == 0:
  417. length = length + 1
  418. chunk.chunksize = chunk.chunksize + length
  419. chunk.file.seek(-1, 1)
  420. #DEBUG end
  421. self._compname = _read_string(chunk)
  422. if self._comptype != 'NONE':
  423. if self._comptype == 'G722':
  424. try:
  425. import audioop
  426. except ImportError:
  427. pass
  428. else:
  429. self._convert = self._adpcm2lin
  430. self._sampwidth = 2
  431. return
  432. # for ULAW and ALAW try Compression Library
  433. try:
  434. import cl
  435. except ImportError:
  436. if self._comptype in ('ULAW', 'ulaw'):
  437. try:
  438. import audioop
  439. self._convert = self._ulaw2lin
  440. self._sampwidth = 2
  441. return
  442. except ImportError:
  443. pass
  444. raise Error, 'cannot read compressed AIFF-C files'
  445. if self._comptype in ('ULAW', 'ulaw'):
  446. scheme = cl.G711_ULAW
  447. elif self._comptype in ('ALAW', 'alaw'):
  448. scheme = cl.G711_ALAW
  449. else:
  450. raise Error, 'unsupported compression type'
  451. self._decomp = cl.OpenDecompressor(scheme)
  452. self._convert = self._decomp_data
  453. self._sampwidth = 2
  454. else:
  455. self._comptype = 'NONE'
  456. self._compname = 'not compressed'
  457. def _readmark(self, chunk):
  458. nmarkers = _read_short(chunk)
  459. # Some files appear to contain invalid counts.
  460. # Cope with this by testing for EOF.
  461. try:
  462. for i in range(nmarkers):
  463. id = _read_short(chunk)
  464. pos = _read_long(chunk)
  465. name = _read_string(chunk)
  466. if pos or name:
  467. # some files appear to have
  468. # dummy markers consisting of
  469. # a position 0 and name ''
  470. self._markers.append((id, pos, name))
  471. except EOFError:
  472. print 'Warning: MARK chunk contains only',
  473. print len(self._markers),
  474. if len(self._markers) == 1: print 'marker',
  475. else: print 'markers',
  476. print 'instead of', nmarkers
  477. class Aifc_write:
  478. # Variables used in this class:
  479. #
  480. # These variables are user settable through appropriate methods
  481. # of this class:
  482. # _file -- the open file with methods write(), close(), tell(), seek()
  483. # set through the __init__() method
  484. # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
  485. # set through the setcomptype() or setparams() method
  486. # _compname -- the human-readable AIFF-C compression type
  487. # set through the setcomptype() or setparams() method
  488. # _nchannels -- the number of audio channels
  489. # set through the setnchannels() or setparams() method
  490. # _sampwidth -- the number of bytes per audio sample
  491. # set through the setsampwidth() or setparams() method
  492. # _framerate -- the sampling frequency
  493. # set through the setframerate() or setparams() method
  494. # _nframes -- the number of audio frames written to the header
  495. # set through the setnframes() or setparams() method
  496. # _aifc -- whether we're writing an AIFF-C file or an AIFF file
  497. # set through the aifc() method, reset through the
  498. # aiff() method
  499. #
  500. # These variables are used internally only:
  501. # _version -- the AIFF-C version number
  502. # _comp -- the compressor from builtin module cl
  503. # _nframeswritten -- the number of audio frames actually written
  504. # _datalength -- the size of the audio samples written to the header
  505. # _datawritten -- the size of the audio samples actually written
  506. def __init__(self, f):
  507. if type(f) == type(''):
  508. filename = f
  509. f = __builtin__.open(f, 'wb')
  510. else:
  511. # else, assume it is an open file object already
  512. filename = '???'
  513. self.initfp(f)
  514. if filename[-5:] == '.aiff':
  515. self._aifc = 0
  516. else:
  517. self._aifc = 1
  518. def initfp(self, file):
  519. self._file = file
  520. self._version = _AIFC_version
  521. self._comptype = 'NONE'
  522. self._compname = 'not compressed'
  523. self._comp = None
  524. self._convert = None
  525. self._nchannels = 0
  526. self._sampwidth = 0
  527. self._framerate = 0
  528. self._nframes = 0
  529. self._nframeswritten = 0
  530. self._datawritten = 0
  531. self._datalength = 0
  532. self._markers = []
  533. self._marklength = 0
  534. self._aifc = 1 # AIFF-C is default
  535. def __del__(self):
  536. if self._file:
  537. self.close()
  538. #
  539. # User visible methods.
  540. #
  541. def aiff(self):
  542. if self._nframeswritten:
  543. raise Error, 'cannot change parameters after starting to write'
  544. self._aifc = 0
  545. def aifc(self):
  546. if self._nframeswritten:
  547. raise Error, 'cannot change parameters after starting to write'
  548. self._aifc = 1
  549. def setnchannels(self, nchannels):
  550. if self._nframeswritten:
  551. raise Error, 'cannot change parameters after starting to write'
  552. if nchannels < 1:
  553. raise Error, 'bad # of channels'
  554. self._nchannels = nchannels
  555. def getnchannels(self):
  556. if not self._nchannels:
  557. raise Error, 'number of channels not set'
  558. return self._nchannels
  559. def setsampwidth(self, sampwidth):
  560. if self._nframeswritten:
  561. raise Error, 'cannot change parameters after starting to write'
  562. if sampwidth < 1 or sampwidth > 4:
  563. raise Error, 'bad sample width'
  564. self._sampwidth = sampwidth
  565. def getsampwidth(self):
  566. if not self._sampwidth:
  567. raise Error, 'sample width not set'
  568. return self._sampwidth
  569. def setframerate(self, framerate):
  570. if self._nframeswritten:
  571. raise Error, 'cannot change parameters after starting to write'
  572. if framerate <= 0:
  573. raise Error, 'bad frame rate'
  574. self._framerate = framerate
  575. def getframerate(self):
  576. if not self._framerate:
  577. raise Error, 'frame rate not set'
  578. return self._framerate
  579. def setnframes(self, nframes):
  580. if self._nframeswritten:
  581. raise Error, 'cannot change parameters after starting to write'
  582. self._nframes = nframes
  583. def getnframes(self):
  584. return self._nframeswritten
  585. def setcomptype(self, comptype, compname):
  586. if self._nframeswritten:
  587. raise Error, 'cannot change parameters after starting to write'
  588. if comptype not in ('NONE', 'ULAW', 'ulaw', 'ALAW', 'alaw', 'G722'):
  589. raise Error, 'unsupported compression type'
  590. self._comptype = comptype
  591. self._compname = compname
  592. def getcomptype(self):
  593. return self._comptype
  594. def getcompname(self):
  595. return self._compname
  596. ## def setversion(self, version):
  597. ## if self._nframeswritten:
  598. ## raise Error, 'cannot change parameters after starting to write'
  599. ## self._version = version
  600. def setparams(self, info):
  601. nchannels, sampwidth, framerate, nframes, comptype, compname = info
  602. if self._nframeswritten:
  603. raise Error, 'cannot change parameters after starting to write'
  604. if comptype not in ('NONE', 'ULAW', 'ulaw', 'ALAW', 'alaw', 'G722'):
  605. raise Error, 'unsupported compression type'
  606. self.setnchannels(nchannels)
  607. self.setsampwidth(sampwidth)
  608. self.setframerate(framerate)
  609. self.setnframes(nframes)
  610. self.setcomptype(comptype, compname)
  611. def getparams(self):
  612. if not self._nchannels or not self._sampwidth or not self._framerate:
  613. raise Error, 'not all parameters set'
  614. return self._nchannels, self._sampwidth, self._framerate, \
  615. self._nframes, self._comptype, self._compname
  616. def setmark(self, id, pos, name):
  617. if id <= 0:
  618. raise Error, 'marker ID must be > 0'
  619. if pos < 0:
  620. raise Error, 'marker position must be >= 0'
  621. if type(name) != type(''):
  622. raise Error, 'marker name must be a string'
  623. for i in range(len(self._markers)):
  624. if id == self._markers[i][0]:
  625. self._markers[i] = id, pos, name
  626. return
  627. self._markers.append((id, pos, name))
  628. def getmark(self, id):
  629. for marker in self._markers:
  630. if id == marker[0]:
  631. return marker
  632. raise Error, 'marker %r does not exist' % (id,)
  633. def getmarkers(self):
  634. if len(self._markers) == 0:
  635. return None
  636. return self._markers
  637. def tell(self):
  638. return self._nframeswritten
  639. def writeframesraw(self, data):
  640. self._ensure_header_written(len(data))
  641. nframes = len(data) // (self._sampwidth * self._nchannels)
  642. if self._convert:
  643. data = self._convert(data)
  644. self._file.write(data)
  645. self._nframeswritten = self._nframeswritten + nframes
  646. self._datawritten = self._datawritten + len(data)
  647. def writeframes(self, data):
  648. self.writeframesraw(data)
  649. if self._nframeswritten != self._nframes or \
  650. self._datalength != self._datawritten:
  651. self._patchheader()
  652. def close(self):
  653. if self._file is None:
  654. return
  655. try:
  656. self._ensure_header_written(0)
  657. if self._datawritten & 1:
  658. # quick pad to even size
  659. self._file.write(chr(0))
  660. self._datawritten = self._datawritten + 1
  661. self._writemarkers()
  662. if self._nframeswritten != self._nframes or \
  663. self._datalength != self._datawritten or \
  664. self._marklength:
  665. self._patchheader()
  666. if self._comp:
  667. self._comp.CloseCompressor()
  668. self._comp = None
  669. finally:
  670. # Prevent ref cycles
  671. self._convert = None
  672. f = self._file
  673. self._file = None
  674. f.close()
  675. #
  676. # Internal methods.
  677. #
  678. def _comp_data(self, data):
  679. import cl
  680. dummy = self._comp.SetParam(cl.FRAME_BUFFER_SIZE, len(data))
  681. dummy = self._comp.SetParam(cl.COMPRESSED_BUFFER_SIZE, len(data))
  682. return self._comp.Compress(self._nframes, data)
  683. def _lin2ulaw(self, data):
  684. import audioop
  685. return audioop.lin2ulaw(data, 2)
  686. def _lin2adpcm(self, data):
  687. import audioop
  688. if not hasattr(self, '_adpcmstate'):
  689. self._adpcmstate = None
  690. data, self._adpcmstate = audioop.lin2adpcm(data, 2,
  691. self._adpcmstate)
  692. return data
  693. def _ensure_header_written(self, datasize):
  694. if not self._nframeswritten:
  695. if self._comptype in ('ULAW', 'ulaw', 'ALAW', 'alaw'):
  696. if not self._sampwidth:
  697. self._sampwidth = 2
  698. if self._sampwidth != 2:
  699. raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
  700. if self._comptype == 'G722':
  701. if not self._sampwidth:
  702. self._sampwidth = 2
  703. if self._sampwidth != 2:
  704. raise Error, 'sample width must be 2 when compressing with G7.22 (ADPCM)'
  705. if not self._nchannels:
  706. raise Error, '# channels not specified'
  707. if not self._sampwidth:
  708. raise Error, 'sample width not specified'
  709. if not self._framerate:
  710. raise Error, 'sampling rate not specified'
  711. self._write_header(datasize)
  712. def _init_compression(self):
  713. if self._comptype == 'G722':
  714. self._convert = self._lin2adpcm
  715. return
  716. try:
  717. import cl
  718. except ImportError:
  719. if self._comptype in ('ULAW', 'ulaw'):
  720. try:
  721. import audioop
  722. self._convert = self._lin2ulaw
  723. return
  724. except ImportError:
  725. pass
  726. raise Error, 'cannot write compressed AIFF-C files'
  727. if self._comptype in ('ULAW', 'ulaw'):
  728. scheme = cl.G711_ULAW
  729. elif self._comptype in ('ALAW', 'alaw'):
  730. scheme = cl.G711_ALAW
  731. else:
  732. raise Error, 'unsupported compression type'
  733. self._comp = cl.OpenCompressor(scheme)
  734. params = [cl.ORIGINAL_FORMAT, 0,
  735. cl.BITS_PER_COMPONENT, self._sampwidth * 8,
  736. cl.FRAME_RATE, self._framerate,
  737. cl.FRAME_BUFFER_SIZE, 100,
  738. cl.COMPRESSED_BUFFER_SIZE, 100]
  739. if self._nchannels == 1:
  740. params[1] = cl.MONO
  741. elif self._nchannels == 2:
  742. params[1] = cl.STEREO_INTERLEAVED
  743. else:
  744. raise Error, 'cannot compress more than 2 channels'
  745. self._comp.SetParams(params)
  746. # the compressor produces a header which we ignore
  747. dummy = self._comp.Compress(0, '')
  748. self._convert = self._comp_data
  749. def _write_header(self, initlength):
  750. if self._aifc and self._comptype != 'NONE':
  751. self._init_compression()
  752. self._file.write('FORM')
  753. if not self._nframes:
  754. self._nframes = initlength // (self._nchannels * self._sampwidth)
  755. self._datalength = self._nframes * self._nchannels * self._sampwidth
  756. if self._datalength & 1:
  757. self._datalength = self._datalength + 1
  758. if self._aifc:
  759. if self._comptype in ('ULAW', 'ulaw', 'ALAW', 'alaw'):
  760. self._datalength = self._datalength // 2
  761. if self._datalength & 1:
  762. self._datalength = self._datalength + 1
  763. elif self._comptype == 'G722':
  764. self._datalength = (self._datalength + 3) // 4
  765. if self._datalength & 1:
  766. self._datalength = self._datalength + 1
  767. try:
  768. self._form_length_pos = self._file.tell()
  769. except (AttributeError, IOError):
  770. self._form_length_pos = None
  771. commlength = self._write_form_length(self._datalength)
  772. if self._aifc:
  773. self._file.write('AIFC')
  774. self._file.write('FVER')
  775. _write_ulong(self._file, 4)
  776. _write_ulong(self._file, self._version)
  777. else:
  778. self._file.write('AIFF')
  779. self._file.write('COMM')
  780. _write_ulong(self._file, commlength)
  781. _write_short(self._file, self._nchannels)
  782. if self._form_length_pos is not None:
  783. self._nframes_pos = self._file.tell()
  784. _write_ulong(self._file, self._nframes)
  785. if self._comptype in ('ULAW', 'ulaw', 'ALAW', 'alaw', 'G722'):
  786. _write_short(self._file, 8)
  787. else:
  788. _write_short(self._file, self._sampwidth * 8)
  789. _write_float(self._file, self._framerate)
  790. if self._aifc:
  791. self._file.write(self._comptype)
  792. _write_string(self._file, self._compname)
  793. self._file.write('SSND')
  794. if self._form_length_pos is not None:
  795. self._ssnd_length_pos = self._file.tell()
  796. _write_ulong(self._file, self._datalength + 8)
  797. _write_ulong(self._file, 0)
  798. _write_ulong(self._file, 0)
  799. def _write_form_length(self, datalength):
  800. if self._aifc:
  801. commlength = 18 + 5 + len(self._compname)
  802. if commlength & 1:
  803. commlength = commlength + 1
  804. verslength = 12
  805. else:
  806. commlength = 18
  807. verslength = 0
  808. _write_ulong(self._file, 4 + verslength + self._marklength + \
  809. 8 + commlength + 16 + datalength)
  810. return commlength
  811. def _patchheader(self):
  812. curpos = self._file.tell()
  813. if self._datawritten & 1:
  814. datalength = self._datawritten + 1
  815. self._file.write(chr(0))
  816. else:
  817. datalength = self._datawritten
  818. if datalength == self._datalength and \
  819. self._nframes == self._nframeswritten and \
  820. self._marklength == 0:
  821. self._file.seek(curpos, 0)
  822. return
  823. self._file.seek(self._form_length_pos, 0)
  824. dummy = self._write_form_length(datalength)
  825. self._file.seek(self._nframes_pos, 0)
  826. _write_ulong(self._file, self._nframeswritten)
  827. self._file.seek(self._ssnd_length_pos, 0)
  828. _write_ulong(self._file, datalength + 8)
  829. self._file.seek(curpos, 0)
  830. self._nframes = self._nframeswritten
  831. self._datalength = datalength
  832. def _writemarkers(self):
  833. if len(self._markers) == 0:
  834. return
  835. self._file.write('MARK')
  836. length = 2
  837. for marker in self._markers:
  838. id, pos, name = marker
  839. length = length + len(name) + 1 + 6
  840. if len(name) & 1 == 0:
  841. length = length + 1
  842. _write_ulong(self._file, length)
  843. self._marklength = length + 8
  844. _write_short(self._file, len(self._markers))
  845. for marker in self._markers:
  846. id, pos, name = marker
  847. _write_short(self._file, id)
  848. _write_ulong(self._file, pos)
  849. _write_string(self._file, name)
  850. def open(f, mode=None):
  851. if mode is None:
  852. if hasattr(f, 'mode'):
  853. mode = f.mode
  854. else:
  855. mode = 'rb'
  856. if mode in ('r', 'rb'):
  857. return Aifc_read(f)
  858. elif mode in ('w', 'wb'):
  859. return Aifc_write(f)
  860. else:
  861. raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
  862. openfp = open # B/W compatibility
  863. if __name__ == '__main__':
  864. import sys
  865. if not sys.argv[1:]:
  866. sys.argv.append('/usr/demos/data/audio/bach.aiff')
  867. fn = sys.argv[1]
  868. f = open(fn, 'r')
  869. try:
  870. print "Reading", fn
  871. print "nchannels =", f.getnchannels()
  872. print "nframes =", f.getnframes()
  873. print "sampwidth =", f.getsampwidth()
  874. print "framerate =", f.getframerate()
  875. print "comptype =", f.getcomptype()
  876. print "compname =", f.getcompname()
  877. if sys.argv[2:]:
  878. gn = sys.argv[2]
  879. print "Writing", gn
  880. g = open(gn, 'w')
  881. try:
  882. g.setparams(f.getparams())
  883. while 1:
  884. data = f.readframes(1024)
  885. if not data:
  886. break
  887. g.writeframes(data)
  888. finally:
  889. g.close()
  890. print "Done."
  891. finally:
  892. f.close()