pulseaudio-output.c 14 KB

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