pulse-input.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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/platform.h>
  15. #include <util/bmem.h>
  16. #include <obs-module.h>
  17. #include "pulse-wrapper.h"
  18. #define NSEC_PER_SEC 1000000000LL
  19. #define NSEC_PER_MSEC 1000000L
  20. #define PULSE_DATA(voidptr) struct pulse_data *data = voidptr;
  21. #define blog(level, msg, ...) blog(level, "pulse-input: " msg, ##__VA_ARGS__)
  22. struct pulse_data {
  23. obs_source_t *source;
  24. pa_stream *stream;
  25. /* user settings */
  26. char *device;
  27. bool input;
  28. /* server info */
  29. enum speaker_layout speakers;
  30. pa_sample_format_t format;
  31. uint_fast32_t samples_per_sec;
  32. uint_fast32_t bytes_per_frame;
  33. uint_fast8_t channels;
  34. uint64_t first_ts;
  35. /* statistics */
  36. uint_fast32_t packets;
  37. uint_fast64_t frames;
  38. };
  39. static void pulse_stop_recording(struct pulse_data *data);
  40. /**
  41. * get obs from pulse audio format
  42. */
  43. static enum audio_format pulse_to_obs_audio_format(
  44. pa_sample_format_t format)
  45. {
  46. switch (format) {
  47. case PA_SAMPLE_U8: return AUDIO_FORMAT_U8BIT;
  48. case PA_SAMPLE_S16LE: return AUDIO_FORMAT_16BIT;
  49. case PA_SAMPLE_S32LE: return AUDIO_FORMAT_32BIT;
  50. case PA_SAMPLE_FLOAT32LE: return AUDIO_FORMAT_FLOAT;
  51. default: return AUDIO_FORMAT_UNKNOWN;
  52. }
  53. return AUDIO_FORMAT_UNKNOWN;
  54. }
  55. /**
  56. * Get obs speaker layout from number of channels
  57. *
  58. * @param channels number of channels reported by pulseaudio
  59. *
  60. * @return obs speaker_layout id
  61. *
  62. * @note This *might* not work for some rather unusual setups, but should work
  63. * fine for the majority of cases.
  64. */
  65. static enum speaker_layout pulse_channels_to_obs_speakers(
  66. uint_fast32_t channels)
  67. {
  68. switch(channels) {
  69. case 1: return SPEAKERS_MONO;
  70. case 2: return SPEAKERS_STEREO;
  71. case 3: return SPEAKERS_2POINT1;
  72. case 4: return SPEAKERS_SURROUND;
  73. case 5: return SPEAKERS_4POINT1;
  74. case 6: return SPEAKERS_5POINT1;
  75. case 8: return SPEAKERS_7POINT1;
  76. }
  77. return SPEAKERS_UNKNOWN;
  78. }
  79. static inline uint64_t samples_to_ns(size_t frames, uint_fast32_t rate)
  80. {
  81. return frames * NSEC_PER_SEC / rate;
  82. }
  83. static inline uint64_t get_sample_time(size_t frames, uint_fast32_t rate)
  84. {
  85. return os_gettime_ns() - samples_to_ns(frames, rate);
  86. }
  87. #define STARTUP_TIMEOUT_NS (500 * NSEC_PER_MSEC)
  88. /**
  89. * Callback for pulse which gets executed when new audio data is available
  90. *
  91. * @warning The function may be called even after disconnecting the stream
  92. */
  93. static void pulse_stream_read(pa_stream *p, size_t nbytes, void *userdata)
  94. {
  95. UNUSED_PARAMETER(p);
  96. UNUSED_PARAMETER(nbytes);
  97. PULSE_DATA(userdata);
  98. const void *frames;
  99. size_t bytes;
  100. if (!data->stream)
  101. goto exit;
  102. pa_stream_peek(data->stream, &frames, &bytes);
  103. // check if we got data
  104. if (!bytes)
  105. goto exit;
  106. if (!frames) {
  107. blog(LOG_ERROR, "Got audio hole of %u bytes",
  108. (unsigned int) bytes);
  109. pa_stream_drop(data->stream);
  110. goto exit;
  111. }
  112. struct obs_source_audio out;
  113. out.speakers = data->speakers;
  114. out.samples_per_sec = data->samples_per_sec;
  115. out.format = pulse_to_obs_audio_format(data->format);
  116. out.data[0] = (uint8_t *) frames;
  117. out.frames = bytes / data->bytes_per_frame;
  118. out.timestamp = get_sample_time(out.frames,
  119. out.samples_per_sec);
  120. if (!data->first_ts)
  121. data->first_ts = out.timestamp + STARTUP_TIMEOUT_NS;
  122. if (out.timestamp > data->first_ts)
  123. obs_source_output_audio(data->source, &out);
  124. data->packets++;
  125. data->frames += out.frames;
  126. pa_stream_drop(data->stream);
  127. exit:
  128. pulse_signal(0);
  129. }
  130. /**
  131. * Server info callback
  132. */
  133. static void pulse_server_info(pa_context *c, const pa_server_info *i,
  134. void *userdata)
  135. {
  136. UNUSED_PARAMETER(c);
  137. PULSE_DATA(userdata);
  138. blog(LOG_INFO, "Server name: '%s %s'",
  139. i->server_name, i->server_version);
  140. if (data->device && strcmp("default", data->device) == 0) {
  141. if (data->input) {
  142. bfree(data->device);
  143. data->device = bstrdup(i->default_source_name);
  144. blog(LOG_DEBUG, "Default input device: '%s'", data->device);
  145. } else {
  146. char *monitor = bzalloc(strlen(i->default_sink_name) + 9);
  147. strcat(monitor, i->default_sink_name);
  148. strcat(monitor, ".monitor");
  149. bfree(data->device);
  150. data->device = bstrdup(monitor);
  151. blog(LOG_DEBUG, "Default output device: '%s'", data->device);
  152. bfree(monitor);
  153. }
  154. }
  155. pulse_signal(0);
  156. }
  157. /**
  158. * Source info callback
  159. *
  160. * We use the default stream settings for recording here unless pulse is
  161. * configured to something obs can't deal with.
  162. */
  163. static void pulse_source_info(pa_context *c, const pa_source_info *i, int eol,
  164. void *userdata)
  165. {
  166. UNUSED_PARAMETER(c);
  167. PULSE_DATA(userdata);
  168. // An error occured
  169. if (eol < 0) {
  170. data->format = PA_SAMPLE_INVALID;
  171. goto skip;
  172. }
  173. // Terminating call for multi instance callbacks
  174. if (eol > 0)
  175. goto skip;
  176. blog(LOG_INFO, "Audio format: %s, %"PRIu32" Hz"
  177. ", %"PRIu8" channels",
  178. pa_sample_format_to_string(i->sample_spec.format),
  179. i->sample_spec.rate,
  180. i->sample_spec.channels);
  181. pa_sample_format_t format = i->sample_spec.format;
  182. if (pulse_to_obs_audio_format(format) == AUDIO_FORMAT_UNKNOWN) {
  183. format = PA_SAMPLE_S16LE;
  184. blog(LOG_INFO, "Sample format %s not supported by OBS,"
  185. "using %s instead for recording",
  186. pa_sample_format_to_string(i->sample_spec.format),
  187. pa_sample_format_to_string(format));
  188. }
  189. uint8_t channels = i->sample_spec.channels;
  190. if (pulse_channels_to_obs_speakers(channels) == SPEAKERS_UNKNOWN) {
  191. channels = 2;
  192. blog(LOG_INFO, "%c channels not supported by OBS,"
  193. "using %c instead for recording",
  194. i->sample_spec.channels,
  195. channels);
  196. }
  197. data->format = format;
  198. data->samples_per_sec = i->sample_spec.rate;
  199. data->channels = channels;
  200. skip:
  201. pulse_signal(0);
  202. }
  203. /**
  204. * Start recording
  205. *
  206. * We request the default format used by pulse here because the data will be
  207. * converted and possibly re-sampled by obs anyway.
  208. *
  209. * For now we request a buffer length of 25ms although pulse seems to ignore
  210. * this setting for monitor streams. For "real" input streams this should work
  211. * fine though.
  212. */
  213. static int_fast32_t pulse_start_recording(struct pulse_data *data)
  214. {
  215. if (pulse_get_server_info(pulse_server_info, (void *) data) < 0) {
  216. blog(LOG_ERROR, "Unable to get server info !");
  217. return -1;
  218. }
  219. if (pulse_get_source_info(pulse_source_info, data->device,
  220. (void *) data) < 0) {
  221. blog(LOG_ERROR, "Unable to get source info !");
  222. return -1;
  223. }
  224. if (data->format == PA_SAMPLE_INVALID) {
  225. blog(LOG_ERROR, "An error occurred while getting the source info!");
  226. return -1;
  227. }
  228. pa_sample_spec spec;
  229. spec.format = data->format;
  230. spec.rate = data->samples_per_sec;
  231. spec.channels = data->channels;
  232. if (!pa_sample_spec_valid(&spec)) {
  233. blog(LOG_ERROR, "Sample spec is not valid");
  234. return -1;
  235. }
  236. data->speakers = pulse_channels_to_obs_speakers(spec.channels);
  237. data->bytes_per_frame = pa_frame_size(&spec);
  238. data->stream = pulse_stream_new(obs_source_get_name(data->source),
  239. &spec, NULL);
  240. if (!data->stream) {
  241. blog(LOG_ERROR, "Unable to create stream");
  242. return -1;
  243. }
  244. pulse_lock();
  245. pa_stream_set_read_callback(data->stream, pulse_stream_read,
  246. (void *) data);
  247. pulse_unlock();
  248. pa_buffer_attr attr;
  249. attr.fragsize = pa_usec_to_bytes(25000, &spec);
  250. attr.maxlength = (uint32_t) -1;
  251. attr.minreq = (uint32_t) -1;
  252. attr.prebuf = (uint32_t) -1;
  253. attr.tlength = (uint32_t) -1;
  254. pa_stream_flags_t flags = PA_STREAM_ADJUST_LATENCY;
  255. pulse_lock();
  256. int_fast32_t ret = pa_stream_connect_record(data->stream, data->device,
  257. &attr, flags);
  258. pulse_unlock();
  259. if (ret < 0) {
  260. pulse_stop_recording(data);
  261. blog(LOG_ERROR, "Unable to connect to stream");
  262. return -1;
  263. }
  264. blog(LOG_INFO, "Started recording from '%s'", data->device);
  265. return 0;
  266. }
  267. /**
  268. * stop recording
  269. */
  270. static void pulse_stop_recording(struct pulse_data *data)
  271. {
  272. if (data->stream) {
  273. pulse_lock();
  274. pa_stream_disconnect(data->stream);
  275. pa_stream_unref(data->stream);
  276. data->stream = NULL;
  277. pulse_unlock();
  278. }
  279. blog(LOG_INFO, "Stopped recording from '%s'", data->device);
  280. blog(LOG_INFO, "Got %"PRIuFAST32" packets with %"PRIuFAST64" frames",
  281. data->packets, data->frames);
  282. data->first_ts = 0;
  283. data->packets = 0;
  284. data->frames = 0;
  285. }
  286. /**
  287. * input info callback
  288. */
  289. static void pulse_input_info(pa_context *c, const pa_source_info *i, int eol,
  290. void *userdata)
  291. {
  292. UNUSED_PARAMETER(c);
  293. if (eol != 0 || i->monitor_of_sink != PA_INVALID_INDEX)
  294. goto skip;
  295. obs_property_list_add_string((obs_property_t*) userdata,
  296. i->description, i->name);
  297. skip:
  298. pulse_signal(0);
  299. }
  300. /**
  301. * output info callback
  302. */
  303. static void pulse_output_info(pa_context *c, const pa_sink_info *i, int eol,
  304. void *userdata)
  305. {
  306. UNUSED_PARAMETER(c);
  307. if (eol != 0 || i->monitor_source == PA_INVALID_INDEX)
  308. goto skip;
  309. obs_property_list_add_string((obs_property_t*) userdata,
  310. i->description, i->monitor_source_name);
  311. skip:
  312. pulse_signal(0);
  313. }
  314. /**
  315. * Get plugin properties
  316. */
  317. static obs_properties_t *pulse_properties(bool input)
  318. {
  319. obs_properties_t *props = obs_properties_create();
  320. obs_property_t *devices = obs_properties_add_list(props, "device_id",
  321. obs_module_text("Device"), OBS_COMBO_TYPE_LIST,
  322. OBS_COMBO_FORMAT_STRING);
  323. pulse_init();
  324. if (input)
  325. pulse_get_source_info_list(pulse_input_info, (void *) devices);
  326. else
  327. pulse_get_sink_info_list(pulse_output_info, (void *) devices);
  328. pulse_unref();
  329. size_t count = obs_property_list_item_count(devices);
  330. if (count > 0)
  331. obs_property_list_insert_string(devices, 0,
  332. obs_module_text("Default"), "default");
  333. return props;
  334. }
  335. static obs_properties_t *pulse_input_properties(void *unused)
  336. {
  337. UNUSED_PARAMETER(unused);
  338. return pulse_properties(true);
  339. }
  340. static obs_properties_t *pulse_output_properties(void *unused)
  341. {
  342. UNUSED_PARAMETER(unused);
  343. return pulse_properties(false);
  344. }
  345. /**
  346. * Get plugin defaults
  347. */
  348. static void pulse_defaults(obs_data_t *settings)
  349. {
  350. obs_data_set_default_string(settings, "device_id", "default");
  351. }
  352. /**
  353. * Returns the name of the plugin
  354. */
  355. static const char *pulse_input_getname(void *unused)
  356. {
  357. UNUSED_PARAMETER(unused);
  358. return obs_module_text("PulseInput");
  359. }
  360. static const char *pulse_output_getname(void *unused)
  361. {
  362. UNUSED_PARAMETER(unused);
  363. return obs_module_text("PulseOutput");
  364. }
  365. /**
  366. * Destroy the plugin object and free all memory
  367. */
  368. static void pulse_destroy(void *vptr)
  369. {
  370. PULSE_DATA(vptr);
  371. if (!data)
  372. return;
  373. if (data->stream)
  374. pulse_stop_recording(data);
  375. pulse_unref();
  376. if (data->device)
  377. bfree(data->device);
  378. bfree(data);
  379. }
  380. /**
  381. * Update the input settings
  382. */
  383. static void pulse_update(void *vptr, obs_data_t *settings)
  384. {
  385. PULSE_DATA(vptr);
  386. bool restart = false;
  387. const char *new_device;
  388. new_device = obs_data_get_string(settings, "device_id");
  389. if (!data->device || strcmp(data->device, new_device) != 0) {
  390. if (data->device)
  391. bfree(data->device);
  392. data->device = bstrdup(new_device);
  393. restart = true;
  394. }
  395. if (!restart)
  396. return;
  397. if (data->stream)
  398. pulse_stop_recording(data);
  399. pulse_start_recording(data);
  400. }
  401. /**
  402. * Create the plugin object
  403. */
  404. static void *pulse_create(obs_data_t *settings, obs_source_t *source, bool input)
  405. {
  406. struct pulse_data *data = bzalloc(sizeof(struct pulse_data));
  407. data->input = input;
  408. data->source = source;
  409. pulse_init();
  410. pulse_update(data, settings);
  411. return data;
  412. }
  413. static void *pulse_input_create(obs_data_t *settings, obs_source_t *source)
  414. {
  415. return pulse_create(settings, source, true);
  416. }
  417. static void *pulse_output_create(obs_data_t *settings, obs_source_t *source)
  418. {
  419. return pulse_create(settings, source, false);
  420. }
  421. struct obs_source_info pulse_input_capture = {
  422. .id = "pulse_input_capture",
  423. .type = OBS_SOURCE_TYPE_INPUT,
  424. .output_flags = OBS_SOURCE_AUDIO |
  425. OBS_SOURCE_DO_NOT_DUPLICATE,
  426. .get_name = pulse_input_getname,
  427. .create = pulse_input_create,
  428. .destroy = pulse_destroy,
  429. .update = pulse_update,
  430. .get_defaults = pulse_defaults,
  431. .get_properties = pulse_input_properties
  432. };
  433. struct obs_source_info pulse_output_capture = {
  434. .id = "pulse_output_capture",
  435. .type = OBS_SOURCE_TYPE_INPUT,
  436. .output_flags = OBS_SOURCE_AUDIO |
  437. OBS_SOURCE_DO_NOT_DUPLICATE |
  438. OBS_SOURCE_DO_NOT_SELF_MONITOR,
  439. .get_name = pulse_output_getname,
  440. .create = pulse_output_create,
  441. .destroy = pulse_destroy,
  442. .update = pulse_update,
  443. .get_defaults = pulse_defaults,
  444. .get_properties = pulse_output_properties
  445. };