aifc.py 32 KB

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