linuxaudiodev.c 13.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Hey Emacs, this is -*-C-*- 
 ******************************************************************************
 * linuxaudiodev.c -- Linux audio device for python.
 * 
 * Author          : Peter Bosch
 * Created On      : Thu Mar  2 21:10:33 2000
 * Status          : Unknown, Use with caution!
 * 
 * Unless other notices are present in any part of this file
 * explicitly claiming copyrights for other people and/or 
 * organizations, the contents of this file is fully copyright 
 * (C) 2000 Peter Bosch, all rights reserved.
 ******************************************************************************
 */

#include "Python.h"
#include "structmember.h"

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
Jeremy Hylton's avatar
Jeremy Hylton committed
25 26 27
#else
#define O_RDONLY 00
#define O_WRONLY 01
28 29
#endif

Jeremy Hylton's avatar
Jeremy Hylton committed
30

31
#include <sys/ioctl.h>
32
#if defined(linux)
33 34 35 36
#include <linux/soundcard.h>

typedef unsigned long uint32_t;

37 38 39 40 41 42 43 44 45
#elif defined(__FreeBSD__)
#include <machine/soundcard.h>

#ifndef SNDCTL_DSP_CHANNELS
#define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
#endif

#endif

46
typedef struct {
47 48
    PyObject_HEAD;
    int		x_fd;		/* The open file */
Jeremy Hylton's avatar
Jeremy Hylton committed
49
    int         x_mode;           /* file mode */
50 51
    int		x_icount;	/* Input count */
    int		x_ocount;	/* Output count */
Jeremy Hylton's avatar
Jeremy Hylton committed
52
    uint32_t	x_afmts;	/* Audio formats supported by hardware*/
53 54
} lad_t;

Jeremy Hylton's avatar
Jeremy Hylton committed
55 56 57 58
/* XXX several format defined in soundcard.h are not supported,
   including _NE (native endian) options and S32 options
*/

