1
0

wasapi-output.c 13 KB

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