alsa-input.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /*
  2. Copyright (C) 2015. Guillermo A. Amaral B. <[email protected]>
  3. Based on Pulse Input plugin by Leonhard Oelke.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include <util/bmem.h>
  16. #include <util/platform.h>
  17. #include <util/threading.h>
  18. #include <obs-module.h>
  19. #include <alsa/asoundlib.h>
  20. #include <alsa/pcm.h>
  21. #include <pthread.h>
  22. #define blog(level, msg, ...) blog(level, "alsa-input: " msg, ##__VA_ARGS__)
  23. #define NSEC_PER_SEC 1000000000LL
  24. #define NSEC_PER_MSEC 1000000L
  25. #define STARTUP_TIMEOUT_NS (500 * NSEC_PER_MSEC)
  26. #define REOPEN_TIMEOUT 1000UL
  27. #define SHUTDOWN_ON_DEACTIVATE false
  28. struct alsa_data {
  29. obs_source_t *source;
  30. #if SHUTDOWN_ON_DEACTIVATE
  31. bool active;
  32. #endif
  33. /* user settings */
  34. char *device;
  35. /* pthread */
  36. pthread_t listen_thread;
  37. pthread_t reopen_thread;
  38. os_event_t *abort_event;
  39. volatile bool listen;
  40. volatile bool reopen;
  41. /* alsa */
  42. snd_pcm_t *handle;
  43. snd_pcm_format_t format;
  44. snd_pcm_uframes_t period_size;
  45. unsigned int channels;
  46. unsigned int rate;
  47. unsigned int sample_size;
  48. uint8_t *buffer;
  49. uint64_t first_ts;
  50. };
  51. static const char *alsa_get_name(void *);
  52. static bool alsa_devices_changed(obs_properties_t *props, obs_property_t *p,
  53. obs_data_t *settings);
  54. static obs_properties_t *alsa_get_properties(void *);
  55. static void *alsa_create(obs_data_t *, obs_source_t *);
  56. static void alsa_destroy(void *);
  57. static void alsa_activate(void *);
  58. static void alsa_deactivate(void *);
  59. static void alsa_get_defaults(obs_data_t *);
  60. static void alsa_update(void *, obs_data_t *);
  61. struct obs_source_info alsa_input_capture = {
  62. .id = "alsa_input_capture",
  63. .type = OBS_SOURCE_TYPE_INPUT,
  64. .output_flags = OBS_SOURCE_AUDIO,
  65. .create = alsa_create,
  66. .destroy = alsa_destroy,
  67. #if SHUTDOWN_ON_DEACTIVATE
  68. .activate = alsa_activate,
  69. .deactivate = alsa_deactivate,
  70. #endif
  71. .update = alsa_update,
  72. .get_defaults = alsa_get_defaults,
  73. .get_name = alsa_get_name,
  74. .get_properties = alsa_get_properties,
  75. .icon_type = OBS_ICON_TYPE_AUDIO_INPUT,
  76. };
  77. static bool _alsa_try_open(struct alsa_data *);
  78. static bool _alsa_open(struct alsa_data *);
  79. static void _alsa_close(struct alsa_data *);
  80. static bool _alsa_configure(struct alsa_data *);
  81. static void _alsa_start_reopen(struct alsa_data *);
  82. static void _alsa_stop_reopen(struct alsa_data *);
  83. static void *_alsa_listen(void *);
  84. static void *_alsa_reopen(void *);
  85. static enum audio_format _alsa_to_obs_audio_format(snd_pcm_format_t);
  86. static enum speaker_layout _alsa_channels_to_obs_speakers(unsigned int);
  87. /*****************************************************************************/
  88. void *alsa_create(obs_data_t *settings, obs_source_t *source)
  89. {
  90. struct alsa_data *data = bzalloc(sizeof(struct alsa_data));
  91. data->source = source;
  92. #if SHUTDOWN_ON_DEACTIVATE
  93. data->active = false;
  94. #endif
  95. data->buffer = NULL;
  96. data->device = NULL;
  97. data->first_ts = 0;
  98. data->handle = NULL;
  99. data->listen = false;
  100. data->reopen = false;
  101. data->listen_thread = 0;
  102. data->reopen_thread = 0;
  103. const char *device = obs_data_get_string(settings, "device_id");
  104. if (strcmp(device, "__custom__") == 0)
  105. device = obs_data_get_string(settings, "custom_pcm");
  106. data->device = bstrdup(device);
  107. data->rate = obs_data_get_int(settings, "rate");
  108. if (os_event_init(&data->abort_event, OS_EVENT_TYPE_MANUAL) != 0) {
  109. blog(LOG_ERROR, "Abort event creation failed!");
  110. goto cleanup;
  111. }
  112. #if !SHUTDOWN_ON_DEACTIVATE
  113. _alsa_try_open(data);
  114. #endif
  115. return data;
  116. cleanup:
  117. if (data->device)
  118. bfree(data->device);
  119. bfree(data);
  120. return NULL;
  121. }
  122. void alsa_destroy(void *vptr)
  123. {
  124. struct alsa_data *data = vptr;
  125. if (data->handle)
  126. _alsa_close(data);
  127. os_event_destroy(data->abort_event);
  128. bfree(data->device);
  129. bfree(data);
  130. }
  131. #if SHUTDOWN_ON_DEACTIVATE
  132. void alsa_activate(void *vptr)
  133. {
  134. struct alsa_data *data = vptr;
  135. data->active = true;
  136. _alsa_try_open(data);
  137. }
  138. void alsa_deactivate(void *vptr)
  139. {
  140. struct alsa_data *data = vptr;
  141. _alsa_stop_reopen(data);
  142. _alsa_close(data);
  143. data->active = false;
  144. }
  145. #endif
  146. void alsa_update(void *vptr, obs_data_t *settings)
  147. {
  148. struct alsa_data *data = vptr;
  149. const char *device;
  150. unsigned int rate;
  151. bool reset = false;
  152. device = obs_data_get_string(settings, "device_id");
  153. if (strcmp(device, "__custom__") == 0)
  154. device = obs_data_get_string(settings, "custom_pcm");
  155. if (strcmp(data->device, device) != 0) {
  156. bfree(data->device);
  157. data->device = bstrdup(device);
  158. reset = true;
  159. }
  160. rate = obs_data_get_int(settings, "rate");
  161. if (data->rate != rate) {
  162. data->rate = rate;
  163. reset = true;
  164. }
  165. #if SHUTDOWN_ON_DEACTIVATE
  166. if (reset && data->handle)
  167. _alsa_close(data);
  168. if (data->active && !data->handle)
  169. _alsa_try_open(data);
  170. #else
  171. if (reset) {
  172. if (data->handle)
  173. _alsa_close(data);
  174. _alsa_try_open(data);
  175. }
  176. #endif
  177. }
  178. const char *alsa_get_name(void *unused)
  179. {
  180. UNUSED_PARAMETER(unused);
  181. return obs_module_text("AlsaInput");
  182. }
  183. void alsa_get_defaults(obs_data_t *settings)
  184. {
  185. obs_data_set_default_string(settings, "device_id", "default");
  186. obs_data_set_default_string(settings, "custom_pcm", "default");
  187. obs_data_set_default_int(settings, "rate", 44100);
  188. }
  189. static bool alsa_devices_changed(obs_properties_t *props, obs_property_t *p,
  190. obs_data_t *settings)
  191. {
  192. UNUSED_PARAMETER(p);
  193. bool visible = false;
  194. const char *device_id = obs_data_get_string(settings, "device_id");
  195. if (strcmp(device_id, "__custom__") == 0)
  196. visible = true;
  197. obs_property_t *custom_pcm = obs_properties_get(props, "custom_pcm");
  198. obs_property_set_visible(custom_pcm, visible);
  199. obs_property_modified(custom_pcm, settings);
  200. return true;
  201. }
  202. obs_properties_t *alsa_get_properties(void *unused)
  203. {
  204. void **hints;
  205. void **hint;
  206. char *name = NULL;
  207. char *descr = NULL;
  208. char *io = NULL;
  209. char *descr_i;
  210. obs_properties_t *props;
  211. obs_property_t *devices;
  212. obs_property_t *rate;
  213. UNUSED_PARAMETER(unused);
  214. props = obs_properties_create();
  215. devices = obs_properties_add_list(props, "device_id",
  216. obs_module_text("Device"),
  217. OBS_COMBO_TYPE_LIST,
  218. OBS_COMBO_FORMAT_STRING);
  219. obs_property_list_add_string(devices, "Default", "default");
  220. obs_properties_add_text(props, "custom_pcm", obs_module_text("PCM"),
  221. OBS_TEXT_DEFAULT);
  222. rate = obs_properties_add_list(props, "rate", obs_module_text("Rate"),
  223. OBS_COMBO_TYPE_LIST,
  224. OBS_COMBO_FORMAT_INT);
  225. obs_property_set_modified_callback(devices, alsa_devices_changed);
  226. obs_property_list_add_int(rate, "32000 Hz", 32000);
  227. obs_property_list_add_int(rate, "44100 Hz", 44100);
  228. obs_property_list_add_int(rate, "48000 Hz", 48000);
  229. if (snd_device_name_hint(-1, "pcm", &hints) < 0)
  230. return props;
  231. hint = hints;
  232. while (*hint != NULL) {
  233. /* check if we're dealing with an Input */
  234. io = snd_device_name_get_hint(*hint, "IOID");
  235. if (io != NULL && strcmp(io, "Input") != 0)
  236. goto next;
  237. name = snd_device_name_get_hint(*hint, "NAME");
  238. if (name == NULL || strstr(name, "front:") == NULL)
  239. goto next;
  240. descr = snd_device_name_get_hint(*hint, "DESC");
  241. if (!descr)
  242. goto next;
  243. descr_i = descr;
  244. while (*descr_i) {
  245. if (*descr_i == '\n') {
  246. *descr_i = '\0';
  247. break;
  248. } else
  249. ++descr_i;
  250. }
  251. obs_property_list_add_string(devices, descr, name);
  252. next:
  253. if (name != NULL)
  254. free(name), name = NULL;
  255. if (descr != NULL)
  256. free(descr), descr = NULL;
  257. if (io != NULL)
  258. free(io), io = NULL;
  259. ++hint;
  260. }
  261. obs_property_list_add_string(devices, "Custom", "__custom__");
  262. snd_device_name_free_hint(hints);
  263. return props;
  264. }
  265. /*****************************************************************************/
  266. bool _alsa_try_open(struct alsa_data *data)
  267. {
  268. _alsa_stop_reopen(data);
  269. if (_alsa_open(data))
  270. return true;
  271. _alsa_start_reopen(data);
  272. return false;
  273. }
  274. bool _alsa_open(struct alsa_data *data)
  275. {
  276. pthread_attr_t attr;
  277. int err;
  278. err = snd_pcm_open(&data->handle, data->device, SND_PCM_STREAM_CAPTURE,
  279. 0);
  280. if (err < 0) {
  281. blog(LOG_ERROR, "Failed to open '%s': %s", data->device,
  282. snd_strerror(err));
  283. return false;
  284. }
  285. if (!_alsa_configure(data))
  286. goto cleanup;
  287. if (snd_pcm_state(data->handle) != SND_PCM_STATE_PREPARED) {
  288. blog(LOG_ERROR, "Device not prepared: '%s'", data->device);
  289. goto cleanup;
  290. }
  291. /* start listening */
  292. err = snd_pcm_start(data->handle);
  293. if (err < 0) {
  294. blog(LOG_ERROR, "Failed to start '%s': %s", data->device,
  295. snd_strerror(err));
  296. goto cleanup;
  297. }
  298. /* create capture thread */
  299. pthread_attr_init(&attr);
  300. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  301. err = pthread_create(&data->listen_thread, &attr, _alsa_listen, data);
  302. if (err) {
  303. pthread_attr_destroy(&attr);
  304. blog(LOG_ERROR,
  305. "Failed to create capture thread for device '%s'.",
  306. data->device);
  307. goto cleanup;
  308. }
  309. pthread_attr_destroy(&attr);
  310. return true;
  311. cleanup:
  312. _alsa_close(data);
  313. return false;
  314. }
  315. void _alsa_close(struct alsa_data *data)
  316. {
  317. if (data->listen_thread) {
  318. os_atomic_set_bool(&data->listen, false);
  319. pthread_join(data->listen_thread, NULL);
  320. data->listen_thread = 0;
  321. }
  322. if (data->handle) {
  323. snd_pcm_drop(data->handle);
  324. snd_pcm_close(data->handle), data->handle = NULL;
  325. }
  326. if (data->buffer)
  327. bfree(data->buffer), data->buffer = NULL;
  328. }
  329. bool _alsa_configure(struct alsa_data *data)
  330. {
  331. snd_pcm_hw_params_t *hwparams;
  332. int err;
  333. int dir;
  334. snd_pcm_hw_params_alloca(&hwparams);
  335. err = snd_pcm_hw_params_any(data->handle, hwparams);
  336. if (err < 0) {
  337. blog(LOG_ERROR, "snd_pcm_hw_params_any failed: %s",
  338. snd_strerror(err));
  339. return false;
  340. }
  341. err = snd_pcm_hw_params_set_access(data->handle, hwparams,
  342. SND_PCM_ACCESS_RW_INTERLEAVED);
  343. if (err < 0) {
  344. blog(LOG_ERROR, "snd_pcm_hw_params_set_access failed: %s",
  345. snd_strerror(err));
  346. return false;
  347. }
  348. data->format = SND_PCM_FORMAT_S16;
  349. err = snd_pcm_hw_params_set_format(data->handle, hwparams,
  350. data->format);
  351. if (err < 0) {
  352. blog(LOG_ERROR, "snd_pcm_hw_params_set_format failed: %s",
  353. snd_strerror(err));
  354. return false;
  355. }
  356. err = snd_pcm_hw_params_set_rate_near(data->handle, hwparams,
  357. &data->rate, 0);
  358. if (err < 0) {
  359. blog(LOG_ERROR, "snd_pcm_hw_params_set_rate_near failed: %s",
  360. snd_strerror(err));
  361. return false;
  362. }
  363. blog(LOG_INFO, "PCM '%s' rate set to %d", data->device, data->rate);
  364. err = snd_pcm_hw_params_get_channels(hwparams, &data->channels);
  365. if (err < 0)
  366. data->channels = 2;
  367. err = snd_pcm_hw_params_set_channels_near(data->handle, hwparams,
  368. &data->channels);
  369. if (err < 0) {
  370. blog(LOG_ERROR,
  371. "snd_pcm_hw_params_set_channels_near failed: %s",
  372. snd_strerror(err));
  373. return false;
  374. }
  375. blog(LOG_INFO, "PCM '%s' channels set to %d", data->device,
  376. data->channels);
  377. err = snd_pcm_hw_params(data->handle, hwparams);
  378. if (err < 0) {
  379. blog(LOG_ERROR, "snd_pcm_hw_params failed: %s",
  380. snd_strerror(err));
  381. return false;
  382. }
  383. err = snd_pcm_hw_params_get_period_size(hwparams, &data->period_size,
  384. &dir);
  385. if (err < 0) {
  386. blog(LOG_ERROR, "snd_pcm_hw_params_get_period_size failed: %s",
  387. snd_strerror(err));
  388. return false;
  389. }
  390. data->sample_size =
  391. (data->channels * snd_pcm_format_physical_width(data->format)) /
  392. 8;
  393. if (data->buffer)
  394. bfree(data->buffer);
  395. data->buffer = bzalloc(data->period_size * data->sample_size);
  396. return true;
  397. }
  398. void _alsa_start_reopen(struct alsa_data *data)
  399. {
  400. pthread_attr_t attr;
  401. int err;
  402. if (os_atomic_load_bool(&data->reopen))
  403. return;
  404. pthread_attr_init(&attr);
  405. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  406. err = pthread_create(&data->reopen_thread, &attr, _alsa_reopen, data);
  407. if (err) {
  408. blog(LOG_ERROR,
  409. "Failed to create reopen thread for device '%s'.",
  410. data->device);
  411. }
  412. pthread_attr_destroy(&attr);
  413. }
  414. void _alsa_stop_reopen(struct alsa_data *data)
  415. {
  416. if (os_atomic_load_bool(&data->reopen))
  417. os_event_signal(data->abort_event);
  418. if (data->reopen_thread) {
  419. pthread_join(data->reopen_thread, NULL);
  420. data->reopen_thread = 0;
  421. }
  422. os_event_reset(data->abort_event);
  423. }
  424. void *_alsa_listen(void *attr)
  425. {
  426. struct alsa_data *data = attr;
  427. struct obs_source_audio out;
  428. blog(LOG_DEBUG, "Capture thread started.");
  429. out.data[0] = data->buffer;
  430. out.format = _alsa_to_obs_audio_format(data->format);
  431. out.speakers = _alsa_channels_to_obs_speakers(data->channels);
  432. out.samples_per_sec = data->rate;
  433. os_atomic_set_bool(&data->listen, true);
  434. do {
  435. snd_pcm_sframes_t frames = snd_pcm_readi(
  436. data->handle, data->buffer, data->period_size);
  437. if (!os_atomic_load_bool(&data->listen))
  438. break;
  439. if (frames <= 0) {
  440. frames = snd_pcm_recover(data->handle, frames, 0);
  441. if (frames <= 0) {
  442. snd_pcm_wait(data->handle, 100);
  443. continue;
  444. }
  445. }
  446. out.frames = frames;
  447. out.timestamp = os_gettime_ns() -
  448. ((frames * NSEC_PER_SEC) / data->rate);
  449. if (!data->first_ts)
  450. data->first_ts = out.timestamp + STARTUP_TIMEOUT_NS;
  451. if (out.timestamp > data->first_ts)
  452. obs_source_output_audio(data->source, &out);
  453. } while (os_atomic_load_bool(&data->listen));
  454. blog(LOG_DEBUG, "Capture thread is about to exit.");
  455. pthread_exit(NULL);
  456. return NULL;
  457. }
  458. void *_alsa_reopen(void *attr)
  459. {
  460. struct alsa_data *data = attr;
  461. unsigned long timeout = REOPEN_TIMEOUT;
  462. blog(LOG_DEBUG, "Reopen thread started.");
  463. os_atomic_set_bool(&data->reopen, true);
  464. while (os_event_timedwait(data->abort_event, timeout) == ETIMEDOUT) {
  465. if (_alsa_open(data))
  466. break;
  467. if (timeout < (REOPEN_TIMEOUT * 5))
  468. timeout += REOPEN_TIMEOUT;
  469. }
  470. os_atomic_set_bool(&data->reopen, false);
  471. blog(LOG_DEBUG, "Reopen thread is about to exit.");
  472. pthread_exit(NULL);
  473. return NULL;
  474. }
  475. enum audio_format _alsa_to_obs_audio_format(snd_pcm_format_t format)
  476. {
  477. switch (format) {
  478. case SND_PCM_FORMAT_U8:
  479. return AUDIO_FORMAT_U8BIT;
  480. case SND_PCM_FORMAT_S16_LE:
  481. return AUDIO_FORMAT_16BIT;
  482. case SND_PCM_FORMAT_S32_LE:
  483. return AUDIO_FORMAT_32BIT;
  484. case SND_PCM_FORMAT_FLOAT_LE:
  485. return AUDIO_FORMAT_FLOAT;
  486. default:
  487. break;
  488. }
  489. return AUDIO_FORMAT_UNKNOWN;
  490. }
  491. enum speaker_layout _alsa_channels_to_obs_speakers(unsigned int channels)
  492. {
  493. switch (channels) {
  494. case 1:
  495. return SPEAKERS_MONO;
  496. case 2:
  497. return SPEAKERS_STEREO;
  498. case 3:
  499. return SPEAKERS_2POINT1;
  500. case 4:
  501. return SPEAKERS_4POINT0;
  502. case 5:
  503. return SPEAKERS_4POINT1;
  504. case 6:
  505. return SPEAKERS_5POINT1;
  506. case 8:
  507. return SPEAKERS_7POINT1;
  508. }
  509. return SPEAKERS_UNKNOWN;
  510. }