noise-suppress-filter.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. #include <stdint.h>
  2. #include <inttypes.h>
  3. #include <util/circlebuf.h>
  4. #include <obs-module.h>
  5. #ifdef LIBSPEEXDSP_ENABLED
  6. #include <speex/speex_preprocess.h>
  7. #endif
  8. #ifdef LIBRNNOISE_ENABLED
  9. #ifdef _MSC_VER
  10. #define ssize_t intptr_t
  11. #endif
  12. #include <rnnoise.h>
  13. #include <media-io/audio-resampler.h>
  14. #endif
  15. bool nvafx_loaded = false;
  16. #ifdef LIBNVAFX_ENABLED
  17. #include "nvafx-load.h"
  18. #include <pthread.h>
  19. #endif
  20. /* -------------------------------------------------------- */
  21. #define do_log(level, format, ...) \
  22. blog(level, "[noise suppress: '%s'] " format, \
  23. obs_source_get_name(ng->context), ##__VA_ARGS__)
  24. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  25. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  26. #ifdef _DEBUG
  27. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  28. #else
  29. #define debug(format, ...)
  30. #endif
  31. /* -------------------------------------------------------- */
  32. #define S_SUPPRESS_LEVEL "suppress_level"
  33. #define S_NVAFX_INTENSITY "intensity"
  34. #define S_METHOD "method"
  35. #define S_METHOD_SPEEX "speex"
  36. #define S_METHOD_RNN "rnnoise"
  37. #define S_METHOD_NVAFX "nvafx"
  38. #define MT_ obs_module_text
  39. #define TEXT_SUPPRESS_LEVEL MT_("NoiseSuppress.SuppressLevel")
  40. #define TEXT_NVAFX_INTENSITY MT_("NoiseSuppress.Intensity")
  41. #define TEXT_METHOD MT_("NoiseSuppress.Method")
  42. #define TEXT_METHOD_SPEEX MT_("NoiseSuppress.Method.Speex")
  43. #define TEXT_METHOD_RNN MT_("NoiseSuppress.Method.RNNoise")
  44. #define TEXT_METHOD_NVAFX MT_("NoiseSuppress.Method.nvafx")
  45. #define MAX_PREPROC_CHANNELS 8
  46. /* RNNoise constants, these can't be changed */
  47. #define RNNOISE_SAMPLE_RATE 48000
  48. #define RNNOISE_FRAME_SIZE 480
  49. /* nvafx constants, these can't be changed */
  50. #define NVAFX_SAMPLE_RATE 48000
  51. #define NVAFX_FRAME_SIZE \
  52. 480 /* the sdk does not explicitly set this as a constant though it relies on it*/
  53. /* If the following constant changes, RNNoise breaks */
  54. #define BUFFER_SIZE_MSEC 10
  55. /* -------------------------------------------------------- */
  56. struct noise_suppress_data {
  57. obs_source_t *context;
  58. int suppress_level;
  59. uint64_t last_timestamp;
  60. uint64_t latency;
  61. size_t frames;
  62. size_t channels;
  63. struct circlebuf info_buffer;
  64. struct circlebuf input_buffers[MAX_PREPROC_CHANNELS];
  65. struct circlebuf output_buffers[MAX_PREPROC_CHANNELS];
  66. bool use_rnnoise;
  67. bool use_nvafx;
  68. bool nvafx_enabled;
  69. #ifdef LIBSPEEXDSP_ENABLED
  70. /* Speex preprocessor state */
  71. SpeexPreprocessState *spx_states[MAX_PREPROC_CHANNELS];
  72. #endif
  73. #ifdef LIBRNNOISE_ENABLED
  74. /* RNNoise state */
  75. DenoiseState *rnn_states[MAX_PREPROC_CHANNELS];
  76. /* Resampler */
  77. audio_resampler_t *rnn_resampler;
  78. audio_resampler_t *rnn_resampler_back;
  79. #endif
  80. #ifdef LIBNVAFX_ENABLED
  81. /* NVAFX handle, one per audio channel */
  82. NvAFX_Handle handle[MAX_PREPROC_CHANNELS];
  83. uint32_t sample_rate;
  84. float intensity_ratio;
  85. unsigned int num_samples_per_frame, num_channels;
  86. char *model;
  87. bool nvafx_initialized;
  88. /* Resampler */
  89. audio_resampler_t *nvafx_resampler;
  90. audio_resampler_t *nvafx_resampler_back;
  91. /* Initialization */
  92. bool nvafx_loading;
  93. pthread_t nvafx_thread;
  94. pthread_mutex_t nvafx_mutex;
  95. #endif
  96. /* PCM buffers */
  97. float *copy_buffers[MAX_PREPROC_CHANNELS];
  98. #ifdef LIBSPEEXDSP_ENABLED
  99. spx_int16_t *spx_segment_buffers[MAX_PREPROC_CHANNELS];
  100. #endif
  101. #ifdef LIBRNNOISE_ENABLED
  102. float *rnn_segment_buffers[MAX_PREPROC_CHANNELS];
  103. #endif
  104. #ifdef LIBNVAFX_ENABLED
  105. float *nvafx_segment_buffers[MAX_PREPROC_CHANNELS];
  106. #endif
  107. /* output data */
  108. struct obs_audio_data output_audio;
  109. DARRAY(float) output_data;
  110. };
  111. #ifdef LIBNVAFX_ENABLED
  112. /* global mutex for nvafx load functions since they aren't thread-safe */
  113. bool nvafx_initializer_mutex_initialized;
  114. pthread_mutex_t nvafx_initializer_mutex;
  115. #endif
  116. /* -------------------------------------------------------- */
  117. #define SUP_MIN -60
  118. #define SUP_MAX 0
  119. #ifdef LIBSPEEXDSP_ENABLED
  120. static const float c_32_to_16 = (float)INT16_MAX;
  121. static const float c_16_to_32 = ((float)INT16_MAX + 1.0f);
  122. #endif
  123. /* -------------------------------------------------------- */
  124. static const char *noise_suppress_name(void *unused)
  125. {
  126. UNUSED_PARAMETER(unused);
  127. return obs_module_text("NoiseSuppress");
  128. }
  129. static void noise_suppress_destroy(void *data)
  130. {
  131. struct noise_suppress_data *ng = data;
  132. #ifdef LIBNVAFX_ENABLED
  133. if (ng->nvafx_enabled)
  134. pthread_mutex_lock(&ng->nvafx_mutex);
  135. #endif
  136. for (size_t i = 0; i < ng->channels; i++) {
  137. #ifdef LIBSPEEXDSP_ENABLED
  138. speex_preprocess_state_destroy(ng->spx_states[i]);
  139. #endif
  140. #ifdef LIBRNNOISE_ENABLED
  141. rnnoise_destroy(ng->rnn_states[i]);
  142. #endif
  143. #ifdef LIBNVAFX_ENABLED
  144. if (ng->handle[0]) {
  145. if (NvAFX_DestroyEffect(ng->handle[i]) !=
  146. NVAFX_STATUS_SUCCESS) {
  147. do_log(LOG_ERROR, "NvAFX_Release() failed");
  148. }
  149. }
  150. #endif
  151. circlebuf_free(&ng->input_buffers[i]);
  152. circlebuf_free(&ng->output_buffers[i]);
  153. }
  154. #ifdef LIBSPEEXDSP_ENABLED
  155. bfree(ng->spx_segment_buffers[0]);
  156. #endif
  157. #ifdef LIBRNNOISE_ENABLED
  158. bfree(ng->rnn_segment_buffers[0]);
  159. if (ng->rnn_resampler) {
  160. audio_resampler_destroy(ng->rnn_resampler);
  161. audio_resampler_destroy(ng->rnn_resampler_back);
  162. }
  163. #endif
  164. #ifdef LIBNVAFX_ENABLED
  165. bfree(ng->nvafx_segment_buffers[0]);
  166. if (ng->nvafx_resampler) {
  167. audio_resampler_destroy(ng->nvafx_resampler);
  168. audio_resampler_destroy(ng->nvafx_resampler_back);
  169. }
  170. bfree(ng->model);
  171. if (ng->nvafx_enabled) {
  172. if (ng->use_nvafx)
  173. pthread_join(ng->nvafx_thread, NULL);
  174. pthread_mutex_unlock(&ng->nvafx_mutex);
  175. pthread_mutex_destroy(&ng->nvafx_mutex);
  176. }
  177. #endif
  178. bfree(ng->copy_buffers[0]);
  179. circlebuf_free(&ng->info_buffer);
  180. da_free(ng->output_data);
  181. bfree(ng);
  182. }
  183. static void *nvafx_initialize(void *data)
  184. {
  185. #ifdef LIBNVAFX_ENABLED
  186. struct noise_suppress_data *ng = data;
  187. int err;
  188. if (!ng->use_nvafx || !nvafx_loaded)
  189. return NULL;
  190. pthread_mutex_lock(&ng->nvafx_mutex);
  191. pthread_mutex_lock(&nvafx_initializer_mutex);
  192. if (!ng->handle[0]) {
  193. ng->sample_rate = NVAFX_SAMPLE_RATE;
  194. for (size_t i = 0; i < ng->channels; i++) {
  195. err = NvAFX_CreateEffect(NVAFX_EFFECT_DENOISER,
  196. &ng->handle[i]);
  197. if (err != NVAFX_STATUS_SUCCESS) {
  198. do_log(LOG_ERROR,
  199. "NvAFX_CreateEffect() failed, error %i",
  200. err);
  201. goto failure;
  202. }
  203. err = NvAFX_SetU32(ng->handle[i],
  204. NVAFX_PARAM_DENOISER_SAMPLE_RATE,
  205. ng->sample_rate);
  206. if (err != NVAFX_STATUS_SUCCESS) {
  207. do_log(LOG_ERROR,
  208. "NvAFX_SetU32(Sample Rate: %u) failed, error %i",
  209. ng->sample_rate, err);
  210. goto failure;
  211. }
  212. // initial setting of intensity to 1.0f
  213. err = NvAFX_SetFloat(
  214. ng->handle[i],
  215. NVAFX_PARAM_DENOISER_INTENSITY_RATIO,
  216. ng->intensity_ratio);
  217. if (err != NVAFX_STATUS_SUCCESS) {
  218. do_log(LOG_ERROR,
  219. "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i",
  220. 1.0f, err);
  221. goto failure;
  222. }
  223. err = NvAFX_SetString(ng->handle[i],
  224. NVAFX_PARAM_DENOISER_MODEL_PATH,
  225. ng->model);
  226. if (err != NVAFX_STATUS_SUCCESS) {
  227. do_log(LOG_ERROR,
  228. "NvAFX_SetString() failed, error %i",
  229. err);
  230. goto failure;
  231. }
  232. err = NvAFX_Load(ng->handle[i]);
  233. if (err != NVAFX_STATUS_SUCCESS) {
  234. do_log(LOG_ERROR,
  235. "NvAFX_Load() failed with error %i",
  236. err);
  237. goto failure;
  238. }
  239. }
  240. if (ng->use_nvafx) {
  241. err = NvAFX_GetU32(ng->handle[0],
  242. NVAFX_PARAM_DENOISER_NUM_CHANNELS,
  243. &ng->num_channels);
  244. if (err != NVAFX_STATUS_SUCCESS) {
  245. do_log(LOG_ERROR,
  246. "NvAFX_GetU32() failed to get the number of channels, error %i",
  247. err);
  248. goto failure;
  249. }
  250. if (ng->num_channels != 1) {
  251. do_log(LOG_ERROR,
  252. "The number of channels is not 1 in the sdk any more ==> update code");
  253. goto failure;
  254. }
  255. NvAFX_Status err = NvAFX_GetU32(
  256. ng->handle[0],
  257. NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME,
  258. &ng->num_samples_per_frame);
  259. if (err != NVAFX_STATUS_SUCCESS) {
  260. do_log(LOG_ERROR,
  261. "NvAFX_GetU32() failed to get the number of samples per frame, error %i",
  262. err);
  263. goto failure;
  264. }
  265. if (ng->num_samples_per_frame != NVAFX_FRAME_SIZE) {
  266. do_log(LOG_ERROR,
  267. "The number of samples per frame has changed from 480 (= 10 ms) ==> update code");
  268. goto failure;
  269. }
  270. }
  271. }
  272. ng->nvafx_initialized = true;
  273. pthread_mutex_unlock(&nvafx_initializer_mutex);
  274. pthread_mutex_unlock(&ng->nvafx_mutex);
  275. return NULL;
  276. failure:
  277. ng->use_nvafx = false;
  278. pthread_mutex_unlock(&nvafx_initializer_mutex);
  279. pthread_mutex_unlock(&ng->nvafx_mutex);
  280. return NULL;
  281. #else
  282. UNUSED_PARAMETER(data);
  283. return NULL;
  284. #endif
  285. }
  286. static inline void alloc_channel(struct noise_suppress_data *ng,
  287. uint32_t sample_rate, size_t channel,
  288. size_t frames)
  289. {
  290. #ifdef LIBSPEEXDSP_ENABLED
  291. ng->spx_states[channel] =
  292. speex_preprocess_state_init((int)frames, sample_rate);
  293. #else
  294. UNUSED_PARAMETER(sample_rate);
  295. #endif
  296. #ifdef LIBRNNOISE_ENABLED
  297. ng->rnn_states[channel] = rnnoise_create(NULL);
  298. #endif
  299. circlebuf_reserve(&ng->input_buffers[channel], frames * sizeof(float));
  300. circlebuf_reserve(&ng->output_buffers[channel], frames * sizeof(float));
  301. }
  302. static inline enum speaker_layout convert_speaker_layout(uint8_t channels)
  303. {
  304. switch (channels) {
  305. case 0:
  306. return SPEAKERS_UNKNOWN;
  307. case 1:
  308. return SPEAKERS_MONO;
  309. case 2:
  310. return SPEAKERS_STEREO;
  311. case 3:
  312. return SPEAKERS_2POINT1;
  313. case 4:
  314. return SPEAKERS_4POINT0;
  315. case 5:
  316. return SPEAKERS_4POINT1;
  317. case 6:
  318. return SPEAKERS_5POINT1;
  319. case 8:
  320. return SPEAKERS_7POINT1;
  321. default:
  322. return SPEAKERS_UNKNOWN;
  323. }
  324. }
  325. static void noise_suppress_update(void *data, obs_data_t *s)
  326. {
  327. struct noise_suppress_data *ng = data;
  328. uint32_t sample_rate = audio_output_get_sample_rate(obs_get_audio());
  329. size_t channels = audio_output_get_channels(obs_get_audio());
  330. size_t frames = (size_t)sample_rate / (1000 / BUFFER_SIZE_MSEC);
  331. const char *method = obs_data_get_string(s, S_METHOD);
  332. ng->suppress_level = (int)obs_data_get_int(s, S_SUPPRESS_LEVEL);
  333. ng->latency = 1000000000LL / (1000 / BUFFER_SIZE_MSEC);
  334. ng->use_rnnoise = strcmp(method, S_METHOD_RNN) == 0;
  335. ng->use_nvafx = ng->nvafx_enabled &&
  336. strcmp(method, S_METHOD_NVAFX) == 0;
  337. /* Process 10 millisecond segments to keep latency low */
  338. /* Also RNNoise only supports buffers of this exact size. */
  339. /* At 48kHz, NVAFX processes 480 samples which corresponds to 10 ms.*/
  340. ng->frames = frames;
  341. ng->channels = channels;
  342. #ifdef LIBNVAFX_ENABLED
  343. ng->intensity_ratio = (float)obs_data_get_double(s, S_NVAFX_INTENSITY);
  344. if (ng->use_nvafx) {
  345. pthread_mutex_lock(&ng->nvafx_mutex);
  346. if (ng->nvafx_initialized) {
  347. int err;
  348. for (size_t i = 0; i < ng->channels; i++) {
  349. err = NvAFX_SetFloat(
  350. ng->handle[i],
  351. NVAFX_PARAM_DENOISER_INTENSITY_RATIO,
  352. ng->intensity_ratio);
  353. if (err != NVAFX_STATUS_SUCCESS) {
  354. do_log(LOG_ERROR,
  355. "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i",
  356. ng->intensity_ratio, err);
  357. ng->use_nvafx = false;
  358. }
  359. }
  360. }
  361. pthread_mutex_unlock(&ng->nvafx_mutex);
  362. }
  363. #endif
  364. /* Ignore if already allocated */
  365. #if defined(LIBSPEEXDSP_ENABLED)
  366. if (!ng->use_rnnoise && !ng->use_nvafx && ng->spx_states[0])
  367. return;
  368. #endif
  369. #ifdef LIBNVAFX_ENABLED
  370. if (ng->use_nvafx && (ng->nvafx_initialized || ng->nvafx_loading))
  371. return;
  372. #endif
  373. #ifdef LIBRNNOISE_ENABLED
  374. if (ng->use_rnnoise && ng->rnn_states[0])
  375. return;
  376. #endif
  377. /* One speex/rnnoise state for each channel (limit 2) */
  378. ng->copy_buffers[0] = bmalloc(frames * channels * sizeof(float));
  379. #ifdef LIBSPEEXDSP_ENABLED
  380. ng->spx_segment_buffers[0] =
  381. bmalloc(frames * channels * sizeof(spx_int16_t));
  382. #endif
  383. #ifdef LIBRNNOISE_ENABLED
  384. ng->rnn_segment_buffers[0] =
  385. bmalloc(RNNOISE_FRAME_SIZE * channels * sizeof(float));
  386. #endif
  387. #ifdef LIBNVAFX_ENABLED
  388. ng->nvafx_segment_buffers[0] =
  389. bmalloc(NVAFX_FRAME_SIZE * channels * sizeof(float));
  390. #endif
  391. for (size_t c = 1; c < channels; ++c) {
  392. ng->copy_buffers[c] = ng->copy_buffers[c - 1] + frames;
  393. #ifdef LIBSPEEXDSP_ENABLED
  394. ng->spx_segment_buffers[c] =
  395. ng->spx_segment_buffers[c - 1] + frames;
  396. #endif
  397. #ifdef LIBRNNOISE_ENABLED
  398. ng->rnn_segment_buffers[c] =
  399. ng->rnn_segment_buffers[c - 1] + RNNOISE_FRAME_SIZE;
  400. #endif
  401. #ifdef LIBNVAFX_ENABLED
  402. ng->nvafx_segment_buffers[c] =
  403. ng->nvafx_segment_buffers[c - 1] + NVAFX_FRAME_SIZE;
  404. #endif
  405. }
  406. #ifdef LIBNVAFX_ENABLED
  407. if (!ng->nvafx_initialized && ng->use_nvafx && !ng->nvafx_loading) {
  408. ng->nvafx_loading = true;
  409. pthread_create(&ng->nvafx_thread, NULL, nvafx_initialize, ng);
  410. }
  411. #endif
  412. for (size_t i = 0; i < channels; i++)
  413. alloc_channel(ng, sample_rate, i, frames);
  414. #ifdef LIBRNNOISE_ENABLED
  415. if (sample_rate == RNNOISE_SAMPLE_RATE) {
  416. ng->rnn_resampler = NULL;
  417. ng->rnn_resampler_back = NULL;
  418. } else {
  419. struct resample_info src, dst;
  420. src.samples_per_sec = sample_rate;
  421. src.format = AUDIO_FORMAT_FLOAT_PLANAR;
  422. src.speakers = convert_speaker_layout((uint8_t)channels);
  423. dst.samples_per_sec = RNNOISE_SAMPLE_RATE;
  424. dst.format = AUDIO_FORMAT_FLOAT_PLANAR;
  425. dst.speakers = convert_speaker_layout((uint8_t)channels);
  426. ng->rnn_resampler = audio_resampler_create(&dst, &src);
  427. ng->rnn_resampler_back = audio_resampler_create(&src, &dst);
  428. }
  429. #endif
  430. #ifdef LIBNVAFX_ENABLED
  431. if (sample_rate == NVAFX_SAMPLE_RATE) {
  432. ng->nvafx_resampler = NULL;
  433. ng->nvafx_resampler_back = NULL;
  434. } else {
  435. struct resample_info src, dst;
  436. src.samples_per_sec = sample_rate;
  437. src.format = AUDIO_FORMAT_FLOAT_PLANAR;
  438. src.speakers = convert_speaker_layout((uint8_t)channels);
  439. dst.samples_per_sec = NVAFX_SAMPLE_RATE;
  440. dst.format = AUDIO_FORMAT_FLOAT_PLANAR;
  441. dst.speakers = convert_speaker_layout((uint8_t)channels);
  442. ng->nvafx_resampler = audio_resampler_create(&dst, &src);
  443. ng->nvafx_resampler_back = audio_resampler_create(&src, &dst);
  444. }
  445. #endif
  446. }
  447. #ifdef _MSC_VER
  448. #pragma warning(push)
  449. #pragma warning(disable : 4706)
  450. #endif
  451. bool load_nvafx(void)
  452. {
  453. #ifdef LIBNVAFX_ENABLED
  454. if (!load_lib()) {
  455. blog(LOG_INFO,
  456. "[noise suppress]: NVIDIA RTX denoiser disabled, redistributable not found");
  457. return false;
  458. }
  459. nvafx_initializer_mutex_initialized =
  460. pthread_mutex_init(&nvafx_initializer_mutex, NULL) == 0;
  461. #define LOAD_SYM_FROM_LIB(sym, lib, dll) \
  462. if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \
  463. DWORD err = GetLastError(); \
  464. printf("[noise suppress]: Couldn't load " #sym " from " dll \
  465. ": %lu (0x%lx)", \
  466. err, err); \
  467. goto unload_everything; \
  468. }
  469. #define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, nv_audiofx, "NVAudioEffects.dll")
  470. LOAD_SYM(NvAFX_GetEffectList);
  471. LOAD_SYM(NvAFX_CreateEffect);
  472. LOAD_SYM(NvAFX_DestroyEffect);
  473. LOAD_SYM(NvAFX_SetU32);
  474. LOAD_SYM(NvAFX_SetString);
  475. LOAD_SYM(NvAFX_SetFloat);
  476. LOAD_SYM(NvAFX_GetU32);
  477. LOAD_SYM(NvAFX_GetString);
  478. LOAD_SYM(NvAFX_GetFloat);
  479. LOAD_SYM(NvAFX_Load);
  480. LOAD_SYM(NvAFX_Run);
  481. #undef LOAD_SYM
  482. int err;
  483. NvAFX_Handle h = NULL;
  484. err = NvAFX_CreateEffect(NVAFX_EFFECT_DENOISER, &h);
  485. if (err != NVAFX_STATUS_SUCCESS) {
  486. if (err == NVAFX_STATUS_GPU_UNSUPPORTED) {
  487. blog(LOG_INFO,
  488. "[noise suppress]: NVIDIA RTX denoiser disabled: unsupported GPU");
  489. } else {
  490. blog(LOG_ERROR,
  491. "[noise suppress]: NVIDIA RTX denoiser disabled: error %i",
  492. err);
  493. }
  494. goto unload_everything;
  495. }
  496. err = NvAFX_DestroyEffect(h);
  497. if (err != NVAFX_STATUS_SUCCESS) {
  498. blog(LOG_ERROR, "NvAFX_DestroyEffect() failed, error %i", err);
  499. goto unload_everything;
  500. }
  501. nvafx_loaded = true;
  502. blog(LOG_INFO, "[noise suppress]: NVIDIA RTX denoiser enabled");
  503. return true;
  504. unload_everything:
  505. release_lib();
  506. #endif
  507. return false;
  508. }
  509. #ifdef _MSC_VER
  510. #pragma warning(pop)
  511. #endif
  512. void unload_nvafx(void)
  513. {
  514. #ifdef LIBNVAFX_ENABLED
  515. release_lib();
  516. if (nvafx_initializer_mutex_initialized) {
  517. pthread_mutex_destroy(&nvafx_initializer_mutex);
  518. nvafx_initializer_mutex_initialized = false;
  519. }
  520. #endif
  521. }
  522. static void *noise_suppress_create(obs_data_t *settings, obs_source_t *filter)
  523. {
  524. struct noise_suppress_data *ng =
  525. bzalloc(sizeof(struct noise_suppress_data));
  526. ng->context = filter;
  527. #ifdef LIBNVAFX_ENABLED
  528. char sdk_path[MAX_PATH];
  529. if (!nvafx_get_sdk_path(sdk_path, sizeof(sdk_path))) {
  530. ng->nvafx_enabled = false;
  531. do_log(LOG_ERROR, "NVAFX redist is not installed.");
  532. } else {
  533. const char *file = "\\models\\denoiser_48k.trtpkg";
  534. size_t size = strlen(sdk_path) + strlen(file) + 1;
  535. char *buffer = (char *)bmalloc(size);
  536. strcpy(buffer, sdk_path);
  537. strcat(buffer, file);
  538. ng->model = buffer;
  539. ng->nvafx_enabled = true;
  540. ng->nvafx_initialized = false;
  541. ng->nvafx_loading = false;
  542. pthread_mutex_init(&ng->nvafx_mutex, NULL);
  543. info("NVAFX SDK redist path was found here %s", sdk_path);
  544. }
  545. #endif
  546. noise_suppress_update(ng, settings);
  547. return ng;
  548. }
  549. static inline void process_speexdsp(struct noise_suppress_data *ng)
  550. {
  551. #ifdef LIBSPEEXDSP_ENABLED
  552. /* Set args */
  553. for (size_t i = 0; i < ng->channels; i++)
  554. speex_preprocess_ctl(ng->spx_states[i],
  555. SPEEX_PREPROCESS_SET_NOISE_SUPPRESS,
  556. &ng->suppress_level);
  557. /* Convert to 16bit */
  558. for (size_t i = 0; i < ng->channels; i++)
  559. for (size_t j = 0; j < ng->frames; j++) {
  560. float s = ng->copy_buffers[i][j];
  561. if (s > 1.0f)
  562. s = 1.0f;
  563. else if (s < -1.0f)
  564. s = -1.0f;
  565. ng->spx_segment_buffers[i][j] =
  566. (spx_int16_t)(s * c_32_to_16);
  567. }
  568. /* Execute */
  569. for (size_t i = 0; i < ng->channels; i++)
  570. speex_preprocess_run(ng->spx_states[i],
  571. ng->spx_segment_buffers[i]);
  572. /* Convert back to 32bit */
  573. for (size_t i = 0; i < ng->channels; i++)
  574. for (size_t j = 0; j < ng->frames; j++)
  575. ng->copy_buffers[i][j] =
  576. (float)ng->spx_segment_buffers[i][j] /
  577. c_16_to_32;
  578. #else
  579. UNUSED_PARAMETER(ng);
  580. #endif
  581. }
  582. static inline void process_rnnoise(struct noise_suppress_data *ng)
  583. {
  584. #ifdef LIBRNNOISE_ENABLED
  585. /* Adjust signal level to what RNNoise expects, resample if necessary */
  586. if (ng->rnn_resampler) {
  587. float *output[MAX_PREPROC_CHANNELS];
  588. uint32_t out_frames;
  589. uint64_t ts_offset;
  590. audio_resampler_resample(ng->rnn_resampler, (uint8_t **)output,
  591. &out_frames, &ts_offset,
  592. (const uint8_t **)ng->copy_buffers,
  593. (uint32_t)ng->frames);
  594. for (size_t i = 0; i < ng->channels; i++) {
  595. for (ssize_t j = 0, k = (ssize_t)out_frames -
  596. RNNOISE_FRAME_SIZE;
  597. j < RNNOISE_FRAME_SIZE; ++j, ++k) {
  598. if (k >= 0) {
  599. ng->rnn_segment_buffers[i][j] =
  600. output[i][k] * 32768.0f;
  601. } else {
  602. ng->rnn_segment_buffers[i][j] = 0;
  603. }
  604. }
  605. }
  606. } else {
  607. for (size_t i = 0; i < ng->channels; i++) {
  608. for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) {
  609. ng->rnn_segment_buffers[i][j] =
  610. ng->copy_buffers[i][j] * 32768.0f;
  611. }
  612. }
  613. }
  614. /* Execute */
  615. for (size_t i = 0; i < ng->channels; i++) {
  616. rnnoise_process_frame(ng->rnn_states[i],
  617. ng->rnn_segment_buffers[i],
  618. ng->rnn_segment_buffers[i]);
  619. }
  620. /* Revert signal level adjustment, resample back if necessary */
  621. if (ng->rnn_resampler) {
  622. float *output[MAX_PREPROC_CHANNELS];
  623. uint32_t out_frames;
  624. uint64_t ts_offset;
  625. audio_resampler_resample(
  626. ng->rnn_resampler_back, (uint8_t **)output, &out_frames,
  627. &ts_offset, (const uint8_t **)ng->rnn_segment_buffers,
  628. RNNOISE_FRAME_SIZE);
  629. for (size_t i = 0; i < ng->channels; i++) {
  630. for (ssize_t j = 0,
  631. k = (ssize_t)out_frames - ng->frames;
  632. j < (ssize_t)ng->frames; ++j, ++k) {
  633. if (k >= 0) {
  634. ng->copy_buffers[i][j] =
  635. output[i][k] / 32768.0f;
  636. } else {
  637. ng->copy_buffers[i][j] = 0;
  638. }
  639. }
  640. }
  641. } else {
  642. for (size_t i = 0; i < ng->channels; i++) {
  643. for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) {
  644. ng->copy_buffers[i][j] =
  645. ng->rnn_segment_buffers[i][j] /
  646. 32768.0f;
  647. }
  648. }
  649. }
  650. #else
  651. UNUSED_PARAMETER(ng);
  652. #endif
  653. }
  654. static inline void process_nvafx(struct noise_suppress_data *ng)
  655. {
  656. #ifdef LIBNVAFX_ENABLED
  657. if (nvafx_loaded && ng->use_nvafx && ng->nvafx_initialized) {
  658. /* Resample if necessary */
  659. if (ng->nvafx_resampler) {
  660. float *output[MAX_PREPROC_CHANNELS];
  661. uint32_t out_frames;
  662. uint64_t ts_offset;
  663. audio_resampler_resample(
  664. ng->nvafx_resampler, (uint8_t **)output,
  665. &out_frames, &ts_offset,
  666. (const uint8_t **)ng->copy_buffers,
  667. (uint32_t)ng->frames);
  668. for (size_t i = 0; i < ng->channels; i++) {
  669. for (ssize_t j = 0, k = (ssize_t)out_frames -
  670. NVAFX_FRAME_SIZE;
  671. j < NVAFX_FRAME_SIZE; ++j, ++k) {
  672. if (k >= 0) {
  673. ng->nvafx_segment_buffers[i][j] =
  674. output[i][k];
  675. } else {
  676. ng->nvafx_segment_buffers[i][j] =
  677. 0;
  678. }
  679. }
  680. }
  681. } else {
  682. for (size_t i = 0; i < ng->channels; i++) {
  683. for (size_t j = 0; j < NVAFX_FRAME_SIZE; ++j) {
  684. ng->nvafx_segment_buffers[i][j] =
  685. ng->copy_buffers[i][j];
  686. }
  687. }
  688. }
  689. /* Execute */
  690. for (size_t i = 0; i < ng->channels; i++) {
  691. NvAFX_Status err = NvAFX_Run(
  692. ng->handle[i], &ng->nvafx_segment_buffers[i],
  693. &ng->nvafx_segment_buffers[i],
  694. ng->num_samples_per_frame, ng->num_channels);
  695. if (err != NVAFX_STATUS_SUCCESS)
  696. do_log(LOG_ERROR,
  697. "NvAFX_Run() failed, error %i", err);
  698. }
  699. /* Revert signal level adjustment, resample back if necessary */
  700. if (ng->nvafx_resampler) {
  701. float *output[MAX_PREPROC_CHANNELS];
  702. uint32_t out_frames;
  703. uint64_t ts_offset;
  704. audio_resampler_resample(
  705. ng->nvafx_resampler_back, (uint8_t **)output,
  706. &out_frames, &ts_offset,
  707. (const uint8_t **)ng->nvafx_segment_buffers,
  708. NVAFX_FRAME_SIZE);
  709. for (size_t i = 0; i < ng->channels; i++) {
  710. for (ssize_t j = 0, k = (ssize_t)out_frames -
  711. ng->frames;
  712. j < (ssize_t)ng->frames; ++j, ++k) {
  713. if (k >= 0) {
  714. ng->copy_buffers[i][j] =
  715. output[i][k];
  716. } else {
  717. ng->copy_buffers[i][j] = 0;
  718. }
  719. }
  720. }
  721. } else {
  722. for (size_t i = 0; i < ng->channels; i++) {
  723. for (size_t j = 0; j < NVAFX_FRAME_SIZE; ++j) {
  724. ng->copy_buffers[i][j] =
  725. ng->nvafx_segment_buffers[i][j];
  726. }
  727. }
  728. }
  729. }
  730. #else
  731. UNUSED_PARAMETER(ng);
  732. #endif
  733. }
  734. static inline void process(struct noise_suppress_data *ng)
  735. {
  736. /* Pop from input circlebuf */
  737. for (size_t i = 0; i < ng->channels; i++)
  738. circlebuf_pop_front(&ng->input_buffers[i], ng->copy_buffers[i],
  739. ng->frames * sizeof(float));
  740. if (ng->use_rnnoise) {
  741. process_rnnoise(ng);
  742. } else if (ng->use_nvafx) {
  743. if (nvafx_loaded) {
  744. process_nvafx(ng);
  745. }
  746. } else {
  747. process_speexdsp(ng);
  748. }
  749. /* Push to output circlebuf */
  750. for (size_t i = 0; i < ng->channels; i++)
  751. circlebuf_push_back(&ng->output_buffers[i], ng->copy_buffers[i],
  752. ng->frames * sizeof(float));
  753. }
  754. struct ng_audio_info {
  755. uint32_t frames;
  756. uint64_t timestamp;
  757. };
  758. static inline void clear_circlebuf(struct circlebuf *buf)
  759. {
  760. circlebuf_pop_front(buf, NULL, buf->size);
  761. }
  762. static void reset_data(struct noise_suppress_data *ng)
  763. {
  764. for (size_t i = 0; i < ng->channels; i++) {
  765. clear_circlebuf(&ng->input_buffers[i]);
  766. clear_circlebuf(&ng->output_buffers[i]);
  767. }
  768. clear_circlebuf(&ng->info_buffer);
  769. }
  770. static struct obs_audio_data *
  771. noise_suppress_filter_audio(void *data, struct obs_audio_data *audio)
  772. {
  773. struct noise_suppress_data *ng = data;
  774. struct ng_audio_info info;
  775. size_t segment_size = ng->frames * sizeof(float);
  776. size_t out_size;
  777. #ifdef LIBSPEEXDSP_ENABLED
  778. if (!ng->spx_states[0])
  779. return audio;
  780. #endif
  781. #ifdef LIBRNNOISE_ENABLED
  782. if (!ng->rnn_states[0])
  783. return audio;
  784. #endif
  785. /* -----------------------------------------------
  786. * if timestamp has dramatically changed, consider it a new stream of
  787. * audio data. clear all circular buffers to prevent old audio data
  788. * from being processed as part of the new data. */
  789. if (ng->last_timestamp) {
  790. int64_t diff = llabs((int64_t)ng->last_timestamp -
  791. (int64_t)audio->timestamp);
  792. if (diff > 1000000000LL)
  793. reset_data(ng);
  794. }
  795. ng->last_timestamp = audio->timestamp;
  796. /* -----------------------------------------------
  797. * push audio packet info (timestamp/frame count) to info circlebuf */
  798. info.frames = audio->frames;
  799. info.timestamp = audio->timestamp;
  800. circlebuf_push_back(&ng->info_buffer, &info, sizeof(info));
  801. /* -----------------------------------------------
  802. * push back current audio data to input circlebuf */
  803. for (size_t i = 0; i < ng->channels; i++)
  804. circlebuf_push_back(&ng->input_buffers[i], audio->data[i],
  805. audio->frames * sizeof(float));
  806. /* -----------------------------------------------
  807. * pop/process each 10ms segments, push back to output circlebuf */
  808. while (ng->input_buffers[0].size >= segment_size)
  809. process(ng);
  810. /* -----------------------------------------------
  811. * peek front of info circlebuf, check to see if we have enough to
  812. * pop the expected packet size, if not, return null */
  813. memset(&info, 0, sizeof(info));
  814. circlebuf_peek_front(&ng->info_buffer, &info, sizeof(info));
  815. out_size = info.frames * sizeof(float);
  816. if (ng->output_buffers[0].size < out_size)
  817. return NULL;
  818. /* -----------------------------------------------
  819. * if there's enough audio data buffered in the output circlebuf,
  820. * pop and return a packet */
  821. circlebuf_pop_front(&ng->info_buffer, NULL, sizeof(info));
  822. da_resize(ng->output_data, out_size * ng->channels);
  823. for (size_t i = 0; i < ng->channels; i++) {
  824. ng->output_audio.data[i] =
  825. (uint8_t *)&ng->output_data.array[i * out_size];
  826. circlebuf_pop_front(&ng->output_buffers[i],
  827. ng->output_audio.data[i], out_size);
  828. }
  829. ng->output_audio.frames = info.frames;
  830. ng->output_audio.timestamp = info.timestamp - ng->latency;
  831. return &ng->output_audio;
  832. }
  833. static bool noise_suppress_method_modified(obs_properties_t *props,
  834. obs_property_t *property,
  835. obs_data_t *settings)
  836. {
  837. obs_property_t *p_suppress_level =
  838. obs_properties_get(props, S_SUPPRESS_LEVEL);
  839. obs_property_t *p_navfx_intensity =
  840. obs_properties_get(props, S_NVAFX_INTENSITY);
  841. const char *method = obs_data_get_string(settings, S_METHOD);
  842. bool enable_level = strcmp(method, S_METHOD_SPEEX) == 0;
  843. bool enable_intensity = strcmp(method, S_METHOD_NVAFX) == 0;
  844. obs_property_set_visible(p_suppress_level, enable_level);
  845. obs_property_set_visible(p_navfx_intensity, enable_intensity);
  846. UNUSED_PARAMETER(property);
  847. return true;
  848. }
  849. static void noise_suppress_defaults_v1(obs_data_t *s)
  850. {
  851. obs_data_set_default_int(s, S_SUPPRESS_LEVEL, -30);
  852. #if defined(LIBRNNOISE_ENABLED) && !defined(LIBSPEEXDSP_ENABLED)
  853. obs_data_set_default_string(s, S_METHOD, S_METHOD_RNN);
  854. #else
  855. obs_data_set_default_string(s, S_METHOD, S_METHOD_SPEEX);
  856. #endif
  857. #if defined(LIBNVAFX_ENABLED)
  858. obs_data_set_default_double(s, S_NVAFX_INTENSITY, 1.0);
  859. #endif
  860. }
  861. static void noise_suppress_defaults_v2(obs_data_t *s)
  862. {
  863. obs_data_set_default_int(s, S_SUPPRESS_LEVEL, -30);
  864. #if defined(LIBRNNOISE_ENABLED)
  865. obs_data_set_default_string(s, S_METHOD, S_METHOD_RNN);
  866. #else
  867. obs_data_set_default_string(s, S_METHOD, S_METHOD_SPEEX);
  868. #endif
  869. #if defined(LIBNVAFX_ENABLED)
  870. obs_data_set_default_double(s, S_NVAFX_INTENSITY, 1.0);
  871. #endif
  872. }
  873. static obs_properties_t *noise_suppress_properties(void *data)
  874. {
  875. obs_properties_t *ppts = obs_properties_create();
  876. #ifdef LIBNVAFX_ENABLED
  877. struct noise_suppress_data *ng = (struct noise_suppress_data *)data;
  878. #else
  879. UNUSED_PARAMETER(data);
  880. #endif
  881. #if defined(LIBRNNOISE_ENABLED) && defined(LIBSPEEXDSP_ENABLED)
  882. obs_property_t *method = obs_properties_add_list(
  883. ppts, S_METHOD, TEXT_METHOD, OBS_COMBO_TYPE_LIST,
  884. OBS_COMBO_FORMAT_STRING);
  885. obs_property_list_add_string(method, TEXT_METHOD_SPEEX, S_METHOD_SPEEX);
  886. obs_property_list_add_string(method, TEXT_METHOD_RNN, S_METHOD_RNN);
  887. #ifdef LIBNVAFX_ENABLED
  888. if (ng->nvafx_enabled)
  889. obs_property_list_add_string(method, TEXT_METHOD_NVAFX,
  890. S_METHOD_NVAFX);
  891. #endif
  892. obs_property_set_modified_callback(method,
  893. noise_suppress_method_modified);
  894. #endif
  895. #ifdef LIBSPEEXDSP_ENABLED
  896. obs_property_t *speex_slider = obs_properties_add_int_slider(
  897. ppts, S_SUPPRESS_LEVEL, TEXT_SUPPRESS_LEVEL, SUP_MIN, SUP_MAX,
  898. 1);
  899. obs_property_int_set_suffix(speex_slider, " dB");
  900. #endif
  901. #ifdef LIBNVAFX_ENABLED
  902. obs_properties_add_float_slider(ppts, S_NVAFX_INTENSITY,
  903. TEXT_NVAFX_INTENSITY, 0.0f, 1.0f,
  904. 0.01f);
  905. #if defined(LIBRNNOISE_ENABLED) && defined(LIBSPEEXDSP_ENABLED)
  906. if (!nvafx_loaded) {
  907. obs_property_list_item_disable(method, 2, true);
  908. }
  909. #endif
  910. #endif
  911. return ppts;
  912. }
  913. struct obs_source_info noise_suppress_filter = {
  914. .id = "noise_suppress_filter",
  915. .type = OBS_SOURCE_TYPE_FILTER,
  916. .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_CAP_OBSOLETE,
  917. .get_name = noise_suppress_name,
  918. .create = noise_suppress_create,
  919. .destroy = noise_suppress_destroy,
  920. .update = noise_suppress_update,
  921. .filter_audio = noise_suppress_filter_audio,
  922. .get_defaults = noise_suppress_defaults_v1,
  923. .get_properties = noise_suppress_properties,
  924. };
  925. struct obs_source_info noise_suppress_filter_v2 = {
  926. .id = "noise_suppress_filter",
  927. .version = 2,
  928. .type = OBS_SOURCE_TYPE_FILTER,
  929. .output_flags = OBS_SOURCE_AUDIO,
  930. .get_name = noise_suppress_name,
  931. .create = noise_suppress_create,
  932. .destroy = noise_suppress_destroy,
  933. .update = noise_suppress_update,
  934. .filter_audio = noise_suppress_filter_audio,
  935. .get_defaults = noise_suppress_defaults_v2,
  936. .get_properties = noise_suppress_properties,
  937. };