sunau.py 18 KB

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