aifc.py 33 KB

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