sunau.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. """Stuff to parse Sun and NeXT audio files.
  2. An audio file consists of a header followed by the data. The structure
  3. of the header is as follows.
  4. +---------------+
  5. | magic word |
  6. +---------------+
  7. | header size |
  8. +---------------+
  9. | data size |
  10. +---------------+
  11. | encoding |
  12. +---------------+
  13. | sample rate |
  14. +---------------+
  15. | # of channels |
  16. +---------------+
  17. | info |
  18. | |
  19. +---------------+
  20. The magic word consists of the 4 characters '.snd'. Apart from the
  21. info field, all header fields are 4 bytes in size. They are all
  22. 32-bit unsigned integers encoded in big-endian byte order.
  23. The header size really gives the start of the data.
  24. The data size is the physical size of the data. From the other
  25. parameters the number of frames can be calculated.
  26. The encoding gives the way in which audio samples are encoded.
  27. Possible values are listed below.
  28. The info field currently consists of an ASCII string giving a
  29. human-readable description of the audio file. The info field is
  30. padded with NUL bytes to the header size.
  31. Usage.
  32. Reading audio files:
  33. f = sunau.open(file, 'r')
  34. where file is either the name of a file or an open file pointer.
  35. The open file pointer must have methods read(), seek(), and close().
  36. When the setpos() and rewind() methods are not used, the seek()
  37. method is not necessary.
  38. This returns an instance of a class with the following public methods:
  39. getnchannels() -- returns number of audio channels (1 for
  40. mono, 2 for stereo)
  41. getsampwidth() -- returns sample width in bytes
  42. getframerate() -- returns sampling frequency
  43. getnframes() -- returns number of audio frames
  44. getcomptype() -- returns compression type ('NONE' or 'ULAW')
  45. getcompname() -- returns human-readable version of
  46. compression type ('not compressed' matches 'NONE')
  47. getparams() -- returns a namedtuple consisting of all of the
  48. above in the above order
  49. getmarkers() -- returns None (for compatibility with the
  50. aifc module)
  51. getmark(id) -- raises an error since the mark does not
  52. exist (for compatibility with the aifc module)
  53. readframes(n) -- returns at most n frames of audio
  54. rewind() -- rewind to the beginning of the audio stream
  55. setpos(pos) -- seek to the specified position
  56. tell() -- return the current position
  57. close() -- close the instance (make it unusable)
  58. The position returned by tell() and the position given to setpos()
  59. are compatible and have nothing to do with the actual position in the
  60. file.
  61. The close() method is called automatically when the class instance
  62. is destroyed.
  63. Writing audio files:
  64. f = sunau.open(file, 'w')
  65. where file is either the name of a file or an open file pointer.
  66. The open file pointer must have methods write(), tell(), seek(), and
  67. close().
  68. This returns an instance of a class with the following public methods:
  69. setnchannels(n) -- set the number of channels
  70. setsampwidth(n) -- set the sample width
  71. setframerate(n) -- set the frame rate
  72. setnframes(n) -- set the number of frames
  73. setcomptype(type, name)
  74. -- set the compression type and the
  75. human-readable compression type
  76. setparams(tuple)-- set all parameters at once
  77. tell() -- return current position in output file
  78. writeframesraw(data)
  79. -- write audio frames without pathing up the
  80. file header
  81. writeframes(data)
  82. -- write audio frames and patch up the file header
  83. close() -- patch up the file header and close the
  84. output file
  85. You should set the parameters before the first writeframesraw or
  86. writeframes. The total number of frames does not need to be set,
  87. but when it is set to the correct value, the header does not have to
  88. be patched up.
  89. It is best to first set all parameters, perhaps possibly the
  90. compression type, and then write audio frames using writeframesraw.
  91. When all frames have been written, either call writeframes(b'') or
  92. close() to patch up the sizes in the header.
  93. The close() method is called automatically when the class instance
  94. is destroyed.
  95. """
  96. from collections import namedtuple
  97. import warnings
  98. warnings._deprecated(__name__, remove=(3, 13))
  99. _sunau_params = namedtuple('_sunau_params',
  100. 'nchannels sampwidth framerate nframes comptype compname')
  101. # from <multimedia/audio_filehdr.h>
  102. AUDIO_FILE_MAGIC = 0x2e736e64
  103. AUDIO_FILE_ENCODING_MULAW_8 = 1
  104. AUDIO_FILE_ENCODING_LINEAR_8 = 2
  105. AUDIO_FILE_ENCODING_LINEAR_16 = 3
  106. AUDIO_FILE_ENCODING_LINEAR_24 = 4
  107. AUDIO_FILE_ENCODING_LINEAR_32 = 5
  108. AUDIO_FILE_ENCODING_FLOAT = 6
  109. AUDIO_FILE_ENCODING_DOUBLE = 7
  110. AUDIO_FILE_ENCODING_ADPCM_G721 = 23
  111. AUDIO_FILE_ENCODING_ADPCM_G722 = 24
  112. AUDIO_FILE_ENCODING_ADPCM_G723_3 = 25
  113. AUDIO_FILE_ENCODING_ADPCM_G723_5 = 26
  114. AUDIO_FILE_ENCODING_ALAW_8 = 27
  115. # from <multimedia/audio_hdr.h>
  116. AUDIO_UNKNOWN_SIZE = 0xFFFFFFFF # ((unsigned)(~0))
  117. _simple_encodings = [AUDIO_FILE_ENCODING_MULAW_8,
  118. AUDIO_FILE_ENCODING_LINEAR_8,
  119. AUDIO_FILE_ENCODING_LINEAR_16,
  120. AUDIO_FILE_ENCODING_LINEAR_24,
  121. AUDIO_FILE_ENCODING_LINEAR_32,
  122. AUDIO_FILE_ENCODING_ALAW_8]
  123. class Error(Exception):
  124. pass
  125. def _read_u32(file):
  126. x = 0
  127. for i in range(4):
  128. byte = file.read(1)
  129. if not byte:
  130. raise EOFError
  131. x = x*256 + ord(byte)
  132. return x
  133. def _write_u32(file, x):
  134. data = []
  135. for i in range(4):
  136. d, m = divmod(x, 256)
  137. data.insert(0, int(m))
  138. x = d
  139. file.write(bytes(data))
  140. class Au_read:
  141. def __init__(self, f):
  142. if isinstance(f, str):
  143. import builtins
  144. f = builtins.open(f, 'rb')
  145. self._opened = True
  146. else:
  147. self._opened = False
  148. self.initfp(f)
  149. def __del__(self):
  150. if self._file:
  151. self.close()
  152. def __enter__(self):
  153. return self
  154. def __exit__(self, *args):
  155. self.close()
  156. def initfp(self, file):
  157. self._file = file
  158. self._soundpos = 0
  159. magic = int(_read_u32(file))
  160. if magic != AUDIO_FILE_MAGIC:
  161. raise Error('bad magic number')
  162. self._hdr_size = int(_read_u32(file))
  163. if self._hdr_size < 24:
  164. raise Error('header size too small')
  165. if self._hdr_size > 100:
  166. raise Error('header size ridiculously large')
  167. self._data_size = _read_u32(file)
  168. if self._data_size != AUDIO_UNKNOWN_SIZE:
  169. self._data_size = int(self._data_size)
  170. self._encoding = int(_read_u32(file))
  171. if self._encoding not in _simple_encodings:
  172. raise Error('encoding not (yet) supported')
  173. if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8,
  174. AUDIO_FILE_ENCODING_ALAW_8):
  175. self._sampwidth = 2
  176. self._framesize = 1
  177. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_8:
  178. self._framesize = self._sampwidth = 1
  179. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_16:
  180. self._framesize = self._sampwidth = 2
  181. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_24:
  182. self._framesize = self._sampwidth = 3
  183. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32:
  184. self._framesize = self._sampwidth = 4
  185. else:
  186. raise Error('unknown encoding')
  187. self._framerate = int(_read_u32(file))
  188. self._nchannels = int(_read_u32(file))
  189. if not self._nchannels:
  190. raise Error('bad # of channels')
  191. self._framesize = self._framesize * self._nchannels
  192. if self._hdr_size > 24:
  193. self._info = file.read(self._hdr_size - 24)
  194. self._info, _, _ = self._info.partition(b'\0')
  195. else:
  196. self._info = b''
  197. try:
  198. self._data_pos = file.tell()
  199. except (AttributeError, OSError):
  200. self._data_pos = None
  201. def getfp(self):
  202. return self._file
  203. def getnchannels(self):
  204. return self._nchannels
  205. def getsampwidth(self):
  206. return self._sampwidth
  207. def getframerate(self):
  208. return self._framerate
  209. def getnframes(self):
  210. if self._data_size == AUDIO_UNKNOWN_SIZE:
  211. return AUDIO_UNKNOWN_SIZE
  212. if self._encoding in _simple_encodings:
  213. return self._data_size // self._framesize
  214. return 0 # XXX--must do some arithmetic here
  215. def getcomptype(self):
  216. if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
  217. return 'ULAW'
  218. elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8:
  219. return 'ALAW'
  220. else:
  221. return 'NONE'
  222. def getcompname(self):
  223. if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
  224. return 'CCITT G.711 u-law'
  225. elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8:
  226. return 'CCITT G.711 A-law'
  227. else:
  228. return 'not compressed'
  229. def getparams(self):
  230. return _sunau_params(self.getnchannels(), self.getsampwidth(),
  231. self.getframerate(), self.getnframes(),
  232. self.getcomptype(), self.getcompname())
  233. def getmarkers(self):
  234. return None
  235. def getmark(self, id):
  236. raise Error('no marks')
  237. def readframes(self, nframes):
  238. if self._encoding in _simple_encodings:
  239. if nframes == AUDIO_UNKNOWN_SIZE:
  240. data = self._file.read()
  241. else:
  242. data = self._file.read(nframes * self._framesize)
  243. self._soundpos += len(data) // self._framesize
  244. if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
  245. with warnings.catch_warnings():
  246. warnings.simplefilter('ignore', category=DeprecationWarning)
  247. import audioop
  248. data = audioop.ulaw2lin(data, self._sampwidth)
  249. return data
  250. return None # XXX--not implemented yet
  251. def rewind(self):
  252. if self._data_pos is None:
  253. raise OSError('cannot seek')
  254. self._file.seek(self._data_pos)
  255. self._soundpos = 0
  256. def tell(self):
  257. return self._soundpos
  258. def setpos(self, pos):
  259. if pos < 0 or pos > self.getnframes():
  260. raise Error('position not in range')
  261. if self._data_pos is None:
  262. raise OSError('cannot seek')
  263. self._file.seek(self._data_pos + pos * self._framesize)
  264. self._soundpos = pos
  265. def close(self):
  266. file = self._file
  267. if file:
  268. self._file = None
  269. if self._opened:
  270. file.close()
  271. class Au_write:
  272. def __init__(self, f):
  273. if isinstance(f, str):
  274. import builtins
  275. f = builtins.open(f, 'wb')
  276. self._opened = True
  277. else:
  278. self._opened = False
  279. self.initfp(f)
  280. def __del__(self):
  281. if self._file:
  282. self.close()
  283. self._file = None
  284. def __enter__(self):
  285. return self
  286. def __exit__(self, *args):
  287. self.close()
  288. def initfp(self, file):
  289. self._file = file
  290. self._framerate = 0
  291. self._nchannels = 0
  292. self._sampwidth = 0
  293. self._framesize = 0
  294. self._nframes = AUDIO_UNKNOWN_SIZE
  295. self._nframeswritten = 0
  296. self._datawritten = 0
  297. self._datalength = 0
  298. self._info = b''
  299. self._comptype = 'ULAW' # default is U-law
  300. def setnchannels(self, nchannels):
  301. if self._nframeswritten:
  302. raise Error('cannot change parameters after starting to write')
  303. if nchannels not in (1, 2, 4):
  304. raise Error('only 1, 2, or 4 channels supported')
  305. self._nchannels = nchannels
  306. def getnchannels(self):
  307. if not self._nchannels:
  308. raise Error('number of channels not set')
  309. return self._nchannels
  310. def setsampwidth(self, sampwidth):
  311. if self._nframeswritten:
  312. raise Error('cannot change parameters after starting to write')
  313. if sampwidth not in (1, 2, 3, 4):
  314. raise Error('bad sample width')
  315. self._sampwidth = sampwidth
  316. def getsampwidth(self):
  317. if not self._framerate:
  318. raise Error('sample width not specified')
  319. return self._sampwidth
  320. def setframerate(self, framerate):
  321. if self._nframeswritten:
  322. raise Error('cannot change parameters after starting to write')
  323. self._framerate = framerate
  324. def getframerate(self):
  325. if not self._framerate:
  326. raise Error('frame rate not set')
  327. return self._framerate
  328. def setnframes(self, nframes):
  329. if self._nframeswritten:
  330. raise Error('cannot change parameters after starting to write')
  331. if nframes < 0:
  332. raise Error('# of frames cannot be negative')
  333. self._nframes = nframes
  334. def getnframes(self):
  335. return self._nframeswritten
  336. def setcomptype(self, type, name):
  337. if type in ('NONE', 'ULAW'):
  338. self._comptype = type
  339. else:
  340. raise Error('unknown compression type')
  341. def getcomptype(self):
  342. return self._comptype
  343. def getcompname(self):
  344. if self._comptype == 'ULAW':
  345. return 'CCITT G.711 u-law'
  346. elif self._comptype == 'ALAW':
  347. return 'CCITT G.711 A-law'
  348. else:
  349. return 'not compressed'
  350. def setparams(self, params):
  351. nchannels, sampwidth, framerate, nframes, comptype, compname = params
  352. self.setnchannels(nchannels)
  353. self.setsampwidth(sampwidth)
  354. self.setframerate(framerate)
  355. self.setnframes(nframes)
  356. self.setcomptype(comptype, compname)
  357. def getparams(self):
  358. return _sunau_params(self.getnchannels(), self.getsampwidth(),
  359. self.getframerate(), self.getnframes(),
  360. self.getcomptype(), self.getcompname())
  361. def tell(self):
  362. return self._nframeswritten
  363. def writeframesraw(self, data):
  364. if not isinstance(data, (bytes, bytearray)):
  365. data = memoryview(data).cast('B')
  366. self._ensure_header_written()
  367. if self._comptype == 'ULAW':
  368. with warnings.catch_warnings():
  369. warnings.simplefilter('ignore', category=DeprecationWarning)
  370. import audioop
  371. data = audioop.lin2ulaw(data, self._sampwidth)
  372. nframes = len(data) // self._framesize
  373. self._file.write(data)
  374. self._nframeswritten = self._nframeswritten + nframes
  375. self._datawritten = self._datawritten + len(data)
  376. def writeframes(self, data):
  377. self.writeframesraw(data)
  378. if self._nframeswritten != self._nframes or \
  379. self._datalength != self._datawritten:
  380. self._patchheader()
  381. def close(self):
  382. if self._file:
  383. try:
  384. self._ensure_header_written()
  385. if self._nframeswritten != self._nframes or \
  386. self._datalength != self._datawritten:
  387. self._patchheader()
  388. self._file.flush()
  389. finally:
  390. file = self._file
  391. self._file = None
  392. if self._opened:
  393. file.close()
  394. #
  395. # private methods
  396. #
  397. def _ensure_header_written(self):
  398. if not self._nframeswritten:
  399. if not self._nchannels:
  400. raise Error('# of channels not specified')
  401. if not self._sampwidth:
  402. raise Error('sample width not specified')
  403. if not self._framerate:
  404. raise Error('frame rate not specified')
  405. self._write_header()
  406. def _write_header(self):
  407. if self._comptype == 'NONE':
  408. if self._sampwidth == 1:
  409. encoding = AUDIO_FILE_ENCODING_LINEAR_8
  410. self._framesize = 1
  411. elif self._sampwidth == 2:
  412. encoding = AUDIO_FILE_ENCODING_LINEAR_16
  413. self._framesize = 2
  414. elif self._sampwidth == 3:
  415. encoding = AUDIO_FILE_ENCODING_LINEAR_24
  416. self._framesize = 3
  417. elif self._sampwidth == 4:
  418. encoding = AUDIO_FILE_ENCODING_LINEAR_32
  419. self._framesize = 4
  420. else:
  421. raise Error('internal error')
  422. elif self._comptype == 'ULAW':
  423. encoding = AUDIO_FILE_ENCODING_MULAW_8
  424. self._framesize = 1
  425. else:
  426. raise Error('internal error')
  427. self._framesize = self._framesize * self._nchannels
  428. _write_u32(self._file, AUDIO_FILE_MAGIC)
  429. header_size = 25 + len(self._info)
  430. header_size = (header_size + 7) & ~7
  431. _write_u32(self._file, header_size)
  432. if self._nframes == AUDIO_UNKNOWN_SIZE:
  433. length = AUDIO_UNKNOWN_SIZE
  434. else:
  435. length = self._nframes * self._framesize
  436. try:
  437. self._form_length_pos = self._file.tell()
  438. except (AttributeError, OSError):
  439. self._form_length_pos = None
  440. _write_u32(self._file, length)
  441. self._datalength = length
  442. _write_u32(self._file, encoding)
  443. _write_u32(self._file, self._framerate)
  444. _write_u32(self._file, self._nchannels)
  445. self._file.write(self._info)
  446. self._file.write(b'\0'*(header_size - len(self._info) - 24))
  447. def _patchheader(self):
  448. if self._form_length_pos is None:
  449. raise OSError('cannot seek')
  450. self._file.seek(self._form_length_pos)
  451. _write_u32(self._file, self._datawritten)
  452. self._datalength = self._datawritten
  453. self._file.seek(0, 2)
  454. def open(f, mode=None):
  455. if mode is None:
  456. if hasattr(f, 'mode'):
  457. mode = f.mode
  458. else:
  459. mode = 'rb'
  460. if mode in ('r', 'rb'):
  461. return Au_read(f)
  462. elif mode in ('w', 'wb'):
  463. return Au_write(f)
  464. else:
  465. raise Error("mode must be 'r', 'rb', 'w', or 'wb'")