gravix-rtc-react-native 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (378) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +20 -0
  3. package/LICENSES/Apache-2.0.txt +175 -0
  4. package/NOTICE +68 -0
  5. package/README.md +313 -2
  6. package/android/build.gradle +137 -0
  7. package/android/consumer-rules.pro +29 -0
  8. package/android/src/main/AndroidManifest.xml +9 -0
  9. package/android/src/main/cpp/CMakeLists.txt +48 -0
  10. package/android/src/main/cpp/gx_dfn_engine.c +332 -0
  11. package/android/src/main/cpp/gx_fx_jni.cpp +34 -0
  12. package/android/src/main/cpp/gx_ns_jni.c +162 -0
  13. package/android/src/main/cpp/third_party/onnxruntime/LICENSE +21 -0
  14. package/android/src/main/cpp/third_party/onnxruntime/include/onnxruntime_c_api.h +9227 -0
  15. package/android/src/main/cpp/third_party/onnxruntime/include/onnxruntime_ep_c_api.h +3315 -0
  16. package/android/src/main/cpp/third_party/onnxruntime/include/onnxruntime_error_code.h +98 -0
  17. package/android/src/main/java/com/gravitycompile/gravixrtc/GravixAudioHooks.kt +144 -0
  18. package/android/src/main/java/com/gravitycompile/gravixrtc/GravixAudioModule.kt +105 -0
  19. package/android/src/main/java/com/gravitycompile/gravixrtc/GravixNativeAudio.kt +310 -0
  20. package/android/src/main/java/com/gravitycompile/gravixrtc/GravixRtc.kt +134 -0
  21. package/android/src/main/java/com/gravitycompile/gravixrtc/GravixRtcModule.kt +176 -0
  22. package/android/src/main/java/com/gravitycompile/gravixrtc/GravixRtcPackage.kt +39 -0
  23. package/android/src/main/java/com/gravitycompile/gravixrtc/audio/AudioDeviceKind.java +44 -0
  24. package/android/src/main/java/com/gravitycompile/gravixrtc/audio/AudioManagerUtils.kt +120 -0
  25. package/android/src/main/java/com/gravitycompile/gravixrtc/audio/AudioSwitchManager.java +270 -0
  26. package/android/src/main/java/com/gravitycompile/gravixrtc/audio/AudioType.kt +50 -0
  27. package/android/src/main/java/com/gravitycompile/gravixrtc/music/MusicCaptureRouter.kt +375 -0
  28. package/android/src/main/java/com/gravitycompile/gravixrtc/music/MusicDecoder.kt +339 -0
  29. package/android/src/main/java/com/gravitycompile/gravixrtc/music/MusicInterruptionWatcher.kt +82 -0
  30. package/android/src/main/java/com/gravitycompile/gravixrtc/music/MusicMicRelease.kt +117 -0
  31. package/android/src/main/java/com/gravitycompile/gravixrtc/music/MusicMixKernel.kt +191 -0
  32. package/android/src/main/java/com/gravitycompile/gravixrtc/music/MusicMixerEngine.kt +617 -0
  33. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/AudioRoutePolicy.kt +137 -0
  34. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GravixCaptureProcessing.kt +67 -0
  35. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxCaptureDump.kt +143 -0
  36. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxCaptureSwitcher.kt +196 -0
  37. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxNoiseProcessor.kt +795 -0
  38. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxNsLogic.kt +180 -0
  39. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxNsNative.kt +83 -0
  40. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxNsStudio.kt +372 -0
  41. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxRecordStartGuard.kt +76 -0
  42. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxRecorderSeam.kt +434 -0
  43. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxSingerSource.kt +37 -0
  44. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/GxVoiceFx.kt +160 -0
  45. package/android/src/main/java/com/gravitycompile/gravixrtc/processing/OtherAppAudioPolicy.kt +143 -0
  46. package/android/src/main/java/org/webrtc/audio/WebRtcAudioTrackHelper.kt +43 -0
  47. package/docs/ANDROID_NATIVE_HOOKS.md +102 -0
  48. package/docs/FEATURE_MATRIX.md +192 -0
  49. package/docs/IOS_NATIVE_HOOKS.md +190 -0
  50. package/gravix-rtc-react-native.podspec +49 -0
  51. package/ios/GravixRtc.h +7 -0
  52. package/ios/GravixRtc.mm +273 -0
  53. package/ios/GravixRtcSetup.h +29 -0
  54. package/ios/GravixRtcSetup.m +52 -0
  55. package/ios/audio/GravixRtcIosAudio.m +157 -0
  56. package/ios/audio/GxAudioDevice.h +62 -0
  57. package/ios/audio/GxAudioDevice.m +857 -0
  58. package/ios/audio/GxAudioSetup.h +34 -0
  59. package/ios/audio/GxAudioSetup.m +70 -0
  60. package/ios/audio/GxCompat.swift +53 -0
  61. package/ios/audio/GxIosAudio.swift +99 -0
  62. package/ios/audio/GxMusicController.swift +150 -0
  63. package/ios/audio/GxMusicPost.swift +362 -0
  64. package/ios/audio/GxNoiseProcessor.swift +718 -0
  65. package/ios/audio/GxNsDfn3CoreML.swift +195 -0
  66. package/ios/audio/GxNsStudioEngine.swift +237 -0
  67. package/ios/audio/GxNsStudioPack.swift +212 -0
  68. package/ios/audio/GxVoiceFx.swift +161 -0
  69. package/ios/audio/gx_adm_state.h +153 -0
  70. package/ios/gxcore/apple/gx_music_post.c +312 -0
  71. package/ios/gxcore/apple/gx_pcm.c +30 -0
  72. package/ios/gxcore/apple/gxns_build.h +19 -0
  73. package/ios/gxcore/apple/gxns_ios.c +17 -0
  74. package/ios/gxcore/apple/include/gx_fx.h +3 -0
  75. package/ios/gxcore/apple/include/gx_music_post.h +88 -0
  76. package/ios/gxcore/apple/include/gx_ns.h +3 -0
  77. package/ios/gxcore/apple/include/gx_pcm.h +33 -0
  78. package/ios/gxcore/apple/include/gxns_ios.h +18 -0
  79. package/ios/gxcore/apple/include/module.modulemap +10 -0
  80. package/ios/gxcore/apple/shim/rnnoise.h +2 -0
  81. package/ios/gxcore/apple/shim/speex_resampler.h +2 -0
  82. package/ios/gxcore/apple/units/gx_fx_forward.cpp +3 -0
  83. package/ios/gxcore/apple/units/gx_ns.c +7 -0
  84. package/ios/gxcore/apple/units/gx_ns_timer.c +7 -0
  85. package/ios/gxcore/apple/units/rnnoise_celt_lpc.c +7 -0
  86. package/ios/gxcore/apple/units/rnnoise_denoise.c +7 -0
  87. package/ios/gxcore/apple/units/rnnoise_kiss_fft.c +7 -0
  88. package/ios/gxcore/apple/units/rnnoise_pitch.c +7 -0
  89. package/ios/gxcore/apple/units/rnnoise_rnn.c +7 -0
  90. package/ios/gxcore/apple/units/rnnoise_rnn_data.c +7 -0
  91. package/ios/gxcore/apple/units/speexdsp_resample.c +7 -0
  92. package/ios/resources/ns/DFN3-NOTICE.txt +10 -0
  93. package/ios/resources/ns/DeepFilterNet-LICENSE-APACHE +201 -0
  94. package/ios/resources/ns/DeepFilterNet-LICENSE-MIT +19 -0
  95. package/ios/resources/ns/gxns_dfn3.mlmodelc/analytics/coremldata.bin +0 -0
  96. package/ios/resources/ns/gxns_dfn3.mlmodelc/coremldata.bin +0 -0
  97. package/ios/resources/ns/gxns_dfn3.mlmodelc/metadata.json +338 -0
  98. package/ios/resources/ns/gxns_dfn3.mlmodelc/model.mil +927 -0
  99. package/ios/resources/ns/gxns_dfn3.mlmodelc/weights/weight.bin +0 -0
  100. package/lib/module/android/bindings.js +49 -0
  101. package/lib/module/android/bindings.js.map +1 -0
  102. package/lib/module/android/index.js +13 -0
  103. package/lib/module/android/index.js.map +1 -0
  104. package/lib/module/android/micMute.js +341 -0
  105. package/lib/module/android/micMute.js.map +1 -0
  106. package/lib/module/android/nativeAudio.js +47 -0
  107. package/lib/module/android/nativeAudio.js.map +1 -0
  108. package/lib/module/android/noiseSuppression.js +170 -0
  109. package/lib/module/android/noiseSuppression.js.map +1 -0
  110. package/lib/module/android/roomMusic.js +142 -0
  111. package/lib/module/android/roomMusic.js.map +1 -0
  112. package/lib/module/android/singerMode.js +31 -0
  113. package/lib/module/android/singerMode.js.map +1 -0
  114. package/lib/module/android/voiceEffects.js +65 -0
  115. package/lib/module/android/voiceEffects.js.map +1 -0
  116. package/lib/module/audio/AudioManager.js +79 -0
  117. package/lib/module/audio/AudioManager.js.map +1 -0
  118. package/lib/module/audio/AudioSession.js +90 -0
  119. package/lib/module/audio/AudioSession.js.map +1 -0
  120. package/lib/module/audio/remoteVolume.js +54 -0
  121. package/lib/module/audio/remoteVolume.js.map +1 -0
  122. package/lib/module/components/VideoView.js +109 -0
  123. package/lib/module/components/VideoView.js.map +1 -0
  124. package/lib/module/features/audioScenario.js +53 -0
  125. package/lib/module/features/audioScenario.js.map +1 -0
  126. package/lib/module/features/beauty.js +828 -0
  127. package/lib/module/features/beauty.js.map +1 -0
  128. package/lib/module/features/micRelease.js +89 -0
  129. package/lib/module/features/micRelease.js.map +1 -0
  130. package/lib/module/features/noiseSuppression.js +213 -0
  131. package/lib/module/features/noiseSuppression.js.map +1 -0
  132. package/lib/module/features/roomMusic.js +90 -0
  133. package/lib/module/features/roomMusic.js.map +1 -0
  134. package/lib/module/features/roomMusicAndroid.js +294 -0
  135. package/lib/module/features/roomMusicAndroid.js.map +1 -0
  136. package/lib/module/features/roomMusicIos.js +250 -0
  137. package/lib/module/features/roomMusicIos.js.map +1 -0
  138. package/lib/module/features/roomMusicTypes.js +53 -0
  139. package/lib/module/features/roomMusicTypes.js.map +1 -0
  140. package/lib/module/features/screenShare.js +22 -0
  141. package/lib/module/features/screenShare.js.map +1 -0
  142. package/lib/module/features/singerMode.js +73 -0
  143. package/lib/module/features/singerMode.js.map +1 -0
  144. package/lib/module/features/voiceEffects.js +148 -0
  145. package/lib/module/features/voiceEffects.js.map +1 -0
  146. package/lib/module/hooks/context.js +34 -0
  147. package/lib/module/hooks/context.js.map +1 -0
  148. package/lib/module/hooks/hooks.js +145 -0
  149. package/lib/module/hooks/hooks.js.map +1 -0
  150. package/lib/module/hooks/types.js +4 -0
  151. package/lib/module/hooks/types.js.map +1 -0
  152. package/lib/module/hooks/useRoomEvents.js +30 -0
  153. package/lib/module/hooks/useRoomEvents.js.map +1 -0
  154. package/lib/module/index.js +43 -0
  155. package/lib/module/index.js.map +1 -0
  156. package/lib/module/ios/autoAttach.js +14 -0
  157. package/lib/module/ios/autoAttach.js.map +1 -0
  158. package/lib/module/ios/iosAudio.js +149 -0
  159. package/lib/module/ios/iosAudio.js.map +1 -0
  160. package/lib/module/join/appStateLifecycle.js +54 -0
  161. package/lib/module/join/appStateLifecycle.js.map +1 -0
  162. package/lib/module/micPolicy.js +249 -0
  163. package/lib/module/micPolicy.js.map +1 -0
  164. package/lib/module/native/NativeGravixAudio.js +18 -0
  165. package/lib/module/native/NativeGravixAudio.js.map +1 -0
  166. package/lib/module/native/NativeGravixRtc.js +13 -0
  167. package/lib/module/native/NativeGravixRtc.js.map +1 -0
  168. package/lib/module/native/module.js +23 -0
  169. package/lib/module/native/module.js.map +1 -0
  170. package/lib/module/package.json +1 -0
  171. package/lib/module/polyfills/DOMException.js +22 -0
  172. package/lib/module/polyfills/DOMException.js.map +1 -0
  173. package/lib/module/polyfills/early.js +18 -0
  174. package/lib/module/polyfills/early.js.map +1 -0
  175. package/lib/module/polyfills/event.js +71 -0
  176. package/lib/module/polyfills/event.js.map +1 -0
  177. package/lib/module/polyfills/sha256.js +92 -0
  178. package/lib/module/polyfills/sha256.js.map +1 -0
  179. package/lib/module/polyfills/subtleHmac.js +91 -0
  180. package/lib/module/polyfills/subtleHmac.js.map +1 -0
  181. package/lib/module/polyfills/textCoding.js +164 -0
  182. package/lib/module/polyfills/textCoding.js.map +1 -0
  183. package/lib/module/registerGlobals.js +135 -0
  184. package/lib/module/registerGlobals.js.map +1 -0
  185. package/lib/module/unsupported.js +90 -0
  186. package/lib/module/unsupported.js.map +1 -0
  187. package/lib/module/version.js +7 -0
  188. package/lib/module/version.js.map +1 -0
  189. package/lib/typescript/package.json +1 -0
  190. package/lib/typescript/src/android/bindings.d.ts +14 -0
  191. package/lib/typescript/src/android/bindings.d.ts.map +1 -0
  192. package/lib/typescript/src/android/index.d.ts +9 -0
  193. package/lib/typescript/src/android/index.d.ts.map +1 -0
  194. package/lib/typescript/src/android/micMute.d.ts +124 -0
  195. package/lib/typescript/src/android/micMute.d.ts.map +1 -0
  196. package/lib/typescript/src/android/nativeAudio.d.ts +40 -0
  197. package/lib/typescript/src/android/nativeAudio.d.ts.map +1 -0
  198. package/lib/typescript/src/android/noiseSuppression.d.ts +48 -0
  199. package/lib/typescript/src/android/noiseSuppression.d.ts.map +1 -0
  200. package/lib/typescript/src/android/roomMusic.d.ts +80 -0
  201. package/lib/typescript/src/android/roomMusic.d.ts.map +1 -0
  202. package/lib/typescript/src/android/singerMode.d.ts +27 -0
  203. package/lib/typescript/src/android/singerMode.d.ts.map +1 -0
  204. package/lib/typescript/src/android/voiceEffects.d.ts +30 -0
  205. package/lib/typescript/src/android/voiceEffects.d.ts.map +1 -0
  206. package/lib/typescript/src/audio/AudioManager.d.ts +32 -0
  207. package/lib/typescript/src/audio/AudioManager.d.ts.map +1 -0
  208. package/lib/typescript/src/audio/AudioSession.d.ts +70 -0
  209. package/lib/typescript/src/audio/AudioSession.d.ts.map +1 -0
  210. package/lib/typescript/src/audio/remoteVolume.d.ts +8 -0
  211. package/lib/typescript/src/audio/remoteVolume.d.ts.map +1 -0
  212. package/lib/typescript/src/components/VideoView.d.ts +44 -0
  213. package/lib/typescript/src/components/VideoView.d.ts.map +1 -0
  214. package/lib/typescript/src/features/audioScenario.d.ts +24 -0
  215. package/lib/typescript/src/features/audioScenario.d.ts.map +1 -0
  216. package/lib/typescript/src/features/beauty.d.ts +377 -0
  217. package/lib/typescript/src/features/beauty.d.ts.map +1 -0
  218. package/lib/typescript/src/features/micRelease.d.ts +28 -0
  219. package/lib/typescript/src/features/micRelease.d.ts.map +1 -0
  220. package/lib/typescript/src/features/noiseSuppression.d.ts +64 -0
  221. package/lib/typescript/src/features/noiseSuppression.d.ts.map +1 -0
  222. package/lib/typescript/src/features/roomMusic.d.ts +41 -0
  223. package/lib/typescript/src/features/roomMusic.d.ts.map +1 -0
  224. package/lib/typescript/src/features/roomMusicAndroid.d.ts +60 -0
  225. package/lib/typescript/src/features/roomMusicAndroid.d.ts.map +1 -0
  226. package/lib/typescript/src/features/roomMusicIos.d.ts +56 -0
  227. package/lib/typescript/src/features/roomMusicIos.d.ts.map +1 -0
  228. package/lib/typescript/src/features/roomMusicTypes.d.ts +76 -0
  229. package/lib/typescript/src/features/roomMusicTypes.d.ts.map +1 -0
  230. package/lib/typescript/src/features/screenShare.d.ts +12 -0
  231. package/lib/typescript/src/features/screenShare.d.ts.map +1 -0
  232. package/lib/typescript/src/features/singerMode.d.ts +20 -0
  233. package/lib/typescript/src/features/singerMode.d.ts.map +1 -0
  234. package/lib/typescript/src/features/voiceEffects.d.ts +46 -0
  235. package/lib/typescript/src/features/voiceEffects.d.ts.map +1 -0
  236. package/lib/typescript/src/hooks/context.d.ts +12 -0
  237. package/lib/typescript/src/hooks/context.d.ts.map +1 -0
  238. package/lib/typescript/src/hooks/hooks.d.ts +54 -0
  239. package/lib/typescript/src/hooks/hooks.d.ts.map +1 -0
  240. package/lib/typescript/src/hooks/types.d.ts +8 -0
  241. package/lib/typescript/src/hooks/types.d.ts.map +1 -0
  242. package/lib/typescript/src/hooks/useRoomEvents.d.ts +13 -0
  243. package/lib/typescript/src/hooks/useRoomEvents.d.ts.map +1 -0
  244. package/lib/typescript/src/index.d.ts +37 -0
  245. package/lib/typescript/src/index.d.ts.map +1 -0
  246. package/lib/typescript/src/ios/autoAttach.d.ts +2 -0
  247. package/lib/typescript/src/ios/autoAttach.d.ts.map +1 -0
  248. package/lib/typescript/src/ios/iosAudio.d.ts +96 -0
  249. package/lib/typescript/src/ios/iosAudio.d.ts.map +1 -0
  250. package/lib/typescript/src/join/appStateLifecycle.d.ts +14 -0
  251. package/lib/typescript/src/join/appStateLifecycle.d.ts.map +1 -0
  252. package/lib/typescript/src/micPolicy.d.ts +104 -0
  253. package/lib/typescript/src/micPolicy.d.ts.map +1 -0
  254. package/lib/typescript/src/native/NativeGravixAudio.d.ts +21 -0
  255. package/lib/typescript/src/native/NativeGravixAudio.d.ts.map +1 -0
  256. package/lib/typescript/src/native/NativeGravixRtc.d.ts +31 -0
  257. package/lib/typescript/src/native/NativeGravixRtc.d.ts.map +1 -0
  258. package/lib/typescript/src/native/module.d.ts +7 -0
  259. package/lib/typescript/src/native/module.d.ts.map +1 -0
  260. package/lib/typescript/src/polyfills/DOMException.d.ts +3 -0
  261. package/lib/typescript/src/polyfills/DOMException.d.ts.map +1 -0
  262. package/lib/typescript/src/polyfills/early.d.ts +2 -0
  263. package/lib/typescript/src/polyfills/early.d.ts.map +1 -0
  264. package/lib/typescript/src/polyfills/event.d.ts +2 -0
  265. package/lib/typescript/src/polyfills/event.d.ts.map +1 -0
  266. package/lib/typescript/src/polyfills/sha256.d.ts +3 -0
  267. package/lib/typescript/src/polyfills/sha256.d.ts.map +1 -0
  268. package/lib/typescript/src/polyfills/subtleHmac.d.ts +37 -0
  269. package/lib/typescript/src/polyfills/subtleHmac.d.ts.map +1 -0
  270. package/lib/typescript/src/polyfills/textCoding.d.ts +36 -0
  271. package/lib/typescript/src/polyfills/textCoding.d.ts.map +1 -0
  272. package/lib/typescript/src/registerGlobals.d.ts +42 -0
  273. package/lib/typescript/src/registerGlobals.d.ts.map +1 -0
  274. package/lib/typescript/src/unsupported.d.ts +42 -0
  275. package/lib/typescript/src/unsupported.d.ts.map +1 -0
  276. package/lib/typescript/src/version.d.ts +3 -0
  277. package/lib/typescript/src/version.d.ts.map +1 -0
  278. package/metro/index.js +39 -0
  279. package/metro/noise-stub.js +10 -0
  280. package/native/gxfx/include/gx_fx.h +82 -0
  281. package/native/gxfx/src/gx_fx.cpp +527 -0
  282. package/native/gxfx/third_party/README.md +4 -0
  283. package/native/gxfx/third_party/signalsmith-linear/LICENSE.txt +21 -0
  284. package/native/gxfx/third_party/signalsmith-linear/approx.h +191 -0
  285. package/native/gxfx/third_party/signalsmith-linear/fft.h +1386 -0
  286. package/native/gxfx/third_party/signalsmith-linear/linear.h +1129 -0
  287. package/native/gxfx/third_party/signalsmith-linear/platform/approx-cmsisdsp.h +40 -0
  288. package/native/gxfx/third_party/signalsmith-linear/platform/basic-fill-warnings.h +61 -0
  289. package/native/gxfx/third_party/signalsmith-linear/platform/fft-accelerate.h +340 -0
  290. package/native/gxfx/third_party/signalsmith-linear/platform/fft-cmsisdsp.h +307 -0
  291. package/native/gxfx/third_party/signalsmith-linear/platform/fft-ipp.h +532 -0
  292. package/native/gxfx/third_party/signalsmith-linear/platform/fft-linear.h +213 -0
  293. package/native/gxfx/third_party/signalsmith-linear/platform/fft-pffft-double.h +221 -0
  294. package/native/gxfx/third_party/signalsmith-linear/platform/fft-pffft.h +221 -0
  295. package/native/gxfx/third_party/signalsmith-linear/platform/linear-accelerate.h +593 -0
  296. package/native/gxfx/third_party/signalsmith-linear/platform/linear-cmsisdsp.h +713 -0
  297. package/native/gxfx/third_party/signalsmith-linear/platform/linear-xsimd-dispatch.cpp +6 -0
  298. package/native/gxfx/third_party/signalsmith-linear/platform/linear-xsimd.h +818 -0
  299. package/native/gxfx/third_party/signalsmith-linear/stft.h +700 -0
  300. package/native/gxfx/third_party/signalsmith-stretch-LICENSE.txt +21 -0
  301. package/native/gxfx/third_party/signalsmith-stretch.h +1060 -0
  302. package/native/gxns/CMakeLists.txt +67 -0
  303. package/native/gxns/include/gx_ns.h +285 -0
  304. package/native/gxns/src/gx_ns.c +1518 -0
  305. package/native/gxns/src/gx_ns_timer.c +84 -0
  306. package/native/gxns/src/gx_ns_timer.h +29 -0
  307. package/native/gxns/third_party/VENDOR.md +43 -0
  308. package/native/gxns/third_party/rnnoise/AUTHORS +1 -0
  309. package/native/gxns/third_party/rnnoise/COPYING +31 -0
  310. package/native/gxns/third_party/rnnoise/include/rnnoise.h +117 -0
  311. package/native/gxns/third_party/rnnoise/src/_kiss_fft_guts.h +182 -0
  312. package/native/gxns/third_party/rnnoise/src/arch.h +261 -0
  313. package/native/gxns/third_party/rnnoise/src/celt_lpc.c +172 -0
  314. package/native/gxns/third_party/rnnoise/src/celt_lpc.h +45 -0
  315. package/native/gxns/third_party/rnnoise/src/common.h +48 -0
  316. package/native/gxns/third_party/rnnoise/src/denoise.c +664 -0
  317. package/native/gxns/third_party/rnnoise/src/kiss_fft.c +601 -0
  318. package/native/gxns/third_party/rnnoise/src/kiss_fft.h +203 -0
  319. package/native/gxns/third_party/rnnoise/src/opus_types.h +159 -0
  320. package/native/gxns/third_party/rnnoise/src/pitch.c +523 -0
  321. package/native/gxns/third_party/rnnoise/src/pitch.h +149 -0
  322. package/native/gxns/third_party/rnnoise/src/rnn.c +178 -0
  323. package/native/gxns/third_party/rnnoise/src/rnn.h +65 -0
  324. package/native/gxns/third_party/rnnoise/src/rnn_data.c +11051 -0
  325. package/native/gxns/third_party/rnnoise/src/rnn_data.h +34 -0
  326. package/native/gxns/third_party/rnnoise/src/tansig_table.h +45 -0
  327. package/native/gxns/third_party/speexdsp/AUTHORS +18 -0
  328. package/native/gxns/third_party/speexdsp/COPYING +35 -0
  329. package/native/gxns/third_party/speexdsp/arch.h +232 -0
  330. package/native/gxns/third_party/speexdsp/resample.c +1239 -0
  331. package/native/gxns/third_party/speexdsp/resample_neon.h +339 -0
  332. package/native/gxns/third_party/speexdsp/resample_sse.h +128 -0
  333. package/native/gxns/third_party/speexdsp/speex_resampler.h +343 -0
  334. package/package.json +186 -4
  335. package/src/android/bindings.ts +61 -0
  336. package/src/android/index.ts +10 -0
  337. package/src/android/micMute.ts +422 -0
  338. package/src/android/nativeAudio.ts +94 -0
  339. package/src/android/noiseSuppression.ts +209 -0
  340. package/src/android/roomMusic.ts +193 -0
  341. package/src/android/singerMode.ts +53 -0
  342. package/src/android/voiceEffects.ts +126 -0
  343. package/src/audio/AudioManager.ts +111 -0
  344. package/src/audio/AudioSession.ts +190 -0
  345. package/src/audio/remoteVolume.ts +58 -0
  346. package/src/components/VideoView.tsx +152 -0
  347. package/src/features/audioScenario.ts +58 -0
  348. package/src/features/beauty.ts +1057 -0
  349. package/src/features/micRelease.ts +108 -0
  350. package/src/features/noiseSuppression.ts +251 -0
  351. package/src/features/roomMusic.ts +106 -0
  352. package/src/features/roomMusicAndroid.ts +310 -0
  353. package/src/features/roomMusicIos.ts +300 -0
  354. package/src/features/roomMusicTypes.ts +97 -0
  355. package/src/features/screenShare.ts +19 -0
  356. package/src/features/singerMode.ts +70 -0
  357. package/src/features/voiceEffects.ts +245 -0
  358. package/src/hooks/context.tsx +38 -0
  359. package/src/hooks/hooks.ts +247 -0
  360. package/src/hooks/types.ts +10 -0
  361. package/src/hooks/useRoomEvents.ts +35 -0
  362. package/src/index.tsx +134 -0
  363. package/src/ios/autoAttach.ts +11 -0
  364. package/src/ios/iosAudio.ts +202 -0
  365. package/src/join/appStateLifecycle.ts +55 -0
  366. package/src/micPolicy.ts +312 -0
  367. package/src/native/NativeGravixAudio.ts +30 -0
  368. package/src/native/NativeGravixRtc.ts +38 -0
  369. package/src/native/module.ts +22 -0
  370. package/src/polyfills/DOMException.ts +20 -0
  371. package/src/polyfills/early.ts +16 -0
  372. package/src/polyfills/event.ts +88 -0
  373. package/src/polyfills/sha256.ts +112 -0
  374. package/src/polyfills/subtleHmac.ts +124 -0
  375. package/src/polyfills/textCoding.ts +197 -0
  376. package/src/registerGlobals.ts +201 -0
  377. package/src/unsupported.ts +139 -0
  378. package/src/version.ts +4 -0
