pulseaudio-output.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #include "obs-internal.h"
  2. #include "pulseaudio-wrapper.h"
  3. #define PULSE_DATA(voidptr) struct audio_monitor *data = voidptr;
  4. #define blog(level, msg, ...) blog(level, "pulse-am: " msg, ##__VA_ARGS__)
  5. struct audio_monitor {
  6. obs_source_t *source;
  7. pa_stream *stream;
  8. char *device;
  9. pa_buffer_attr attr;
  10. enum speaker_layout speakers;
  11. pa_sample_format_t format;
  12. uint_fast32_t samples_per_sec;
  13. uint_fast32_t bytes_per_frame;
  14. uint_fast8_t channels;
  15. uint_fast32_t packets;
  16. uint_fast64_t frames;
  17. struct deque new_data;
  18. audio_resampler_t *resampler;
  19. bool ignore;
  20. pthread_mutex_t playback_mutex;
  21. };
  22. static enum speaker_layout pulseaudio_channels_to_obs_speakers(uint_fast32_t channels)
  23. {
  24. switch (channels) {
  25. case 0:
  26. return SPEAKERS_UNKNOWN;
  27. case 1:
  28. return SPEAKERS_MONO;
  29. case 2:
  30. return SPEAKERS_STEREO;
  31. case 3:
  32. return SPEAKERS_2POINT1;
  33. case 4:
  34. return SPEAKERS_4POINT0;
  35. case 5:
  36. return SPEAKERS_4POINT1;
  37. case 6:
  38. return SPEAKERS_5POINT1;
  39. case 8:
  40. return SPEAKERS_7POINT1;
  41. default:
  42. return SPEAKERS_UNKNOWN;
  43. }
  44. }
  45. static enum audio_format pulseaudio_to_obs_audio_format(pa_sample_format_t format)
  46. {
  47. switch (format) {
  48. case PA_SAMPLE_U8:
  49. return AUDIO_FORMAT_U8BIT;
  50. case PA_SAMPLE_S16LE:
  51. return AUDIO_FORMAT_16BIT;
  52. case PA_SAMPLE_S32LE:
  53. return AUDIO_FORMAT_32BIT;
  54. case PA_SAMPLE_FLOAT32LE:
  55. return AUDIO_FORMAT_FLOAT;
  56. default:
  57. return AUDIO_FORMAT_UNKNOWN;
  58. }
  59. }
  60. static pa_channel_map pulseaudio_channel_map(enum speaker_layout layout)
  61. {
  62. pa_channel_map ret;
  63. ret.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
  64. ret.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
  65. ret.map[2] = PA_CHANNEL_POSITION_FRONT_CENTER;
  66. ret.map[3] = PA_CHANNEL_POSITION_LFE;
  67. ret.map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
  68. ret.map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
  69. ret.map[6] = PA_CHANNEL_POSITION_SIDE_LEFT;
  70. ret.map[7] = PA_CHANNEL_POSITION_SIDE_RIGHT;
  71. switch (layout) {
  72. case SPEAKERS_MONO:
  73. ret.channels = 1;
  74. ret.map[0] = PA_CHANNEL_POSITION_MONO;
  75. break;
  76. case SPEAKERS_STEREO:
  77. ret.channels = 2;
  78. break;
  79. case SPEAKERS_2POINT1:
  80. ret.channels = 3;
  81. ret.map[2] = PA_CHANNEL_POSITION_LFE;
  82. break;
  83. case SPEAKERS_4POINT0:
  84. ret.channels = 4;
  85. ret.map[3] = PA_CHANNEL_POSITION_REAR_CENTER;
  86. break;
  87. case SPEAKERS_4POINT1:
  88. ret.channels = 5;
  89. ret.map[4] = PA_CHANNEL_POSITION_REAR_CENTER;
  90. break;
  91. case SPEAKERS_5POINT1:
  92. ret.channels = 6;
  93. break;
  94. case SPEAKERS_7POINT1:
  95. ret.channels = 8;
  96. break;
  97. case SPEAKERS_UNKNOWN:
  98. default:
  99. ret.channels = 0;
  100. break;
  101. }
  102. return ret;
  103. }
  104. static void process_byte(void *p, size_t frames, size_t channels, float vol)
  105. {
  106. register uint8_t *cur = (uint8_t *)p;
  107. register uint8_t *end = cur + frames * channels;
  108. for (; cur < end; cur++)
  109. *cur = ((int)*cur - 128) * vol + 128;
  110. }
  111. static void process_s16(void *p, size_t frames, size_t channels, float vol)
  112. {
  113. register int16_t *cur = (int16_t *)p;
  114. register int16_t *end = cur + frames * channels;
  115. while (cur < end)
  116. *(cur++) *= vol;
  117. }
  118. static void process_s32(void *p, size_t frames, size_t channels, float vol)
  119. {
  120. register int32_t *cur = (int32_t *)p;
  121. register int32_t *end = cur + frames * channels;
  122. while (cur < end)
  123. *(cur++) *= vol;
  124. }
  125. static void process_float(void *p, size_t frames, size_t channels, float vol)
  126. {
  127. register float *cur = (float *)p;
  128. register float *end = cur + frames * channels;
  129. while (cur < end)
  130. *(cur++) *= vol;
  131. }
  132. void process_volume(const struct audio_monitor *monitor, float vol, uint8_t *const *resample_data,
  133. uint32_t resample_frames)
  134. {
  135. switch (monitor->format) {
  136. case PA_SAMPLE_U8:
  137. process_byte(resample_data[0], resample_frames, monitor->channels, vol);
  138. break;
  139. case PA_SAMPLE_S16LE:
  140. process_s16(resample_data[0], resample_frames, monitor->channels, vol);
  141. break;
  142. case PA_SAMPLE_S32LE:
  143. process_s32(resample_data[0], resample_frames, monitor->channels, vol);
  144. break;
  145. case PA_SAMPLE_FLOAT32LE:
  146. process_float(resample_data[0], resample_frames, monitor->channels, vol);
  147. break;
  148. default:
  149. // just ignore
  150. break;
  151. }
  152. }
  153. static void do_stream_write(void *param)
  154. {
  155. PULSE_DATA(param);
  156. uint8_t *buffer = NULL;
  157. pulseaudio_lock();
  158. pthread_mutex_lock(&data->playback_mutex);
  159. // If we have grown a large buffer internally, grow the pulse buffer to match so we can write our data out.
  160. if (data->new_data.size > data->attr.tlength * 2) {
  161. data->attr.fragsize = (uint32_t)-1;
  162. data->attr.maxlength = (uint32_t)-1;
  163. data->attr.prebuf = (uint32_t)-1;
  164. data->attr.minreq = (uint32_t)-1;
  165. data->attr.tlength = data->new_data.size;
  166. pa_stream_set_buffer_attr(data->stream, &data->attr, NULL, NULL);
  167. }
  168. // Buffer up enough data before we start playing.
  169. if (pa_stream_is_corked(data->stream)) {
  170. if (data->new_data.size >= data->attr.tlength) {
  171. pa_stream_cork(data->stream, 0, NULL, NULL);
  172. } else {
  173. goto finish;
  174. }
  175. }
  176. while (data->new_data.size > 0) {
  177. size_t bytesToFill = data->new_data.size;
  178. if (pa_stream_begin_write(data->stream, (void **)&buffer, &bytesToFill))
  179. goto finish;
  180. // PA may request we submit more or less data than we have.
  181. // Wait for more data if we cannot perform a full write.
  182. if (bytesToFill > data->new_data.size) {
  183. pa_stream_cancel_write(data->stream);
  184. goto finish;
  185. }
  186. deque_pop_front(&data->new_data, buffer, bytesToFill);
  187. pa_stream_write(data->stream, buffer, bytesToFill, NULL, 0LL, PA_SEEK_RELATIVE);
  188. }
  189. finish:
  190. pthread_mutex_unlock(&data->playback_mutex);
  191. pulseaudio_unlock();
  192. }
  193. static void on_audio_playback(void *param, obs_source_t *source, const struct audio_data *audio_data, bool muted)
  194. {
  195. struct audio_monitor *monitor = param;
  196. float vol = source->user_volume;
  197. size_t bytes;
  198. uint8_t *resample_data[MAX_AV_PLANES];
  199. uint32_t resample_frames;
  200. uint64_t ts_offset;
  201. bool success;
  202. if (pthread_mutex_trylock(&monitor->playback_mutex) != 0)
  203. return;
  204. if (os_atomic_load_long(&source->activate_refs) == 0)
  205. goto unlock;
  206. success = audio_resampler_resample(monitor->resampler, resample_data, &resample_frames, &ts_offset,
  207. (const uint8_t *const *)audio_data->data, (uint32_t)audio_data->frames);
  208. if (!success)
  209. goto unlock;
  210. bytes = monitor->bytes_per_frame * resample_frames;
  211. if (muted) {
  212. memset(resample_data[0], 0, bytes);
  213. } else {
  214. if (!close_float(vol, 1.0f, EPSILON)) {
  215. process_volume(monitor, vol, resample_data, resample_frames);
  216. }
  217. }
  218. deque_push_back(&monitor->new_data, resample_data[0], bytes);
  219. monitor->packets++;
  220. monitor->frames += resample_frames;
  221. unlock:
  222. pthread_mutex_unlock(&monitor->playback_mutex);
  223. do_stream_write(param);
  224. }
  225. static void pulseaudio_server_info(pa_context *c, const pa_server_info *i, void *userdata)
  226. {
  227. UNUSED_PARAMETER(c);
  228. UNUSED_PARAMETER(userdata);
  229. blog(LOG_INFO, "Server name: '%s %s'", i->server_name, i->server_version);
  230. pulseaudio_signal(0);
  231. }
  232. static void pulseaudio_sink_info(pa_context *c, const pa_sink_info *i, int eol, void *userdata)
  233. {
  234. UNUSED_PARAMETER(c);
  235. PULSE_DATA(userdata);
  236. // An error occurred
  237. if (eol < 0) {
  238. data->format = PA_SAMPLE_INVALID;
  239. goto skip;
  240. }
  241. // Terminating call for multi instance callbacks
  242. if (eol > 0)
  243. goto skip;
  244. blog(LOG_INFO, "Audio format: %s, %" PRIu32 " Hz, %" PRIu8 " channels",
  245. pa_sample_format_to_string(i->sample_spec.format), i->sample_spec.rate, i->sample_spec.channels);
  246. pa_sample_format_t format = i->sample_spec.format;
  247. if (pulseaudio_to_obs_audio_format(format) == AUDIO_FORMAT_UNKNOWN) {
  248. format = PA_SAMPLE_FLOAT32LE;
  249. blog(LOG_INFO,
  250. "Sample format %s not supported by OBS,"
  251. "using %s instead for recording",
  252. pa_sample_format_to_string(i->sample_spec.format), pa_sample_format_to_string(format));
  253. }
  254. uint8_t channels = i->sample_spec.channels;
  255. if (pulseaudio_channels_to_obs_speakers(channels) == SPEAKERS_UNKNOWN) {
  256. channels = 2;
  257. blog(LOG_INFO,
  258. "%c channels not supported by OBS,"
  259. "using %c instead for recording",
  260. i->sample_spec.channels, channels);
  261. }
  262. data->format = format;
  263. data->samples_per_sec = i->sample_spec.rate;
  264. data->channels = channels;
  265. skip:
  266. pulseaudio_signal(0);
  267. }
  268. static void pulseaudio_stop_playback(struct audio_monitor *monitor)
  269. {
  270. if (monitor->stream) {
  271. /* Stop the stream */
  272. pulseaudio_lock();
  273. pa_stream_disconnect(monitor->stream);
  274. pulseaudio_unlock();
  275. /* Remove the callbacks, to ensure we no longer try to do anything
  276. * with this stream object */
  277. pulseaudio_write_callback(monitor->stream, NULL, NULL);
  278. /* Unreference the stream and drop it. PA will free it when it can. */
  279. pulseaudio_lock();
  280. pa_stream_unref(monitor->stream);
  281. pulseaudio_unlock();
  282. monitor->stream = NULL;
  283. }
  284. blog(LOG_INFO, "Stopped Monitoring in '%s'", monitor->device);
  285. blog(LOG_INFO, "Got %" PRIuFAST32 " packets with %" PRIuFAST64 " frames", monitor->packets, monitor->frames);
  286. monitor->packets = 0;
  287. monitor->frames = 0;
  288. }
  289. static bool audio_monitor_init(struct audio_monitor *monitor, obs_source_t *source)
  290. {
  291. pthread_mutex_init_value(&monitor->playback_mutex);
  292. monitor->source = source;
  293. const char *id = obs->audio.monitoring_device_id;
  294. if (!id)
  295. return false;
  296. if (source->info.output_flags & OBS_SOURCE_DO_NOT_SELF_MONITOR) {
  297. obs_data_t *s = obs_source_get_settings(source);
  298. const char *s_dev_id = obs_data_get_string(s, "device_id");
  299. bool match = devices_match(s_dev_id, id);
  300. obs_data_release(s);
  301. if (match) {
  302. monitor->ignore = true;
  303. blog(LOG_INFO, "Prevented feedback-loop in '%s'", s_dev_id);
  304. return true;
  305. }
  306. }
  307. pulseaudio_init();
  308. if (strcmp(id, "default") == 0)
  309. get_default_id(&monitor->device);
  310. else
  311. monitor->device = bstrdup(id);
  312. if (!monitor->device)
  313. return false;
  314. if (pulseaudio_get_server_info(pulseaudio_server_info, (void *)monitor) < 0) {
  315. blog(LOG_ERROR, "Unable to get server info !");
  316. return false;
  317. }
  318. if (pulseaudio_get_sink_info(pulseaudio_sink_info, monitor->device, (void *)monitor) < 0) {
  319. blog(LOG_ERROR, "Unable to get sink info !");
  320. return false;
  321. }
  322. if (monitor->format == PA_SAMPLE_INVALID) {
  323. blog(LOG_ERROR, "An error occurred while getting the source info!");
  324. return false;
  325. }
  326. pa_sample_spec spec;
  327. spec.format = monitor->format;
  328. spec.rate = (uint32_t)monitor->samples_per_sec;
  329. spec.channels = monitor->channels;
  330. if (!pa_sample_spec_valid(&spec)) {
  331. blog(LOG_ERROR, "Sample spec is not valid");
  332. return false;
  333. }
  334. const struct audio_output_info *info = audio_output_get_info(obs->audio.audio);
  335. struct resample_info from = {.samples_per_sec = info->samples_per_sec,
  336. .speakers = info->speakers,
  337. .format = AUDIO_FORMAT_FLOAT_PLANAR};
  338. struct resample_info to = {.samples_per_sec = (uint32_t)monitor->samples_per_sec,
  339. .speakers = pulseaudio_channels_to_obs_speakers(monitor->channels),
  340. .format = pulseaudio_to_obs_audio_format(monitor->format)};
  341. monitor->resampler = audio_resampler_create(&to, &from);
  342. if (!monitor->resampler) {
  343. blog(LOG_WARNING, "%s: %s", __FUNCTION__, "Failed to create resampler");
  344. return false;
  345. }
  346. monitor->speakers = pulseaudio_channels_to_obs_speakers(spec.channels);
  347. monitor->bytes_per_frame = pa_frame_size(&spec);
  348. pa_channel_map channel_map = pulseaudio_channel_map(monitor->speakers);
  349. monitor->stream = pulseaudio_stream_new(obs_source_get_name(monitor->source), &spec, &channel_map);
  350. if (!monitor->stream) {
  351. blog(LOG_ERROR, "Unable to create stream");
  352. return false;
  353. }
  354. monitor->attr.fragsize = (uint32_t)-1;
  355. monitor->attr.maxlength = (uint32_t)-1;
  356. monitor->attr.minreq = (uint32_t)-1;
  357. monitor->attr.prebuf = (uint32_t)-1;
  358. monitor->attr.tlength = pa_usec_to_bytes(25000, &spec);
  359. pa_stream_flags_t flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_START_CORKED;
  360. int_fast32_t ret = pulseaudio_connect_playback(monitor->stream, monitor->device, &monitor->attr, flags);
  361. if (ret < 0) {
  362. pulseaudio_stop_playback(monitor);
  363. blog(LOG_ERROR, "Unable to connect to stream");
  364. return false;
  365. }
  366. blog(LOG_INFO, "Started Monitoring in '%s'", monitor->device);
  367. return true;
  368. }
  369. static void audio_monitor_init_final(struct audio_monitor *monitor)
  370. {
  371. if (monitor->ignore)
  372. return;
  373. obs_source_add_audio_capture_callback(monitor->source, on_audio_playback, monitor);
  374. }
  375. static inline void audio_monitor_free(struct audio_monitor *monitor)
  376. {
  377. if (monitor->ignore)
  378. return;
  379. if (monitor->source)
  380. obs_source_remove_audio_capture_callback(monitor->source, on_audio_playback, monitor);
  381. audio_resampler_destroy(monitor->resampler);
  382. deque_free(&monitor->new_data);
  383. if (monitor->stream)
  384. pulseaudio_stop_playback(monitor);
  385. pulseaudio_unref();
  386. bfree(monitor->device);
  387. }
  388. struct audio_monitor *audio_monitor_create(obs_source_t *source)
  389. {
  390. struct audio_monitor monitor = {0};
  391. struct audio_monitor *out;
  392. if (!audio_monitor_init(&monitor, source))
  393. goto fail;
  394. out = bmemdup(&monitor, sizeof(monitor));
  395. pthread_mutex_lock(&obs->audio.monitoring_mutex);
  396. da_push_back(obs->audio.monitors, &out);
  397. pthread_mutex_unlock(&obs->audio.monitoring_mutex);
  398. audio_monitor_init_final(out);
  399. return out;
  400. fail:
  401. audio_monitor_free(&monitor);
  402. return NULL;
  403. }
  404. void audio_monitor_reset(struct audio_monitor *monitor)
  405. {
  406. struct audio_monitor new_monitor = {0};
  407. bool success;
  408. audio_monitor_free(monitor);
  409. pthread_mutex_lock(&monitor->playback_mutex);
  410. success = audio_monitor_init(&new_monitor, monitor->source);
  411. pthread_mutex_unlock(&monitor->playback_mutex);
  412. if (success) {
  413. *monitor = new_monitor;
  414. audio_monitor_init_final(monitor);
  415. } else {
  416. audio_monitor_free(&new_monitor);
  417. }
  418. }
  419. void audio_monitor_destroy(struct audio_monitor *monitor)
  420. {
  421. if (monitor) {
  422. audio_monitor_free(monitor);
  423. pthread_mutex_lock(&obs->audio.monitoring_mutex);
  424. da_erase_item(obs->audio.monitors, &monitor);
  425. pthread_mutex_unlock(&obs->audio.monitoring_mutex);
  426. bfree(monitor);
  427. }
  428. }