59
static struct {
60 61
    int		a_bps;
    uint32_t	a_fmt;
Jeremy Hylton's avatar
Jeremy Hylton committed
62
    char       *a_name;
63
} audio_types[] = {
64 65 66 67 68 69 70 71
    {  8, 	AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
    {  8, 	AFMT_A_LAW,  "logarithmic A-law 8-bit audio" },
    {  8,	AFMT_U8,     "linear unsigned 8-bit audio" },
    {  8, 	AFMT_S8,     "linear signed 8-bit audio" },
    { 16, 	AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
    { 16, 	AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
    { 16, 	AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
    { 16, 	AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
72
    { 16, 	AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
73 74
};

Jeremy Hylton's avatar
Jeremy Hylton committed
75
static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]);
76 77 78 79 80 81 82 83

staticforward PyTypeObject Ladtype;

static PyObject *LinuxAudioError;

static lad_t *
newladobject(PyObject *arg)
{
84 85 86 87 88 89 90 91
    lad_t *xp;
    int fd, afmts, imode;
    char *mode;
    char *basedev;

    /* Check arg for r/w/rw */
    if (!PyArg_ParseTuple(arg, "s:open", &mode)) return NULL;
    if (strcmp(mode, "r") == 0)
Jeremy Hylton's avatar
Jeremy Hylton committed
92
        imode = O_RDONLY;
93
    else if (strcmp(mode, "w") == 0)
Jeremy Hylton's avatar
Jeremy Hylton committed
94
        imode = O_WRONLY;
95
    else {
96
        PyErr_SetString(LinuxAudioError, "mode should be 'r' or 'w'");
97 98 99 100
        return NULL;
    }

    /* Open the correct device.  The base device name comes from the
Jeremy Hylton's avatar
Jeremy Hylton committed
101
     * AUDIODEV environment variable first, then /dev/dsp.  The
102
     * control device tacks "ctl" onto the base device name.
Jeremy Hylton's avatar
Jeremy Hylton committed
103 104 105 106
     * 
     * Note that the only difference between /dev/audio and /dev/dsp
     * is that the former uses logarithmic mu-law encoding and the
     * latter uses 8-bit unsigned encoding.
107
     */
Jeremy Hylton's avatar
Jeremy Hylton committed
108

109 110 111 112
    basedev = getenv("AUDIODEV");
    if (!basedev)
        basedev = "/dev/dsp";

Jeremy Hylton's avatar
Jeremy Hylton committed
113
    if ((fd = open(basedev, imode)) == -1) {
114 115 116
        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
        return NULL;
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
117
    if (imode == O_WRONLY && ioctl(fd, SNDCTL_DSP_NONBLOCK, NULL) == -1) {
118 119 120
        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
        return NULL;
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
121
    if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
122 123
        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
        return NULL;
124
    }
125 126 127 128 129
    /* Create and initialize the object */
    if ((xp = PyObject_New(lad_t, &Ladtype)) == NULL) {
        close(fd);
        return NULL;
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
130 131
    xp->x_fd = fd;
    xp->x_mode = imode;
132 133 134
    xp->x_icount = xp->x_ocount = 0;
    xp->x_afmts  = afmts;
    return xp;
135 136 137 138 139
}

static void
lad_dealloc(lad_t *xp)
{
140 141 142
    /* if already closed, don't reclose it */
    if (xp->x_fd != -1)
	close(xp->x_fd);
143
    PyObject_Del(xp);
144 145 146 147 148
}

static PyObject *
lad_read(lad_t *self, PyObject *args)
{
149 150 151
    int size, count;
    char *cp;
    PyObject *rv;
152
	
153 154 155 156 157
    if (!PyArg_ParseTuple(args, "i:read", &size))
        return NULL;
    rv = PyString_FromStringAndSize(NULL, size);
    if (rv == NULL)
        return NULL;
Jeremy Hylton's avatar
Jeremy Hylton committed
158
    cp = PyString_AS_STRING(rv);
159 160 161 162 163 164
    if ((count = read(self->x_fd, cp, size)) < 0) {
        PyErr_SetFromErrno(LinuxAudioError);
        Py_DECREF(rv);
        return NULL;
    }
    self->x_icount += count;
Jeremy Hylton's avatar
Jeremy Hylton committed
165 166
    if (_PyString_Resize(&rv, count) == -1)
	return NULL;
167
    return rv;
168 169 170 171 172
}

static PyObject *
lad_write(lad_t *self, PyObject *args)
{
173 174
    char *cp;
    int rv, size;
175 176 177 178
    fd_set write_set_fds;
    struct timeval tv;
    int select_retval;
    
Jeremy Hylton's avatar
Jeremy Hylton committed
179 180
    if (!PyArg_ParseTuple(args, "s#:write", &cp, &size)) 
	return NULL;
181

182 183 184 185 186 187
    /* use select to wait for audio device to be available */
    FD_ZERO(&write_set_fds);
    FD_SET(self->x_fd, &write_set_fds);
    tv.tv_sec = 4; /* timeout values */
    tv.tv_usec = 0; 

188
    while (size > 0) {
189 190 191
      select_retval = select(self->x_fd+1, NULL, &write_set_fds, NULL, &tv);
      tv.tv_sec = 1; tv.tv_usec = 0; /* willing to wait this long next time*/
      if (select_retval) {
Jeremy Hylton's avatar
Jeremy Hylton committed
192
        if ((rv = write(self->x_fd, cp, size)) == -1) {
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
	  if (errno != EAGAIN) {
	    PyErr_SetFromErrno(LinuxAudioError);
	    return NULL;
	  } else {
	    errno = 0; /* EAGAIN: buffer is full, try again */
	  }
        } else {
	  self->x_ocount += rv;
	  size -= rv;
	  cp += rv;
	}
      } else {
	/* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
	PyErr_SetFromErrno(LinuxAudioError);
	return NULL;
      }
209
    }
210 211
    Py_INCREF(Py_None);
    return Py_None;
212 213 214 215 216
}

static PyObject *
lad_close(lad_t *self, PyObject *args)
{
Jeremy Hylton's avatar
Jeremy Hylton committed
217 218 219
    if (!PyArg_ParseTuple(args, ":close"))
	return NULL;

220 221 222 223 224 225
    if (self->x_fd >= 0) {
        close(self->x_fd);
        self->x_fd = -1;
    }
    Py_INCREF(Py_None);
    return Py_None;
226 227 228 229 230
}

static PyObject *
lad_fileno(lad_t *self, PyObject *args)
{
Jeremy Hylton's avatar
Jeremy Hylton committed
231 232
    if (!PyArg_ParseTuple(args, ":fileno")) 
	return NULL;
233
    return PyInt_FromLong(self->x_fd);
234 235 236 237 238
}

static PyObject *
lad_setparameters(lad_t *self, PyObject *args)
{
Jeremy Hylton's avatar
Jeremy Hylton committed
239
    int rate, ssize, nchannels, n, fmt, emulate=0;
240

Jeremy Hylton's avatar
Jeremy Hylton committed
241 242
    if (!PyArg_ParseTuple(args, "iiii|i:setparameters",
                          &rate, &ssize, &nchannels, &fmt, &emulate))
243
        return NULL;
244
  
Jeremy Hylton's avatar
Jeremy Hylton committed
245 246 247 248
    if (rate < 0) {
	PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
		     rate); 
	return NULL;
249
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
250 251 252 253 254 255 256 257 258
    if (ssize < 0) {
	PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
		     ssize);
	return NULL;
    }
    if (nchannels != 1 && nchannels != 2) {
	PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
		     nchannels);
	return NULL;
259
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
260 261

    for (n = 0; n < n_audio_types; n++)
262 263
        if (fmt == audio_types[n].a_fmt)
            break;
Jeremy Hylton's avatar
Jeremy Hylton committed
264 265 266 267 268 269
    if (n == n_audio_types) {
	PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
	return NULL;
    }
    if (audio_types[n].a_bps != ssize) {
	PyErr_Format(PyExc_ValueError, 
270 271
		     "for %s, expected sample size %d, not %d",
		     audio_types[n].a_name, audio_types[n].a_bps, ssize);
Jeremy Hylton's avatar
Jeremy Hylton committed
272 273
	return NULL;
    }
274

Jeremy Hylton's avatar
Jeremy Hylton committed
275 276 277
    if (emulate == 0) {
	if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
	    PyErr_Format(PyExc_ValueError, 
278
			 "%s format not supported by device",
Jeremy Hylton's avatar
Jeremy Hylton committed
279 280 281
			 audio_types[n].a_name);
	    return NULL;
	}
282
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
283 284
    if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, 
	      &audio_types[n].a_fmt) == -1) {
285 286 287
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
288 289 290 291 292 293 294 295
    if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, &nchannels) == -1) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    if (ioctl(self->x_fd, SNDCTL_DSP_SPEED, &rate) == -1) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
296

297 298
    Py_INCREF(Py_None);
    return Py_None;
299 300 301 302 303
}

static int
_ssize(lad_t *self, int *nchannels, int *ssize)
{
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    int fmt;

    fmt = 0;
    if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0) 
        return -errno;

    switch (fmt) {
    case AFMT_MU_LAW:
    case AFMT_A_LAW:
    case AFMT_U8:
    case AFMT_S8:
        *ssize = sizeof(char);
        break;
    case AFMT_S16_LE:
    case AFMT_S16_BE:
    case AFMT_U16_LE:
    case AFMT_U16_BE:
        *ssize = sizeof(short);
        break;
    case AFMT_MPEG:
    case AFMT_IMA_ADPCM:
    default:
        return -EOPNOTSUPP;
    }
    *nchannels = 0;
    if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, nchannels) < 0)
        return -errno;
    return 0;
332 333 334 335
}


/* bufsize returns the size of the hardware audio buffer in number 
336
   of samples */
337 338 339
static PyObject *
lad_bufsize(lad_t *self, PyObject *args)
{
340 341
    audio_buf_info ai;
    int nchannels, ssize;
342

343
    if (!PyArg_ParseTuple(args, ":bufsize")) return NULL;
344

345 346 347 348 349 350 351 352 353
    if (_ssize(self, &nchannels, &ssize) < 0) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    return PyInt_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
354 355 356 357 358 359 360
}

/* obufcount returns the number of samples that are available in the 
   hardware for playing */
static PyObject *
lad_obufcount(lad_t *self, PyObject *args)
{
361 362
    audio_buf_info ai;
    int nchannels, ssize;
363

364 365
    if (!PyArg_ParseTuple(args, ":obufcount"))
        return NULL;
366

367 368 369 370 371 372 373 374 375 376
    if (_ssize(self, &nchannels, &ssize) < 0) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) / 
                          (ssize * nchannels));
377 378 379
}

/* obufcount returns the number of samples that can be played without
380
   blocking */
381 382 383
static PyObject *
lad_obuffree(lad_t *self, PyObject *args)
{
384 385
    audio_buf_info ai;
    int nchannels, ssize;
386

387 388
    if (!PyArg_ParseTuple(args, ":obuffree"))
        return NULL;
389

390 391 392 393 394 395 396 397 398
    if (_ssize(self, &nchannels, &ssize) < 0) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    return PyInt_FromLong(ai.bytes / (ssize * nchannels));
399 400 401 402 403 404
}

/* Flush the device */
static PyObject *
lad_flush(lad_t *self, PyObject *args)
{
405
    if (!PyArg_ParseTuple(args, ":flush")) return NULL;
406

Jeremy Hylton's avatar
Jeremy Hylton committed
407
    if (ioctl(self->x_fd, SNDCTL_DSP_SYNC, NULL) == -1) {
408 409 410 411 412
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    Py_INCREF(Py_None);
    return Py_None;
413 414
}

Jeremy Hylton's avatar
Jeremy Hylton committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
static PyObject *
lad_getptr(lad_t *self, PyObject *args)
{
    count_info info;
    int req;

    if (!PyArg_ParseTuple(args, ":getptr"))
	return NULL;
    
    if (self->x_mode == O_RDONLY)
	req = SNDCTL_DSP_GETIPTR;
    else
	req = SNDCTL_DSP_GETOPTR;
    if (ioctl(self->x_fd, req, &info) == -1) {
        PyErr_SetFromErrno(LinuxAudioError);
        return NULL;
    }
    return Py_BuildValue("iii", info.bytes, info.blocks, info.ptr);
}

435
static PyMethodDef lad_methods[] = {
436 437 438 439 440 441 442 443 444
    { "read",		(PyCFunction)lad_read, METH_VARARGS },
    { "write",		(PyCFunction)lad_write, METH_VARARGS },
    { "setparameters",	(PyCFunction)lad_setparameters, METH_VARARGS },
    { "bufsize",	(PyCFunction)lad_bufsize, METH_VARARGS },
    { "obufcount",	(PyCFunction)lad_obufcount, METH_VARARGS },
    { "obuffree",	(PyCFunction)lad_obuffree, METH_VARARGS },
    { "flush",		(PyCFunction)lad_flush, METH_VARARGS },
    { "close",		(PyCFunction)lad_close, METH_VARARGS },
    { "fileno",     	(PyCFunction)lad_fileno, METH_VARARGS },
Jeremy Hylton's avatar
Jeremy Hylton committed
445
    { "getptr",         (PyCFunction)lad_getptr, METH_VARARGS },
446
    { NULL,		NULL}		/* sentinel */
447 448 449 450 451
};

static PyObject *
lad_getattr(lad_t *xp, char *name)
{
452
    return Py_FindMethod(lad_methods, (PyObject *)xp, name);
453 454 455
}

static PyTypeObject Ladtype = {
456 457
    PyObject_HEAD_INIT(&PyType_Type)
    0,				/*ob_size*/
458
    "linuxaudiodev.linux_audio_device", /*tp_name*/
459 460 461 462 463 464 465 466 467
    sizeof(lad_t),		/*tp_size*/
    0,				/*tp_itemsize*/
    /* methods */
    (destructor)lad_dealloc,	/*tp_dealloc*/
    0,				/*tp_print*/
    (getattrfunc)lad_getattr,	/*tp_getattr*/
    0,				/*tp_setattr*/
    0,				/*tp_compare*/
    0,				/*tp_repr*/
468 469 470 471 472
};

static PyObject *
ladopen(PyObject *self, PyObject *args)
{
473
    return (PyObject *)newladobject(args);
474 475 476
}

static PyMethodDef linuxaudiodev_methods[] = {
477 478
    { "open", ladopen, METH_VARARGS },
    { 0, 0 },
479 480 481
};

void
482
initlinuxaudiodev(void)
483
{
Jeremy Hylton's avatar
Jeremy Hylton committed
484
    PyObject *m;
485
  
486 487 488 489
    m = Py_InitModule("linuxaudiodev", linuxaudiodev_methods);

    LinuxAudioError = PyErr_NewException("linuxaudiodev.error", NULL, NULL);
    if (LinuxAudioError)
Jeremy Hylton's avatar
Jeremy Hylton committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
	PyModule_AddObject(m, "error", LinuxAudioError);

    if (PyModule_AddIntConstant(m, "AFMT_MU_LAW", (long)AFMT_MU_LAW) == -1)
	return;
    if (PyModule_AddIntConstant(m, "AFMT_A_LAW", (long)AFMT_A_LAW) == -1)
	return;
    if (PyModule_AddIntConstant(m, "AFMT_U8", (long)AFMT_U8) == -1)
	return;
    if (PyModule_AddIntConstant(m, "AFMT_S8", (long)AFMT_S8) == -1)
	return;
    if (PyModule_AddIntConstant(m, "AFMT_U16_BE", (long)AFMT_U16_BE) == -1)
	return;
    if (PyModule_AddIntConstant(m, "AFMT_U16_LE", (long)AFMT_U16_LE) == -1)
	return;
    if (PyModule_AddIntConstant(m, "AFMT_S16_BE", (long)AFMT_S16_BE) == -1)
	return;
    if (PyModule_AddIntConstant(m, "AFMT_S16_LE", (long)AFMT_S16_LE) == -1)
	return;
508 509
    if (PyModule_AddIntConstant(m, "AFMT_S16_NE", (long)AFMT_S16_NE) == -1)
	return;
Jeremy Hylton's avatar
Jeremy Hylton committed
510

511
    return;
512
}