This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Modules / linuxaudiodev.c
blob37ad5ff4c612346205b3293903ce9ef2add50f3e
1 /* Hey Emacs, this is -*-C-*-
2 ******************************************************************************
3 * linuxaudiodev.c -- Linux audio device for python.
4 *
5 * Author : Peter Bosch
6 * Created On : Thu Mar 2 21:10:33 2000
7 * Status : Unknown, Use with caution!
8 *
9 * Unless other notices are present in any part of this file
10 * explicitly claiming copyrights for other people and/or
11 * organizations, the contents of this file is fully copyright
12 * (C) 2000 Peter Bosch, all rights reserved.
13 ******************************************************************************
16 #include "Python.h"
17 #include "structmember.h"
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
23 #ifdef HAVE_FCNTL_H
24 #include <fcntl.h>
25 #else
26 #define O_RDONLY 00
27 #define O_WRONLY 01
28 #endif
31 #include <sys/ioctl.h>
32 #if defined(linux)
33 #include <linux/soundcard.h>
35 typedef unsigned long uint32_t;
37 #elif defined(__FreeBSD__)
38 #include <machine/soundcard.h>
40 #ifndef SNDCTL_DSP_CHANNELS
41 #define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
42 #endif
44 #endif
46 typedef struct {
47 PyObject_HEAD;
48 int x_fd; /* The open file */
49 int x_mode; /* file mode */
50 int x_icount; /* Input count */
51 int x_ocount; /* Output count */
52 uint32_t x_afmts; /* Audio formats supported by hardware*/
53 } lad_t;
55 /* XXX several format defined in soundcard.h are not supported,
56 including _NE (native endian) options and S32 options
59 static struct {
60 int a_bps;
61 uint32_t a_fmt;
62 char *a_name;
63 } audio_types[] = {
64 { 8, AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
65 { 8, AFMT_A_LAW, "logarithmic A-law 8-bit audio" },
66 { 8, AFMT_U8, "linear unsigned 8-bit audio" },
67 { 8, AFMT_S8, "linear signed 8-bit audio" },
68 { 16, AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
69 { 16, AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
70 { 16, AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
71 { 16, AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
72 { 16, AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
75 static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]);
77 staticforward PyTypeObject Ladtype;
79 static PyObject *LinuxAudioError;
81 static lad_t *
82 newladobject(PyObject *arg)
84 lad_t *xp;
85 int fd, afmts, imode;
86 char *mode;
87 char *basedev;
89 /* Check arg for r/w/rw */
90 if (!PyArg_ParseTuple(arg, "s:open", &mode)) return NULL;
91 if (strcmp(mode, "r") == 0)
92 imode = O_RDONLY;
93 else if (strcmp(mode, "w") == 0)
94 imode = O_WRONLY;
95 else {
96 PyErr_SetString(LinuxAudioError, "mode should be 'r' or 'w'");
97 return NULL;
100 /* Open the correct device. The base device name comes from the
101 * AUDIODEV environment variable first, then /dev/dsp. The
102 * control device tacks "ctl" onto the base device name.
104 * Note that the only difference between /dev/audio and /dev/dsp
105 * is that the former uses logarithmic mu-law encoding and the
106 * latter uses 8-bit unsigned encoding.
109 basedev = getenv("AUDIODEV");
110 if (!basedev)
111 basedev = "/dev/dsp";
113 if ((fd = open(basedev, imode)) == -1) {
114 PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
115 return NULL;
117 if (imode == O_WRONLY && ioctl(fd, SNDCTL_DSP_NONBLOCK, NULL) == -1) {
118 PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
119 return NULL;
121 if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
122 PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
123 return NULL;
125 /* Create and initialize the object */
126 if ((xp = PyObject_New(lad_t, &Ladtype)) == NULL) {
127 close(fd);
128 return NULL;
130 xp->x_fd = fd;
131 xp->x_mode = imode;
132 xp->x_icount = xp->x_ocount = 0;
133 xp->x_afmts = afmts;
134 return xp;
137 static void
138 lad_dealloc(lad_t *xp)
140 /* if already closed, don't reclose it */
141 if (xp->x_fd != -1)
142 close(xp->x_fd);
143 PyObject_Del(xp);
146 static PyObject *
147 lad_read(lad_t *self, PyObject *args)
149 int size, count;
150 char *cp;
151 PyObject *rv;
153 if (!PyArg_ParseTuple(args, "i:read", &size))
154 return NULL;
155 rv = PyString_FromStringAndSize(NULL, size);
156 if (rv == NULL)
157 return NULL;
158 cp = PyString_AS_STRING(rv);
159 if ((count = read(self->x_fd, cp, size)) < 0) {
160 PyErr_SetFromErrno(LinuxAudioError);
161 Py_DECREF(rv);
162 return NULL;
164 self->x_icount += count;
165 if (_PyString_Resize(&rv, count) == -1)
166 return NULL;
167 return rv;
170 static PyObject *
171 lad_write(lad_t *self, PyObject *args)
173 char *cp;
174 int rv, size;
175 fd_set write_set_fds;
176 struct timeval tv;
177 int select_retval;
179 if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
180 return NULL;
182 /* use select to wait for audio device to be available */
183 FD_ZERO(&write_set_fds);
184 FD_SET(self->x_fd, &write_set_fds);
185 tv.tv_sec = 4; /* timeout values */
186 tv.tv_usec = 0;
188 while (size > 0) {
189 select_retval = select(self->x_fd+1, NULL, &write_set_fds, NULL, &tv);
190 tv.tv_sec = 1; tv.tv_usec = 0; /* willing to wait this long next time*/
191 if (select_retval) {
192 if ((rv = write(self->x_fd, cp, size)) == -1) {
193 if (errno != EAGAIN) {
194 PyErr_SetFromErrno(LinuxAudioError);
195 return NULL;
196 } else {
197 errno = 0; /* EAGAIN: buffer is full, try again */
199 } else {
200 self->x_ocount += rv;
201 size -= rv;
202 cp += rv;
204 } else {
205 /* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
206 PyErr_SetFromErrno(LinuxAudioError);
207 return NULL;
210 Py_INCREF(Py_None);
211 return Py_None;
214 static PyObject *
215 lad_close(lad_t *self, PyObject *args)
217 if (!PyArg_ParseTuple(args, ":close"))
218 return NULL;
220 if (self->x_fd >= 0) {
221 close(self->x_fd);
222 self->x_fd = -1;
224 Py_INCREF(Py_None);
225 return Py_None;
228 static PyObject *
229 lad_fileno(lad_t *self, PyObject *args)
231 if (!PyArg_ParseTuple(args, ":fileno"))
232 return NULL;
233 return PyInt_FromLong(self->x_fd);
236 static PyObject *
237 lad_setparameters(lad_t *self, PyObject *args)
239 int rate, ssize, nchannels, n, fmt, emulate=0;
241 if (!PyArg_ParseTuple(args, "iiii|i:setparameters",
242 &rate, &ssize, &nchannels, &fmt, &emulate))
243 return NULL;
245 if (rate < 0) {
246 PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
247 rate);
248 return NULL;
250 if (ssize < 0) {
251 PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
252 ssize);
253 return NULL;
255 if (nchannels != 1 && nchannels != 2) {
256 PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
257 nchannels);
258 return NULL;
261 if (ioctl(self->x_fd, SNDCTL_DSP_SPEED, &rate) == -1) {
262 PyErr_SetFromErrno(LinuxAudioError);
263 return NULL;
265 if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, &nchannels) == -1) {
266 PyErr_SetFromErrno(LinuxAudioError);
267 return NULL;
270 for (n = 0; n < n_audio_types; n++)
271 if (fmt == audio_types[n].a_fmt)
272 break;
273 if (n == n_audio_types) {
274 PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
275 return NULL;
277 if (audio_types[n].a_bps != ssize) {
278 PyErr_Format(PyExc_ValueError,
279 "for %s, expected sample size %d, not %d",
280 audio_types[n].a_name, audio_types[n].a_bps, ssize);
281 return NULL;
284 if (emulate == 0) {
285 if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
286 PyErr_Format(PyExc_ValueError,
287 "%s format not supported by device",
288 audio_types[n].a_name);
289 return NULL;
292 if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT,
293 &audio_types[n].a_fmt) == -1) {
294 PyErr_SetFromErrno(LinuxAudioError);
295 return NULL;
298 Py_INCREF(Py_None);
299 return Py_None;
302 static int
303 _ssize(lad_t *self, int *nchannels, int *ssize)
305 int fmt;
307 fmt = 0;
308 if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
309 return -errno;
311 switch (fmt) {
312 case AFMT_MU_LAW:
313 case AFMT_A_LAW:
314 case AFMT_U8:
315 case AFMT_S8:
316 *ssize = sizeof(char);
317 break;
318 case AFMT_S16_LE:
319 case AFMT_S16_BE:
320 case AFMT_U16_LE:
321 case AFMT_U16_BE:
322 *ssize = sizeof(short);
323 break;
324 case AFMT_MPEG:
325 case AFMT_IMA_ADPCM:
326 default:
327 return -EOPNOTSUPP;
329 *nchannels = 0;
330 if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, nchannels) < 0)
331 return -errno;
332 return 0;
336 /* bufsize returns the size of the hardware audio buffer in number
337 of samples */
338 static PyObject *
339 lad_bufsize(lad_t *self, PyObject *args)
341 audio_buf_info ai;
342 int nchannels, ssize;
344 if (!PyArg_ParseTuple(args, ":bufsize")) return NULL;
346 if (_ssize(self, &nchannels, &ssize) < 0) {
347 PyErr_SetFromErrno(LinuxAudioError);
348 return NULL;
350 if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
351 PyErr_SetFromErrno(LinuxAudioError);
352 return NULL;
354 return PyInt_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
357 /* obufcount returns the number of samples that are available in the
358 hardware for playing */
359 static PyObject *
360 lad_obufcount(lad_t *self, PyObject *args)
362 audio_buf_info ai;
363 int nchannels, ssize;
365 if (!PyArg_ParseTuple(args, ":obufcount"))
366 return NULL;
368 if (_ssize(self, &nchannels, &ssize) < 0) {
369 PyErr_SetFromErrno(LinuxAudioError);
370 return NULL;
372 if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
373 PyErr_SetFromErrno(LinuxAudioError);
374 return NULL;
376 return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
377 (ssize * nchannels));
380 /* obufcount returns the number of samples that can be played without
381 blocking */
382 static PyObject *
383 lad_obuffree(lad_t *self, PyObject *args)
385 audio_buf_info ai;
386 int nchannels, ssize;
388 if (!PyArg_ParseTuple(args, ":obuffree"))
389 return NULL;
391 if (_ssize(self, &nchannels, &ssize) < 0) {
392 PyErr_SetFromErrno(LinuxAudioError);
393 return NULL;
395 if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
396 PyErr_SetFromErrno(LinuxAudioError);
397 return NULL;
399 return PyInt_FromLong(ai.bytes / (ssize * nchannels));
402 /* Flush the device */
403 static PyObject *
404 lad_flush(lad_t *self, PyObject *args)
406 if (!PyArg_ParseTuple(args, ":flush")) return NULL;
408 if (ioctl(self->x_fd, SNDCTL_DSP_SYNC, NULL) == -1) {
409 PyErr_SetFromErrno(LinuxAudioError);
410 return NULL;
412 Py_INCREF(Py_None);
413 return Py_None;
416 static PyObject *
417 lad_getptr(lad_t *self, PyObject *args)
419 count_info info;
420 int req;
422 if (!PyArg_ParseTuple(args, ":getptr"))
423 return NULL;
425 if (self->x_mode == O_RDONLY)
426 req = SNDCTL_DSP_GETIPTR;
427 else
428 req = SNDCTL_DSP_GETOPTR;
429 if (ioctl(self->x_fd, req, &info) == -1) {
430 PyErr_SetFromErrno(LinuxAudioError);
431 return NULL;
433 return Py_BuildValue("iii", info.bytes, info.blocks, info.ptr);
436 static PyMethodDef lad_methods[] = {
437 { "read", (PyCFunction)lad_read, METH_VARARGS },
438 { "write", (PyCFunction)lad_write, METH_VARARGS },
439 { "setparameters", (PyCFunction)lad_setparameters, METH_VARARGS },
440 { "bufsize", (PyCFunction)lad_bufsize, METH_VARARGS },
441 { "obufcount", (PyCFunction)lad_obufcount, METH_VARARGS },
442 { "obuffree", (PyCFunction)lad_obuffree, METH_VARARGS },
443 { "flush", (PyCFunction)lad_flush, METH_VARARGS },
444 { "close", (PyCFunction)lad_close, METH_VARARGS },
445 { "fileno", (PyCFunction)lad_fileno, METH_VARARGS },
446 { "getptr", (PyCFunction)lad_getptr, METH_VARARGS },
447 { NULL, NULL} /* sentinel */
450 static PyObject *
451 lad_getattr(lad_t *xp, char *name)
453 return Py_FindMethod(lad_methods, (PyObject *)xp, name);
456 static PyTypeObject Ladtype = {
457 PyObject_HEAD_INIT(&PyType_Type)
458 0, /*ob_size*/
459 "linux_audio_device", /*tp_name*/
460 sizeof(lad_t), /*tp_size*/
461 0, /*tp_itemsize*/
462 /* methods */
463 (destructor)lad_dealloc, /*tp_dealloc*/
464 0, /*tp_print*/
465 (getattrfunc)lad_getattr, /*tp_getattr*/
466 0, /*tp_setattr*/
467 0, /*tp_compare*/
468 0, /*tp_repr*/
471 static PyObject *
472 ladopen(PyObject *self, PyObject *args)
474 return (PyObject *)newladobject(args);
477 static PyMethodDef linuxaudiodev_methods[] = {
478 { "open", ladopen, METH_VARARGS },
479 { 0, 0 },
482 void
483 initlinuxaudiodev(void)
485 PyObject *m;
487 m = Py_InitModule("linuxaudiodev", linuxaudiodev_methods);
489 LinuxAudioError = PyErr_NewException("linuxaudiodev.error", NULL, NULL);
490 if (LinuxAudioError)
491 PyModule_AddObject(m, "error", LinuxAudioError);
493 if (PyModule_AddIntConstant(m, "AFMT_MU_LAW", (long)AFMT_MU_LAW) == -1)
494 return;
495 if (PyModule_AddIntConstant(m, "AFMT_A_LAW", (long)AFMT_A_LAW) == -1)
496 return;
497 if (PyModule_AddIntConstant(m, "AFMT_U8", (long)AFMT_U8) == -1)
498 return;
499 if (PyModule_AddIntConstant(m, "AFMT_S8", (long)AFMT_S8) == -1)
500 return;
501 if (PyModule_AddIntConstant(m, "AFMT_U16_BE", (long)AFMT_U16_BE) == -1)
502 return;
503 if (PyModule_AddIntConstant(m, "AFMT_U16_LE", (long)AFMT_U16_LE) == -1)
504 return;
505 if (PyModule_AddIntConstant(m, "AFMT_S16_BE", (long)AFMT_S16_BE) == -1)
506 return;
507 if (PyModule_AddIntConstant(m, "AFMT_S16_LE", (long)AFMT_S16_LE) == -1)
508 return;
509 if (PyModule_AddIntConstant(m, "AFMT_S16_NE", (long)AFMT_S16_NE) == -1)
510 return;
512 return;