wasapi-output.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. #include "../../media-io/audio-resampler.h"
  2. #include "../../util/deque.h"
  3. #include "../../util/platform.h"
  4. #include "../../util/darray.h"
  5. #include "../../util/util_uint64.h"
  6. #include "../../obs-internal.h"
  7. #include "wasapi-output.h"
  8. #define ACTUALLY_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
  9. EXTERN_C const GUID DECLSPEC_SELECTANY \
  10. name = {l, w1, w2, {b1, b2, b3, b4, b5, b6, b7, b8}}
  11. #define do_log(level, format, ...) \
  12. blog(level, "[audio monitoring: '%s'] " format, \
  13. obs_source_get_name(monitor->source), ##__VA_ARGS__)
  14. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  15. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  16. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  17. ACTUALLY_DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, 0x8E,
  18. 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E);
  19. ACTUALLY_DEFINE_GUID(IID_IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, 0xA7,
  20. 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6);
  21. ACTUALLY_DEFINE_GUID(IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4C32, 0xB1, 0x78,
  22. 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2);
  23. ACTUALLY_DEFINE_GUID(IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, 0xA7,
  24. 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2);
  25. struct audio_monitor {
  26. obs_source_t *source;
  27. IAudioClient *client;
  28. IAudioRenderClient *render;
  29. uint64_t last_recv_time;
  30. uint64_t prev_video_ts;
  31. uint64_t time_since_prev;
  32. audio_resampler_t *resampler;
  33. uint32_t sample_rate;
  34. uint32_t channels;
  35. bool source_has_video;
  36. bool ignore;
  37. int64_t lowest_audio_offset;
  38. struct deque delay_buffer;
  39. uint32_t delay_size;
  40. DARRAY(float) buf;
  41. SRWLOCK playback_mutex;
  42. };
  43. /* #define DEBUG_AUDIO */
  44. static bool process_audio_delay(struct audio_monitor *monitor, float **data,
  45. uint32_t *frames, uint64_t ts, uint32_t pad)
  46. {
  47. obs_source_t *s = monitor->source;
  48. uint64_t last_frame_ts = s->last_frame_ts;
  49. uint64_t cur_time = os_gettime_ns();
  50. uint64_t front_ts;
  51. uint64_t cur_ts;
  52. int64_t diff;
  53. uint32_t blocksize = monitor->channels * sizeof(float);
  54. /* cut off audio if long-since leftover audio in delay buffer */
  55. if (cur_time - monitor->last_recv_time > 1000000000)
  56. deque_free(&monitor->delay_buffer);
  57. monitor->last_recv_time = cur_time;
  58. ts += monitor->source->sync_offset;
  59. deque_push_back(&monitor->delay_buffer, &ts, sizeof(ts));
  60. deque_push_back(&monitor->delay_buffer, frames, sizeof(*frames));
  61. deque_push_back(&monitor->delay_buffer, *data, *frames * blocksize);
  62. if (!monitor->prev_video_ts) {
  63. monitor->prev_video_ts = last_frame_ts;
  64. } else if (monitor->prev_video_ts == last_frame_ts) {
  65. monitor->time_since_prev += util_mul_div64(
  66. *frames, 1000000000ULL, monitor->sample_rate);
  67. } else {
  68. monitor->time_since_prev = 0;
  69. }
  70. while (monitor->delay_buffer.size != 0) {
  71. size_t size;
  72. bool bad_diff;
  73. deque_peek_front(&monitor->delay_buffer, &cur_ts, sizeof(ts));
  74. front_ts = cur_ts - util_mul_div64(pad, 1000000000ULL,
  75. monitor->sample_rate);
  76. diff = (int64_t)front_ts - (int64_t)last_frame_ts;
  77. bad_diff = !last_frame_ts || llabs(diff) > 5000000000 ||
  78. monitor->time_since_prev > 100000000ULL;
  79. /* delay audio if rushing */
  80. if (!bad_diff && diff > 75000000) {
  81. #ifdef DEBUG_AUDIO
  82. blog(LOG_INFO,
  83. "audio rushing, cutting audio, "
  84. "diff: %lld, delay buffer size: %lu, "
  85. "v: %llu: a: %llu",
  86. diff, (int)monitor->delay_buffer.size,
  87. last_frame_ts, front_ts);
  88. #endif
  89. return false;
  90. }
  91. deque_pop_front(&monitor->delay_buffer, NULL, sizeof(ts));
  92. deque_pop_front(&monitor->delay_buffer, frames,
  93. sizeof(*frames));
  94. size = *frames * blocksize;
  95. da_resize(monitor->buf, size);
  96. deque_pop_front(&monitor->delay_buffer, monitor->buf.array,
  97. size);
  98. /* cut audio if dragging */
  99. if (!bad_diff && diff < -75000000 &&
  100. monitor->delay_buffer.size > 0) {
  101. #ifdef DEBUG_AUDIO
  102. blog(LOG_INFO,
  103. "audio dragging, cutting audio, "
  104. "diff: %lld, delay buffer size: %lu, "
  105. "v: %llu: a: %llu",
  106. diff, (int)monitor->delay_buffer.size,
  107. last_frame_ts, front_ts);
  108. #endif
  109. continue;
  110. }
  111. *data = monitor->buf.array;
  112. return true;
  113. }
  114. return false;
  115. }
  116. static enum speaker_layout convert_speaker_layout(DWORD layout, WORD channels)
  117. {
  118. switch (layout) {
  119. case KSAUDIO_SPEAKER_2POINT1:
  120. return SPEAKERS_2POINT1;
  121. case KSAUDIO_SPEAKER_SURROUND:
  122. return SPEAKERS_4POINT0;
  123. case KSAUDIO_SPEAKER_4POINT1:
  124. return SPEAKERS_4POINT1;
  125. case KSAUDIO_SPEAKER_5POINT1:
  126. return SPEAKERS_5POINT1;
  127. case KSAUDIO_SPEAKER_7POINT1:
  128. return SPEAKERS_7POINT1;
  129. }
  130. return (enum speaker_layout)channels;
  131. }
  132. static bool audio_monitor_init_wasapi(struct audio_monitor *monitor)
  133. {
  134. bool success = false;
  135. IMMDeviceEnumerator *immde = NULL;
  136. WAVEFORMATEX *wfex = NULL;
  137. UINT32 frames;
  138. HRESULT hr;
  139. /* ------------------------------------------ *
  140. * Init device */
  141. hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
  142. &IID_IMMDeviceEnumerator, (void **)&immde);
  143. if (FAILED(hr)) {
  144. warn("%s: Failed to create IMMDeviceEnumerator: %08lX",
  145. __FUNCTION__, hr);
  146. return false;
  147. }
  148. IMMDevice *device = NULL;
  149. const char *const id = obs->audio.monitoring_device_id;
  150. if (strcmp(id, "default") == 0) {
  151. hr = immde->lpVtbl->GetDefaultAudioEndpoint(immde, eRender,
  152. eConsole, &device);
  153. } else {
  154. wchar_t w_id[512];
  155. os_utf8_to_wcs(id, 0, w_id, 512);
  156. hr = immde->lpVtbl->GetDevice(immde, w_id, &device);
  157. }
  158. if (FAILED(hr)) {
  159. warn("%s: Failed to get device: %08lX", __FUNCTION__, hr);
  160. goto fail;
  161. }
  162. /* ------------------------------------------ *
  163. * Init client */
  164. hr = device->lpVtbl->Activate(device, &IID_IAudioClient, CLSCTX_ALL,
  165. NULL, (void **)&monitor->client);
  166. device->lpVtbl->Release(device);
  167. if (FAILED(hr)) {
  168. warn("%s: Failed to activate device: %08lX", __FUNCTION__, hr);
  169. goto fail;
  170. }
  171. hr = monitor->client->lpVtbl->GetMixFormat(monitor->client, &wfex);
  172. if (FAILED(hr)) {
  173. warn("%s: Failed to get mix format: %08lX", __FUNCTION__, hr);
  174. goto fail;
  175. }
  176. hr = monitor->client->lpVtbl->Initialize(monitor->client,
  177. AUDCLNT_SHAREMODE_SHARED, 0,
  178. 10000000, 0, wfex, NULL);
  179. if (FAILED(hr)) {
  180. warn("%s: Failed to initialize: %08lX", __FUNCTION__, hr);
  181. goto fail;
  182. }
  183. /* ------------------------------------------ *
  184. * Init resampler */
  185. const struct audio_output_info *info =
  186. audio_output_get_info(obs->audio.audio);
  187. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE *)wfex;
  188. struct resample_info from;
  189. struct resample_info to;
  190. from.samples_per_sec = info->samples_per_sec;
  191. from.speakers = info->speakers;
  192. from.format = AUDIO_FORMAT_FLOAT_PLANAR;
  193. to.samples_per_sec = (uint32_t)wfex->nSamplesPerSec;
  194. to.speakers =
  195. convert_speaker_layout(ext->dwChannelMask, wfex->nChannels);
  196. to.format = AUDIO_FORMAT_FLOAT;
  197. monitor->sample_rate = (uint32_t)wfex->nSamplesPerSec;
  198. monitor->channels = wfex->nChannels;
  199. monitor->resampler = audio_resampler_create(&to, &from);
  200. if (!monitor->resampler) {
  201. goto fail;
  202. }
  203. /* ------------------------------------------ *
  204. * Init client */
  205. hr = monitor->client->lpVtbl->GetBufferSize(monitor->client, &frames);
  206. if (FAILED(hr)) {
  207. warn("%s: Failed to get buffer size: %08lX", __FUNCTION__, hr);
  208. goto fail;
  209. }
  210. hr = monitor->client->lpVtbl->GetService(monitor->client,
  211. &IID_IAudioRenderClient,
  212. (void **)&monitor->render);
  213. if (FAILED(hr)) {
  214. warn("%s: Failed to get IAudioRenderClient: %08lX",
  215. __FUNCTION__, hr);
  216. goto fail;
  217. }
  218. hr = monitor->client->lpVtbl->Start(monitor->client);
  219. if (FAILED(hr)) {
  220. warn("%s: Failed to start audio: %08lX", __FUNCTION__, hr);
  221. goto fail;
  222. }
  223. success = true;
  224. fail:
  225. safe_release(immde);
  226. if (wfex)
  227. CoTaskMemFree(wfex);
  228. return success;
  229. }
  230. static void audio_monitor_free_for_reconnect(struct audio_monitor *monitor)
  231. {
  232. if (monitor->client)
  233. monitor->client->lpVtbl->Stop(monitor->client);
  234. if (monitor->render) {
  235. monitor->render->lpVtbl->Release(monitor->render);
  236. monitor->render = NULL;
  237. }
  238. if (monitor->client) {
  239. monitor->client->lpVtbl->Stop(monitor->client);
  240. monitor->client->lpVtbl->Release(monitor->client);
  241. monitor->client = NULL;
  242. }
  243. audio_resampler_destroy(monitor->resampler);
  244. monitor->resampler = NULL;
  245. deque_free(&monitor->delay_buffer);
  246. da_free(monitor->buf);
  247. }
  248. static void on_audio_playback(void *param, obs_source_t *source,
  249. const struct audio_data *audio_data, bool muted)
  250. {
  251. struct audio_monitor *monitor = param;
  252. uint8_t *resample_data[MAX_AV_PLANES];
  253. float vol = source->user_volume;
  254. uint32_t resample_frames;
  255. uint64_t ts_offset;
  256. bool success;
  257. BYTE *output;
  258. if (!TryAcquireSRWLockExclusive(&monitor->playback_mutex)) {
  259. return;
  260. }
  261. if (os_atomic_load_long(&source->activate_refs) == 0) {
  262. goto unlock;
  263. }
  264. if (!monitor->client && !audio_monitor_init_wasapi(monitor)) {
  265. goto free_for_reconnect;
  266. }
  267. success = audio_resampler_resample(
  268. monitor->resampler, resample_data, &resample_frames, &ts_offset,
  269. (const uint8_t *const *)audio_data->data,
  270. (uint32_t)audio_data->frames);
  271. if (!success) {
  272. goto unlock;
  273. }
  274. UINT32 pad = 0;
  275. HRESULT hr = monitor->client->lpVtbl->GetCurrentPadding(monitor->client,
  276. &pad);
  277. if (FAILED(hr)) {
  278. goto free_for_reconnect;
  279. }
  280. bool decouple_audio = source->async_unbuffered &&
  281. source->async_decoupled;
  282. if (monitor->source_has_video && !decouple_audio) {
  283. uint64_t ts = audio_data->timestamp - ts_offset;
  284. if (!process_audio_delay(monitor, (float **)(&resample_data[0]),
  285. &resample_frames, ts, pad)) {
  286. goto unlock;
  287. }
  288. }
  289. IAudioRenderClient *const render = monitor->render;
  290. hr = render->lpVtbl->GetBuffer(render, resample_frames, &output);
  291. if (FAILED(hr)) {
  292. goto free_for_reconnect;
  293. }
  294. if (!muted) {
  295. /* apply volume */
  296. if (!close_float(vol, 1.0f, EPSILON)) {
  297. register float *cur = (float *)resample_data[0];
  298. register float *end =
  299. cur + resample_frames * monitor->channels;
  300. while (cur < end)
  301. *(cur++) *= vol;
  302. }
  303. memcpy(output, resample_data[0],
  304. resample_frames * monitor->channels * sizeof(float));
  305. }
  306. hr = render->lpVtbl->ReleaseBuffer(render, resample_frames,
  307. muted ? AUDCLNT_BUFFERFLAGS_SILENT
  308. : 0);
  309. if (FAILED(hr)) {
  310. goto free_for_reconnect;
  311. }
  312. goto unlock;
  313. free_for_reconnect:
  314. audio_monitor_free_for_reconnect(monitor);
  315. unlock:
  316. ReleaseSRWLockExclusive(&monitor->playback_mutex);
  317. }
  318. static inline void audio_monitor_free(struct audio_monitor *monitor)
  319. {
  320. if (monitor->ignore)
  321. return;
  322. if (monitor->source) {
  323. obs_source_remove_audio_capture_callback(
  324. monitor->source, on_audio_playback, monitor);
  325. }
  326. if (monitor->client)
  327. monitor->client->lpVtbl->Stop(monitor->client);
  328. safe_release(monitor->client);
  329. safe_release(monitor->render);
  330. audio_resampler_destroy(monitor->resampler);
  331. deque_free(&monitor->delay_buffer);
  332. da_free(monitor->buf);
  333. }
  334. extern bool devices_match(const char *id1, const char *id2);
  335. static bool audio_monitor_init(struct audio_monitor *monitor,
  336. obs_source_t *source)
  337. {
  338. monitor->source = source;
  339. const char *id = obs->audio.monitoring_device_id;
  340. if (!id) {
  341. warn("%s: No device ID set", __FUNCTION__);
  342. return false;
  343. }
  344. if (source->info.output_flags & OBS_SOURCE_DO_NOT_SELF_MONITOR) {
  345. obs_data_t *s = obs_source_get_settings(source);
  346. const char *s_dev_id = obs_data_get_string(s, "device_id");
  347. bool match = devices_match(s_dev_id, id);
  348. obs_data_release(s);
  349. if (match) {
  350. monitor->ignore = true;
  351. return true;
  352. }
  353. }
  354. InitializeSRWLock(&monitor->playback_mutex);
  355. return audio_monitor_init_wasapi(monitor);
  356. }
  357. static void audio_monitor_init_final(struct audio_monitor *monitor)
  358. {
  359. if (monitor->ignore)
  360. return;
  361. monitor->source_has_video =
  362. (monitor->source->info.output_flags & OBS_SOURCE_VIDEO) != 0;
  363. obs_source_add_audio_capture_callback(monitor->source,
  364. on_audio_playback, monitor);
  365. }
  366. struct audio_monitor *audio_monitor_create(obs_source_t *source)
  367. {
  368. struct audio_monitor monitor = {0};
  369. struct audio_monitor *out;
  370. if (!audio_monitor_init(&monitor, source)) {
  371. goto fail;
  372. }
  373. out = bmemdup(&monitor, sizeof(monitor));
  374. pthread_mutex_lock(&obs->audio.monitoring_mutex);
  375. da_push_back(obs->audio.monitors, &out);
  376. pthread_mutex_unlock(&obs->audio.monitoring_mutex);
  377. audio_monitor_init_final(out);
  378. return out;
  379. fail:
  380. audio_monitor_free(&monitor);
  381. return NULL;
  382. }
  383. void audio_monitor_reset(struct audio_monitor *monitor)
  384. {
  385. struct audio_monitor new_monitor = {0};
  386. bool success;
  387. AcquireSRWLockExclusive(&monitor->playback_mutex);
  388. success = audio_monitor_init(&new_monitor, monitor->source);
  389. ReleaseSRWLockExclusive(&monitor->playback_mutex);
  390. if (success) {
  391. obs_source_t *source = monitor->source;
  392. audio_monitor_free(monitor);
  393. *monitor = new_monitor;
  394. audio_monitor_init_final(monitor);
  395. } else {
  396. audio_monitor_free(&new_monitor);
  397. }
  398. }
  399. void audio_monitor_destroy(struct audio_monitor *monitor)
  400. {
  401. if (monitor) {
  402. audio_monitor_free(monitor);
  403. pthread_mutex_lock(&obs->audio.monitoring_mutex);
  404. da_erase_item(obs->audio.monitors, &monitor);
  405. pthread_mutex_unlock(&obs->audio.monitoring_mutex);
  406. bfree(monitor);
  407. }
  408. }