blob: 96f54af29b58ec74dc2ee3be2d894bd8245fdd8a [file] [log] [blame]
Greg Ward04613a92002-11-30 22:47:45 +00001/*
2 * ossaudiodev -- Python interface to the OSS (Open Sound System) API.
3 * This is the standard audio API for Linux and some
4 * flavours of BSD [XXX which ones?]; it is also available
5 * for a wide range of commercial Unices.
6 *
7 * Originally written by Peter Bosch, March 2000, as linuxaudiodev.
8 *
9 * Renamed to ossaudiodev and rearranged/revised/hacked up
10 * by Greg Ward <gward@python.net>, November 2002.
11 *
12 * (c) 2000 Peter Bosch. All Rights Reserved.
13 * (c) 2002 Gregory P. Ward. All Rights Reserved.
14 * (c) 2002 Python Software Foundation. All Rights Reserved.
15 *
16 * XXX need a license statement
17 *
18 * $Id$
19 */
20
21#include "Python.h"
22#include "structmember.h"
23
24#ifdef HAVE_FCNTL_H
25#include <fcntl.h>
26#else
27#define O_RDONLY 00
28#define O_WRONLY 01
29#endif
30
31
32#include <sys/ioctl.h>
33#if defined(linux)
34#include <linux/soundcard.h>
35
36typedef unsigned long uint32_t;
37
38#elif defined(__FreeBSD__)
39#include <machine/soundcard.h>
40
41#ifndef SNDCTL_DSP_CHANNELS
42#define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
43#endif
44
45#endif
46
47typedef struct {
48 PyObject_HEAD;
49 int x_fd; /* The open file */
50 int x_mode; /* file mode */
51 int x_icount; /* Input count */
52 int x_ocount; /* Output count */
53 uint32_t x_afmts; /* Audio formats supported by hardware*/
54} lad_t;
55
56/* XXX several format defined in soundcard.h are not supported,
57 including _NE (native endian) options and S32 options
58*/
59
60static struct {
61 int a_bps;
62 uint32_t a_fmt;
63 char *a_name;
64} audio_types[] = {
65 { 8, AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
66 { 8, AFMT_A_LAW, "logarithmic A-law 8-bit audio" },
67 { 8, AFMT_U8, "linear unsigned 8-bit audio" },
68 { 8, AFMT_S8, "linear signed 8-bit audio" },
69 { 16, AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
70 { 16, AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
71 { 16, AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
72 { 16, AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
73 { 16, AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
74};
75
76static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]);
77
78static PyTypeObject Ladtype;
79
80static PyObject *LinuxAudioError;
81
82static lad_t *
83newladobject(PyObject *arg)
84{
85 lad_t *xp;
86 int fd, afmts, imode;
87 char *basedev = NULL;
88 char *mode = NULL;
89
90 /* Two ways to call linuxaudiodev.open():
91 open(device, mode) (for consistency with builtin open())
92 open(mode) (for backwards compatibility)
93 because the *first* argument is optional, parsing args is
94 a wee bit tricky. */
95 if (!PyArg_ParseTuple(arg, "s|s:open", &basedev, &mode))
96 return NULL;
97 if (mode == NULL) { /* only one arg supplied */
98 mode = basedev;
99 basedev = NULL;
100 }
101
102 if (strcmp(mode, "r") == 0)
103 imode = O_RDONLY;
104 else if (strcmp(mode, "w") == 0)
105 imode = O_WRONLY;
106 else {
107 PyErr_SetString(LinuxAudioError, "mode should be 'r' or 'w'");
108 return NULL;
109 }
110
111 /* Open the correct device. The base device name comes from the
112 * AUDIODEV environment variable first, then /dev/dsp. The
113 * control device tacks "ctl" onto the base device name.
114 *
115 * Note that the only difference between /dev/audio and /dev/dsp
116 * is that the former uses logarithmic mu-law encoding and the
117 * latter uses 8-bit unsigned encoding.
118 */
119
120 if (basedev == NULL) { /* called with one arg */
121 basedev = getenv("AUDIODEV");
122 if (basedev == NULL) /* $AUDIODEV not set */
123 basedev = "/dev/dsp";
124 }
125
126 if ((fd = open(basedev, imode)) == -1) {
127 PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
128 return NULL;
129 }
130 if (imode == O_WRONLY && ioctl(fd, SNDCTL_DSP_NONBLOCK, NULL) == -1) {
131 PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
132 return NULL;
133 }
134 if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
135 PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
136 return NULL;
137 }
138 /* Create and initialize the object */
139 if ((xp = PyObject_New(lad_t, &Ladtype)) == NULL) {
140 close(fd);
141 return NULL;
142 }
143 xp->x_fd = fd;
144 xp->x_mode = imode;
145 xp->x_icount = xp->x_ocount = 0;
146 xp->x_afmts = afmts;
147 return xp;
148}
149
150static void
151lad_dealloc(lad_t *xp)
152{
153 /* if already closed, don't reclose it */
154 if (xp->x_fd != -1)
155 close(xp->x_fd);
156 PyObject_Del(xp);
157}
158
159static PyObject *
160lad_read(lad_t *self, PyObject *args)
161{
162 int size, count;
163 char *cp;
164 PyObject *rv;
165
166 if (!PyArg_ParseTuple(args, "i:read", &size))
167 return NULL;
168 rv = PyString_FromStringAndSize(NULL, size);
169 if (rv == NULL)
170 return NULL;
171 cp = PyString_AS_STRING(rv);
172 if ((count = read(self->x_fd, cp, size)) < 0) {
173 PyErr_SetFromErrno(LinuxAudioError);
174 Py_DECREF(rv);
175 return NULL;
176 }
177 self->x_icount += count;
178 _PyString_Resize(&rv, count);
179 return rv;
180}
181
182static PyObject *
183lad_write(lad_t *self, PyObject *args)
184{
185 char *cp;
186 int rv, size;
187 fd_set write_set_fds;
188 struct timeval tv;
189 int select_retval;
190
191 if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
192 return NULL;
193
194 /* use select to wait for audio device to be available */
195 FD_ZERO(&write_set_fds);
196 FD_SET(self->x_fd, &write_set_fds);
197 tv.tv_sec = 4; /* timeout values */
198 tv.tv_usec = 0;
199
200 while (size > 0) {
201 select_retval = select(self->x_fd+1, NULL, &write_set_fds, NULL, &tv);
202 tv.tv_sec = 1; tv.tv_usec = 0; /* willing to wait this long next time*/
203 if (select_retval) {
204 if ((rv = write(self->x_fd, cp, size)) == -1) {
205 if (errno != EAGAIN) {
206 PyErr_SetFromErrno(LinuxAudioError);
207 return NULL;
208 } else {
209 errno = 0; /* EAGAIN: buffer is full, try again */
210 }
211 } else {
212 self->x_ocount += rv;
213 size -= rv;
214 cp += rv;
215 }
216 } else {
217 /* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
218 PyErr_SetFromErrno(LinuxAudioError);
219 return NULL;
220 }
221 }
222 Py_INCREF(Py_None);
223 return Py_None;
224}
225
226static PyObject *
227lad_close(lad_t *self, PyObject *args)
228{
229 if (!PyArg_ParseTuple(args, ":close"))
230 return NULL;
231
232 if (self->x_fd >= 0) {
233 close(self->x_fd);
234 self->x_fd = -1;
235 }
236 Py_INCREF(Py_None);
237 return Py_None;
238}
239
240static PyObject *
241lad_fileno(lad_t *self, PyObject *args)
242{
243 if (!PyArg_ParseTuple(args, ":fileno"))
244 return NULL;
245 return PyInt_FromLong(self->x_fd);
246}
247
248static PyObject *
249lad_setparameters(lad_t *self, PyObject *args)
250{
251 int rate, ssize, nchannels, n, fmt, emulate=0;
252
253 if (!PyArg_ParseTuple(args, "iiii|i:setparameters",
254 &rate, &ssize, &nchannels, &fmt, &emulate))
255 return NULL;
256
257 if (rate < 0) {
258 PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
259 rate);
260 return NULL;
261 }
262 if (ssize < 0) {
263 PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
264 ssize);
265 return NULL;
266 }
267 if (nchannels != 1 && nchannels != 2) {
268 PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
269 nchannels);
270 return NULL;
271 }
272
273 for (n = 0; n < n_audio_types; n++)
274 if (fmt == audio_types[n].a_fmt)
275 break;
276 if (n == n_audio_types) {
277 PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
278 return NULL;
279 }
280 if (audio_types[n].a_bps != ssize) {
281 PyErr_Format(PyExc_ValueError,
282 "for %s, expected sample size %d, not %d",
283 audio_types[n].a_name, audio_types[n].a_bps, ssize);
284 return NULL;
285 }
286
287 if (emulate == 0) {
288 if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
289 PyErr_Format(PyExc_ValueError,
290 "%s format not supported by device",
291 audio_types[n].a_name);
292 return NULL;
293 }
294 }
295 if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT,
296 &audio_types[n].a_fmt) == -1) {
297 PyErr_SetFromErrno(LinuxAudioError);
298 return NULL;
299 }
300 if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, &nchannels) == -1) {
301 PyErr_SetFromErrno(LinuxAudioError);
302 return NULL;
303 }
304 if (ioctl(self->x_fd, SNDCTL_DSP_SPEED, &rate) == -1) {
305 PyErr_SetFromErrno(LinuxAudioError);
306 return NULL;
307 }
308
309 Py_INCREF(Py_None);
310 return Py_None;
311}
312
313static int
314_ssize(lad_t *self, int *nchannels, int *ssize)
315{
316 int fmt;
317
318 fmt = 0;
319 if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
320 return -errno;
321
322 switch (fmt) {
323 case AFMT_MU_LAW:
324 case AFMT_A_LAW:
325 case AFMT_U8:
326 case AFMT_S8:
327 *ssize = sizeof(char);
328 break;
329 case AFMT_S16_LE:
330 case AFMT_S16_BE:
331 case AFMT_U16_LE:
332 case AFMT_U16_BE:
333 *ssize = sizeof(short);
334 break;
335 case AFMT_MPEG:
336 case AFMT_IMA_ADPCM:
337 default:
338 return -EOPNOTSUPP;
339 }
340 *nchannels = 0;
341 if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, nchannels) < 0)
342 return -errno;
343 return 0;
344}
345
346
347/* bufsize returns the size of the hardware audio buffer in number
348 of samples */
349static PyObject *
350lad_bufsize(lad_t *self, PyObject *args)
351{
352 audio_buf_info ai;
353 int nchannels, ssize;
354
355 if (!PyArg_ParseTuple(args, ":bufsize")) return NULL;
356
357 if (_ssize(self, &nchannels, &ssize) < 0) {
358 PyErr_SetFromErrno(LinuxAudioError);
359 return NULL;
360 }
361 if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
362 PyErr_SetFromErrno(LinuxAudioError);
363 return NULL;
364 }
365 return PyInt_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
366}
367
368/* obufcount returns the number of samples that are available in the
369 hardware for playing */
370static PyObject *
371lad_obufcount(lad_t *self, PyObject *args)
372{
373 audio_buf_info ai;
374 int nchannels, ssize;
375
376 if (!PyArg_ParseTuple(args, ":obufcount"))
377 return NULL;
378
379 if (_ssize(self, &nchannels, &ssize) < 0) {
380 PyErr_SetFromErrno(LinuxAudioError);
381 return NULL;
382 }
383 if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
384 PyErr_SetFromErrno(LinuxAudioError);
385 return NULL;
386 }
387 return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
388 (ssize * nchannels));
389}
390
391/* obufcount returns the number of samples that can be played without
392 blocking */
393static PyObject *
394lad_obuffree(lad_t *self, PyObject *args)
395{
396 audio_buf_info ai;
397 int nchannels, ssize;
398
399 if (!PyArg_ParseTuple(args, ":obuffree"))
400 return NULL;
401
402 if (_ssize(self, &nchannels, &ssize) < 0) {
403 PyErr_SetFromErrno(LinuxAudioError);
404 return NULL;
405 }
406 if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
407 PyErr_SetFromErrno(LinuxAudioError);
408 return NULL;
409 }
410 return PyInt_FromLong(ai.bytes / (ssize * nchannels));
411}
412
413/* Flush the device */
414static PyObject *
415lad_flush(lad_t *self, PyObject *args)
416{
417 if (!PyArg_ParseTuple(args, ":flush")) return NULL;
418
419 if (ioctl(self->x_fd, SNDCTL_DSP_SYNC, NULL) == -1) {
420 PyErr_SetFromErrno(LinuxAudioError);
421 return NULL;
422 }
423 Py_INCREF(Py_None);
424 return Py_None;
425}
426
427static PyObject *
428lad_getptr(lad_t *self, PyObject *args)
429{
430 count_info info;
431 int req;
432
433 if (!PyArg_ParseTuple(args, ":getptr"))
434 return NULL;
435
436 if (self->x_mode == O_RDONLY)
437 req = SNDCTL_DSP_GETIPTR;
438 else
439 req = SNDCTL_DSP_GETOPTR;
440 if (ioctl(self->x_fd, req, &info) == -1) {
441 PyErr_SetFromErrno(LinuxAudioError);
442 return NULL;
443 }
444 return Py_BuildValue("iii", info.bytes, info.blocks, info.ptr);
445}
446
447static PyMethodDef lad_methods[] = {
448 { "read", (PyCFunction)lad_read, METH_VARARGS },
449 { "write", (PyCFunction)lad_write, METH_VARARGS },
450 { "setparameters", (PyCFunction)lad_setparameters, METH_VARARGS },
451 { "bufsize", (PyCFunction)lad_bufsize, METH_VARARGS },
452 { "obufcount", (PyCFunction)lad_obufcount, METH_VARARGS },
453 { "obuffree", (PyCFunction)lad_obuffree, METH_VARARGS },
454 { "flush", (PyCFunction)lad_flush, METH_VARARGS },
455 { "close", (PyCFunction)lad_close, METH_VARARGS },
456 { "fileno", (PyCFunction)lad_fileno, METH_VARARGS },
457 { "getptr", (PyCFunction)lad_getptr, METH_VARARGS },
458 { NULL, NULL} /* sentinel */
459};
460
461static PyObject *
462lad_getattr(lad_t *xp, char *name)
463{
464 return Py_FindMethod(lad_methods, (PyObject *)xp, name);
465}
466
467static PyTypeObject Ladtype = {
468 PyObject_HEAD_INIT(&PyType_Type)
469 0, /*ob_size*/
470 "linuxaudiodev.linux_audio_device", /*tp_name*/
471 sizeof(lad_t), /*tp_size*/
472 0, /*tp_itemsize*/
473 /* methods */
474 (destructor)lad_dealloc, /*tp_dealloc*/
475 0, /*tp_print*/
476 (getattrfunc)lad_getattr, /*tp_getattr*/
477 0, /*tp_setattr*/
478 0, /*tp_compare*/
479 0, /*tp_repr*/
480};
481
482static PyObject *
483ladopen(PyObject *self, PyObject *args)
484{
485 return (PyObject *)newladobject(args);
486}
487
488static PyMethodDef linuxaudiodev_methods[] = {
489 { "open", ladopen, METH_VARARGS },
490 { 0, 0 },
491};
492
493void
494initlinuxaudiodev(void)
495{
496 PyObject *m;
497
498 m = Py_InitModule("linuxaudiodev", linuxaudiodev_methods);
499
500 LinuxAudioError = PyErr_NewException("linuxaudiodev.error", NULL, NULL);
501 if (LinuxAudioError)
502 PyModule_AddObject(m, "error", LinuxAudioError);
503
504 if (PyModule_AddIntConstant(m, "AFMT_MU_LAW", (long)AFMT_MU_LAW) == -1)
505 return;
506 if (PyModule_AddIntConstant(m, "AFMT_A_LAW", (long)AFMT_A_LAW) == -1)
507 return;
508 if (PyModule_AddIntConstant(m, "AFMT_U8", (long)AFMT_U8) == -1)
509 return;
510 if (PyModule_AddIntConstant(m, "AFMT_S8", (long)AFMT_S8) == -1)
511 return;
512 if (PyModule_AddIntConstant(m, "AFMT_U16_BE", (long)AFMT_U16_BE) == -1)
513 return;
514 if (PyModule_AddIntConstant(m, "AFMT_U16_LE", (long)AFMT_U16_LE) == -1)
515 return;
516 if (PyModule_AddIntConstant(m, "AFMT_S16_BE", (long)AFMT_S16_BE) == -1)
517 return;
518 if (PyModule_AddIntConstant(m, "AFMT_S16_LE", (long)AFMT_S16_LE) == -1)
519 return;
520 if (PyModule_AddIntConstant(m, "AFMT_S16_NE", (long)AFMT_S16_NE) == -1)
521 return;
522
523 return;
524}