sunau.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 tuple 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('') 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 <multimedia/audio_filehdr.h>
  97. AUDIO_FILE_MAGIC = 0x2e736e64
  98. AUDIO_FILE_ENCODING_MULAW_8 = 1
  99. AUDIO_FILE_ENCODING_LINEAR_8 = 2
  100. AUDIO_FILE_ENCODING_LINEAR_16 = 3
  101. AUDIO_FILE_ENCODING_LINEAR_24 = 4
  102. AUDIO_FILE_ENCODING_LINEAR_32 = 5
  103. AUDIO_FILE_ENCODING_FLOAT = 6
  104. AUDIO_FILE_ENCODING_DOUBLE = 7
  105. AUDIO_FILE_ENCODING_ADPCM_G721 = 23
  106. AUDIO_FILE_ENCODING_ADPCM_G722 = 24
  107. AUDIO_FILE_ENCODING_ADPCM_G723_3 = 25
  108. AUDIO_FILE_ENCODING_ADPCM_G723_5 = 26
  109. AUDIO_FILE_ENCODING_ALAW_8 = 27
  110. # from <multimedia/audio_hdr.h>
  111. AUDIO_UNKNOWN_SIZE = 0xFFFFFFFFL # ((unsigned)(~0))
  112. _simple_encodings = [AUDIO_FILE_ENCODING_MULAW_8,
  113. AUDIO_FILE_ENCODING_LINEAR_8,
  114. AUDIO_FILE_ENCODING_LINEAR_16,
  115. AUDIO_FILE_ENCODING_LINEAR_24,
  116. AUDIO_FILE_ENCODING_LINEAR_32,
  117. AUDIO_FILE_ENCODING_ALAW_8]
  118. class Error(Exception):
  119. pass
  120. def _read_u32(file):
  121. x = 0L
  122. for i in range(4):
  123. byte = file.read(1)
  124. if byte == '':
  125. raise EOFError
  126. x = x*256 + ord(byte)
  127. return x
  128. def _write_u32(file, x):
  129. data = []
  130. for i in range(4):
  131. d, m = divmod(x, 256)
  132. data.insert(0, m)
  133. x = d
  134. for i in range(4):
  135. file.write(chr(int(data[i])))
  136. class Au_read:
  137. def __init__(self, f):
  138. if type(f) == type(''):
  139. import __builtin__
  140. f = __builtin__.open(f, 'rb')
  141. self.initfp(f)
  142. def __del__(self):
  143. if self._file:
  144. self.close()
  145. def initfp(self, file):
  146. self._file = file
  147. self._soundpos = 0
  148. magic = int(_read_u32(file))
  149. if magic != AUDIO_FILE_MAGIC:
  150. raise Error, 'bad magic number'
  151. self._hdr_size = int(_read_u32(file))
  152. if self._hdr_size < 24:
  153. raise Error, 'header size too small'
  154. if self._hdr_size > 100:
  155. raise Error, 'header size ridiculously large'
  156. self._data_size = _read_u32(file)
  157. if self._data_size != AUDIO_UNKNOWN_SIZE:
  158. self._data_size = int(self._data_size)
  159. self._encoding = int(_read_u32(file))
  160. if self._encoding not in _simple_encodings:
  161. raise Error, 'encoding not (yet) supported'
  162. if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8,
  163. AUDIO_FILE_ENCODING_ALAW_8):
  164. self._sampwidth = 2
  165. self._framesize = 1
  166. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_8:
  167. self._framesize = self._sampwidth = 1
  168. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_16:
  169. self._framesize = self._sampwidth = 2
  170. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_24:
  171. self._framesize = self._sampwidth = 3
  172. elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32:
  173. self._framesize = self._sampwidth = 4
  174. else:
  175. raise Error, 'unknown encoding'
  176. self._framerate = int(_read_u32(file))
  177. self._nchannels = int(_read_u32(file))
  178. self._framesize = self._framesize * self._nchannels
  179. if self._hdr_size > 24:
  180. self._info = file.read(self._hdr_size - 24)
  181. for i in range(len(self._info)):
  182. if self._info[i] == '\0':
  183. self._info = self._info[:i]
  184. break
  185. else:
  186. self._info = ''
  187. try:
  188. self._data_pos = file.tell()
  189. except (AttributeError, IOError):
  190. self._data_pos = None
  191. def getfp(self):
  192. return self._file
  193. def getnchannels(self):
  194. return self._nchannels
  195. def getsampwidth(self):
  196. return self._sampwidth
  197. def getframerate(self):
  198. return self._framerate
  199. def getnframes(self):
  200. if self._data_size == AUDIO_UNKNOWN_SIZE:
  201. return AUDIO_UNKNOWN_SIZE
  202. if self._encoding in _simple_encodings:
  203. return self._data_size // self._framesize
  204. return 0 # XXX--must do some arithmetic here
  205. def getcomptype(self):
  206. if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
  207. return 'ULAW'
  208. elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8:
  209. return 'ALAW'
  210. else:
  211. return 'NONE'
  212. def getcompname(self):
  213. if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
  214. return 'CCITT G.711 u-law'
  215. elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8:
  216. return 'CCITT G.711 A-law'
  217. else:
  218. return 'not compressed'
  219. def getparams(self):
  220. return self.getnchannels(), self.getsampwidth(), \
  221. self.getframerate(), self.getnframes(), \
  222. self.getcomptype(), self.getcompname()
  223. def getmarkers(self):
  224. return None
  225. def getmark(self, id):
  226. raise Error, 'no marks'
  227. def readframes(self, nframes):
  228. if self._encoding in _simple_encodings:
  229. if nframes == AUDIO_UNKNOWN_SIZE:
  230. data = self._file.read()
  231. else:
  232. data = self._file.read(nframes * self._framesize)
  233. self._soundpos += len(data) // self._framesize
  234. if self._encoding == AUDIO_FILE_ENCODING_MULAW_8:
  235. import audioop
  236. data = audioop.ulaw2lin(data, self._sampwidth)
  237. return data
  238. return None # XXX--not implemented yet
  239. def rewind(self):
  240. if self._data_pos is None:
  241. raise IOError('cannot seek')
  242. self._file.seek(self._data_pos)
  243. self._soundpos = 0
  244. def tell(self):
  245. return self._soundpos
  246. def setpos(self, pos):
  247. if pos < 0 or pos > self.getnframes():
  248. raise Error, 'position not in range'
  249. if self._data_pos is None:
  250. raise IOError('cannot seek')
  251. self._file.seek(self._data_pos + pos * self._framesize)
  252. self._soundpos = pos
  253. def close(self):
  254. self._file = None
  255. class Au_write:
  256. def __init__(self, f):
  257. if type(f) == type(''):
  258. import __builtin__
  259. f = __builtin__.open(f, 'wb')
  260. self.initfp(f)
  261. def __del__(self):
  262. if self._file:
  263. self.close()
  264. def initfp(self, file):
  265. self._file = file
  266. self._framerate = 0
  267. self._nchannels = 0
  268. self._sampwidth = 0
  269. self._framesize = 0
  270. self._nframes = AUDIO_UNKNOWN_SIZE
  271. self._nframeswritten = 0
  272. self._datawritten = 0
  273. self._datalength = 0
  274. self._info = ''
  275. self._comptype = 'ULAW' # default is U-law
  276. def setnchannels(self, nchannels):
  277. if self._nframeswritten:
  278. raise Error, 'cannot change parameters after starting to write'
  279. if nchannels not in (1, 2, 4):
  280. raise Error, 'only 1, 2, or 4 channels supported'
  281. self._nchannels = nchannels
  282. def getnchannels(self):
  283. if not self._nchannels:
  284. raise Error, 'number of channels not set'
  285. return self._nchannels
  286. def setsampwidth(self, sampwidth):
  287. if self._nframeswritten:
  288. raise Error, 'cannot change parameters after starting to write'
  289. if sampwidth not in (1, 2, 4):
  290. raise Error, 'bad sample width'
  291. self._sampwidth = sampwidth
  292. def getsampwidth(self):
  293. if not self._framerate:
  294. raise Error, 'sample width not specified'
  295. return self._sampwidth
  296. def setframerate(self, framerate):
  297. if self._nframeswritten:
  298. raise Error, 'cannot change parameters after starting to write'
  299. self._framerate = framerate
  300. def getframerate(self):
  301. if not self._framerate:
  302. raise Error, 'frame rate not set'
  303. return self._framerate
  304. def setnframes(self, nframes):
  305. if self._nframeswritten:
  306. raise Error, 'cannot change parameters after starting to write'
  307. if nframes < 0:
  308. raise Error, '# of frames cannot be negative'
  309. self._nframes = nframes
  310. def getnframes(self):
  311. return self._nframeswritten
  312. def setcomptype(self, type, name):
  313. if type in ('NONE', 'ULAW'):
  314. self._comptype = type
  315. else:
  316. raise Error, 'unknown compression type'
  317. def getcomptype(self):
  318. return self._comptype
  319. def getcompname(self):
  320. if self._comptype == 'ULAW':
  321. return 'CCITT G.711 u-law'
  322. elif self._comptype == 'ALAW':
  323. return 'CCITT G.711 A-law'
  324. else:
  325. return 'not compressed'
  326. def setparams(self, params):
  327. nchannels, sampwidth, framerate, nframes, comptype, compname = params
  328. self.setnchannels(nchannels)
  329. self.setsampwidth(sampwidth)
  330. self.setframerate(framerate)
  331. self.setnframes(nframes)
  332. self.setcomptype(comptype, compname)
  333. def getparams(self):
  334. return self.getnchannels(), self.getsampwidth(), \
  335. self.getframerate(), self.getnframes(), \
  336. self.getcomptype(), self.getcompname()
  337. def tell(self):
  338. return self._nframeswritten
  339. def writeframesraw(self, data):
  340. self._ensure_header_written()
  341. if self._comptype == 'ULAW':
  342. import audioop
  343. data = audioop.lin2ulaw(data, self._sampwidth)
  344. nframes = len(data) // self._framesize
  345. self._file.write(data)
  346. self._nframeswritten = self._nframeswritten + nframes
  347. self._datawritten = self._datawritten + len(data)
  348. def writeframes(self, data):
  349. self.writeframesraw(data)
  350. if self._nframeswritten != self._nframes or \
  351. self._datalength != self._datawritten:
  352. self._patchheader()
  353. def close(self):
  354. if self._file:
  355. try:
  356. self._ensure_header_written()
  357. if self._nframeswritten != self._nframes or \
  358. self._datalength != self._datawritten:
  359. self._patchheader()
  360. self._file.flush()
  361. finally:
  362. self._file = None
  363. #
  364. # private methods
  365. #
  366. def _ensure_header_written(self):
  367. if not self._nframeswritten:
  368. if not self._nchannels:
  369. raise Error, '# of channels not specified'
  370. if not self._sampwidth:
  371. raise Error, 'sample width not specified'
  372. if not self._framerate:
  373. raise Error, 'frame rate not specified'
  374. self._write_header()
  375. def _write_header(self):
  376. if self._comptype == 'NONE':
  377. if self._sampwidth == 1:
  378. encoding = AUDIO_FILE_ENCODING_LINEAR_8
  379. self._framesize = 1
  380. elif self._sampwidth == 2:
  381. encoding = AUDIO_FILE_ENCODING_LINEAR_16
  382. self._framesize = 2
  383. elif self._sampwidth == 4:
  384. encoding = AUDIO_FILE_ENCODING_LINEAR_32
  385. self._framesize = 4
  386. else:
  387. raise Error, 'internal error'
  388. elif self._comptype == 'ULAW':
  389. encoding = AUDIO_FILE_ENCODING_MULAW_8
  390. self._framesize = 1
  391. else:
  392. raise Error, 'internal error'
  393. self._framesize = self._framesize * self._nchannels
  394. _write_u32(self._file, AUDIO_FILE_MAGIC)
  395. header_size = 25 + len(self._info)
  396. header_size = (header_size + 7) & ~7
  397. _write_u32(self._file, header_size)
  398. if self._nframes == AUDIO_UNKNOWN_SIZE:
  399. length = AUDIO_UNKNOWN_SIZE
  400. else:
  401. length = self._nframes * self._framesize
  402. try:
  403. self._form_length_pos = self._file.tell()
  404. except (AttributeError, IOError):
  405. self._form_length_pos = None
  406. _write_u32(self._file, length)
  407. self._datalength = length
  408. _write_u32(self._file, encoding)
  409. _write_u32(self._file, self._framerate)
  410. _write_u32(self._file, self._nchannels)
  411. self._file.write(self._info)
  412. self._file.write('\0'*(header_size - len(self._info) - 24))
  413. def _patchheader(self):
  414. if self._form_length_pos is None:
  415. raise IOError('cannot seek')
  416. self._file.seek(self._form_length_pos)
  417. _write_u32(self._file, self._datawritten)
  418. self._datalength = self._datawritten
  419. self._file.seek(0, 2)
  420. def open(f, mode=None):
  421. if mode is None:
  422. if hasattr(f, 'mode'):
  423. mode = f.mode
  424. else:
  425. mode = 'rb'
  426. if mode in ('r', 'rb'):
  427. return Au_read(f)
  428. elif mode in ('w', 'wb'):
  429. return Au_write(f)
  430. else:
  431. raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
  432. openfp = open