pulseaudio-output.c 15 KB

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