PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/aifc.py

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