pulse-input.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. /*
  2. Copyright (C) 2014 by Leonhard Oelke <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <util/bmem.h>
  15. #include <util/threading.h>
  16. #include <util/platform.h>
  17. #include <pulse/thread-mainloop.h>
  18. #include <pulse/mainloop.h>
  19. #include <pulse/context.h>
  20. #include <pulse/introspect.h>
  21. #include <pulse/stream.h>
  22. #include <pulse/error.h>
  23. #include <obs.h>
  24. #define PULSE_DATA(voidptr) struct pulse_data *data = voidptr;
  25. /*
  26. * delay in usecs before starting to record, this eliminates problems with
  27. * pulse audio sending weird data/timestamps when the stream is connected
  28. *
  29. * for more information see:
  30. * github.com/MaartenBaert/ssr/blob/master/src/AV/Input/PulseAudioInput.cpp
  31. */
  32. const uint64_t pulse_start_delay = 100000;
  33. struct pulse_data {
  34. pthread_t thread;
  35. os_event_t event;
  36. obs_source_t source;
  37. enum speaker_layout speakers;
  38. pa_sample_format_t format;
  39. uint_fast32_t samples_per_sec;
  40. uint_fast8_t channels;
  41. uint_fast32_t bytes_per_frame;
  42. pa_mainloop *mainloop;
  43. pa_context *context;
  44. pa_stream *stream;
  45. pa_proplist *props;
  46. };
  47. struct pulse_context_change {
  48. pa_threaded_mainloop *mainloop;
  49. pa_context_state_t state;
  50. };
  51. struct pulse_enumerate {
  52. pa_threaded_mainloop *mainloop;
  53. obs_property_t devices;
  54. bool input;
  55. };
  56. /*
  57. * get obs from pulse audio format
  58. */
  59. static enum audio_format pulse_to_obs_audio_format(
  60. pa_sample_format_t format)
  61. {
  62. switch (format) {
  63. case PA_SAMPLE_U8:
  64. return AUDIO_FORMAT_U8BIT;
  65. case PA_SAMPLE_S16LE:
  66. return AUDIO_FORMAT_16BIT;
  67. case PA_SAMPLE_S24_32LE:
  68. return AUDIO_FORMAT_32BIT;
  69. case PA_SAMPLE_FLOAT32LE:
  70. return AUDIO_FORMAT_FLOAT;
  71. default:
  72. return AUDIO_FORMAT_UNKNOWN;
  73. }
  74. return AUDIO_FORMAT_UNKNOWN;
  75. }
  76. /*
  77. * get the number of frames from bytes and current format
  78. */
  79. static uint_fast32_t frames_to_bytes(struct pulse_data *data, size_t bytes)
  80. {
  81. return (bytes / data->bytes_per_frame);
  82. }
  83. /*
  84. * get the buffer size needed for length msec with current settings
  85. */
  86. static uint_fast32_t get_buffer_size(struct pulse_data *data,
  87. uint_fast32_t length)
  88. {
  89. return (length * data->samples_per_sec * data->bytes_per_frame) / 1000;
  90. }
  91. /*
  92. * Get latency for a pulse audio stream
  93. */
  94. static int pulse_get_stream_latency(pa_stream *stream, int64_t *latency)
  95. {
  96. int ret;
  97. int sign;
  98. pa_usec_t abs;
  99. ret = pa_stream_get_latency(stream, &abs, &sign);
  100. *latency = (sign) ? -(int64_t) abs : (int64_t) abs;
  101. return ret;
  102. }
  103. /*
  104. * Iterate the mainloop
  105. *
  106. * The custom implementation gives better performance than the function
  107. * provided by pulse audio, maybe due to the timeout set in prepare ?
  108. */
  109. static void pulse_iterate(struct pulse_data *data)
  110. {
  111. if (pa_mainloop_prepare(data->mainloop, 1000) < 0) {
  112. blog(LOG_ERROR, "Unable to prepare main loop");
  113. return;
  114. }
  115. if (pa_mainloop_poll(data->mainloop) < 0) {
  116. blog(LOG_ERROR, "Unable to poll main loop");
  117. return;
  118. }
  119. if (pa_mainloop_dispatch(data->mainloop) < 0)
  120. blog(LOG_ERROR, "Unable to dispatch main loop");
  121. }
  122. /*
  123. * Server info callback, this is called from pa_mainloop_dispatch
  124. * TODO: how to free the server info struct ?
  125. */
  126. static void pulse_get_server_info_cb(pa_context *c, const pa_server_info *i,
  127. void *userdata)
  128. {
  129. UNUSED_PARAMETER(c);
  130. PULSE_DATA(userdata);
  131. const pa_sample_spec *spec = &i->sample_spec;
  132. data->format = spec->format;
  133. data->samples_per_sec = spec->rate;
  134. blog(LOG_DEBUG, "pulse-input: Default format: %s, %u Hz, %u channels",
  135. pa_sample_format_to_string(spec->format),
  136. spec->rate,
  137. spec->channels);
  138. }
  139. /*
  140. * Request pulse audio server info
  141. * TODO: handle failures ?
  142. */
  143. static int pulse_get_server_info(struct pulse_data *data)
  144. {
  145. pa_server_info_cb_t cb = pulse_get_server_info_cb;
  146. pa_operation *op = pa_context_get_server_info(data->context, cb, data);
  147. for(;;) {
  148. pulse_iterate(data);
  149. pa_operation_state_t state = pa_operation_get_state(op);
  150. if (state == PA_OPERATION_DONE) {
  151. pa_operation_unref(op);
  152. break;
  153. }
  154. }
  155. return 0;
  156. }
  157. /*
  158. * Create a new pulse audio main loop and connect to the server
  159. *
  160. * Returns a negative value on error
  161. */
  162. static int pulse_connect(struct pulse_data *data)
  163. {
  164. data->mainloop = pa_mainloop_new();
  165. if (!data->mainloop) {
  166. blog(LOG_ERROR, "pulse-input: Unable to create main loop");
  167. return -1;
  168. }
  169. data->context = pa_context_new_with_proplist(
  170. pa_mainloop_get_api(data->mainloop), "OBS Studio", data->props);
  171. if (!data->context) {
  172. blog(LOG_ERROR, "pulse-input: Unable to create context");
  173. return -1;
  174. }
  175. int status = pa_context_connect(
  176. data->context, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL);
  177. if (status < 0) {
  178. blog(LOG_ERROR, "pulse-input: Unable to connect! Status: %d",
  179. status);
  180. return -1;
  181. }
  182. // wait until connected
  183. for (;;) {
  184. pulse_iterate(data);
  185. pa_context_state_t state = pa_context_get_state(data->context);
  186. if (state == PA_CONTEXT_READY) {
  187. blog(LOG_DEBUG, "pulse-input: Context ready");
  188. break;
  189. }
  190. if (!PA_CONTEXT_IS_GOOD(state)) {
  191. blog(LOG_ERROR, "pulse-input: Context connect failed");
  192. return -1;
  193. }
  194. }
  195. return 0;
  196. }
  197. /*
  198. * Disconnect from the pulse audio server and destroy the main loop
  199. */
  200. static void pulse_disconnect(struct pulse_data *data)
  201. {
  202. if (data->context) {
  203. pa_context_disconnect(data->context);
  204. pa_context_unref(data->context);
  205. }
  206. if (data->mainloop)
  207. pa_mainloop_free(data->mainloop);
  208. }
  209. /*
  210. * Create a new pulse audio stream and connect to it
  211. *
  212. * Return a negative value on error
  213. */
  214. static int pulse_connect_stream(struct pulse_data *data)
  215. {
  216. pa_sample_spec spec;
  217. spec.format = data->format;
  218. spec.rate = data->samples_per_sec;
  219. spec.channels = get_audio_channels(data->speakers);
  220. if (!pa_sample_spec_valid(&spec)) {
  221. blog(LOG_ERROR, "pulse-input: Sample spec is not valid");
  222. return -1;
  223. }
  224. data->bytes_per_frame = pa_frame_size(&spec);
  225. blog(LOG_DEBUG, "pulse-input: %u bytes per frame",
  226. (unsigned int) data->bytes_per_frame);
  227. pa_buffer_attr attr;
  228. attr.fragsize = get_buffer_size(data, 250);
  229. attr.maxlength = (uint32_t) -1;
  230. attr.minreq = (uint32_t) -1;
  231. attr.prebuf = (uint32_t) -1;
  232. attr.tlength = (uint32_t) -1;
  233. data->stream = pa_stream_new_with_proplist(data->context,
  234. obs_source_getname(data->source), &spec, NULL, data->props);
  235. if (!data->stream) {
  236. blog(LOG_ERROR, "pulse-input: Unable to create stream");
  237. return -1;
  238. }
  239. pa_stream_flags_t flags =
  240. PA_STREAM_INTERPOLATE_TIMING
  241. | PA_STREAM_AUTO_TIMING_UPDATE
  242. | PA_STREAM_ADJUST_LATENCY;
  243. if (pa_stream_connect_record(data->stream, NULL, &attr, flags) < 0) {
  244. blog(LOG_ERROR, "pulse-input: Unable to connect to stream");
  245. return -1;
  246. }
  247. for (;;) {
  248. pulse_iterate(data);
  249. pa_stream_state_t state = pa_stream_get_state(data->stream);
  250. if (state == PA_STREAM_READY) {
  251. blog(LOG_DEBUG, "pulse-input: Stream ready");
  252. break;
  253. }
  254. if (!PA_STREAM_IS_GOOD(state)) {
  255. blog(LOG_ERROR, "pulse-input: Stream connect failed");
  256. return -1;
  257. }
  258. }
  259. return 0;
  260. }
  261. /*
  262. * Disconnect from the pulse audio stream
  263. */
  264. static void pulse_diconnect_stream(struct pulse_data *data)
  265. {
  266. if (data->stream) {
  267. pa_stream_disconnect(data->stream);
  268. pa_stream_unref(data->stream);
  269. }
  270. }
  271. /*
  272. * Loop to skip the first few samples of a stream
  273. */
  274. static int pulse_skip(struct pulse_data *data)
  275. {
  276. uint64_t skip = 1;
  277. const void *frames;
  278. size_t bytes;
  279. uint64_t pa_time;
  280. while (os_event_try(data->event) == EAGAIN) {
  281. pulse_iterate(data);
  282. pa_stream_peek(data->stream, &frames, &bytes);
  283. if (!bytes)
  284. continue;
  285. if (!frames || pa_stream_get_time(data->stream, &pa_time) < 0) {
  286. pa_stream_drop(data->stream);
  287. continue;
  288. }
  289. if (skip == 1 && pa_time)
  290. skip = pa_time;
  291. if (skip + pulse_start_delay < pa_time)
  292. return 0;
  293. pa_stream_drop(data->stream);
  294. }
  295. return -1;
  296. }
  297. /*
  298. * Worker thread to get audio data
  299. *
  300. * Will run until signaled
  301. */
  302. static void *pulse_thread(void *vptr)
  303. {
  304. PULSE_DATA(vptr);
  305. if (pulse_connect(data) < 0)
  306. return NULL;
  307. if (pulse_get_server_info(data) < 0)
  308. return NULL;
  309. if (pulse_connect_stream(data) < 0)
  310. return NULL;
  311. if (pulse_skip(data) < 0)
  312. return NULL;
  313. blog(LOG_DEBUG, "pulse-input: Start recording");
  314. const void *frames;
  315. size_t bytes;
  316. uint64_t pa_time;
  317. int64_t pa_latency;
  318. struct source_audio out;
  319. out.speakers = data->speakers;
  320. out.samples_per_sec = data->samples_per_sec;
  321. out.format = pulse_to_obs_audio_format(data->format);
  322. while (os_event_try(data->event) == EAGAIN) {
  323. pulse_iterate(data);
  324. pa_stream_peek(data->stream, &frames, &bytes);
  325. // check if we got data
  326. if (!bytes)
  327. continue;
  328. if (!frames) {
  329. blog(LOG_DEBUG,
  330. "pulse-input: Got audio hole of %u bytes",
  331. (unsigned int) bytes);
  332. pa_stream_drop(data->stream);
  333. continue;
  334. }
  335. if (pa_stream_get_time(data->stream, &pa_time) < 0) {
  336. blog(LOG_ERROR,
  337. "pulse-input: Failed to get timing info !");
  338. pa_stream_drop(data->stream);
  339. continue;
  340. }
  341. pulse_get_stream_latency(data->stream, &pa_latency);
  342. out.data[0] = (uint8_t *) frames;
  343. out.frames = frames_to_bytes(data, bytes);
  344. out.timestamp = (pa_time - pa_latency) * 1000;
  345. obs_source_output_audio(data->source, &out);
  346. pa_stream_drop(data->stream);
  347. }
  348. pulse_diconnect_stream(data);
  349. pulse_disconnect(data);
  350. return NULL;
  351. }
  352. /*
  353. * Create a new pulseaudio context
  354. */
  355. static pa_context *pulse_context_create(pa_threaded_mainloop *m)
  356. {
  357. pa_context *c;
  358. pa_proplist *p;
  359. p = pa_proplist_new();
  360. pa_proplist_sets(p, PA_PROP_APPLICATION_NAME, "OBS Studio");
  361. pa_proplist_sets(p, PA_PROP_APPLICATION_ICON_NAME, "application-exit");
  362. pa_proplist_sets(p, PA_PROP_MEDIA_ROLE, "production");
  363. pa_threaded_mainloop_lock(m);
  364. c = pa_context_new_with_proplist(pa_threaded_mainloop_get_api(m),
  365. "OBS Studio", p);
  366. pa_threaded_mainloop_unlock(m);
  367. pa_proplist_free(p);
  368. return c;
  369. }
  370. /**
  371. * Context state callback
  372. */
  373. static void pulse_context_state_changed(pa_context *c, void *userdata)
  374. {
  375. struct pulse_context_change *ctx =
  376. (struct pulse_context_change *) userdata;
  377. ctx->state = pa_context_get_state(c);
  378. pa_threaded_mainloop_signal(ctx->mainloop, 0);
  379. }
  380. /*
  381. * Connect context
  382. */
  383. static int pulse_context_connect(pa_threaded_mainloop *m, pa_context *c)
  384. {
  385. int status = 0;
  386. struct pulse_context_change ctx;
  387. ctx.mainloop = m;
  388. ctx.state = PA_CONTEXT_UNCONNECTED;
  389. pa_threaded_mainloop_lock(m);
  390. pa_context_set_state_callback(c, pulse_context_state_changed,
  391. (void *) &ctx);
  392. status = pa_context_connect(c, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL);
  393. if (status < 0) {
  394. blog(LOG_ERROR, "pulse-input: Unable to connect! Status: %d",
  395. status);
  396. }
  397. else {
  398. for (;;) {
  399. if (ctx.state == PA_CONTEXT_READY) {
  400. blog(LOG_DEBUG, "pulse-input: Context Ready");
  401. break;
  402. }
  403. if (!PA_CONTEXT_IS_GOOD(ctx.state)) {
  404. blog(LOG_ERROR,
  405. "pulse-input: Context connect failed !");
  406. status = -1;
  407. break;
  408. }
  409. pa_threaded_mainloop_wait(m);
  410. }
  411. }
  412. pa_threaded_mainloop_unlock(m);
  413. return status;
  414. }
  415. /*
  416. * Source properties callback
  417. */
  418. static void pulse_source_info(pa_context *c, const pa_source_info *i, int eol,
  419. void *userdata)
  420. {
  421. UNUSED_PARAMETER(c);
  422. if (eol != 0)
  423. return;
  424. struct pulse_enumerate *e = (struct pulse_enumerate *) userdata;
  425. if ((e->input) ^ (i->monitor_of_sink == PA_INVALID_INDEX))
  426. return;
  427. blog(LOG_DEBUG, "pulse-input: Got source #%u '%s'",
  428. i->index, i->description);
  429. obs_property_list_add_item(e->devices, i->description, i->name);
  430. pa_threaded_mainloop_signal(e->mainloop, 0);
  431. }
  432. /*
  433. * enumerate input/output devices
  434. */
  435. static void pulse_enumerate_devices(obs_properties_t props, bool input)
  436. {
  437. pa_context *c;
  438. pa_operation *op;
  439. pa_threaded_mainloop *m = pa_threaded_mainloop_new();
  440. struct pulse_enumerate e;
  441. e.mainloop = m;
  442. e.devices = obs_properties_add_list(props, "device_id", "Device",
  443. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  444. e.input = input;
  445. pa_threaded_mainloop_start(m);
  446. c = pulse_context_create(m);
  447. if (pulse_context_connect(m, c) < 0)
  448. goto fail;
  449. pa_threaded_mainloop_lock(m);
  450. op = pa_context_get_source_info_list(c, pulse_source_info, (void *) &e);
  451. while (pa_operation_get_state(op) == PA_OPERATION_RUNNING)
  452. pa_threaded_mainloop_wait(m);
  453. pa_operation_unref(op);
  454. pa_threaded_mainloop_unlock(m);
  455. pa_context_disconnect(c);
  456. fail:
  457. pa_context_unref(c);
  458. pa_threaded_mainloop_stop(m);
  459. pa_threaded_mainloop_free(m);
  460. }
  461. /*
  462. * get plugin properties
  463. */
  464. static obs_properties_t pulse_properties(const char *locale, bool input)
  465. {
  466. UNUSED_PARAMETER(locale);
  467. blog(LOG_DEBUG, "pulse-input: properties requested !");
  468. obs_properties_t props = obs_properties_create();
  469. pulse_enumerate_devices(props, input);
  470. return props;
  471. }
  472. static obs_properties_t pulse_input_properties(const char *locale)
  473. {
  474. return pulse_properties(locale, true);
  475. }
  476. static obs_properties_t pulse_output_properties(const char *locale)
  477. {
  478. return pulse_properties(locale, false);
  479. }
  480. /*
  481. * get plugin defaults
  482. */
  483. static void pulse_defaults(obs_data_t settings)
  484. {
  485. obs_data_set_default_string(settings, "device_id", "default");
  486. }
  487. /*
  488. * Returns the name of the plugin
  489. */
  490. static const char *pulse_input_getname(const char *locale)
  491. {
  492. UNUSED_PARAMETER(locale);
  493. return "Pulse Audio Input Capture";
  494. }
  495. static const char *pulse_output_getname(const char *locale)
  496. {
  497. UNUSED_PARAMETER(locale);
  498. return "Pulse Audio Output Capture";
  499. }
  500. /*
  501. * Destroy the plugin object and free all memory
  502. */
  503. static void pulse_destroy(void *vptr)
  504. {
  505. PULSE_DATA(vptr);
  506. if (!data)
  507. return;
  508. if (data->thread) {
  509. void *ret;
  510. os_event_signal(data->event);
  511. pthread_join(data->thread, &ret);
  512. }
  513. os_event_destroy(data->event);
  514. pa_proplist_free(data->props);
  515. blog(LOG_DEBUG, "pulse-input: Input destroyed");
  516. bfree(data);
  517. }
  518. /*
  519. * Create the plugin object
  520. */
  521. static void *pulse_create(obs_data_t settings, obs_source_t source)
  522. {
  523. UNUSED_PARAMETER(settings);
  524. struct pulse_data *data = bmalloc(sizeof(struct pulse_data));
  525. memset(data, 0, sizeof(struct pulse_data));
  526. data->source = source;
  527. data->speakers = SPEAKERS_STEREO;
  528. blog(LOG_DEBUG, "pulse-input: obs wants '%s'",
  529. obs_data_getstring(settings, "device_id"));
  530. /* TODO: use obs-studio icon */
  531. data->props = pa_proplist_new();
  532. pa_proplist_sets(data->props, PA_PROP_APPLICATION_NAME,
  533. "OBS Studio");
  534. pa_proplist_sets(data->props, PA_PROP_APPLICATION_ICON_NAME,
  535. "application-exit");
  536. pa_proplist_sets(data->props, PA_PROP_MEDIA_ROLE,
  537. "production");
  538. if (os_event_init(&data->event, OS_EVENT_TYPE_MANUAL) != 0)
  539. goto fail;
  540. if (pthread_create(&data->thread, NULL, pulse_thread, data) != 0)
  541. goto fail;
  542. return data;
  543. fail:
  544. pulse_destroy(data);
  545. return NULL;
  546. }
  547. struct obs_source_info pulse_input_capture = {
  548. .id = "pulse_input_capture",
  549. .type = OBS_SOURCE_TYPE_INPUT,
  550. .output_flags = OBS_SOURCE_AUDIO,
  551. .getname = pulse_input_getname,
  552. .create = pulse_create,
  553. .destroy = pulse_destroy,
  554. .defaults = pulse_defaults,
  555. .properties = pulse_input_properties
  556. };
  557. struct obs_source_info pulse_output_capture = {
  558. .id = "pulse_output_capture",
  559. .type = OBS_SOURCE_TYPE_INPUT,
  560. .output_flags = OBS_SOURCE_AUDIO,
  561. .getname = pulse_output_getname,
  562. .create = pulse_create,
  563. .destroy = pulse_destroy,
  564. .defaults = pulse_defaults,
  565. .properties = pulse_output_properties
  566. };