home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Modules / linuxaudiodev.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  12.7 KB  |  494 lines

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