PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/aifc.py

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