1
0

wasapi-output.c 11 KB

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