@@ -0,0 +1,718 @@
1
+ // Copyright (c) 2024-2026 Gravity Compile. MIT License; see LICENSE.
2
+
3
+ #if os(iOS)
4
+ import AVFoundation
5
+ import Foundation
6
+ @_implementationOnly import gxns
7
+ import UIKit
8
+
9
+ /// On-device noise suppression on iOS (plan §1b, Phase 2b item 13).
10
+ ///
11
+ /// React Native port (react-native-webrtc 155): called by the Gravix audio
12
+ /// device (`GxAudioDevice`, installed as `WebRTCModuleOptions.audioDevice` by
13
+ /// `GravixRtcSetup.setup()`) on each capture block, AFTER VPIO (AEC/NS/AGC)
14
+ /// and BEFORE WebRTC's software APM (stock WebRTC has no post-processing slot):
15
+ ///
16
+ /// mic -> VPIO -> GxNoiseProcessor (gx_ns) -> voice FX -> music -> APM -> encoder
17
+ ///
18
+ /// Until Dart configures it (`nsConfigure`), `audioProcessingProcess` returns
19
+ /// after one atomic load: the processor is pure pass-through and allocates
20
+ /// nothing. The gx_ns instance is created on the first configure (off the
21
+ /// audio thread) and lives for the process.
22
+ ///
23
+ /// Order (owner decision, default `ownAfterNs`): our NS, then our VAD-gated
24
+ /// AGC + limiter (inside gx_ns). Dart turns WebRTC's software NS + AGC off on
25
+ /// the track; VPIO's AGC is turned off on the input node in configureInput.
26
+ /// VPIO's own NS CANNOT be turned off alone on iOS (only the whole voice
27
+ /// processing unit, which also kills AEC), so on iOS ours always runs after
28
+ /// Apple's voice-processing NS. `webrtcBeforeNs` keeps WebRTC/VPIO AGC and
29
+ /// disables ours.
30
+ ///
31
+ /// Threads: process() = WebRTC capture thread (never allocates/locks/logs);
32
+ /// control + watchdog = `queue`; JS events = GxEvents (any thread).
33
+ final class GxNoiseProcessor: NSObject {
34
+ static let shared = GxNoiseProcessor()
35
+
36
+ // MARK: audio-thread state (written before `enabled` is published)
37
+
38
+ private var ns: OpaquePointer? // struct gx_ns *
39
+ private let enabled: OpaquePointer = gxns_flag_new(0)!
40
+ /// Last channel count seen (multi-channel capture: ch0 is processed and copied).
41
+ private let channelsSeen: OpaquePointer = gxns_flag_new(0)!
42
+ private let initRate: OpaquePointer = gxns_flag_new(0)!
43
+ /// Snapshot for configureInput (engine thread must not wait on `queue`).
44
+ private let wantVpioAgcOff: OpaquePointer = gxns_flag_new(0)!
45
+
46
+ // MARK: control state (`queue` only)
47
+
48
+ private let queue = DispatchQueue(label: "gravix.ns.control", qos: .utility)
49
+ private var installed = false
50
+ /// `installed` for any thread (never waits on `queue`, which can be busy
51
+ /// with a Core ML load + benchmark).
52
+ private let installedFlag: OpaquePointer = gxns_flag_new(0)!
53
+ private var config = Config()
54
+ private var studioBox: GxNsStudioBox?
55
+ private var retiredBoxes: [(box: GxNsStudioBox, block: UInt32)] = []
56
+ private var studioReason = ""
57
+ private var demotion: String? // watchdog / thermal / battery_saver while studio was wanted
58
+ private var watchdogRetryUsed = false
59
+ private var watchdogDemotedAt: Date?
60
+ private var timer: DispatchSourceTimer?
61
+ private var lastStatus = gx_ns_status()
62
+ private var lastOver: UInt32 = 0
63
+ private var lastRate: Int32 = 0
64
+ private var lastSummary = Date()
65
+ private var startedAt = Date()
66
+ private var route = "unknown"
67
+ private var musicActive = false
68
+ /// Singer mode: our chain bypassed (limiter-only path), like Android.
69
+ private var singerMode = false
70
+ private var bypassWanted: Bool { singerMode || (config.musicBypass && musicActive) }
71
+ /// Auto music (2026-11-20): gx_ns detected music on the mic (relaxed chain).
72
+ private var musicDetected = false
73
+ private var musicDetectedSince = Date()
74
+ private var observers: [NSObjectProtocol] = []
75
+ private let packQueue = DispatchQueue(label: "gravix.ns.pack", qos: .utility)
76
+ private var packInFlight = false
77
+ private var packFailed: String?
78
+
79
+ struct Config {
80
+ var engine = "off" // off | rnnoise | dfn3 (resolved by Dart)
81
+ var agcEnabled = true
82
+ var agcOrder = "ownAfterNs"
83
+ var musicBypass = true
84
+ var autoMusic = true
85
+ var vpioAgcOff = true
86
+ var watchdogUs: Int32 = 8000
87
+ var watchdogConsecutive: UInt32 = 3
88
+ var thermalFallback = true
89
+ var batterySaverFallback = true
90
+ var benchmarkP95Us = 3000
91
+ var benchmarkCachedP95Us: Int?
92
+ var studioModel = "std" // std (bundled) | ll (downloaded pack)
93
+ var studioLlUrl: String?
94
+ var studioDownload = "unmeteredIdle" // never | unmeteredIdle | any
95
+ var studioComputeUnits = "cpuOnly"
96
+ var studioAttenLimitDb: Float = 40 // GX_NS_DEFAULT_ATTEN_LIM_DB; 0 = none
97
+ var studioP95BudgetUs: Int32 = 3000 // rolling p95 over the window -> RNNoise (studio_slow)
98
+ var studioP95WindowMs: Int32 = 2000
99
+ }
100
+
101
+ private override init() { super.init() }
102
+
103
+ // MARK: install (GravixRtcSetup, before the peer connection factory exists)
104
+
105
+ /// Records that the Gravix audio device feeds this processor.
106
+ func markInstalled(slot: String) {
107
+ gxns_flag_set(installedFlag, 1)
108
+ queue.sync {
109
+ guard !installed else { return }
110
+ installed = true
111
+ log("install", detail: "slot=\(slot) passthrough=1")
112
+ }
113
+ }
114
+
115
+ var isInstalled: Bool { gxns_flag_get(installedFlag) != 0 }
116
+
117
+ // MARK: capture stream (GxAudioDevice)
118
+
119
+ /// A new capture stream (unit start, HFP 16 k, route change): fade back
120
+ /// in. Audio device thread, not the IO thread.
121
+ func audioProcessingInitialize(sampleRate sampleRateHz: Int, channels: Int) {
122
+ gxns_flag_set(initRate, Int32(sampleRateHz))
123
+ gxns_flag_set(channelsSeen, Int32(channels))
124
+ guard gxns_flag_get(enabled) != 0, let ns else { return }
125
+ gx_ns_request_reset(ns)
126
+ queue.async { self.log("init", rate: Int32(sampleRateHz), detail: "ch=\(channels) src=device") }
127
+ }
128
+
129
+ /// One capture block, mono int16-scale floats, in place. IO thread: never
130
+ /// allocates, locks or logs.
131
+ func processCapture(_ samples: UnsafeMutablePointer<Float>, frames: Int, rate: Int32) {
132
+ processNoise(samples, frames: frames, rate: rate)
133
+ GxVoiceFx.shared.process(samples, frames: frames, rate: rate)
134
+ // 0.12.0: room music joins here, after the effect (GxMusicPost)
135
+ if #available(iOS 13.0, *) { GxMusicPost.shared.process(samples, frames: frames, rate: rate) }
136
+ }
137
+
138
+ /// Whether VPIO's AGC should be off (our AGC runs). Any thread (atomic).
139
+ var wantsVpioAgcOff: Bool { gxns_flag_get(wantVpioAgcOff) != 0 }
140
+
141
+ /// The noise suppressor's algorithmic delay at [rate] (0 when off). Any
142
+ /// thread but the audio thread.
143
+ func latencySamples(atRate rate: Int) -> Int {
144
+ queue.sync {
145
+ guard gxns_flag_get(enabled) != 0, let ns else { return 0 }
146
+ return Int(gx_ns_latency_samples(ns, Int32(rate)))
147
+ }
148
+ }
149
+
150
+ private func processNoise(_ samples: UnsafeMutablePointer<Float>, frames: Int, rate: Int32) {
151
+ guard gxns_flag_get(enabled) != 0, let ns, frames > 0 else { return }
152
+ // Any block size (gx_ns re-blocks internally) at the device rate.
153
+ _ = gx_ns_process(ns, samples, Int32(frames), rate)
154
+ }
155
+
156
+ // MARK: JS methods (GravixRtcIosAudio)
157
+
158
+ func handle(_ call: GxMethodCall, result: @escaping GxResult) -> Bool {
159
+ let args = call.arguments as? [String: Any?] ?? [:]
160
+ switch call.method {
161
+ case "nsConfigure":
162
+ queue.async {
163
+ self.configure(args)
164
+ let state = self.stateMap()
165
+ DispatchQueue.main.async { result(state) }
166
+ }
167
+ case "nsSetMusicBypass":
168
+ let on = (args["on"] as? Bool) ?? false
169
+ queue.async { self.setMusicActive(on, source: "js"); DispatchQueue.main.async { result(nil) } }
170
+ case "nsSetSingerMode":
171
+ // iOS: our chain bypass only; the capture source stays (no MIC switch here)
172
+ let on = (args["on"] as? Bool) ?? false
173
+ queue.async {
174
+ if self.singerMode != on {
175
+ self.singerMode = on
176
+ if let ns = self.ns { gx_ns_set_bypass(ns, self.bypassWanted ? 1 : 0) }
177
+ self.log("singerMode", detail: "on=\(on ? 1 : 0) bypass=\(self.bypassWanted ? 1 : 0)")
178
+ self.emit(["type": "singerMode", "singerMode": on])
179
+ }
180
+ DispatchQueue.main.async { result(["ok": true, "sourceRequested": NSNull()]) }
181
+ }
182
+ case "nsGetState":
183
+ queue.async { let s = self.stateMap(); DispatchQueue.main.async { result(s) } }
184
+ case "nsDeviceFacts":
185
+ // Facts for the shared Dart resolver (same keys as Android).
186
+ result(Self.deviceFacts())
187
+ case "nsBenchmark":
188
+ // The studio benchmark on its own engine instance, off the audio
189
+ // path; Dart caches it and sends benchmarkCachedP95Us back.
190
+ // config belongs to `queue`: read it there, then load off it
191
+ queue.async {
192
+ let units = self.config.studioComputeUnits
193
+ DispatchQueue.global(qos: .utility).async {
194
+ let loaded = GxNsStudioEngines.loadBundled(computeUnits: units)
195
+ guard let engine = loaded.engine else {
196
+ DispatchQueue.main.async { result(["ok": false, "reason": loaded.reason]) }
197
+ return
198
+ }
199
+ let r = GxNsBenchmark.run(engine)
200
+ self.log("bench", detail: "p95=\(r.p95Us)us max=\(r.maxUs)us ok=\(r.outputOk ? 1 : 0) frames=\(r.frames) quietIn=\(String(format: "%.1f", r.quietInDb))dB quietOut=\(String(format: "%.1f", r.quietOutDb))dB model=\(engine.name) src=dart")
201
+ let m: [String: Any] = [
202
+ "ok": true, "model": "std", "sha256": engine.modelSha256, "p95Us": r.p95Us,
203
+ "maxUs": r.maxUs, "outputOk": r.outputOk, "runtime": "coreml",
204
+ ]
205
+ DispatchQueue.main.async { result(m) }
206
+ }
207
+ }
208
+ default:
209
+ return false
210
+ }
211
+ return true
212
+ }
213
+
214
+ // MARK: control (queue)
215
+
216
+ private func configure(_ a: [String: Any?]) {
217
+ var c = config
218
+ if let v = a["engine"] as? String { c.engine = v }
219
+ if let v = a["agcOrder"] as? String { c.agcOrder = v }
220
+ // off / kill switch: WebRTC's AGC is back on there, ours must not stack on it (review #1)
221
+ let agcWanted = (a["agc"] as? Bool) ?? (c.agcOrder != "webrtcBeforeNs")
222
+ c.agcEnabled = c.engine != "off" && agcWanted
223
+ if let v = a["musicBypass"] as? Bool { c.musicBypass = v }
224
+ if let v = a["autoMusic"] as? Bool { c.autoMusic = v }
225
+ if let v = a["vpioAgcOff"] as? Bool { c.vpioAgcOff = v }
226
+ if let v = a["watchdogUs"] as? Int { c.watchdogUs = Int32(v) }
227
+ if let v = a["watchdogConsecutive"] as? Int { c.watchdogConsecutive = UInt32(max(1, v)) }
228
+ if let v = a["thermalFallback"] as? Bool { c.thermalFallback = v }
229
+ if let v = a["batterySaverFallback"] as? Bool { c.batterySaverFallback = v }
230
+ if let v = a["benchmarkP95Us"] as? Int { c.benchmarkP95Us = v }
231
+ c.benchmarkCachedP95Us = a["benchmarkCachedP95Us"] as? Int
232
+ if let v = a["studioModel"] as? String { c.studioModel = v }
233
+ if a.keys.contains("studioLlUrl") { c.studioLlUrl = a["studioLlUrl"] as? String }
234
+ if let v = a["studioDownload"] as? String { c.studioDownload = v }
235
+ if let v = a["studioComputeUnits"] as? String { c.studioComputeUnits = v }
236
+ if let v = a["studioAttenLimitDb"] as? NSNumber { c.studioAttenLimitDb = v.floatValue }
237
+ if let v = a["studioP95BudgetUs"] as? Int { c.studioP95BudgetUs = Int32(max(0, v)) }
238
+ if let v = a["studioP95WindowMs"] as? Int { c.studioP95WindowMs = Int32(max(200, v)) }
239
+ let studioChanged = c.studioModel != config.studioModel || c.studioComputeUnits != config.studioComputeUnits
240
+ let wasEngine = config.engine
241
+ config = c
242
+ gxns_flag_set(wantVpioAgcOff, (c.vpioAgcOff && c.agcEnabled && c.engine != "off") ? 1 : 0)
243
+
244
+ if ns == nil {
245
+ if c.engine == "off" {
246
+ // Never enabled + off = stay pure pass-through (legacy sound).
247
+ log("static", detail: "requested=off passthrough=1")
248
+ return
249
+ }
250
+ var cfg = gx_ns_config()
251
+ gx_ns_default_config(&cfg)
252
+ cfg.initial_engine = GX_NS_ENGINE_RNNOISE
253
+ cfg.agc_enabled = c.agcEnabled ? 1 : 0
254
+ cfg.watchdog_us = c.watchdogUs
255
+ cfg.max_external_latency = 1440 + 480 // DFN3 std 30 ms (+ margin)
256
+ cfg.ext_p95_window = c.studioP95WindowMs / 10 // 10 ms blocks
257
+ guard let st = gx_ns_create(&cfg) else {
258
+ log("install", detail: "error=gx_ns_create_failed")
259
+ return
260
+ }
261
+ ns = st
262
+ startObservers()
263
+ startTimer()
264
+ startedAt = Date()
265
+ route = Self.currentRoute()
266
+ gxns_flag_set(enabled, 1) // publishes `ns` to the audio thread
267
+ }
268
+ guard let ns else { return }
269
+ gx_ns_set_agc(ns, c.agcEnabled ? 1 : 0)
270
+ gx_ns_set_agc_order(ns, GX_NS_AGC_AFTER_NS)
271
+ gx_ns_set_atten_limit(ns, c.studioAttenLimitDb)
272
+ gx_ns_set_ext_p95_budget(ns, c.studioP95BudgetUs)
273
+ gx_ns_set_auto_music(ns, c.autoMusic ? 1 : 0)
274
+ if musicActive || singerMode { gx_ns_set_bypass(ns, bypassWanted ? 1 : 0) }
275
+ log("policy", detail: "engine=\(c.engine) agc=\(c.agcEnabled ? 1 : 0) order=\(c.agcOrder) music=\(c.musicBypass ? 1 : 0) autoMusic=\(c.autoMusic ? 1 : 0) wd=\(c.watchdogUs)us/\(c.watchdogConsecutive)")
276
+
277
+ switch c.engine {
278
+ case "off":
279
+ detachStudio(reason: "mode_off")
280
+ gx_ns_set_engine(ns, GX_NS_ENGINE_OFF)
281
+ case "dfn3":
282
+ gx_ns_set_engine(ns, GX_NS_ENGINE_RNNOISE) // meanwhile
283
+ if wasEngine != "dfn3" || studioBox == nil { demotion = nil; watchdogRetryUsed = false }
284
+ if studioChanged { detachStudio(reason: "studio_model_changed") }
285
+ // after the nsConfigure reply: the Core ML load + benchmark never delay it
286
+ queue.async { self.startStudio() }
287
+ default:
288
+ detachStudio(reason: "mode_standard")
289
+ gx_ns_set_engine(ns, GX_NS_ENGINE_RNNOISE)
290
+ }
291
+ }
292
+
293
+ /// Studio: load the bundled engine, benchmark it (also for an explicit
294
+ /// studio request), attach only if p95 < limit and output sane.
295
+ private func startStudio() {
296
+ guard let ns, config.engine == "dfn3" else { return } // changed while queued
297
+ if studioBox != nil {
298
+ if demotion == nil { gx_ns_set_engine(ns, GX_NS_ENGINE_DFN3) }
299
+ return
300
+ }
301
+ var loaded = GxNsStudioEngines.loadBundled(computeUnits: config.studioComputeUnits)
302
+ if config.studioModel == "ll" {
303
+ if let url = GxNsStudioPack.cachedModel(GxNsStudioPack.ll) {
304
+ let ll = GxNsStudioEngines.loadCompiled(url, spec: GxNsStudioPack.ll, computeUnits: config.studioComputeUnits)
305
+ if ll.engine != nil { loaded = ll } else { log("pack", detail: "id=\(GxNsStudioPack.ll.id) load=failed reason=\(ll.reason) using=std") }
306
+ } else {
307
+ fetchLlPack() // std meanwhile
308
+ }
309
+ }
310
+ guard let engine = loaded.engine else {
311
+ studioReason = "studio_unavailable"
312
+ log("static", detail: "studio=unavailable reason=\(loaded.reason) fallback=rnnoise")
313
+ emit(["type": "engineChanged", "from": "dfn3", "to": "rnnoise", "reason": "studio_unavailable", "detail": loaded.reason])
314
+ return
315
+ }
316
+ let limit = config.benchmarkP95Us
317
+ let p95: Int
318
+ var outputOk = true
319
+ if let cached = config.benchmarkCachedP95Us {
320
+ p95 = cached
321
+ log("bench", detail: "p95=\(cached)us cached=1 limit=\(limit)us model=\(engine.name)")
322
+ } else {
323
+ let r = GxNsBenchmark.run(engine)
324
+ p95 = r.p95Us
325
+ outputOk = r.outputOk
326
+ log("bench", detail: "p95=\(r.p95Us)us max=\(r.maxUs)us ok=\(r.outputOk ? 1 : 0) frames=\(r.frames) quietIn=\(String(format: "%.1f", r.quietInDb))dB quietOut=\(String(format: "%.1f", r.quietOutDb))dB limit=\(limit)us model=\(engine.name)")
327
+ emit(["type": "benchmark", "p95Us": r.p95Us, "maxUs": r.maxUs, "outputOk": r.outputOk, "model": engine.name, "modelSha256": engine.modelSha256])
328
+ }
329
+ guard config.engine == "dfn3" else { return } // changed meanwhile
330
+ guard outputOk else { return reject("benchmark_bad_output") }
331
+ guard p95 < limit else { return reject("benchmark_slow") }
332
+ let box = GxNsStudioBox(engine)
333
+ var ext = box.cEngine()
334
+ guard gx_ns_set_external_engine(ns, &ext) == 0 else { return reject("latency_too_large") }
335
+ studioBox = box
336
+ studioReason = ""
337
+ if demotion == nil { gx_ns_set_engine(ns, GX_NS_ENGINE_DFN3) }
338
+ }
339
+
340
+ /// Download + verify + compile the LL pack in the background; switch to it
341
+ /// when ready if studio/ll is still wanted.
342
+ private func fetchLlPack() {
343
+ guard !packInFlight, packFailed == nil else { return }
344
+ guard #available(iOS 16.0, *) else { return }
345
+ let urlString = config.studioLlUrl
346
+ let policy = GxNsStudioPack.Download(rawValue: config.studioDownload) ?? .unmeteredIdle
347
+ packInFlight = true
348
+ log("pack", detail: "id=\(GxNsStudioPack.ll.id) fetch=start policy=\(policy.rawValue) url=\(urlString == nil ? "none" : "set")")
349
+ packQueue.async {
350
+ var failure: String?
351
+ do {
352
+ _ = try GxNsStudioPack.ensure(GxNsStudioPack.ll, remote: urlString.flatMap(URL.init(string:)), policy: policy) { line in
353
+ self.queue.async { self.log("pack", detail: line.replacingOccurrences(of: "pack ", with: "")) }
354
+ }
355
+ } catch {
356
+ failure = (error as NSError).localizedDescription
357
+ }
358
+ self.queue.async {
359
+ self.packInFlight = false
360
+ if let failure {
361
+ self.packFailed = failure
362
+ self.log("pack", detail: "id=\(GxNsStudioPack.ll.id) fetch=failed reason=\(failure) using=std")
363
+ self.emit(["type": "download", "id": GxNsStudioPack.ll.id, "ok": false, "reason": failure])
364
+ return
365
+ }
366
+ self.emit(["type": "download", "id": GxNsStudioPack.ll.id, "ok": true])
367
+ guard self.config.engine == "dfn3", self.config.studioModel == "ll" else { return }
368
+ self.detachStudio(reason: "ll_ready")
369
+ self.startStudio()
370
+ }
371
+ }
372
+ }
373
+
374
+ private func reject(_ reason: String) {
375
+ studioReason = reason
376
+ log("switch", detail: "from=dfn3 to=rnnoise reason=\(reason)")
377
+ emit(["type": "engineChanged", "from": "dfn3", "to": "rnnoise", "reason": reason])
378
+ }
379
+
380
+ private func detachStudio(reason: String) {
381
+ guard let ns, let box = studioBox else { return }
382
+ gx_ns_set_external_engine(ns, nil)
383
+ // Keep the box alive until the audio thread has passed a block boundary.
384
+ retiredBoxes.append((box, gx_ns_blocks_processed(ns)))
385
+ studioBox = nil
386
+ log("switch", detail: "studio=detached reason=\(reason)")
387
+ }
388
+
389
+ private func setMusicActive(_ on: Bool, source: String) {
390
+ GxVoiceFx.shared.setMusicActive(on)
391
+ guard musicActive != on else { return }
392
+ musicActive = on
393
+ guard let ns, config.musicBypass || singerMode else { return }
394
+ gx_ns_set_bypass(ns, bypassWanted ? 1 : 0)
395
+ log("musicBypass", detail: "on=\(on ? 1 : 0) src=\(source)")
396
+ emit(["type": "musicBypass", "on": on])
397
+ }
398
+
399
+ /// Demote studio -> RNNoise (watchdog / thermal / battery saver).
400
+ private func demote(_ reason: String) {
401
+ guard let ns, config.engine == "dfn3", studioBox != nil, demotion == nil else { return }
402
+ demotion = reason
403
+ gx_ns_set_engine(ns, GX_NS_ENGINE_RNNOISE)
404
+ log("switch", detail: "from=dfn3 to=rnnoise reason=\(reason)")
405
+ emit(["type": "engineChanged", "from": "dfn3", "to": "rnnoise", "reason": reason])
406
+ }
407
+
408
+ private func restoreIfAllowed() {
409
+ guard let ns, config.engine == "dfn3", studioBox != nil, let d = demotion else { return }
410
+ if d == "studio_slow" || d == "studio_suppress" {
411
+ return // gx_ns keeps it until the engine is re-attached (next configure)
412
+ }
413
+ if d == "watchdog" {
414
+ // One retry per call, after a cooldown.
415
+ guard !watchdogRetryUsed, let at = watchdogDemotedAt, Date().timeIntervalSince(at) > 60 else { return }
416
+ watchdogRetryUsed = true
417
+ } else if fallbackCondition() != nil {
418
+ return
419
+ }
420
+ demotion = nil
421
+ gx_ns_set_engine(ns, GX_NS_ENGINE_DFN3)
422
+ log("switch", detail: "from=rnnoise to=dfn3 reason=\(d)_cleared")
423
+ emit(["type": "engineChanged", "from": "rnnoise", "to": "dfn3", "reason": "\(d)_cleared"])
424
+ }
425
+
426
+ private func fallbackCondition() -> String? {
427
+ let info = ProcessInfo.processInfo
428
+ if config.thermalFallback, info.thermalState.rawValue >= ProcessInfo.ThermalState.serious.rawValue { return "thermal" }
429
+ if config.batterySaverFallback, info.isLowPowerModeEnabled { return "battery_saver" }
430
+ return nil
431
+ }
432
+
433
+ // MARK: watchdog + logs (queue, 1 s)
434
+
435
+ private func startTimer() {
436
+ let t = DispatchSource.makeTimerSource(queue: queue)
437
+ t.schedule(deadline: .now() + 1, repeating: 1, leeway: .milliseconds(200))
438
+ t.setEventHandler { [weak self] in self?.tick() }
439
+ t.resume()
440
+ timer = t
441
+ }
442
+
443
+ private func tick() {
444
+ guard let ns else { return }
445
+ var s = gx_ns_status()
446
+ gx_ns_get_status(ns, &s)
447
+ var st = gx_ns_stats()
448
+ gx_ns_get_stats(ns, &st)
449
+
450
+ if s.rate != lastRate, s.rate > 0 {
451
+ log("init", rate: s.rate, detail: "src=frames apmInit=\(gxns_flag_get(initRate)) ch=\(gxns_flag_get(channelsSeen)) latency=\(s.latency_samples)")
452
+ lastRate = s.rate
453
+ }
454
+ if s.active.rawValue != lastStatus.active.rawValue, s.crossfading == 0 {
455
+ let from = String(cString: gx_ns_engine_name(lastStatus.active))
456
+ let to = String(cString: gx_ns_engine_name(s.active))
457
+ let reason = String(cString: gx_ns_reason_name(s.reason))
458
+ log("switch", rate: s.rate, detail: "from=\(from) to=\(to) reason=\(demotion ?? reason) done=1")
459
+ emit(["type": "engineChanged", "from": from, "to": to, "reason": demotion ?? reason])
460
+ lastStatus = s
461
+ } else if s.crossfading == 0 {
462
+ lastStatus = s
463
+ }
464
+
465
+ // Watchdog: N consecutive calls over budget, or N over-budget calls
466
+ // within the last second.
467
+ let overDelta = st.over_budget &- lastOver
468
+ lastOver = st.over_budget
469
+ if st.consecutive_over >= config.watchdogConsecutive || overDelta >= config.watchdogConsecutive {
470
+ if s.active.rawValue == GX_NS_ENGINE_DFN3.rawValue || s.requested.rawValue == GX_NS_ENGINE_DFN3.rawValue {
471
+ watchdogDemotedAt = Date()
472
+ demote("watchdog")
473
+ } else if overDelta > 0 {
474
+ log("watchdog", rate: s.rate, detail: "over=\(overDelta) consecutive=\(st.consecutive_over) max=\(st.max_us)us engine=rnnoise action=none")
475
+ }
476
+ }
477
+ // gx_ns rolling p95 of the studio engine over the window above budget
478
+ // (thermal drift mid-call): it already plays RNNoise; record why.
479
+ if st.ext_slow != 0, demotion == nil, config.engine == "dfn3" {
480
+ log("watchdog", rate: s.rate, detail: "studio_slow p95=\(st.ext_p95_us)us>budget=\(config.studioP95BudgetUs)us window=\(config.studioP95WindowMs)ms model=\(config.studioModel) -> rnnoise")
481
+ demote("studio_slow")
482
+ }
483
+ // gx_ns live guard: the studio output speech collapsed vs its input for
484
+ // 2 s of speech (an engine erasing quiet speech); it already plays RNNoise.
485
+ if st.ext_suppress != 0, demotion == nil, config.engine == "dfn3" {
486
+ log("watchdog", rate: s.rate, detail: "studio_suppress model=\(config.studioModel) -> rnnoise")
487
+ demote("studio_suppress")
488
+ }
489
+ restoreIfAllowed()
490
+
491
+ // Free retired studio engines once the audio thread moved on.
492
+ let blocks = gx_ns_blocks_processed(ns)
493
+ retiredBoxes.removeAll { $0.block != blocks }
494
+
495
+ let music = s.music_detected != 0
496
+ if music != musicDetected {
497
+ let ms = Int(Date().timeIntervalSince(musicDetectedSince) * 1000)
498
+ musicDetected = music
499
+ musicDetectedSince = Date()
500
+ log("musicDetected", rate: s.rate, detail: "on=\(music ? 1 : 0) ms=\(ms) agcApplied=\(String(format: "%.1f", s.agc_applied_db))dB preApplied=\(String(format: "%.1f", s.pregain_applied_db))dB")
501
+ emit(["type": "musicDetected", "on": music])
502
+ }
503
+ if Date().timeIntervalSince(lastSummary) >= 60 {
504
+ lastSummary = Date()
505
+ logSummary(s, st)
506
+ }
507
+ }
508
+
509
+ private func logSummary(_ s: gx_ns_status, _ st: gx_ns_stats) {
510
+ log("summary", rate: s.rate, detail: "p50=\(st.p50_us)us p95=\(st.p95_us)us p99=\(st.p99_us)us max=\(st.max_us)us over=\(st.over_budget) frames=\(st.frames) underflows=\(st.underflows) extErr=\(st.ext_errors) switches=\(st.engine_switches) agc=\(String(format: "%.1f", s.agc_gain_db))dB pre=\(String(format: "%.1f", s.pregain_db))dB agcApplied=\(String(format: "%.1f", s.agc_applied_db))dB preApplied=\(String(format: "%.1f", s.pregain_applied_db))dB pauseAtt=\(String(format: "%.1f", s.pause_att_db))dB cpu=\(String(format: "%.1f", Self.processCpuPercent()))%")
511
+ }
512
+
513
+ // MARK: route / engine hooks
514
+
515
+ private func startObservers() {
516
+ let nc = NotificationCenter.default
517
+ observers.append(nc.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: nil) { [weak self] n in
518
+ let raw = n.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt ?? 0
519
+ self?.queue.async { self?.routeChanged(reason: raw) }
520
+ })
521
+ observers.append(nc.addObserver(forName: ProcessInfo.thermalStateDidChangeNotification, object: nil, queue: nil) { [weak self] _ in
522
+ self?.queue.async { self?.powerChanged() }
523
+ })
524
+ observers.append(nc.addObserver(forName: Notification.Name.NSProcessInfoPowerStateDidChange, object: nil, queue: nil) { [weak self] _ in
525
+ self?.queue.async { self?.powerChanged() }
526
+ })
527
+ }
528
+
529
+ private func routeChanged(reason raw: UInt) {
530
+ guard let ns else { return }
531
+ let reason = AVAudioSession.RouteChangeReason(rawValue: raw) ?? .unknown
532
+ // Category / override changes without a device change still re-route
533
+ // the input on some devices: reset on everything but a no-op config.
534
+ let newRoute = Self.currentRoute()
535
+ if reason == .categoryChange, newRoute == route { return }
536
+ route = newRoute
537
+ gx_ns_request_reset(ns)
538
+ log("routeReset", detail: "why=\(Self.reasonName(reason)) hwRate=\(Int(AVAudioSession.sharedInstance().sampleRate))")
539
+ emit(["type": "routeReset", "route": newRoute, "why": Self.reasonName(reason)])
540
+ }
541
+
542
+ private func powerChanged() {
543
+ if let why = fallbackCondition() {
544
+ demote(why)
545
+ } else {
546
+ restoreIfAllowed()
547
+ }
548
+ }
549
+
550
+ /// GxAudioDevice rebuilt the voice processing unit (start, route or rate
551
+ /// change); `vpioAgc` is the AGC state it applied (`wantsVpioAgcOff`).
552
+ func deviceConfiguredInput(rate: Int, vpioAgc: String) {
553
+ guard gxns_flag_get(enabled) != 0 else { return }
554
+ queue.async {
555
+ if let ns = self.ns { gx_ns_request_reset(ns) }
556
+ self.route = Self.currentRoute()
557
+ self.log("routeReset", rate: Int32(rate), detail: "why=configureInput ch=1 vpioAgc=\(vpioAgc)")
558
+ }
559
+ }
560
+
561
+ /// Music mixer session started / stopped (native, no Dart round trip).
562
+ func musicSession(active: Bool) {
563
+ queue.async { self.setMusicActive(active, source: "mixer") }
564
+ }
565
+
566
+ // MARK: state / logs / events
567
+
568
+ private func stateMap() -> [String: Any] {
569
+ var m: [String: Any] = [
570
+ "platform": "ios",
571
+ "installed": installed,
572
+ "enabled": gxns_flag_get(enabled) != 0,
573
+ "requested": config.engine,
574
+ "route": route,
575
+ "apmInitRate": Int(gxns_flag_get(initRate)),
576
+ "musicActive": musicActive,
577
+ "musicDetected": musicDetected,
578
+ "studioAvailable": GxNsStudioEngines.bundledModelURL() != nil,
579
+ "studioModel": config.studioModel,
580
+ "studioEngine": studioBox?.engine.name ?? "",
581
+ "llCached": GxNsStudioPack.cachedModel(GxNsStudioPack.ll) != nil,
582
+ "studioAttached": studioBox != nil,
583
+ ]
584
+ if !studioReason.isEmpty { m["studioReason"] = studioReason }
585
+ if let demotion { m["demotion"] = demotion }
586
+ if let packFailed { m["packError"] = packFailed }
587
+ guard let ns else { m["active"] = "off"; return m }
588
+ var s = gx_ns_status()
589
+ gx_ns_get_status(ns, &s)
590
+ var st = gx_ns_stats()
591
+ gx_ns_get_stats(ns, &st)
592
+ m["active"] = String(cString: gx_ns_engine_name(s.active))
593
+ m["reason"] = demotion ?? String(cString: gx_ns_reason_name(s.reason))
594
+ m["rate"] = Int(s.rate)
595
+ m["latencySamples"] = Int(s.latency_samples)
596
+ m["crossfading"] = s.crossfading != 0
597
+ m["vad"] = Double(s.vad)
598
+ m["agcGainDb"] = Double(s.agc_gain_db)
599
+ m["preGainDb"] = Double(s.pregain_db)
600
+ m["agcAppliedDb"] = Double(s.agc_applied_db)
601
+ m["preGainAppliedDb"] = Double(s.pregain_applied_db)
602
+ m["pauseAttDb"] = Double(s.pause_att_db)
603
+ m["stats"] = [
604
+ "frames": Int(st.frames), "p50Us": Int(st.p50_us), "p95Us": Int(st.p95_us),
605
+ "p99Us": Int(st.p99_us), "maxUs": Int(st.max_us), "overBudget": Int(st.over_budget),
606
+ "underflows": Int(st.underflows), "extErrors": Int(st.ext_errors),
607
+ "engineSwitches": Int(st.engine_switches),
608
+ ]
609
+ return m
610
+ }
611
+
612
+ private func activeEngineName() -> String {
613
+ guard let ns else { return "off" }
614
+ var s = gx_ns_status()
615
+ gx_ns_get_status(ns, &s)
616
+ return String(cString: gx_ns_engine_name(s.active))
617
+ }
618
+
619
+ /// `[GravixNS] <step> eng=<..> route=<..> rate=<..> +<ms>ms detail`
620
+ /// (same format as lib/src/noise/gravix_noise_report.dart).
621
+ private func log(_ step: String, rate: Int32? = nil, detail: String = "") {
622
+ let r = rate ?? lastRate
623
+ let ms = Int(Date().timeIntervalSince(startedAt) * 1000)
624
+ NSLog("[GravixNS] %@ eng=%@ route=%@ rate=%@ +%dms %@", step, activeEngineName(), route,
625
+ r > 0 ? "\(r)" : "?", ms, detail)
626
+ }
627
+
628
+ private func emit(_ event: [String: Any]) {
629
+ GxEvents.emit("onNsEvent", event)
630
+ }
631
+
632
+ static func deviceFacts() -> [String: Any] {
633
+ var sys = utsname()
634
+ uname(&sys)
635
+ let model = withUnsafePointer(to: &sys.machine) {
636
+ $0.withMemoryRebound(to: CChar.self, capacity: 1) { String(cString: $0) }
637
+ }
638
+ let studio = GxNsStudioEngines.bundledModelURL() != nil
639
+ var m: [String: Any] = [
640
+ "model": model,
641
+ "manufacturer": "Apple",
642
+ "osVersion": UIDevice.current.systemVersion,
643
+ "ramMb": Int(ProcessInfo.processInfo.physicalMemory / (1024 * 1024)),
644
+ "osBuild": "\(model)/\(UIDevice.current.systemVersion)",
645
+ "studioAvailable": studio,
646
+ "studioRuntime": "coreml",
647
+ ]
648
+ if studio {
649
+ m["studioModel"] = "std"
650
+ m["studioSha"] = GxNsStudioEngines.bundledModelSha256
651
+ }
652
+ return m
653
+ }
654
+
655
+ static func currentRoute() -> String {
656
+ let r = AVAudioSession.sharedInstance().currentRoute
657
+ let input = r.inputs.first?.portType
658
+ let output = r.outputs.first?.portType
659
+ switch input {
660
+ case .bluetoothHFP?: return "bt-sco"
661
+ case .bluetoothLE?: return "bt-le"
662
+ case .headsetMic?: return "wired"
663
+ case .usbAudio?: return "usb"
664
+ default: break
665
+ }
666
+ switch output {
667
+ case .bluetoothA2DP?: return "bt-a2dp"
668
+ case .bluetoothLE?: return "bt-le"
669
+ case .headphones?: return "wired"
670
+ case .builtInReceiver?: return "earpiece"
671
+ case .builtInSpeaker?: return "speaker"
672
+ case .usbAudio?: return "usb"
673
+ default: return "unknown"
674
+ }
675
+ }
676
+
677
+ static func reasonName(_ r: AVAudioSession.RouteChangeReason) -> String {
678
+ switch r {
679
+ case .newDeviceAvailable: return "newDevice"
680
+ case .oldDeviceUnavailable: return "oldDeviceGone"
681
+ case .categoryChange: return "category"
682
+ case .override: return "override"
683
+ case .wakeFromSleep: return "wake"
684
+ case .noSuitableRouteForCategory: return "noRoute"
685
+ case .routeConfigurationChange: return "config"
686
+ default: return "unknown"
687
+ }
688
+ }
689
+
690
+ /// Process CPU% since the last call (task_info), for the summary line.
691
+ private static var lastCpu: (time: Double, wall: Double)?
692
+ static func processCpuPercent() -> Double {
693
+ var info = task_thread_times_info_data_t()
694
+ var count = mach_msg_type_number_t(MemoryLayout<task_thread_times_info_data_t>.size / MemoryLayout<natural_t>.size)
695
+ let kr = withUnsafeMutablePointer(to: &info) {
696
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
697
+ task_info(mach_task_self_, task_flavor_t(TASK_THREAD_TIMES_INFO), $0, &count)
698
+ }
699
+ }
700
+ guard kr == KERN_SUCCESS else { return -1 }
701
+ var basic = mach_task_basic_info()
702
+ var bcount = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size / MemoryLayout<natural_t>.size)
703
+ let kb = withUnsafeMutablePointer(to: &basic) {
704
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(bcount)) {
705
+ task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &bcount)
706
+ }
707
+ }
708
+ func secs(_ t: time_value_t) -> Double { Double(t.seconds) + Double(t.microseconds) / 1e6 }
709
+ // live threads + terminated threads
710
+ var cpu = secs(info.user_time) + secs(info.system_time)
711
+ if kb == KERN_SUCCESS { cpu += secs(basic.user_time) + secs(basic.system_time) }
712
+ let wall = Date().timeIntervalSince1970
713
+ defer { lastCpu = (cpu, wall) }
714
+ guard let last = lastCpu, wall > last.wall else { return 0 }
715
+ return (cpu - last.time) / (wall - last.wall) * 100
716
+ }
717
+ }
718
+ #endif