Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

606 lines
21KB

  1. /************************************************************************/
  2. /* PyRtAudio: a python wrapper around RtAudio
  3. Copyright (c) 2011 Antoine Lefebvre
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation files
  6. (the "Software"), to deal in the Software without restriction,
  7. including without limitation the rights to use, copy, modify, merge,
  8. publish, distribute, sublicense, and/or sell copies of the Software,
  9. and to permit persons to whom the Software is furnished to do so,
  10. subject to the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. Any person wishing to distribute modifications to the Software is
  14. asked to send the modifications to the original developer so that
  15. they can be incorporated into the canonical version. This is,
  16. however, not a binding provision of this license.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  20. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  21. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  22. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  23. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. */
  25. /************************************************************************/
  26. // This software is in the development stage
  27. // Do not expect compatibility with future versions.
  28. // Comments, suggestions, new features, bug fixes, etc. are welcome
  29. #include <Python.h>
  30. #include "RtAudio.h"
  31. extern "C" {
  32. typedef struct
  33. {
  34. PyObject_HEAD;
  35. RtAudio *dac;
  36. RtAudioFormat _format;
  37. int _bufferSize;
  38. unsigned int inputChannels;
  39. PyObject *callback_func;
  40. } PyRtAudio;
  41. static PyObject *RtAudioError;
  42. static int callback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
  43. double streamTime, RtAudioStreamStatus status, void *data )
  44. {
  45. PyRtAudio* self = (PyRtAudio*) data;
  46. if (status == RTAUDIO_OUTPUT_UNDERFLOW)
  47. printf("underflow.\n");
  48. if (self == NULL) return -1;
  49. float* in = (float *) inputBuffer;
  50. float* out = (float *) outputBuffer;
  51. PyObject *py_callback_func = self->callback_func;
  52. int retval = 0;
  53. if (py_callback_func) {
  54. PyGILState_STATE gstate = PyGILState_Ensure();
  55. PyObject* iBuffer = PyBuffer_FromMemory(in, sizeof(float) * self->inputChannels * nBufferFrames);
  56. PyObject* oBuffer = PyBuffer_FromReadWriteMemory(out, sizeof(float) * nBufferFrames);
  57. PyObject *arglist = Py_BuildValue("(O,O)", oBuffer, iBuffer);
  58. if (arglist == NULL) {
  59. printf("error.\n");
  60. PyErr_Print();
  61. PyGILState_Release(gstate);
  62. return 2;
  63. }
  64. // Calling the callback
  65. PyObject *result = PyEval_CallObject(py_callback_func, arglist);
  66. if (PyErr_Occurred() != NULL) {
  67. PyErr_Print();
  68. }
  69. else if PyInt_Check(result) {
  70. retval = PyInt_AsLong(result);
  71. }
  72. Py_DECREF(arglist);
  73. Py_DECREF(oBuffer);
  74. Py_DECREF(iBuffer);
  75. Py_XDECREF(result);
  76. PyGILState_Release(gstate);
  77. }
  78. return retval;
  79. }
  80. static void RtAudio_dealloc(PyRtAudio *self)
  81. {
  82. printf("RtAudio_dealloc.\n");
  83. if (self == NULL) return;
  84. if (self->dac) {
  85. self->dac->closeStream();
  86. Py_CLEAR(self->callback_func);
  87. delete self->dac;
  88. }
  89. self->ob_type->tp_free((PyObject *) self);
  90. }
  91. static PyObject* RtAudio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  92. {
  93. printf("RtAudio_new.\n");
  94. PyRtAudio *self;
  95. char *api = NULL;
  96. if(!PyArg_ParseTuple(args, "|s", &api))
  97. return NULL;
  98. self = (PyRtAudio *) type->tp_alloc(type, 0);
  99. if(self == NULL) return NULL;
  100. self->dac = NULL;
  101. self->callback_func = NULL;
  102. try {
  103. if (api == NULL)
  104. self->dac = new RtAudio;
  105. else if(!strcmp(api, "jack"))
  106. self->dac = new RtAudio(RtAudio::UNIX_JACK);
  107. else if(!strcmp(api, "alsa"))
  108. self->dac = new RtAudio(RtAudio::LINUX_ALSA);
  109. else if(!strcmp(api, "oss"))
  110. self->dac = new RtAudio(RtAudio::LINUX_ALSA);
  111. else if(!strcmp(api, "core"))
  112. self->dac = new RtAudio(RtAudio::MACOSX_CORE);
  113. else if(!strcmp(api, "asio"))
  114. self->dac = new RtAudio(RtAudio::WINDOWS_ASIO);
  115. else if(!strcmp(api, "directsound"))
  116. self->dac = new RtAudio(RtAudio::WINDOWS_DS);
  117. }
  118. catch (RtError &error) {
  119. PyErr_SetString(RtAudioError, error.getMessage().c_str());
  120. Py_INCREF(RtAudioError);
  121. return NULL;
  122. }
  123. self->dac->showWarnings(false);
  124. //Py_XINCREF(self);
  125. return (PyObject *) self;
  126. }
  127. static int RtAudio_init(PyRtAudio *self, PyObject *args, PyObject *kwds)
  128. {
  129. printf("RtAudio_init.\n");
  130. //if (self == NULL) return 0;
  131. return 0;
  132. }
  133. // This functions does not yet support all the features of the RtAudio::openStream method.
  134. // Please send your patches if you improves this.
  135. static PyObject* RtAudio_openStream(PyRtAudio *self, PyObject *args)
  136. {
  137. if (self == NULL) return NULL;
  138. if (self->dac == NULL) {
  139. printf("the dac is null.\n");
  140. Py_RETURN_NONE;
  141. }
  142. PyObject *oParamsObj;
  143. PyObject *iParamsObj;
  144. int fs;
  145. unsigned int bf;
  146. PyObject *pycallback;
  147. if (!PyArg_ParseTuple(args, "OOiiO", &oParamsObj, &iParamsObj, &fs, &bf, &pycallback))
  148. return NULL;
  149. RtAudio::StreamParameters oParams;
  150. oParams.deviceId = 1;
  151. oParams.nChannels = 1;
  152. oParams.firstChannel = 0;
  153. if (PyDict_Check(oParamsObj)) {
  154. if (PyDict_Contains(oParamsObj, PyString_FromString("deviceId"))) {
  155. PyObject *value = PyDict_GetItem(oParamsObj, PyString_FromString("deviceId"));
  156. oParams.deviceId = PyInt_AsLong(value);
  157. }
  158. if (PyDict_Contains(oParamsObj, PyString_FromString("nChannels"))) {
  159. PyObject *value = PyDict_GetItem(oParamsObj, PyString_FromString("nChannels"));
  160. oParams.nChannels = PyInt_AsLong(value);
  161. }
  162. if (PyDict_Contains(oParamsObj, PyString_FromString("firstChannel"))) {
  163. PyObject *value = PyDict_GetItem(oParamsObj, PyString_FromString("firstChannel"));
  164. oParams.firstChannel = PyInt_AsLong(value);
  165. }
  166. }
  167. else {
  168. printf("First argument must be a dictionary. Default values will be used.\n");
  169. }
  170. RtAudio::StreamParameters iParams;
  171. iParams.deviceId = 1;
  172. iParams.nChannels = 2;
  173. iParams.firstChannel = 0;
  174. if (PyDict_Check(iParamsObj)) {
  175. if (PyDict_Contains(iParamsObj, PyString_FromString("deviceId"))) {
  176. PyObject *value = PyDict_GetItem(iParamsObj, PyString_FromString("deviceId"));
  177. iParams.deviceId = PyInt_AsLong(value);
  178. }
  179. if (PyDict_Contains(iParamsObj, PyString_FromString("nChannels"))) {
  180. PyObject *value = PyDict_GetItem(iParamsObj, PyString_FromString("nChannels"));
  181. iParams.nChannels = PyInt_AsLong(value);
  182. }
  183. if (PyDict_Contains(iParamsObj, PyString_FromString("firstChannel"))) {
  184. PyObject *value = PyDict_GetItem(iParamsObj, PyString_FromString("firstChannel"));
  185. iParams.firstChannel = PyInt_AsLong(value);
  186. }
  187. }
  188. else {
  189. printf("Second argument must be a dictionary. Default values will be used.\n");
  190. }
  191. if (!PyCallable_Check(pycallback)) {
  192. PyErr_SetString(PyExc_TypeError, "Need a callable object!");
  193. Py_XINCREF(PyExc_TypeError);
  194. return NULL;
  195. }
  196. // sanity check the callback ?
  197. Py_INCREF(pycallback); /* Add a reference to new callback */
  198. self->callback_func = pycallback; /*Remember new callback */
  199. // add support for other format
  200. self->_format = RTAUDIO_FLOAT32;
  201. // add support for other options
  202. RtAudio::StreamOptions options;
  203. options.flags = RTAUDIO_NONINTERLEAVED;
  204. try {
  205. if (self->dac->isStreamOpen())
  206. self->dac->closeStream();
  207. self->dac->openStream(&oParams, &iParams, self->_format, fs, &bf, &callback, self, &options);
  208. }
  209. catch ( RtError& error ) {
  210. PyErr_SetString(RtAudioError, error.getMessage().c_str());
  211. Py_INCREF(RtAudioError);
  212. return NULL;
  213. }
  214. self->inputChannels = iParams.nChannels;
  215. Py_RETURN_NONE;
  216. }
  217. static PyObject* RtAudio_closeStream(PyRtAudio *self, PyObject *args)
  218. {
  219. printf("RtAudio_closeStream.\n");
  220. if (self == NULL || self->dac == NULL) return NULL;
  221. try {
  222. self->dac->closeStream();
  223. Py_CLEAR(self->callback_func);
  224. }
  225. catch(RtError &error) {
  226. PyErr_SetString(RtAudioError, error.getMessage().c_str());
  227. Py_INCREF(RtAudioError);
  228. return NULL;
  229. }
  230. Py_RETURN_NONE;
  231. }
  232. static PyObject* RtAudio_startStream(PyRtAudio *self, PyObject *args)
  233. {
  234. if (self == NULL || self->dac == NULL) return NULL;
  235. try {
  236. self->dac->startStream();
  237. }
  238. catch(RtError &error) {
  239. PyErr_SetString(RtAudioError, error.getMessage().c_str());
  240. Py_INCREF(RtAudioError);
  241. return NULL;
  242. }
  243. Py_RETURN_NONE;
  244. }
  245. static PyObject* RtAudio_stopStream(PyRtAudio *self, PyObject *args)
  246. {
  247. printf("RtAudio_stopStream.\n");
  248. if (self == NULL || self->dac == NULL) return NULL;
  249. try {
  250. self->dac->stopStream();
  251. }
  252. catch(RtError &error) {
  253. PyErr_SetString(RtAudioError, error.getMessage().c_str());
  254. Py_INCREF(RtAudioError);
  255. return NULL;
  256. }
  257. Py_RETURN_NONE;
  258. }
  259. static PyObject* RtAudio_abortStream(PyRtAudio *self, PyObject *args)
  260. {
  261. printf("RtAudio_abortStream.\n");
  262. if (self == NULL || self->dac == NULL) return NULL;
  263. try {
  264. self->dac->abortStream();
  265. }
  266. catch(RtError &error) {
  267. PyErr_SetString(RtAudioError, error.getMessage().c_str());
  268. Py_INCREF(RtAudioError);
  269. return NULL;
  270. }
  271. Py_RETURN_NONE;
  272. }
  273. static PyObject* RtAudio_isStreamRunning(PyRtAudio *self, PyObject *args)
  274. {
  275. if (self == NULL || self->dac == NULL) return NULL;
  276. if (self->dac == NULL) {
  277. Py_RETURN_FALSE;
  278. }
  279. if (self->dac->isStreamRunning())
  280. Py_RETURN_TRUE;
  281. else
  282. Py_RETURN_FALSE;
  283. }
  284. static PyObject* RtAudio_isStreamOpen(PyRtAudio *self, PyObject *args)
  285. {
  286. if (self == NULL || self->dac == NULL) return NULL;
  287. if (self->dac == NULL) {
  288. Py_RETURN_FALSE;
  289. }
  290. if (self->dac->isStreamOpen())
  291. Py_RETURN_TRUE;
  292. else
  293. Py_RETURN_FALSE;
  294. }
  295. static PyObject* RtAudio_getDeviceCount(PyRtAudio *self, PyObject *args)
  296. {
  297. if (self == NULL || self->dac == NULL) return NULL;
  298. return PyInt_FromLong(self->dac->getDeviceCount());
  299. }
  300. static PyObject* RtAudio_getDeviceInfo(PyRtAudio *self, PyObject *args)
  301. {
  302. if (self == NULL || self->dac == NULL) return NULL;
  303. int device;
  304. if (!PyArg_ParseTuple(args, "i", &device))
  305. return NULL;
  306. try {
  307. RtAudio::DeviceInfo info = self->dac->getDeviceInfo(device);
  308. PyObject* info_dict = PyDict_New();
  309. if (info.probed) {
  310. Py_INCREF(Py_True);
  311. PyDict_SetItemString(info_dict, "probed", Py_True);
  312. }
  313. else {
  314. Py_INCREF(Py_False);
  315. PyDict_SetItemString(info_dict, "probed", Py_False);
  316. }
  317. PyObject* obj;
  318. obj = PyString_FromString(info.name.c_str());
  319. PyDict_SetItemString(info_dict, "name", obj);
  320. obj = PyInt_FromLong(info.outputChannels);
  321. PyDict_SetItemString(info_dict, "outputChannels", obj);
  322. obj = PyInt_FromLong(info.inputChannels);
  323. PyDict_SetItemString(info_dict, "inputChannels", obj);
  324. obj = PyInt_FromLong(info.duplexChannels);
  325. PyDict_SetItemString(info_dict, "duplexChannels", obj);
  326. if (info.isDefaultOutput) {
  327. Py_INCREF(Py_True);
  328. PyDict_SetItemString(info_dict, "isDefaultOutput", Py_True);
  329. }
  330. else {
  331. Py_INCREF(Py_False);
  332. PyDict_SetItemString(info_dict, "isDefaultOutput", Py_False);
  333. }
  334. if (info.isDefaultInput) {
  335. Py_INCREF(Py_True);
  336. PyDict_SetItemString(info_dict, "isDefaultInput", Py_True);
  337. }
  338. else {
  339. Py_INCREF(Py_False);
  340. PyDict_SetItemString(info_dict, "isDefaultInput", Py_False);
  341. }
  342. return info_dict;
  343. }
  344. catch(RtError &error) {
  345. PyErr_SetString(RtAudioError, error.getMessage().c_str());
  346. Py_INCREF(RtAudioError);
  347. return NULL;
  348. }
  349. }
  350. static PyObject* RtAudio_getDefaultOutputDevice(PyRtAudio *self, PyObject *args)
  351. {
  352. if (self == NULL || self->dac == NULL) return NULL;
  353. return PyInt_FromLong(self->dac->getDefaultOutputDevice());
  354. }
  355. static PyObject* RtAudio_getDefaultInputDevice(PyRtAudio *self, PyObject *args)
  356. {
  357. if (self == NULL || self->dac == NULL) return NULL;
  358. return PyInt_FromLong(self->dac->getDefaultInputDevice());
  359. }
  360. static PyObject* RtAudio_getStreamTime(PyRtAudio *self, PyObject *args)
  361. {
  362. if (self == NULL || self->dac == NULL) return NULL;
  363. return PyFloat_FromDouble( self->dac->getStreamTime() );
  364. }
  365. static PyObject* RtAudio_getStreamLatency(PyRtAudio *self, PyObject *args)
  366. {
  367. if (self == NULL || self->dac == NULL) return NULL;
  368. return PyInt_FromLong( self->dac->getStreamLatency() );
  369. }
  370. static PyObject* RtAudio_getStreamSampleRate(PyRtAudio *self, PyObject *args)
  371. {
  372. if (self == NULL || self->dac == NULL) return NULL;
  373. return PyInt_FromLong( self->dac->getStreamSampleRate() );
  374. }
  375. static PyObject* RtAudio_showWarnings(PyRtAudio *self, PyObject *args)
  376. {
  377. if (self == NULL || self->dac == NULL) return NULL;
  378. PyObject *obj;
  379. if (!PyArg_ParseTuple(args, "O", &obj))
  380. return NULL;
  381. if (!PyBool_Check(obj))
  382. return NULL;
  383. if (obj == Py_True)
  384. self->dac->showWarnings(true);
  385. else if (obj == Py_False)
  386. self->dac->showWarnings(false);
  387. else {
  388. printf("not true nor false\n");
  389. }
  390. Py_RETURN_NONE;
  391. }
  392. static PyMethodDef RtAudio_methods[] =
  393. {
  394. // TO BE DONE: getCurrentApi(void)
  395. {"getDeviceCount", (PyCFunction) RtAudio_getDeviceCount, METH_NOARGS,
  396. "A public function that queries for the number of audio devices available."},
  397. {"getDeviceInfo", (PyCFunction) RtAudio_getDeviceInfo, METH_VARARGS,
  398. "Return a dictionary with information for a specified device number."},
  399. {"getDefaultOutputDevice", (PyCFunction) RtAudio_getDefaultOutputDevice, METH_NOARGS,
  400. "A function that returns the index of the default output device."},
  401. {"getDefaultInputDevice", (PyCFunction) RtAudio_getDefaultInputDevice, METH_NOARGS,
  402. "A function that returns the index of the default input device."},
  403. {"openStream", (PyCFunction) RtAudio_openStream, METH_VARARGS,
  404. "A public method for opening a stream with the specified parameters."},
  405. {"closeStream", (PyCFunction) RtAudio_closeStream, METH_NOARGS,
  406. "A function that closes a stream and frees any associated stream memory. "},
  407. {"startStream", (PyCFunction) RtAudio_startStream, METH_NOARGS,
  408. "A function that starts a stream. "},
  409. {"stopStream", (PyCFunction) RtAudio_stopStream, METH_NOARGS,
  410. "Stop a stream, allowing any samples remaining in the output queue to be played. "},
  411. {"abortStream", (PyCFunction) RtAudio_abortStream, METH_NOARGS,
  412. "Stop a stream, discarding any samples remaining in the input/output queue."},
  413. {"isStreamOpen", (PyCFunction) RtAudio_isStreamOpen, METH_NOARGS,
  414. "Returns true if a stream is open and false if not."},
  415. {"isStreamRunning", (PyCFunction) RtAudio_isStreamRunning, METH_NOARGS,
  416. "Returns true if the stream is running and false if it is stopped or not open."},
  417. {"getStreamTime", (PyCFunction) RtAudio_getStreamTime, METH_NOARGS,
  418. "Returns the number of elapsed seconds since the stream was started."},
  419. {"getStreamLatency", (PyCFunction) RtAudio_getStreamLatency, METH_NOARGS,
  420. "Returns the internal stream latency in sample frames."},
  421. {"getStreamSampleRate", (PyCFunction) RtAudio_getStreamSampleRate, METH_NOARGS,
  422. "Returns actual sample rate in use by the stream."},
  423. {"showWarnings", (PyCFunction) RtAudio_showWarnings, METH_VARARGS,
  424. "Specify whether warning messages should be printed to stderr."},
  425. // TO BE DONE: getCompiledApi (std::vector< RtAudio::Api > &apis) throw ()
  426. {NULL}
  427. };
  428. static PyTypeObject RtAudio_type = {
  429. PyObject_HEAD_INIT(NULL)
  430. 0, /*ob_size*/
  431. "rtaudio.RtAudio", /*tp_name*/
  432. sizeof(RtAudio), /*tp_basicsize*/
  433. 0, /*tp_itemsize*/
  434. (destructor) RtAudio_dealloc, /*tp_dealloc*/
  435. 0, /*tp_print*/
  436. 0, /*tp_getattr*/
  437. 0, /*tp_setattr*/
  438. 0, /*tp_compare*/
  439. 0, /*tp_repr*/
  440. 0, /*tp_as_number*/
  441. 0, /*tp_as_sequence*/
  442. 0, /*tp_as_mapping*/
  443. 0, /*tp_hash */
  444. 0, /*tp_call*/
  445. 0, /*tp_str*/
  446. 0, /*tp_getattro*/
  447. 0, /*tp_setattro*/
  448. 0, /*tp_as_buffer*/
  449. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  450. "Audio input device", /* tp_doc */
  451. 0, /* tp_traverse */
  452. 0, /* tp_clear */
  453. 0, /* tp_richcompare */
  454. 0, /* tp_weaklistoffset */
  455. 0, /* tp_iter */
  456. 0, /* tp_iternext */
  457. RtAudio_methods, /* tp_methods */
  458. 0, /* tp_members */
  459. 0, /* tp_getset */
  460. 0, /* tp_base */
  461. 0, /* tp_dict */
  462. 0, /* tp_descr_get */
  463. 0, /* tp_descr_set */
  464. 0, /* tp_dictoffset */
  465. (initproc)RtAudio_init, /* tp_init */
  466. 0, /* tp_alloc */
  467. RtAudio_new, /* tp_new */
  468. 0, /* Low-level free-memory routine */
  469. 0, /* For PyObject_IS_GC */
  470. 0, // PyObject *tp_bases;
  471. 0, // PyObject *tp_mro; /* method resolution order */
  472. 0, //PyObject *tp_cache;
  473. 0, //PyObject *tp_subclasses;
  474. 0, //PyObject *tp_weaklist;
  475. 0, //destructor tp_del;
  476. //0, /* Type attribute cache version tag. Added in version 2.6 */
  477. };
  478. #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
  479. #define PyMODINIT_FUNC void
  480. #endif
  481. PyMODINIT_FUNC
  482. initrtaudio(void)
  483. {
  484. PyEval_InitThreads();
  485. if (PyType_Ready(&RtAudio_type) < 0)
  486. return;
  487. PyObject* module = Py_InitModule3("rtaudio", NULL, "RtAudio wrapper.");
  488. if (module == NULL)
  489. return;
  490. Py_INCREF(&RtAudio_type);
  491. PyModule_AddObject(module, "RtAudio", (PyObject *)&RtAudio_type);
  492. RtAudioError = PyErr_NewException("rtaudio.RtError", NULL, NULL);
  493. Py_INCREF(RtAudioError);
  494. PyModule_AddObject(module, "RtError", RtAudioError);
  495. }
  496. }