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,795 @@
1
+ package com.gravitycompile.gravixrtc.processing
2
+
3
+ import android.app.ActivityManager
4
+ import android.content.BroadcastReceiver
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.content.IntentFilter
8
+ import android.os.Build
9
+ import android.os.Handler
10
+ import android.os.HandlerThread
11
+ import android.os.PowerManager
12
+ import android.os.Process
13
+ import android.os.SystemClock
14
+ import android.util.Log
15
+ import java.io.File
16
+ import java.nio.ByteBuffer
17
+
18
+ /**
19
+ * On-device noise suppression on WebRTC's capture path (plan 2026-10-15 §1b):
20
+ * flutter_webrtc's APM capturePostProcessing slot, i.e. after AEC (and after
21
+ * WebRTC's own NS/AGC, which the SDK turns off while ours runs). One processor
22
+ * per process: the audio device module has one capture stream.
23
+ *
24
+ * process() runs on WebRTC's audio thread, in place on the APM's direct float
25
+ * buffer (int16 scale), through libgxns (RNNoise + crossfades + our AGC +
26
+ * limiter). It never allocates or logs; a 1 s ticker thread does the logging
27
+ * (`[GravixNS]`, tag GravixNS) and the events to Dart.
28
+ *
29
+ * The native state is created once and kept for the process lifetime (never
30
+ * destroyed under a running audio thread). "Off" after install = engine OFF
31
+ * (dry, +10 ms delay), so a later "on" crossfades instead of jumping.
32
+ */
33
+ internal object GxNoiseProcessor : GravixCaptureProcessing.Processor {
34
+ private const val TAG = "GravixNS"
35
+ private const val SUMMARY_EVERY_S = 10
36
+
37
+ @Volatile private var handle = 0L
38
+ /** On [GravixCaptureProcessing] (the APM post-processing slot GravixRtc.setup installs). */
39
+ @Volatile private var installed = false
40
+ @Volatile private var appContext: Context? = null
41
+
42
+ /** Events to Dart (`onNoiseSuppression`); set by GravixClientPlugin. Called on the ticker/main thread. */
43
+ @Volatile var eventSink: ((Map<String, Any?>) -> Unit)? = null
44
+
45
+ /** WebRTC's audio processing state readback (is its NS/AGC really off?); set by GravixClientPlugin. */
46
+ @Volatile var stateReader: (() -> String?)? = null
47
+
48
+ // --- configuration from Dart (nsConfigure) ---
49
+ @Volatile private var mode = "off"
50
+ @Volatile private var requested = GxNsNative.ENGINE_OFF
51
+ @Volatile private var requestReason = "mode_off"
52
+ @Volatile private var agcOn = true
53
+ @Volatile private var agcOrder = GxNsNative.AGC_AFTER_NS
54
+ @Volatile private var agcOrderName = "ownAfterNs"
55
+ @Volatile private var musicBypassEnabled = true
56
+ // auto music (2026-11-20): gx_ns detects music on the mic and relaxes the chain
57
+ @Volatile private var autoMusic = true
58
+ private var musicDetected = false
59
+ private var musicDetectedSinceMs = 0L
60
+ @Volatile private var preferHeadset = false
61
+ @Volatile private var thermalFallback = true
62
+ @Volatile private var saverFallback = true
63
+ @Volatile private var watchdogNs = 8_000_000L
64
+ @Volatile private var watchdogConsecutive = 3
65
+
66
+ // --- live conditions ---
67
+ @Volatile private var route = "unknown"
68
+ @Volatile private var thermalHot = false
69
+ @Volatile private var batterySaver = false
70
+ @Volatile private var musicActive = false
71
+ @Volatile private var musicSinceMs = 0L
72
+ // singer mode (GravixRoomService.setSingerMode, 2026-11-20): our chain stays
73
+ // bypassed (dry + limiter near clip, our AGC and pause expander at unity)
74
+ // while it is on, with or without room music
75
+ @Volatile private var singerMode = false
76
+ // the recorder source singer mode asked for (GxSingerSource), null = kept
77
+ @Volatile private var singerSource: Int? = null
78
+ @Volatile private var makeupDb = 0f
79
+ // singer level normaliser (0.11.4, GravixSingerOptions.level*): the settings
80
+ // from Dart and what applyMakeup last set
81
+ @Volatile private var singerLevel = GxSingerLevel()
82
+ @Volatile private var levelMaxDb = 0f
83
+ @Volatile private var decided = GxNsNative.ENGINE_OFF
84
+ @Volatile private var decidedReason = "mode_off"
85
+
86
+ // --- audio thread state ---
87
+ @Volatile private var initRate = 0
88
+ @Volatile private var initChannels = 0
89
+ @Volatile private var lastNumFrames = -1
90
+ @Volatile private var lastBands = -1
91
+ @Volatile private var lastCap = -1
92
+ @Volatile private var lastDirect = false
93
+ @Volatile private var procRate = 0
94
+ @Volatile private var shapeReject: String? = "no_frame"
95
+ @Volatile private var shapeSeq = 0
96
+ @Volatile private var processErrors = 0
97
+ @Volatile private var audioTid = 0
98
+ @Volatile private var watchdog = GxNsWatchdog(watchdogNs, watchdogConsecutive)
99
+ @Volatile private var watchdogTripped = false
100
+ // studio attenuation limit + mid-call rolling-p95 fallback (gx_ns), LL opt-in
101
+ @Volatile private var studioAttenLimitDb = 40.0
102
+ @Volatile private var studioP95BudgetUs = 3000
103
+ @Volatile private var studioP95WindowMs = 2000
104
+ @Volatile private var studioLowLatency = false
105
+ @Volatile private var studioSlow = false
106
+ @Volatile private var studioSuppress = false
107
+ @Volatile private var watchdogLogged = false
108
+
109
+ // --- studio (DFN3) ---
110
+ @Volatile private var studioModel: GxNsStudio.Model = GxNsStudio.STD
111
+ @Volatile private var studioEngine: GxNsStudio.Engine? = null
112
+ @Volatile private var studioAttached = false
113
+ @Volatile private var studioLoading = false
114
+ @Volatile private var studioSource = "auto"
115
+ @Volatile private var studioDownload = "unmeteredIdle"
116
+ @Volatile private var studioPackUrl: String? = null
117
+ /** Is a capture block inside gx_ns right now (frees retired engines without waiting). */
118
+ private val inFlight = GxNsInFlight()
119
+ private val studioExec = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "GravixNS-studio") }
120
+
121
+ // --- ticker ---
122
+ private var ticker: Handler? = null
123
+ private var shapeSeqLogged = 0
124
+ private var lastActive = -1
125
+ private var lastReasonName = ""
126
+ private var tick = 0
127
+ private var cpuTicks0 = -1L
128
+ private var cpuWall0 = 0L
129
+ private val statsBuf = IntArray(13)
130
+ private val statusBuf = IntArray(19)
131
+
132
+ // ============================== audio thread ==============================
133
+
134
+ override fun initialize(sampleRateHz: Int, numChannels: Int) {
135
+ initRate = sampleRateHz
136
+ initChannels = numChannels
137
+ lastNumFrames = -1 // re-check the shape at the next frame
138
+ handle.let { if (it != 0L) GxNsNative.nativeResetMusic(it) } // a new capture: auto music starts over
139
+ }
140
+
141
+ override fun reset(newRate: Int) {
142
+ initRate = newRate
143
+ lastNumFrames = -1
144
+ handle.let { if (it != 0L) GxNsNative.nativeResetMusic(it) }
145
+ }
146
+
147
+ override fun process(numBands: Int, numFrames: Int, buffer: ByteBuffer) {
148
+ processNoise(numBands, numFrames, buffer)
149
+ GxVoiceFx.process(buffer, numFrames, initChannels)
150
+ // room music joins here, after the effect, while a voice effect is on (MusicCaptureRouter)
151
+ com.gravitycompile.gravixrtc.music.MusicMixerEngine.onPostProcess(buffer, numFrames, initChannels)
152
+ }
153
+
154
+ private fun processNoise(numBands: Int, numFrames: Int, buffer: ByteBuffer) {
155
+ val h = handle
156
+ if (h == 0L) return
157
+ val cap = buffer.capacity()
158
+ if (numFrames != lastNumFrames || cap != lastCap || numBands != lastBands) {
159
+ // first frame or a new shape (rare): validate, the ticker logs it
160
+ lastNumFrames = numFrames
161
+ lastCap = cap
162
+ lastBands = numBands
163
+ lastDirect = buffer.isDirect
164
+ procRate = GxNsFrameShape.rateOf(numFrames) ?: 0
165
+ shapeReject = GxNsFrameShape.reject(numFrames, cap, lastDirect, initChannels)
166
+ audioTid = Process.myTid()
167
+ shapeSeq++
168
+ if (procRate > 0) GxCaptureDump.start(appContext, procRate) // diagnostic: no-op unless debug.gravix.capdump=1
169
+ }
170
+ GxCaptureDump.onPre(buffer, numFrames)
171
+ if (shapeReject != null) {
172
+ GxCaptureDump.onPost(buffer, numFrames, false)
173
+ return
174
+ }
175
+ val t0 = System.nanoTime()
176
+ inFlight.enter()
177
+ try {
178
+ if (GxNsNative.nativeProcess(h, buffer, numFrames, procRate) != 0) processErrors++
179
+ } finally {
180
+ inFlight.exit()
181
+ }
182
+ GxCaptureDump.onPost(buffer, numFrames, true)
183
+ if (watchdog.onFrame(System.nanoTime() - t0)) {
184
+ watchdogTripped = true
185
+ // studio -> standard right here (an atomic store in gx_ns); RNNoise over
186
+ // budget is only logged (nothing lighter to fall back to)
187
+ if (requested == GxNsNative.ENGINE_DFN3) GxNsNative.nativeSetEngine(h, GxNsNative.ENGINE_RNNOISE)
188
+ }
189
+ }
190
+
191
+ // ============================== control (main thread) ==============================
192
+
193
+ /** nsConfigure from Dart. Returns `{ok, installed, reason?, engine, route, rate}`. */
194
+ @Synchronized
195
+ fun configure(context: Context?, args: Map<String, Any?>): Map<String, Any?> {
196
+ val t0 = SystemClock.elapsedRealtime()
197
+ if (context != null) appContext = context.applicationContext
198
+ mode = args["mode"] as? String ?: "off"
199
+ requested = GxNsNative.engineOf(args["engine"] as? String)
200
+ requestReason = args["reason"] as? String ?: "mode_$mode"
201
+ // off / kill switch: WebRTC's AGC is back on there, ours must not stack on it (review #1)
202
+ agcOn = GxNsAgc.ownOn(requested, args["agcOrder"] as? String)
203
+ agcOrderName = args["agcOrder"] as? String ?: "ownAfterNs"
204
+ agcOrder = GxNsNative.AGC_AFTER_NS
205
+ musicBypassEnabled = args["musicBypass"] as? Boolean ?: true
206
+ autoMusic = args["autoMusic"] as? Boolean ?: true
207
+ preferHeadset = args["headsetNs"] == "preferHeadset"
208
+ thermalFallback = args["thermalFallback"] as? Boolean ?: true
209
+ saverFallback = args["batterySaverFallback"] as? Boolean ?: true
210
+ watchdogNs = ((args["watchdogFrameUs"] as? Number)?.toLong() ?: 8000L) * 1000L
211
+ watchdogConsecutive = (args["watchdogConsecutive"] as? Number)?.toInt() ?: 3
212
+ watchdog = GxNsWatchdog(watchdogNs, watchdogConsecutive)
213
+ watchdogTripped = false
214
+ watchdogLogged = false
215
+ studioAttenLimitDb = (args["studioAttenLimitDb"] as? Number)?.toDouble() ?: 40.0
216
+ studioP95BudgetUs = (args["studioP95BudgetUs"] as? Number)?.toInt() ?: 3000
217
+ studioP95WindowMs = (args["studioP95WindowMs"] as? Number)?.toInt() ?: 2000
218
+ studioLowLatency = args["studioLowLatency"] as? Boolean ?: false
219
+ studioSlow = false
220
+ studioSuppress = false
221
+ studioSource = args["studioSource"] as? String ?: "auto"
222
+ studioDownload = args["studioDownload"] as? String ?: "unmeteredIdle"
223
+ studioPackUrl = args["studioPackUrl"] as? String
224
+ // LL only when the app opted in (studioLowLatency); otherwise the bundled standard model
225
+ (args["studioModel"] as? String)?.let { studioModel = if (it == "ll" && studioLowLatency) GxNsStudio.LL else GxNsStudio.STD }
226
+ if (!studioLowLatency) studioModel = GxNsStudio.STD
227
+
228
+ if (!GxNsNative.available()) {
229
+ val why = GxNsNative.loadError ?: "library_missing"
230
+ log("install", GxNsNative.ENGINE_OFF, "ok=false reason=$why abi=${Build.SUPPORTED_ABIS.firstOrNull()}", t0)
231
+ return mapOf("ok" to false, "installed" to false, "reason" to why)
232
+ }
233
+ if (handle == 0L) {
234
+ if (requested == GxNsNative.ENGINE_OFF) {
235
+ // legacy / off at join: nothing on the capture path, zero cost
236
+ log("install", GxNsNative.ENGINE_OFF, "skipped mode=$mode", t0)
237
+ return mapOf("ok" to true, "installed" to false, "engine" to "off", "route" to route)
238
+ }
239
+ val h = GxNsNative.nativeCreate(requested, if (agcOn) 1 else 0, agcOrder, (watchdogNs / 1000L).toInt(), studioP95WindowMs / 10)
240
+ if (h == 0L) {
241
+ log("install", GxNsNative.ENGINE_OFF, "ok=false reason=create_failed", t0)
242
+ return mapOf("ok" to false, "installed" to false, "reason" to "create_failed")
243
+ }
244
+ handle = h
245
+ startTicker()
246
+ watchPower()
247
+ }
248
+ val h = handle
249
+ GxNsNative.nativeSetAgc(h, agcOn, agcOrder)
250
+ GxNsNative.nativeSetStudioLimits(h, (studioAttenLimitDb * 100).toInt(), studioP95BudgetUs)
251
+ GxNsNative.nativeSetBypass(h, bypassWanted())
252
+ GxNsNative.nativeSetAutoMusic(h, autoMusic)
253
+ applyMakeup("configure")
254
+ applyDecision("configure")
255
+ val installed = installOn("configure")
256
+ if ((mode == "auto" || mode == "studio") && studioLowLatency) ensurePack()
257
+ log(
258
+ "init", decided,
259
+ "mode=$mode requested=${GxNsNative.engineName(requested)} reason=$decidedReason agc=${if (agcOn) "ownAfterNs" else agcOrderName} " +
260
+ "musicBypass=$musicBypassEnabled autoMusic=$autoMusic headsetNs=${if (preferHeadset) "preferHeadset" else "keepOurs"} installed=$installed",
261
+ t0,
262
+ )
263
+ return mapOf(
264
+ "ok" to true, "installed" to installed, "engine" to GxNsNative.engineName(decided),
265
+ "reason" to decidedReason, "route" to route, "rate" to procRate,
266
+ )
267
+ }
268
+
269
+ /**
270
+ * Adds the processor to the APM post-processing slot (idempotent). Called at
271
+ * configure and in handleStartLocalRecording, before the record thread
272
+ * starts (the adapter forwards initialize() only to processors present then;
273
+ * process() does not depend on it: rate = numFrames * 100).
274
+ */
275
+ @Synchronized
276
+ fun installOn(where: String): Boolean {
277
+ // a capture (re)starts: auto music must not carry the last session's state
278
+ if (where == "startLocalRecording") handle.let { if (it != 0L) GxNsNative.nativeResetMusic(it) }
279
+ if (handle == 0L && !GxVoiceFx.wanted()) return false
280
+ // React Native: GravixRtc.setup built the audio device module whose recorder
281
+ // feeds GravixCaptureProcessing (GxRecorderSeam); it attaches at the first capture.
282
+ if (!GxRecorderSeam.everAttached) {
283
+ log("install", decided, "where=$where pending: the capture seam attaches at the next recording start")
284
+ }
285
+ if (installed && GravixCaptureProcessing.contains(this)) return true
286
+ return try {
287
+ GravixCaptureProcessing.add(this)
288
+ installed = true
289
+ lastNumFrames = -1
290
+ log("install", decided, "where=$where seam=${GxRecorderSeam.everAttached}")
291
+ true
292
+ } catch (t: Throwable) {
293
+ Log.w(TAG, "[GravixNS] install failed where=$where: $t")
294
+ false
295
+ }
296
+ }
297
+
298
+ /** Studio seam: attach a `gx_ns_external_engine*` (0 = detach). Phase 3 wires the ORT DFN3 engine here. */
299
+ @Synchronized
300
+ fun attachExternalEngine(enginePtr: Long): Int {
301
+ val h = handle
302
+ if (h == 0L) return -1
303
+ val rc = GxNsNative.nativeAttachExternal(h, enginePtr)
304
+ log("pack", decided, "external=${if (enginePtr == 0L) "detached" else "attached"} rc=$rc")
305
+ return rc
306
+ }
307
+
308
+ /** GxAudioSwitchManager.onRoutesChanged (main thread). */
309
+ fun onRoutes(snapshot: Map<String, Any?>) {
310
+ val next = GxNsRoute.of(snapshot["current"] as? String, (snapshot["mode"] as? Number)?.toInt())
311
+ onRoute(next, snapshot["reason"] as? String ?: "routes")
312
+ }
313
+
314
+ /** Chatroom model: SCO engaged / released (main thread). */
315
+ fun onChatroom(engaged: Boolean) {
316
+ if (engaged) onRoute("bt-sco", "chatroom")
317
+ }
318
+
319
+ @Synchronized
320
+ private fun onRoute(next: String, why: String) {
321
+ val prev = route
322
+ if (next == prev) return
323
+ route = next
324
+ val h = handle
325
+ if (h == 0L) return
326
+ // soft reset: fade to dry, reset the engine state, fade back (~40 ms)
327
+ GxNsNative.nativeRequestReset(h)
328
+ lastNumFrames = -1 // re-check the shape and rate at the next frame
329
+ applyDecision("route")
330
+ applyMakeup("route")
331
+ log("routeReset", decided, "from=$prev why=$why narrowband=${GxNsRoute.isNarrowband(next)}")
332
+ emit("routeReset", mapOf("from" to prev))
333
+ }
334
+
335
+ private fun bypassWanted(): Boolean = (musicBypassEnabled && musicActive) || singerMode
336
+
337
+ /** Singer mode on / off (nsSetSingerMode from Dart, any thread); [source] = the GxSingerSource asked for. */
338
+ fun setSingerMode(on: Boolean, source: Int? = null, level: GxSingerLevel? = null) {
339
+ singerSource = if (on) source else null
340
+ if (level != null) singerLevel = level
341
+ if (singerMode == on) { applyMakeup("source"); return }
342
+ singerMode = on
343
+ val h = handle
344
+ if (h != 0L) GxNsNative.nativeSetBypass(h, bypassWanted())
345
+ applyMakeup("singerMode")
346
+ if (h == 0L) return
347
+ log("singerMode", decided, "on=$on bypass=${bypassWanted()} makeupDb=$makeupDb")
348
+ emit("singerMode", mapOf("singerMode" to on))
349
+ }
350
+
351
+ /**
352
+ * Singer mode gains on the bypassed signal, before the -1 dBFS limiter
353
+ * (0.11.4): the raw sources (MIC / VOICE_RECOGNITION / UNPROCESSED) have no
354
+ * HAL AGC and come in quiet (field: sung median -39 dBFS vs the -14 dBFS
355
+ * talk target). The level normaliser (boost-only by measurement, so a hot
356
+ * sound card gets nothing) on built-in mics (also an unknown route), wired
357
+ * and Bluetooth per the options, never USB (an interface sets its own
358
+ * level); the fixed makeup on built-in mics only. Neither while room music
359
+ * plays: on the PRE route it is in the same buffer and would be lifted with
360
+ * the voice.
361
+ */
362
+ @Synchronized
363
+ private fun applyMakeup(why: String) {
364
+ val lv = singerLevel
365
+ val on = singerMode && !musicActive
366
+ val builtIn = route == "speaker" || route == "earpiece" || route == "unknown"
367
+ val routeOk = builtIn || (route == "wired" && lv.onWired) || (GxNsRoute.isBluetooth(route) && lv.onBluetooth)
368
+ val maxDb = if (on && lv.enabled && routeOk) lv.maxDb else 0f
369
+ val fixed = if (on && builtIn) lv.builtInMakeupDb else 0f
370
+ val h = handle
371
+ if (h != 0L) {
372
+ GxNsNative.nativeSetSingerLevel(h, lv.targetDbfs, maxDb, lv.riseDbPerS)
373
+ GxNsNative.nativeSetBypassMakeup(h, fixed)
374
+ }
375
+ if (fixed != makeupDb || maxDb != levelMaxDb) {
376
+ makeupDb = fixed
377
+ levelMaxDb = maxDb
378
+ if (h != 0L) log("singerMakeup", decided, "levelMax=$maxDb target=${lv.targetDbfs} rise=${lv.riseDbPerS} fixed=$fixed why=$why source=$singerSource route=$route")
379
+ }
380
+ }
381
+
382
+ /** MusicMixerEngine session start / end (any thread). */
383
+ fun onMusic(active: Boolean) {
384
+ GxVoiceFx.onMusic(active)
385
+ if (musicActive == active) return
386
+ musicActive = active
387
+ val now = SystemClock.elapsedRealtime()
388
+ val h = handle
389
+ val bypass = musicBypassEnabled && active
390
+ if (h != 0L && (musicBypassEnabled || singerMode)) GxNsNative.nativeSetBypass(h, bypassWanted())
391
+ applyMakeup("music")
392
+ if (h == 0L) return
393
+ val detail = if (active) {
394
+ musicSinceMs = now
395
+ "on enabled=$musicBypassEnabled"
396
+ } else {
397
+ "off ms=${now - musicSinceMs}"
398
+ }
399
+ log("musicBypass", decided, detail)
400
+ emit("musicBypass", mapOf("musicBypass" to bypass))
401
+ }
402
+
403
+ @Synchronized
404
+ private fun applyDecision(why: String) {
405
+ val h = handle
406
+ if (h == 0L) return
407
+ val d = GxNsFallback.decide(
408
+ requested, requestReason, watchdogTripped, thermalHot, batterySaver, preferHeadset, route,
409
+ thermalFallback, saverFallback, studioSlow, studioSuppress,
410
+ )
411
+ val changed = d.engine != decided || d.reason != decidedReason
412
+ val from = decided
413
+ decided = d.engine
414
+ decidedReason = d.reason
415
+ if (d.engine == GxNsNative.ENGINE_DFN3) ensureStudioAttached() else detachStudio()
416
+ GxNsNative.nativeSetEngine(h, d.engine)
417
+ if (changed && why != "configure") {
418
+ log("switch", d.engine, "from=${GxNsNative.engineName(from)} to=${GxNsNative.engineName(d.engine)} reason=${d.reason}")
419
+ emit("switch", mapOf("from" to GxNsNative.engineName(from), "to" to GxNsNative.engineName(d.engine)))
420
+ }
421
+ }
422
+
423
+ // ============================== studio engine ==============================
424
+
425
+ /** Loads (background) and attaches the DFN3 engine of [studioModel]; gx_ns plays RNNoise until it is in. */
426
+ private fun ensureStudioAttached() {
427
+ val h = handle
428
+ val ctx = appContext ?: return
429
+ val want = studioModel
430
+ val cur = studioEngine
431
+ if (cur != null && cur.model == want) {
432
+ if (!studioAttached) {
433
+ val rc = GxNsNative.nativeAttachExternal(h, cur.ptr)
434
+ studioAttached = rc == 0
435
+ log("pack", decided, "attach model=${want.id} rc=$rc reused=true")
436
+ }
437
+ return
438
+ }
439
+ if (studioLoading) return
440
+ studioLoading = true
441
+ studioExec.execute {
442
+ val t0 = SystemClock.elapsedRealtime()
443
+ try {
444
+ val e = GxNsStudio.create(ctx, want)
445
+ if (e == null) {
446
+ log("pack", decided, "load model=${want.id} ok=false reason=${GxNsStudio.loadError ?: "load_failed"}", t0)
447
+ return@execute
448
+ }
449
+ synchronized(this) {
450
+ val old = studioEngine
451
+ if (old != null && studioAttached) GxNsNative.nativeAttachExternal(handle, 0L)
452
+ studioAttached = false
453
+ if (old != null) retire(old)
454
+ studioEngine = e
455
+ if (decided == GxNsNative.ENGINE_DFN3 && handle != 0L) {
456
+ val rc = GxNsNative.nativeAttachExternal(handle, e.ptr)
457
+ studioAttached = rc == 0
458
+ log("pack", decided, "src=${if (want === GxNsStudio.STD) "bundled" else "pack"} model=${want.id} sha=ok attach rc=$rc latency=${want.latency}", t0)
459
+ }
460
+ }
461
+ } finally {
462
+ studioLoading = false
463
+ }
464
+ }
465
+ }
466
+
467
+ /** Detached engines stay loaded for reuse (no +latency on the other engines while detached). */
468
+ private fun detachStudio() {
469
+ if (!studioAttached) return
470
+ GxNsNative.nativeAttachExternal(handle, 0L)
471
+ studioAttached = false
472
+ log("pack", decided, "detach model=${studioEngine?.model?.id}")
473
+ }
474
+
475
+ /**
476
+ * Frees an engine once gx_ns cannot reference it any more: right away when no
477
+ * capture block is inside gx_ns (the detach is already visible to the next
478
+ * one), else once that block has returned. Called on [studioExec].
479
+ */
480
+ private fun retire(e: GxNsStudio.Engine) {
481
+ val s0 = inFlight.snapshot()
482
+ if (handle == 0L || GxNsInFlight.idle(s0)) {
483
+ GxNsStudio.destroy(e)
484
+ return
485
+ }
486
+ studioExec.execute {
487
+ val deadline = SystemClock.elapsedRealtime() + 2000
488
+ while (!inFlight.advancedSince(s0) && SystemClock.elapsedRealtime() < deadline) {
489
+ try { Thread.sleep(5) } catch (_: InterruptedException) { break }
490
+ }
491
+ if (inFlight.advancedSince(s0)) GxNsStudio.destroy(e) // else leak rather than race
492
+ }
493
+ }
494
+
495
+ /** The LL pack in the background (never blocks a join). */
496
+ private fun ensurePack() {
497
+ val ctx = appContext ?: return
498
+ if (!GxNsStudio.available(ctx)) return
499
+ val src = studioSource
500
+ val dl = studioDownload
501
+ val url = studioPackUrl
502
+ studioExec.execute {
503
+ val t0 = SystemClock.elapsedRealtime()
504
+ val r = try { GxNsPack.ensure(ctx, src, dl, url) } catch (t: Throwable) { "error: $t" }
505
+ log("pack", decided, "ll=$r src=$src download=$dl play=${GxNsPack.isPlayInstall(ctx)}", t0)
506
+ }
507
+ }
508
+
509
+ /**
510
+ * nsBenchmark: LL first when the app opted in (studioLowLatency) and its pack is
511
+ * present (chosen if p95 < budget and the output is sane), else standard. Background thread; [reply] on the caller's handler.
512
+ */
513
+ fun benchmark(context: Context?, budgetUs: Int, reply: (Map<String, Any?>) -> Unit) {
514
+ val ctx = (context ?: appContext)?.applicationContext
515
+ if (ctx == null || !GxNsStudio.available(ctx)) {
516
+ reply(mapOf("ok" to false, "reason" to (GxNsStudio.loadError ?: "studio_unavailable")))
517
+ return
518
+ }
519
+ studioExec.execute {
520
+ val runs = ArrayList<Map<String, Any?>>()
521
+ var chosen: Map<String, Any?>? = null
522
+ if (studioLowLatency && GxNsPack.llFile(ctx) != null) {
523
+ val ll = GxNsStudio.benchmark(ctx, GxNsStudio.LL)
524
+ runs.add(ll)
525
+ if (ll["ok"] == true && ll["outputOk"] == true && ((ll["p95Us"] as? Int) ?: Int.MAX_VALUE) < budgetUs) chosen = ll
526
+ }
527
+ if (chosen == null) {
528
+ val std = GxNsStudio.benchmark(ctx, GxNsStudio.STD)
529
+ runs.add(std)
530
+ chosen = std
531
+ }
532
+ val c = chosen
533
+ if (c["ok"] == true) studioModel = if (c["model"] == "ll") GxNsStudio.LL else GxNsStudio.STD
534
+ for (r in runs) {
535
+ log("bench", decided, "model=${r["model"]} ok=${r["ok"]} p50=${r["p50Us"]} p95=${r["p95Us"]} max=${r["maxUs"]} " +
536
+ "outputOk=${r["outputOk"]} parity=${r["paritySnrDb"]} inDb=${r["inDb"]} outDb=${r["outDb"]} " +
537
+ "quietInDb=${r["quietInDb"]} quietOutDb=${r["quietOutDb"]} ms=${r["ms"]} reason=${r["reason"]}")
538
+ }
539
+ reply(HashMap(c).apply { put("runs", runs.size) })
540
+ }
541
+ }
542
+
543
+ /** nsStats: the last stats + status (any thread). */
544
+ fun stats(): Map<String, Any?>? {
545
+ val h = handle
546
+ if (h == 0L) return null
547
+ val s = IntArray(10)
548
+ val st = IntArray(19)
549
+ GxNsNative.nativeStats(h, s)
550
+ GxNsNative.nativeStatus(h, st)
551
+ return mapOf(
552
+ "frames" to s[0], "p50Us" to s[1], "p95Us" to s[2], "p99Us" to s[3], "maxUs" to s[4], "over" to s[5],
553
+ "underflows" to s[7], "switches" to s[9],
554
+ "eng" to GxNsNative.engineName(st[1]), "requested" to GxNsNative.engineName(st[0]),
555
+ "reason" to if (st[3] != 0) GxNsNative.nativeReasonName(st[3]) else decidedReason,
556
+ "route" to route, "rate" to st[4], "latencySamples" to st[5], "agcGainDb" to st[6] / 100.0,
557
+ "preGainDb" to st[7] / 100.0, "agcAppliedDb" to st[9] / 100.0, "preGainAppliedDb" to st[8] / 100.0,
558
+ "pauseAttDb" to st[10] / 100.0, "musicDetected" to (st[11] != 0),
559
+ "preRmsDb" to st[12] / 100.0, "prePeakDb" to st[13] / 100.0, "postRmsDb" to st[14] / 100.0, "postPeakDb" to st[15] / 100.0,
560
+ "makeupDb" to st[16] / 100.0, "singerGainDb" to st[17] / 100.0, "singerLevelDb" to st[18] / 100.0,
561
+ "singerMode" to singerMode,
562
+ "musicBypass" to (musicActive && musicBypassEnabled), "installed" to installed,
563
+ "shapeReject" to shapeReject,
564
+ "studioModel" to studioEngine?.model?.id, "studioAttached" to studioAttached,
565
+ )
566
+ }
567
+
568
+ // ============================== device facts ==============================
569
+
570
+ fun deviceFacts(context: Context?): Map<String, Any?> {
571
+ val am = context?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
572
+ val mem = ActivityManager.MemoryInfo().also { am?.getMemoryInfo(it) }
573
+ return mapOf(
574
+ "model" to Build.MODEL,
575
+ "manufacturer" to Build.MANUFACTURER,
576
+ "soc" to (if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL else null),
577
+ "osVersion" to Build.VERSION.RELEASE,
578
+ "abi" to Build.SUPPORTED_ABIS.firstOrNull(),
579
+ "ramMb" to (if (mem.totalMem > 0) (mem.totalMem / (1024L * 1024L)).toInt() else null),
580
+ "isLowRamDevice" to am?.isLowRamDevice,
581
+ "mediaPerformanceClass" to (if (Build.VERSION.SDK_INT >= 31) Build.VERSION.MEDIA_PERFORMANCE_CLASS else 0),
582
+ "cpuMaxFreqMhz" to cpuMaxFreqMhz(),
583
+ "osBuild" to Build.FINGERPRINT,
584
+ ) + studioFacts(context)
585
+ }
586
+
587
+ private fun studioFacts(context: Context?): Map<String, Any?> {
588
+ val ctx = context ?: return mapOf("studioAvailable" to false)
589
+ val ok = GxNsStudio.available(ctx)
590
+ val best = if (ok) GxNsStudio.bestModel(ctx) else null
591
+ return mapOf(
592
+ "studioAvailable" to ok,
593
+ "studioReason" to (if (ok) null else GxNsStudio.loadError),
594
+ "studioModel" to best?.id,
595
+ "studioSha" to best?.sha256,
596
+ "studioRuntime" to GxNsStudio.RUNTIME,
597
+ )
598
+ }
599
+
600
+ private fun cpuMaxFreqMhz(): Int? = try {
601
+ (File("/sys/devices/system/cpu").listFiles() ?: emptyArray())
602
+ .filter { it.name.matches(Regex("cpu\\d+")) }
603
+ .mapNotNull { File(it, "cpufreq/cpuinfo_max_freq").takeIf { f -> f.canRead() }?.readText()?.trim()?.toLongOrNull() }
604
+ .maxOrNull()?.let { (it / 1000L).toInt() }
605
+ } catch (_: Throwable) {
606
+ null
607
+ }
608
+
609
+ // ============================== power watch ==============================
610
+
611
+ private fun watchPower() {
612
+ val ctx = appContext ?: return
613
+ val pm = ctx.getSystemService(Context.POWER_SERVICE) as? PowerManager ?: return
614
+ batterySaver = pm.isPowerSaveMode
615
+ try {
616
+ val filter = IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
617
+ val r = object : BroadcastReceiver() {
618
+ override fun onReceive(c: Context?, i: Intent?) {
619
+ val on = pm.isPowerSaveMode
620
+ if (on != batterySaver) {
621
+ batterySaver = on
622
+ log("power", decided, "batterySaver=$on")
623
+ applyDecision("battery_saver")
624
+ }
625
+ }
626
+ }
627
+ if (Build.VERSION.SDK_INT >= 33) ctx.registerReceiver(r, filter, Context.RECEIVER_NOT_EXPORTED)
628
+ else ctx.registerReceiver(r, filter)
629
+ } catch (t: Throwable) {
630
+ Log.w(TAG, "[GravixNS] battery saver watch failed: $t")
631
+ }
632
+ if (Build.VERSION.SDK_INT >= 29) {
633
+ try {
634
+ thermalHot = pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_MODERATE
635
+ pm.addThermalStatusListener(ctx.mainExecutor) { status ->
636
+ val hot = status >= PowerManager.THERMAL_STATUS_MODERATE
637
+ if (hot != thermalHot) {
638
+ thermalHot = hot
639
+ log("power", decided, "thermalStatus=$status hot=$hot")
640
+ applyDecision("thermal")
641
+ }
642
+ }
643
+ } catch (t: Throwable) {
644
+ Log.w(TAG, "[GravixNS] thermal watch failed: $t")
645
+ }
646
+ }
647
+ }
648
+
649
+ // ============================== ticker (logs, events) ==============================
650
+
651
+ private fun startTicker() {
652
+ if (ticker != null) return
653
+ val t = HandlerThread("GravixNS").apply { start() }
654
+ val h = Handler(t.looper)
655
+ ticker = h
656
+ h.postDelayed(object : Runnable {
657
+ override fun run() {
658
+ try {
659
+ onTick()
660
+ } catch (e: Throwable) {
661
+ Log.w(TAG, "[GravixNS] ticker: $e")
662
+ }
663
+ h.postDelayed(this, 1000)
664
+ }
665
+ }, 1000)
666
+ }
667
+
668
+ private fun onTick() {
669
+ val h = handle
670
+ if (h == 0L) return
671
+ tick++
672
+ val seq = shapeSeq
673
+ if (seq != shapeSeqLogged) {
674
+ shapeSeqLogged = seq
675
+ // the APM hook's frame shape (plan [P]: Phase 0 measured here)
676
+ log(
677
+ "init", decided,
678
+ "bands=$lastBands frames=$lastNumFrames cap=$lastCap direct=$lastDirect initRate=$initRate initCh=$initChannels " +
679
+ "tid=$audioTid process=${if (shapeReject == null) "yes" else "no reason=$shapeReject"} " +
680
+ "webrtc=${try { stateReader?.invoke() } catch (t: Throwable) { "unreadable" }}",
681
+ )
682
+ val rej = shapeReject
683
+ // passthrough: say so (eng=off), the resolved engine is not running
684
+ if (rej != null) emit("init", mapOf("shapeReject" to rej, "eng" to "off", "reason" to "shape_$rej"))
685
+ else emit("init", mapOf("shapeReject" to null))
686
+ }
687
+ if (watchdogTripped && !watchdogLogged) {
688
+ watchdogLogged = true
689
+ if (requested == GxNsNative.ENGINE_DFN3) {
690
+ applyDecision("watchdog")
691
+ } else {
692
+ log("watchdog", decided, "over=${watchdogConsecutive}x>${watchdogNs / 1000}us kept (nothing lighter)")
693
+ }
694
+ }
695
+ GxNsNative.nativeStatus(h, statusBuf)
696
+ val active = statusBuf[1]
697
+ val reasonName = if (statusBuf[3] != 0) GxNsNative.nativeReasonName(statusBuf[3]) else decidedReason
698
+ if (reasonName == "studio_slow" && !studioSlow && requested == GxNsNative.ENGINE_DFN3) {
699
+ // gx_ns already plays RNNoise (crossfade); record why and detach the studio engine
700
+ studioSlow = true
701
+ GxNsNative.nativeStats(h, statsBuf)
702
+ log(
703
+ "watchdog", GxNsNative.ENGINE_RNNOISE,
704
+ "studio_slow p95=${statsBuf[10]}us>budget=${studioP95BudgetUs}us window=${studioP95WindowMs}ms model=${studioEngine?.model?.id} -> rnnoise",
705
+ )
706
+ applyDecision("studio_slow")
707
+ }
708
+ if (reasonName == "studio_suppress" && !studioSuppress && requested == GxNsNative.ENGINE_DFN3) {
709
+ // gx_ns already plays RNNoise: the studio output speech collapsed vs its input for 2 s
710
+ studioSuppress = true
711
+ log("watchdog", GxNsNative.ENGINE_RNNOISE, "studio_suppress model=${studioEngine?.model?.id} -> rnnoise")
712
+ applyDecision("studio_suppress")
713
+ }
714
+ if (statusBuf[2] == 0 && (active != lastActive || reasonName != lastReasonName)) {
715
+ if (lastActive >= 0) {
716
+ log("active", active, "from=${GxNsNative.engineName(lastActive)} reason=$reasonName")
717
+ }
718
+ lastActive = active
719
+ lastReasonName = reasonName
720
+ }
721
+ val music = statusBuf[11] != 0
722
+ if (music != musicDetected) {
723
+ val now = SystemClock.elapsedRealtime()
724
+ val ms = if (musicDetectedSinceMs > 0) now - musicDetectedSinceMs else 0L
725
+ musicDetected = music
726
+ musicDetectedSinceMs = now
727
+ log("musicDetected", decided, "on=$music ms=$ms agcAppliedDb=${statusBuf[9] / 100.0} preAppliedDb=${statusBuf[8] / 100.0}")
728
+ emit("musicDetected", mapOf("musicDetected" to music))
729
+ }
730
+ if (tick % SUMMARY_EVERY_S == 0) summary(h)
731
+ }
732
+
733
+ private fun summary(h: Long) {
734
+ GxNsNative.nativeStats(h, statsBuf)
735
+ if (statsBuf[0] == 0) return
736
+ val cpu = processCpuPercent()
737
+ val detail = "p50=${statsBuf[1]} p95=${statsBuf[2]} p99=${statsBuf[3]} max=${statsBuf[4]} over=${statsBuf[5]}" +
738
+ (if (cpu != null) " cpu=${String.format(java.util.Locale.US, "%.1f", cpu)}" else "") +
739
+ " frames=${statsBuf[0]} underflows=${statsBuf[7]} switches=${statsBuf[9]} errors=$processErrors" +
740
+ " music=${musicActive && musicBypassEnabled} musicDetected=$musicDetected agcDb=${statusBuf[6] / 100.0} preDb=${statusBuf[7] / 100.0}" +
741
+ " agcAppliedDb=${statusBuf[9] / 100.0} preAppliedDb=${statusBuf[8] / 100.0} pauseAttDb=${statusBuf[10] / 100.0}" +
742
+ " pre=${statusBuf[12] / 100.0}/${statusBuf[13] / 100.0} post=${statusBuf[14] / 100.0}/${statusBuf[15] / 100.0}" +
743
+ " singer=$singerMode makeupDb=${statusBuf[16] / 100.0} singerGainDb=${statusBuf[17] / 100.0} singerLevelDb=${statusBuf[18] / 100.0}"
744
+ log("summary", lastActive.coerceAtLeast(0), detail)
745
+ emit(
746
+ "summary",
747
+ mapOf(
748
+ "p50Us" to statsBuf[1], "p95Us" to statsBuf[2], "p99Us" to statsBuf[3], "maxUs" to statsBuf[4],
749
+ "over" to statsBuf[5], "cpu" to cpu,
750
+ "preRmsDb" to statusBuf[12] / 100.0, "prePeakDb" to statusBuf[13] / 100.0,
751
+ "postRmsDb" to statusBuf[14] / 100.0, "postPeakDb" to statusBuf[15] / 100.0,
752
+ "agcAppliedDb" to statusBuf[9] / 100.0, "preGainAppliedDb" to statusBuf[8] / 100.0,
753
+ "makeupDb" to statusBuf[16] / 100.0, "singerGainDb" to statusBuf[17] / 100.0,
754
+ ),
755
+ )
756
+ GxNsNative.nativeResetStats(h)
757
+ }
758
+
759
+ /** Whole-process CPU % of one core since the last call (/proc/self/stat utime+stime). */
760
+ private fun processCpuPercent(): Double? = try {
761
+ val f = File("/proc/self/stat").readText()
762
+ val rest = f.substring(f.lastIndexOf(')') + 2).split(' ')
763
+ val ticks = rest[11].toLong() + rest[12].toLong() // fields 14, 15
764
+ val now = SystemClock.elapsedRealtime()
765
+ val prev = cpuTicks0
766
+ val prevWall = cpuWall0
767
+ cpuTicks0 = ticks
768
+ cpuWall0 = now
769
+ if (prev < 0 || now <= prevWall) null else (ticks - prev) * 10.0 * 100.0 / (now - prevWall) // 100 Hz clock
770
+ } catch (_: Throwable) {
771
+ null
772
+ }
773
+
774
+ // ============================== logging ==============================
775
+
776
+ private fun log(step: String, eng: Int, detail: String?, t0: Long? = null) {
777
+ val elapsed = t0?.let { SystemClock.elapsedRealtime() - it }
778
+ Log.i(TAG, gxNsLine(step, GxNsNative.engineName(eng), route, procRate, elapsed, detail))
779
+ }
780
+
781
+ private fun emit(step: String, extra: Map<String, Any?>) {
782
+ val sink = eventSink ?: return
783
+ val m = HashMap<String, Any?>()
784
+ m["step"] = step
785
+ m["eng"] = GxNsNative.engineName(decided)
786
+ m["reason"] = decidedReason
787
+ m["route"] = route
788
+ m["rate"] = procRate
789
+ m.putAll(extra)
790
+ try {
791
+ sink(m)
792
+ } catch (_: Throwable) {
793
+ }
794
+ }
795
+ }