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. if (monitor->source_has_video) {
  142. uint64_t ts = audio_data->timestamp - ts_offset;
  143. if (!process_audio_delay(monitor, (float**)(&resample_data[0]),
  144. &resample_frames, ts, pad)) {
  145. goto unlock;
  146. }
  147. }
  148. HRESULT hr = render->lpVtbl->GetBuffer(render, resample_frames,
  149. &output);
  150. if (FAILED(hr)) {
  151. goto unlock;
  152. }
  153. if (!muted) {
  154. /* apply volume */
  155. if (!close_float(vol, 1.0f, EPSILON)) {
  156. register float *cur = (float*)resample_data[0];
  157. register float *end = cur +
  158. resample_frames * monitor->channels;
  159. while (cur < end)
  160. *(cur++) *= vol;
  161. }
  162. memcpy(output, resample_data[0],
  163. resample_frames * monitor->channels *
  164. sizeof(float));
  165. }
  166. render->lpVtbl->ReleaseBuffer(render, resample_frames,
  167. muted ? AUDCLNT_BUFFERFLAGS_SILENT : 0);
  168. unlock:
  169. pthread_mutex_unlock(&monitor->playback_mutex);
  170. }
  171. static inline void audio_monitor_free(struct audio_monitor *monitor)
  172. {
  173. if (monitor->ignore)
  174. return;
  175. if (monitor->source) {
  176. obs_source_remove_audio_capture_callback(
  177. monitor->source, on_audio_playback, monitor);
  178. }
  179. if (monitor->client)
  180. monitor->client->lpVtbl->Stop(monitor->client);
  181. safe_release(monitor->device);
  182. safe_release(monitor->client);
  183. safe_release(monitor->render);
  184. audio_resampler_destroy(monitor->resampler);
  185. circlebuf_free(&monitor->delay_buffer);
  186. da_free(monitor->buf);
  187. }
  188. static enum speaker_layout convert_speaker_layout(DWORD layout, WORD channels)
  189. {
  190. switch (layout) {
  191. case KSAUDIO_SPEAKER_QUAD: return SPEAKERS_QUAD;
  192. case KSAUDIO_SPEAKER_2POINT1: return SPEAKERS_2POINT1;
  193. case KSAUDIO_SPEAKER_4POINT1: return SPEAKERS_4POINT1;
  194. case KSAUDIO_SPEAKER_SURROUND: return SPEAKERS_SURROUND;
  195. case KSAUDIO_SPEAKER_5POINT1: return SPEAKERS_5POINT1;
  196. case KSAUDIO_SPEAKER_5POINT1_SURROUND: return SPEAKERS_5POINT1_SURROUND;
  197. case KSAUDIO_SPEAKER_7POINT1: return SPEAKERS_7POINT1;
  198. case KSAUDIO_SPEAKER_7POINT1_SURROUND: return SPEAKERS_7POINT1_SURROUND;
  199. }
  200. return (enum speaker_layout)channels;
  201. }
  202. extern bool devices_match(const char *id1, const char *id2);
  203. static bool audio_monitor_init(struct audio_monitor *monitor,
  204. obs_source_t *source)
  205. {
  206. IMMDeviceEnumerator *immde = NULL;
  207. WAVEFORMATEX *wfex = NULL;
  208. bool success = false;
  209. UINT32 frames;
  210. HRESULT hr;
  211. pthread_mutex_init_value(&monitor->playback_mutex);
  212. monitor->source = source;
  213. const char *id = obs->audio.monitoring_device_id;
  214. if (!id) {
  215. return false;
  216. }
  217. if (source->info.output_flags & OBS_SOURCE_DO_NOT_SELF_MONITOR) {
  218. obs_data_t *s = obs_source_get_settings(source);
  219. const char *s_dev_id = obs_data_get_string(s, "device_id");
  220. bool match = devices_match(s_dev_id, id);
  221. obs_data_release(s);
  222. if (match) {
  223. monitor->ignore = true;
  224. return true;
  225. }
  226. }
  227. /* ------------------------------------------ *
  228. * Init device */
  229. hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
  230. &IID_IMMDeviceEnumerator, (void**)&immde);
  231. if (FAILED(hr)) {
  232. return false;
  233. }
  234. if (strcmp(id, "default") == 0) {
  235. hr = immde->lpVtbl->GetDefaultAudioEndpoint(immde,
  236. eRender, eConsole, &monitor->device);
  237. } else {
  238. wchar_t w_id[512];
  239. os_utf8_to_wcs(id, 0, w_id, 512);
  240. hr = immde->lpVtbl->GetDevice(immde, w_id, &monitor->device);
  241. }
  242. if (FAILED(hr)) {
  243. goto fail;
  244. }
  245. /* ------------------------------------------ *
  246. * Init client */
  247. hr = monitor->device->lpVtbl->Activate(monitor->device,
  248. &IID_IAudioClient, CLSCTX_ALL, NULL,
  249. (void**)&monitor->client);
  250. if (FAILED(hr)) {
  251. goto fail;
  252. }
  253. hr = monitor->client->lpVtbl->GetMixFormat(monitor->client, &wfex);
  254. if (FAILED(hr)) {
  255. goto fail;
  256. }
  257. hr = monitor->client->lpVtbl->Initialize(monitor->client,
  258. AUDCLNT_SHAREMODE_SHARED, 0,
  259. 10000000, 0, wfex, NULL);
  260. if (FAILED(hr)) {
  261. goto fail;
  262. }
  263. /* ------------------------------------------ *
  264. * Init resampler */
  265. const struct audio_output_info *info = audio_output_get_info(
  266. obs->audio.audio);
  267. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)wfex;
  268. struct resample_info from;
  269. struct resample_info to;
  270. from.samples_per_sec = info->samples_per_sec;
  271. from.speakers = info->speakers;
  272. from.format = AUDIO_FORMAT_FLOAT_PLANAR;
  273. to.samples_per_sec = (uint32_t)wfex->nSamplesPerSec;
  274. to.speakers = convert_speaker_layout(ext->dwChannelMask,
  275. wfex->nChannels);
  276. to.format = AUDIO_FORMAT_FLOAT;
  277. monitor->sample_rate = (uint32_t)wfex->nSamplesPerSec;
  278. monitor->channels = wfex->nChannels;
  279. monitor->resampler = audio_resampler_create(&to, &from);
  280. if (!monitor->resampler) {
  281. goto fail;
  282. }
  283. /* ------------------------------------------ *
  284. * Init client */
  285. hr = monitor->client->lpVtbl->GetBufferSize(monitor->client, &frames);
  286. if (FAILED(hr)) {
  287. goto fail;
  288. }
  289. hr = monitor->client->lpVtbl->GetService(monitor->client,
  290. &IID_IAudioRenderClient, (void**)&monitor->render);
  291. if (FAILED(hr)) {
  292. goto fail;
  293. }
  294. if (pthread_mutex_init(&monitor->playback_mutex, NULL) != 0) {
  295. goto fail;
  296. }
  297. hr = monitor->client->lpVtbl->Start(monitor->client);
  298. if (FAILED(hr)) {
  299. goto fail;
  300. }
  301. success = true;
  302. fail:
  303. safe_release(immde);
  304. if (wfex)
  305. CoTaskMemFree(wfex);
  306. return success;
  307. }
  308. static void audio_monitor_init_final(struct audio_monitor *monitor)
  309. {
  310. if (monitor->ignore)
  311. return;
  312. monitor->source_has_video =
  313. (monitor->source->info.output_flags & OBS_SOURCE_VIDEO) != 0;
  314. obs_source_add_audio_capture_callback(monitor->source,
  315. on_audio_playback, monitor);
  316. }
  317. struct audio_monitor *audio_monitor_create(obs_source_t *source)
  318. {
  319. struct audio_monitor monitor = {0};
  320. struct audio_monitor *out;
  321. if (!audio_monitor_init(&monitor, source)) {
  322. goto fail;
  323. }
  324. out = bmemdup(&monitor, sizeof(monitor));
  325. pthread_mutex_lock(&obs->audio.monitoring_mutex);
  326. da_push_back(obs->audio.monitors, &out);
  327. pthread_mutex_unlock(&obs->audio.monitoring_mutex);
  328. audio_monitor_init_final(out);
  329. return out;
  330. fail:
  331. audio_monitor_free(&monitor);
  332. return NULL;
  333. }
  334. void audio_monitor_reset(struct audio_monitor *monitor)
  335. {
  336. struct audio_monitor new_monitor = {0};
  337. bool success;
  338. pthread_mutex_lock(&monitor->playback_mutex);
  339. success = audio_monitor_init(&new_monitor, monitor->source);
  340. pthread_mutex_unlock(&monitor->playback_mutex);
  341. if (success) {
  342. obs_source_t *source = monitor->source;
  343. audio_monitor_free(monitor);
  344. *monitor = new_monitor;
  345. audio_monitor_init_final(monitor);
  346. } else {
  347. audio_monitor_free(&new_monitor);
  348. }
  349. }
  350. void audio_monitor_destroy(struct audio_monitor *monitor)
  351. {
  352. if (monitor) {
  353. audio_monitor_free(monitor);
  354. pthread_mutex_lock(&obs->audio.monitoring_mutex);
  355. da_erase_item(obs->audio.monitors, &monitor);
  356. pthread_mutex_unlock(&obs->audio.monitoring_mutex);
  357. bfree(monitor);
  358. }
  359. }