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,857 @@
1
+ // Copyright (c) 2026 Gravity Compile. MIT License; see LICENSE.
2
+
3
+ #import "GxAudioDevice.h"
4
+
5
+ #import <AVFAudio/AVFAudio.h>
6
+ #import <AudioToolbox/AudioToolbox.h>
7
+ #import <os/lock.h>
8
+ #import <pthread.h>
9
+ #import <stdatomic.h>
10
+ #import "gx_adm_state.h"
11
+ #import "gx_pcm.h"
12
+ #import "gravix_rtc_react_native-Swift.h"
13
+
14
+ // Swift @_cdecl entry points (GxIosAudio.swift): plain C calls on the IO threads.
15
+ extern void gx_ios_capture_process(float *_Nonnull samples, int32_t frames, int32_t rate);
16
+ extern int32_t gx_ios_monitor_read(float *_Nonnull dst, int32_t frames);
17
+
18
+ static const double kGxFallbackRate = 48000.0;
19
+ static const int kGxInitAttempts = 3;
20
+
21
+ /// Real-time context: written on the audio device thread (control mutex held)
22
+ /// only while no unit runs (AudioOutputUnitStop waits for the IO callbacks to
23
+ /// return), read by the IO callbacks. The flags are atomics because they also
24
+ /// change while running. A takeover swaps `deliver` / `getPlayout` only after
25
+ /// stopping the unit, under the same mutex as every unit start, so no callback
26
+ /// ever sees an older factory's blocks after its factory lost the device.
27
+ typedef struct {
28
+ AudioUnit unit;
29
+ int32_t rate;
30
+ void *deliver; // RTCAudioDeviceDeliverRecordedDataBlock, unretained (the device holds it)
31
+ void *getPlayout; // RTCAudioDeviceGetPlayoutDataBlock, unretained
32
+ _Atomic int32_t recordOn;
33
+ _Atomic int32_t playOn;
34
+ _Atomic int32_t chainOn;
35
+ _Atomic uint32_t inBlocks;
36
+ _Atomic uint32_t outBlocks;
37
+ _Atomic uint32_t chainBlocks;
38
+ _Atomic uint32_t monitorBlocks;
39
+ _Atomic uint32_t renderErrors;
40
+ _Atomic uint32_t oversize;
41
+ _Atomic uint32_t lastInFrames;
42
+ int16_t rec[GX_PCM_MAX_FRAMES];
43
+ float capture[GX_PCM_MAX_FRAMES];
44
+ float monitor[GX_PCM_MAX_FRAMES];
45
+ } GxIo;
46
+
47
+ static GxIo gIo;
48
+
49
+ #pragma mark - IO callbacks (real-time)
50
+
51
+ static OSStatus GxInputCallback(void *ref, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts,
52
+ UInt32 bus, UInt32 frames, AudioBufferList *unused)
53
+ {
54
+ GxIo *io = (GxIo *)ref;
55
+ __unsafe_unretained RTCAudioDeviceDeliverRecordedDataBlock deliver =
56
+ (__bridge RTCAudioDeviceDeliverRecordedDataBlock)io->deliver;
57
+ if (deliver == nil || frames == 0) {
58
+ return noErr;
59
+ }
60
+ if (frames > GX_PCM_MAX_FRAMES) {
61
+ // Not expected (MaximumFramesPerSlice = GX_PCM_MAX_FRAMES): count and drop.
62
+ atomic_fetch_add_explicit(&io->oversize, 1, memory_order_relaxed);
63
+ return noErr;
64
+ }
65
+ AudioBufferList abl;
66
+ abl.mNumberBuffers = 1;
67
+ abl.mBuffers[0].mNumberChannels = 1;
68
+ abl.mBuffers[0].mDataByteSize = frames * (UInt32)sizeof(int16_t);
69
+ abl.mBuffers[0].mData = io->rec;
70
+ OSStatus st = AudioUnitRender(io->unit, flags, ts, bus, frames, &abl);
71
+ if (st != noErr) {
72
+ atomic_fetch_add_explicit(&io->renderErrors, 1, memory_order_relaxed);
73
+ return st;
74
+ }
75
+ if (atomic_load_explicit(&io->recordOn, memory_order_relaxed) == 0) {
76
+ return noErr;
77
+ }
78
+ atomic_store_explicit(&io->lastInFrames, frames, memory_order_relaxed);
79
+ if (atomic_load_explicit(&io->chainOn, memory_order_relaxed) != 0 &&
80
+ gx_pcm_run_chain(io->rec, io->capture, (int32_t)frames, io->rate, gx_ios_capture_process)) {
81
+ atomic_fetch_add_explicit(&io->chainBlocks, 1, memory_order_relaxed);
82
+ }
83
+ atomic_fetch_add_explicit(&io->inBlocks, 1, memory_order_relaxed);
84
+ return deliver(flags, ts, bus, frames, &abl, NULL, nil);
85
+ }
86
+
87
+ static OSStatus GxOutputCallback(void *ref, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts,
88
+ UInt32 bus, UInt32 frames, AudioBufferList *data)
89
+ {
90
+ GxIo *io = (GxIo *)ref;
91
+ __unsafe_unretained RTCAudioDeviceGetPlayoutDataBlock getPlayout =
92
+ (__bridge RTCAudioDeviceGetPlayoutDataBlock)io->getPlayout;
93
+ if (getPlayout == nil || atomic_load_explicit(&io->playOn, memory_order_relaxed) == 0) {
94
+ for (UInt32 i = 0; i < data->mNumberBuffers; i++) {
95
+ memset(data->mBuffers[i].mData, 0, data->mBuffers[i].mDataByteSize);
96
+ }
97
+ *flags |= kAudioUnitRenderAction_OutputIsSilence;
98
+ return noErr;
99
+ }
100
+ OSStatus st = getPlayout(flags, ts, (NSInteger)bus, frames, data);
101
+ atomic_fetch_add_explicit(&io->outBlocks, 1, memory_order_relaxed);
102
+ // The monitor follows the capture position: only while capture runs (with the
103
+ // mic closed for a mute it would loop its 100 ms lead).
104
+ if (st == noErr && atomic_load_explicit(&io->recordOn, memory_order_relaxed) != 0 &&
105
+ frames <= GX_PCM_MAX_FRAMES && data->mNumberBuffers >= 1 &&
106
+ data->mBuffers[0].mData != NULL && data->mBuffers[0].mDataByteSize >= frames * sizeof(int16_t) &&
107
+ gx_ios_monitor_read(io->monitor, (int32_t)frames) != 0) {
108
+ gx_pcm_mix_into_s16((int16_t *)data->mBuffers[0].mData, io->monitor, (int32_t)frames);
109
+ atomic_fetch_add_explicit(&io->monitorBlocks, 1, memory_order_relaxed);
110
+ }
111
+ return st;
112
+ }
113
+
114
+ #pragma mark - Device
115
+
116
+ @interface GxAudioDevice () <RTCAudioSessionDelegate>
117
+ @end
118
+
119
+ @implementation GxAudioDevice {
120
+ // Control mutex + owner token / generation (gx_adm_state.h: the takeover rule).
121
+ // Everything below up to the atomics is touched only with the mutex held.
122
+ gx_control_t _ctl;
123
+ id<RTCAudioDeviceDelegate> _delegate; // also guarded by _delegateLock (read from any thread)
124
+ os_unfair_lock _delegateLock; // lock order: _ctl, then _delegateLock
125
+ int _startRetries;
126
+ RTCAudioDeviceDeliverRecordedDataBlock _deliver;
127
+ RTCAudioDeviceGetPlayoutDataBlock _getPlayout;
128
+ BOOL _playoutInitialized;
129
+ BOOL _recordingInitialized;
130
+ BOOL _sessionActive;
131
+ BOOL _interrupted;
132
+ BOOL _unitHasInput;
133
+ BOOL _observing;
134
+ double _rate;
135
+ NSTimeInterval _ioDuration;
136
+ NSTimeInterval _inputLatency;
137
+ NSTimeInterval _outputLatency;
138
+ dispatch_source_t _statsTimer;
139
+ // Read from any thread (recorderState, the protocol's state getters).
140
+ _Atomic int32_t _playing;
141
+ _Atomic int32_t _recording;
142
+ _Atomic int32_t _unitRunning;
143
+ _Atomic int32_t _unitInput;
144
+ _Atomic int32_t _captureClosed; // gx_gate state: OPEN / CLOSED / CLOSED_UNTIL_STOP
145
+ }
146
+
147
+ + (instancetype)shared
148
+ {
149
+ static GxAudioDevice *instance;
150
+ static dispatch_once_t once;
151
+ dispatch_once(&once, ^{
152
+ instance = [[GxAudioDevice alloc] init];
153
+ });
154
+ return instance;
155
+ }
156
+
157
+ - (instancetype)init
158
+ {
159
+ if ((self = [super init])) {
160
+ _rate = kGxFallbackRate;
161
+ _ioDuration = 0.01;
162
+ _delegateLock = OS_UNFAIR_LOCK_INIT;
163
+ gx_control_init(&_ctl);
164
+ }
165
+ return self;
166
+ }
167
+
168
+ static void GxLog(NSString *step, NSString *detail)
169
+ {
170
+ NSLog(@"[GravixAudioDevice] step=%@ %@", step, detail ?: @"");
171
+ }
172
+
173
+ static void GxControlScopeEnd(gx_control_t *_Nullable *_Nonnull held)
174
+ {
175
+ if (*held != NULL) {
176
+ gx_control_leave(*held);
177
+ }
178
+ }
179
+
180
+ /// Lifecycle entry (gx_adm_state.h rule 2): takes the control mutex, then returns
181
+ /// `foreign` when an older factory calls (no-op); the mutex is released at scope end.
182
+ #define GX_CONTROL_SCOPE(foreign) \
183
+ gx_control_t *gxHeld __attribute__((cleanup(GxControlScopeEnd), unused)) = \
184
+ gx_control_enter(&self->_ctl, gx_thread_token()) ? &self->_ctl : NULL; \
185
+ if (gxHeld == NULL) { \
186
+ return (foreign); \
187
+ }
188
+
189
+ #pragma mark RTCAudioDevice: parameters
190
+
191
+ - (double)deviceInputSampleRate { return _rate; }
192
+ - (NSTimeInterval)inputIOBufferDuration { return _ioDuration; }
193
+ - (NSInteger)inputNumberOfChannels { return 1; }
194
+ - (NSTimeInterval)inputLatency { return _inputLatency; }
195
+ - (double)deviceOutputSampleRate { return _rate; }
196
+ - (NSTimeInterval)outputIOBufferDuration { return _ioDuration; }
197
+ - (NSInteger)outputNumberOfChannels { return 1; }
198
+ - (NSTimeInterval)outputLatency { return _outputLatency; }
199
+
200
+ #pragma mark RTCAudioDevice: lifecycle
201
+
202
+ /// A second react-native-webrtc factory (RN reload, a second RN host) may
203
+ /// exist before the first one is destroyed: it calls from its own thread. The
204
+ /// device follows the newest factory; calls from an older one are no-ops (the
205
+ /// takeover rule, gx_adm_state.h).
206
+ - (BOOL)isOwnerThread
207
+ {
208
+ return gx_owner_is(&_ctl, gx_thread_token());
209
+ }
210
+
211
+ - (id<RTCAudioDeviceDelegate>)currentDelegate
212
+ {
213
+ os_unfair_lock_lock(&_delegateLock);
214
+ id<RTCAudioDeviceDelegate> d = _delegate;
215
+ os_unfair_lock_unlock(&_delegateLock);
216
+ return d;
217
+ }
218
+
219
+ - (BOOL)isInitialized
220
+ {
221
+ // Per factory: initialised for the owning WebRTC thread only, so a newer
222
+ // factory (another thread) hands over its delegate with initializeWithDelegate.
223
+ return [self isOwnerThread];
224
+ }
225
+
226
+ - (BOOL)isUsable
227
+ {
228
+ return gx_owner_any(&_ctl);
229
+ }
230
+
231
+ - (BOOL)initializeWithDelegate:(id<RTCAudioDeviceDelegate>)delegate
232
+ {
233
+ uintptr_t me = gx_thread_token();
234
+ // Unconditional: a newer factory must wait here until the older factory's
235
+ // call in progress (unit start with its init retries, stop, terminate, an
236
+ // event block) has returned, and every later older-factory call sees the new
237
+ // owner under the same mutex and is a no-op.
238
+ gx_control_lock(&_ctl);
239
+ if (gx_owner_any(&_ctl)) {
240
+ if (gx_owner_is(&_ctl, me) && [self currentDelegate] == delegate) {
241
+ gx_control_leave(&_ctl);
242
+ return YES;
243
+ }
244
+ // Takeover by a newer factory: stop the old factory's unit (synchronous: no
245
+ // IO callback with the old blocks runs after this), drop its state, then
246
+ // adopt the new owner and delegate. Its queued blocks see a new generation.
247
+ GxLog(@"initialize", @"takeover=1 (a newer WebRTC factory)");
248
+ [self stopUnit:@"takeover"];
249
+ atomic_store(&_playing, 0);
250
+ atomic_store(&_recording, 0);
251
+ _playoutInitialized = NO;
252
+ _recordingInitialized = NO;
253
+ _startRetries = 0;
254
+ // The newer factory's JS starts unmuted: no mute close survives it.
255
+ gx_gate_reset(&_captureClosed);
256
+ }
257
+ gx_owner_adopt(&_ctl, me);
258
+ _interrupted = NO; // an interruption that ended while no observer ran must not block the unit
259
+ os_unfair_lock_lock(&_delegateLock);
260
+ _delegate = delegate;
261
+ os_unfair_lock_unlock(&_delegateLock);
262
+ _deliver = delegate.deliverRecordedData;
263
+ _getPlayout = delegate.getPlayoutData;
264
+ gIo.deliver = (__bridge void *)_deliver;
265
+ gIo.getPlayout = (__bridge void *)_getPlayout;
266
+ [self startObserving];
267
+ [self readSessionFormat];
268
+ GxLog(@"initialize", [NSString stringWithFormat:@"rate=%.0f io_ms=%.1f preferred_rate=%.0f gen=%u", _rate,
269
+ _ioDuration * 1000, delegate.preferredInputSampleRate,
270
+ gx_owner_gen(&_ctl)]);
271
+ gx_control_leave(&_ctl);
272
+ return YES;
273
+ }
274
+
275
+ - (BOOL)terminateDevice
276
+ {
277
+ if (!gx_control_enter(&_ctl, gx_thread_token())) {
278
+ GxLog(@"terminate", @"ignored=1 (an older WebRTC factory)");
279
+ return YES;
280
+ }
281
+ atomic_store(&_playing, 0);
282
+ atomic_store(&_recording, 0);
283
+ _playoutInitialized = NO;
284
+ _recordingInitialized = NO;
285
+ [self stopUnit:@"terminate"];
286
+ [self deactivateSessionIfIdle];
287
+ [self stopObserving];
288
+ _interrupted = NO;
289
+ _startRetries = 0;
290
+ gIo.deliver = NULL;
291
+ gIo.getPlayout = NULL;
292
+ _deliver = nil;
293
+ _getPlayout = nil;
294
+ os_unfair_lock_lock(&_delegateLock);
295
+ _delegate = nil;
296
+ os_unfair_lock_unlock(&_delegateLock);
297
+ gx_gate_reset(&_captureClosed);
298
+ gx_owner_clear(&_ctl);
299
+ GxLog(@"terminate", nil);
300
+ gx_control_leave(&_ctl);
301
+ return YES;
302
+ }
303
+
304
+ - (BOOL)isPlayoutInitialized { return _playoutInitialized; }
305
+ - (BOOL)isPlaying { return atomic_load(&_playing) != 0; }
306
+ - (BOOL)isRecordingInitialized { return _recordingInitialized; }
307
+ - (BOOL)isRecording { return atomic_load(&_recording) != 0; }
308
+
309
+ - (BOOL)initializePlayout
310
+ {
311
+ GX_CONTROL_SCOPE(NO);
312
+ _playoutInitialized = [self activateSession];
313
+ GxLog(@"initPlayout", [NSString stringWithFormat:@"ok=%d rate=%.0f", _playoutInitialized, _rate]);
314
+ return _playoutInitialized;
315
+ }
316
+
317
+ - (BOOL)startPlayout
318
+ {
319
+ GX_CONTROL_SCOPE(NO);
320
+ atomic_store(&_playing, 1);
321
+ GxLog(@"startPlayout", nil);
322
+ if (![self updateUnit:@"startPlayout"]) {
323
+ atomic_store(&_playing, 0);
324
+ [self updateUnit:@"startPlayout_failed"];
325
+ return NO;
326
+ }
327
+ return YES;
328
+ }
329
+
330
+ - (BOOL)stopPlayout
331
+ {
332
+ GX_CONTROL_SCOPE(YES);
333
+ atomic_store(&_playing, 0);
334
+ _playoutInitialized = NO;
335
+ GxLog(@"stopPlayout", nil);
336
+ [self updateUnit:@"stopPlayout"];
337
+ [self deactivateSessionIfIdle];
338
+ return YES;
339
+ }
340
+
341
+ - (BOOL)initializeRecording
342
+ {
343
+ GX_CONTROL_SCOPE(NO);
344
+ _recordingInitialized = [self activateSession];
345
+ GxLog(@"initRecording", [NSString stringWithFormat:@"ok=%d rate=%.0f", _recordingInitialized, _rate]);
346
+ return _recordingInitialized;
347
+ }
348
+
349
+ - (BOOL)startRecording
350
+ {
351
+ GX_CONTROL_SCOPE(NO);
352
+ atomic_store(&_recording, 1);
353
+ // A mic closed for a mute stays closed (gate state): a reconnect republish of a
354
+ // muted mic starts WebRTC's recording on the playout-only unit, no input opens.
355
+ GxLog(@"startRecording", [NSString stringWithFormat:@"captureClosed=%d", gx_gate_closed(&_captureClosed)]);
356
+ if (![self updateUnit:@"startRecording"]) {
357
+ atomic_store(&_recording, 0);
358
+ [self updateUnit:@"startRecording_failed"];
359
+ return NO;
360
+ }
361
+ return YES;
362
+ }
363
+
364
+ - (BOOL)stopRecording
365
+ {
366
+ GX_CONTROL_SCOPE(YES);
367
+ atomic_store(&_recording, 0);
368
+ _recordingInitialized = NO;
369
+ // A plain mute close survives (the same muted mic is republished after a
370
+ // reconnect: WebRTC stops, then starts recording again). Only a close the JS
371
+ // released (the muted publication ended) opens here.
372
+ int opened = gx_gate_recording_stopped(&_captureClosed);
373
+ // Mute releases the mic: playout continues on an input-less unit.
374
+ GxLog(@"stopRecording", [NSString stringWithFormat:@"mic=release captureClosed=%d released=%d",
375
+ gx_gate_closed(&_captureClosed), opened]);
376
+ [self updateUnit:@"stopRecording"];
377
+ [self deactivateSessionIfIdle];
378
+ return YES;
379
+ }
380
+
381
+ #pragma mark Audio session
382
+
383
+ - (BOOL)audioAllowed
384
+ {
385
+ RTCAudioSession *session = [RTCAudioSession sharedInstance];
386
+ return !session.useManualAudio || session.isAudioEnabled;
387
+ }
388
+
389
+ - (BOOL)activateSession
390
+ {
391
+ if (_sessionActive) {
392
+ return YES;
393
+ }
394
+ RTCAudioSession *session = [RTCAudioSession sharedInstance];
395
+ RTCAudioSessionConfiguration *config = [RTCAudioSessionConfiguration webRTCConfiguration];
396
+ NSError *error = nil;
397
+ [session lockForConfiguration];
398
+ // A preferred attribute the route refuses (rate, IO buffer) is not fatal.
399
+ BOOL ok = [session setConfiguration:config error:&error];
400
+ NSError *activeError = nil;
401
+ if (!(session.useManualAudio && !session.isAudioEnabled)) {
402
+ // Our own activation count: only a successful setActive:YES is ours to undo.
403
+ _sessionActive = [session setActive:YES error:&activeError];
404
+ }
405
+ // (CallKit style, manual audio not enabled yet: the app activates the session.)
406
+ [session unlockForConfiguration];
407
+ if (activeError != nil) {
408
+ error = activeError;
409
+ }
410
+ [self readSessionFormat];
411
+ GxLog(@"session", [NSString stringWithFormat:@"activate ok=%d active=%d manual=%d category=%@ mode=%@ rate=%.0f err=%@",
412
+ ok, _sessionActive, session.useManualAudio, session.category,
413
+ session.mode, _rate, error.localizedDescription ?: @"none"]);
414
+ return _sessionActive || (session.useManualAudio && !session.isAudioEnabled);
415
+ }
416
+
417
+ - (void)deactivateSessionIfIdle
418
+ {
419
+ if (!_sessionActive || self.isPlaying || self.isRecording) {
420
+ return;
421
+ }
422
+ RTCAudioSession *session = [RTCAudioSession sharedInstance];
423
+ NSError *error = nil;
424
+ [session lockForConfiguration];
425
+ BOOL ok = [session setActive:NO error:&error];
426
+ [session unlockForConfiguration];
427
+ _sessionActive = NO;
428
+ GxLog(@"session", [NSString stringWithFormat:@"deactivate ok=%d err=%@", ok, error.localizedDescription ?: @"none"]);
429
+ }
430
+
431
+ - (void)readSessionFormat
432
+ {
433
+ AVAudioSession *s = [AVAudioSession sharedInstance];
434
+ double rate = s.sampleRate;
435
+ _rate = rate > 0 ? rate : kGxFallbackRate;
436
+ NSTimeInterval io = s.IOBufferDuration;
437
+ _ioDuration = io > 0 ? io : 0.01;
438
+ _inputLatency = s.inputLatency;
439
+ _outputLatency = s.outputLatency;
440
+ }
441
+
442
+ #pragma mark Unit
443
+
444
+ /// Brings the unit in line with playing / recording / interruption: none,
445
+ /// playout-only RemoteIO, or VPIO with input. Audio device thread.
446
+ - (BOOL)updateUnit:(NSString *)reason
447
+ {
448
+ BOOL playing = self.isPlaying;
449
+ BOOL recording = self.isRecording && !gx_gate_closed(&_captureClosed);
450
+ BOOL want = (playing || recording) && !_interrupted && [self audioAllowed];
451
+ BOOL running = atomic_load(&_unitRunning) != 0;
452
+ atomic_store_explicit(&gIo.playOn, playing ? 1 : 0, memory_order_relaxed);
453
+ atomic_store_explicit(&gIo.recordOn, recording ? 1 : 0, memory_order_relaxed);
454
+ if (running && (!want || _unitHasInput != recording)) {
455
+ [self stopUnit:reason];
456
+ running = NO;
457
+ }
458
+ if (!want || running) {
459
+ return YES;
460
+ }
461
+ return [self startUnitWithInput:recording reason:reason];
462
+ }
463
+
464
+ - (void)notifyThreadChange
465
+ {
466
+ id<RTCAudioDeviceDelegate> delegate = [self currentDelegate];
467
+ if (delegate == nil) {
468
+ return;
469
+ }
470
+ [delegate dispatchSync:^{
471
+ [delegate notifyAudioInputInterrupted];
472
+ [delegate notifyAudioOutputInterrupted];
473
+ }];
474
+ }
475
+
476
+ - (BOOL)startUnitWithInput:(BOOL)input reason:(NSString *)reason
477
+ {
478
+ if (!_sessionActive && ![self activateSession]) {
479
+ GxLog(@"unitStart", [NSString stringWithFormat:@"ok=0 reason=%@ cause=session_inactive", reason]);
480
+ return NO;
481
+ }
482
+ [self readSessionFormat];
483
+ // Always re-sync WebRTC's buffers with the current rate / IO size / latency
484
+ // (activation itself may have changed them; a no-op when nothing changed).
485
+ id<RTCAudioDeviceDelegate> delegate = [self currentDelegate];
486
+ if (delegate != nil) {
487
+ [delegate dispatchSync:^{
488
+ [delegate notifyAudioInputParametersChange];
489
+ [delegate notifyAudioOutputParametersChange];
490
+ }];
491
+ }
492
+ // A new unit runs its callbacks on a new thread.
493
+ [self notifyThreadChange];
494
+
495
+ AudioComponentDescription desc = {
496
+ .componentType = kAudioUnitType_Output,
497
+ .componentSubType = input ? kAudioUnitSubType_VoiceProcessingIO : kAudioUnitSubType_RemoteIO,
498
+ .componentManufacturer = kAudioUnitManufacturer_Apple,
499
+ };
500
+ AudioComponent comp = AudioComponentFindNext(NULL, &desc);
501
+ AudioUnit unit = NULL;
502
+ OSStatus st = comp ? AudioComponentInstanceNew(comp, &unit) : kAudioUnitErr_NoConnection;
503
+ if (st != noErr || unit == NULL) {
504
+ GxLog(@"unitStart", [NSString stringWithFormat:@"ok=0 reason=%@ cause=instance_new os=%d", reason, (int)st]);
505
+ return NO;
506
+ }
507
+ UInt32 one = 1;
508
+ UInt32 inputFlag = input ? 1 : 0;
509
+ UInt32 zero = 0;
510
+ UInt32 maxFrames = GX_PCM_MAX_FRAMES;
511
+ AudioStreamBasicDescription fmt = {
512
+ .mSampleRate = _rate,
513
+ .mFormatID = kAudioFormatLinearPCM,
514
+ .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked,
515
+ .mBytesPerPacket = 2,
516
+ .mFramesPerPacket = 1,
517
+ .mBytesPerFrame = 2,
518
+ .mChannelsPerFrame = 1,
519
+ .mBitsPerChannel = 16,
520
+ };
521
+ NSString *step = @"enable_io";
522
+ st = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &inputFlag, sizeof(inputFlag));
523
+ if (st == noErr) {
524
+ st = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &one, sizeof(one));
525
+ }
526
+ if (st == noErr) {
527
+ step = @"format_out";
528
+ st = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &fmt, sizeof(fmt));
529
+ }
530
+ if (st == noErr && input) {
531
+ step = @"format_in";
532
+ st = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &fmt, sizeof(fmt));
533
+ }
534
+ if (st == noErr) {
535
+ step = @"max_frames";
536
+ st = AudioUnitSetProperty(unit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &maxFrames,
537
+ sizeof(maxFrames));
538
+ }
539
+ if (st == noErr) {
540
+ step = @"render_cb";
541
+ AURenderCallbackStruct cb = {.inputProc = GxOutputCallback, .inputProcRefCon = &gIo};
542
+ st = AudioUnitSetProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &cb, sizeof(cb));
543
+ }
544
+ NSString *agc = @"n/a";
545
+ if (st == noErr && input) {
546
+ step = @"input_cb";
547
+ AudioUnitSetProperty(unit, kAudioUnitProperty_ShouldAllocateBuffer, kAudioUnitScope_Output, 1, &zero, sizeof(zero));
548
+ AURenderCallbackStruct cb = {.inputProc = GxInputCallback, .inputProcRefCon = &gIo};
549
+ st = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 1, &cb, sizeof(cb));
550
+ if (st == noErr) {
551
+ // Our AGC runs (noise suppression on): VPIO's must not stack on it.
552
+ UInt32 agcOn = GxIosAudio.wantsVpioAgcOff ? 0 : 1;
553
+ OSStatus a = AudioUnitSetProperty(unit, kAUVoiceIOProperty_VoiceProcessingEnableAGC, kAudioUnitScope_Global, 1,
554
+ &agcOn, sizeof(agcOn));
555
+ agc = a == noErr ? (agcOn ? @"on" : @"off") : [NSString stringWithFormat:@"err%d", (int)a];
556
+ }
557
+ }
558
+ if (st == noErr) {
559
+ step = @"initialize";
560
+ for (int attempt = 1; attempt <= kGxInitAttempts; attempt++) {
561
+ st = AudioUnitInitialize(unit);
562
+ if (st == noErr) {
563
+ break;
564
+ }
565
+ GxLog(@"unitInit", [NSString stringWithFormat:@"attempt=%d os=%d", attempt, (int)st]);
566
+ [NSThread sleepForTimeInterval:0.1];
567
+ }
568
+ }
569
+ if (st != noErr) {
570
+ GxLog(@"unitStart", [NSString stringWithFormat:@"ok=0 reason=%@ cause=%@ os=%d", reason, step, (int)st]);
571
+ AudioComponentInstanceDispose(unit);
572
+ return NO;
573
+ }
574
+ gIo.unit = unit;
575
+ gIo.rate = (int32_t)lround(_rate);
576
+ atomic_store(&gIo.chainOn, (input && GxIosAudio.isProcessingInstalled) ? 1 : 0);
577
+ if (input) {
578
+ // New capture stream: the noise suppressor fades back in at this rate.
579
+ [GxIosAudio captureStreamStartedWithRate:gIo.rate vpioAgc:agc];
580
+ }
581
+ st = AudioOutputUnitStart(unit);
582
+ if (st != noErr) {
583
+ GxLog(@"unitStart", [NSString stringWithFormat:@"ok=0 reason=%@ cause=start os=%d", reason, (int)st]);
584
+ AudioUnitUninitialize(unit);
585
+ AudioComponentInstanceDispose(unit);
586
+ gIo.unit = NULL;
587
+ atomic_store(&gIo.chainOn, 0);
588
+ return NO;
589
+ }
590
+ _unitHasInput = input;
591
+ atomic_store(&_unitInput, input ? 1 : 0);
592
+ atomic_store(&_unitRunning, 1);
593
+ [GxIosAudio setDeviceActive:YES];
594
+ [self startStats];
595
+ GxLog(@"unitStart", [NSString stringWithFormat:@"ok=1 reason=%@ unit=%@ rate=%d io_ms=%.1f vpioAgc=%@ chain=%d", reason,
596
+ input ? @"vpio" : @"remoteio_playout_only", gIo.rate,
597
+ _ioDuration * 1000, agc, atomic_load(&gIo.chainOn)]);
598
+ return YES;
599
+ }
600
+
601
+ - (void)stopUnit:(NSString *)reason
602
+ {
603
+ if (atomic_load(&_unitRunning) == 0) {
604
+ return;
605
+ }
606
+ AudioUnit unit = gIo.unit;
607
+ // Synchronous: no IO callback runs after this returns.
608
+ AudioOutputUnitStop(unit);
609
+ AudioUnitUninitialize(unit);
610
+ AudioComponentInstanceDispose(unit);
611
+ gIo.unit = NULL;
612
+ atomic_store(&gIo.chainOn, 0);
613
+ atomic_store(&_unitRunning, 0);
614
+ atomic_store(&_unitInput, 0);
615
+ _unitHasInput = NO;
616
+ [GxIosAudio setDeviceActive:NO];
617
+ [self stopStats];
618
+ GxLog(@"unitStop", [NSString stringWithFormat:@"reason=%@ %@", reason, [self statsLine]]);
619
+ }
620
+
621
+ #pragma mark Stats (every 5 s while a unit runs; the IO threads only count)
622
+
623
+ - (NSString *)statsLine
624
+ {
625
+ return [NSString stringWithFormat:@"in=%u chain=%u out=%u monitor=%u in_frames=%u render_err=%u oversize=%u",
626
+ atomic_load(&gIo.inBlocks), atomic_load(&gIo.chainBlocks),
627
+ atomic_load(&gIo.outBlocks), atomic_load(&gIo.monitorBlocks),
628
+ atomic_load(&gIo.lastInFrames), atomic_load(&gIo.renderErrors),
629
+ atomic_load(&gIo.oversize)];
630
+ }
631
+
632
+ - (void)startStats
633
+ {
634
+ [self stopStats];
635
+ dispatch_source_t t =
636
+ dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
637
+ dispatch_source_set_timer(t, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), 5 * NSEC_PER_SEC, NSEC_PER_SEC);
638
+ __weak GxAudioDevice *weakSelf = self;
639
+ dispatch_source_set_event_handler(t, ^{
640
+ GxAudioDevice *strongSelf = weakSelf;
641
+ if (strongSelf != nil) {
642
+ GxLog(@"stats", [strongSelf statsLine]);
643
+ }
644
+ });
645
+ dispatch_resume(t);
646
+ _statsTimer = t;
647
+ }
648
+
649
+ - (void)stopStats
650
+ {
651
+ if (_statsTimer != nil) {
652
+ dispatch_source_cancel(_statsTimer);
653
+ _statsTimer = nil;
654
+ }
655
+ }
656
+
657
+ #pragma mark Session events (any thread -> audio device thread)
658
+
659
+ - (void)startObserving
660
+ {
661
+ if (_observing) {
662
+ return;
663
+ }
664
+ _observing = YES;
665
+ RTCAudioSession *session = [RTCAudioSession sharedInstance];
666
+ [session addDelegate:self];
667
+ [session addObserver:self forKeyPath:@"isAudioEnabled" options:0 context:NULL];
668
+ }
669
+
670
+ - (void)stopObserving
671
+ {
672
+ if (!_observing) {
673
+ return;
674
+ }
675
+ _observing = NO;
676
+ RTCAudioSession *session = [RTCAudioSession sharedInstance];
677
+ [session removeDelegate:self];
678
+ [session removeObserver:self forKeyPath:@"isAudioEnabled"];
679
+ }
680
+
681
+ /// Runs `block` on the audio device thread, inside the control mutex, if the
682
+ /// device still has the same owner and generation then (rule 3, gx_adm_state.h).
683
+ - (void)onDeviceThread:(void (^)(void))block
684
+ {
685
+ [self onDeviceThreadGen:gx_owner_gen(&_ctl) block:block];
686
+ }
687
+
688
+ - (void)onDeviceThreadGen:(uint32_t)gen block:(void (^)(void))block
689
+ {
690
+ __weak GxAudioDevice *weakSelf = self;
691
+ // Held across dispatchAsync: terminateDevice cannot drop the delegate (and
692
+ // its thread) in between.
693
+ os_unfair_lock_lock(&_delegateLock);
694
+ id<RTCAudioDeviceDelegate> delegate = _delegate;
695
+ [delegate dispatchAsync:^{
696
+ GxAudioDevice *strongSelf = weakSelf;
697
+ if (strongSelf == nil || !gx_control_enter_gen(&strongSelf->_ctl, gx_thread_token(), gen)) {
698
+ return;
699
+ }
700
+ block();
701
+ gx_control_leave(&strongSelf->_ctl);
702
+ }];
703
+ os_unfair_lock_unlock(&_delegateLock);
704
+ }
705
+
706
+ /// S3: a unit start that failed on an event path (interruption end, route,
707
+ /// reset, mute reopen) is retried a few times, 300 ms apart. Control mutex held;
708
+ /// a retry belongs to the generation that scheduled it.
709
+ - (void)updateUnitWithRetry:(NSString *)reason
710
+ {
711
+ if ([self updateUnit:reason]) {
712
+ _startRetries = 0;
713
+ return;
714
+ }
715
+ if (_startRetries >= 3) {
716
+ GxLog(@"unitRetry", [NSString stringWithFormat:@"reason=%@ gave_up=1", reason]);
717
+ _startRetries = 0;
718
+ return;
719
+ }
720
+ _startRetries++;
721
+ uint32_t gen = gx_owner_gen(&_ctl);
722
+ __weak GxAudioDevice *weakSelf = self;
723
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 300 * NSEC_PER_MSEC), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
724
+ [weakSelf onDeviceThreadGen:gen block:^{
725
+ [weakSelf updateUnitWithRetry:reason];
726
+ }];
727
+ });
728
+ }
729
+
730
+ - (void)observeValueForKeyPath:(NSString *)keyPath
731
+ ofObject:(id)object
732
+ change:(NSDictionary<NSKeyValueChangeKey, id> *)change
733
+ context:(void *)context
734
+ {
735
+ if (![keyPath isEqualToString:@"isAudioEnabled"]) {
736
+ return;
737
+ }
738
+ [self onDeviceThread:^{
739
+ GxLog(@"audioEnabled", [NSString stringWithFormat:@"enabled=%d", [RTCAudioSession sharedInstance].isAudioEnabled]);
740
+ if ([self audioAllowed] && (self.isPlaying || self.isRecording)) {
741
+ [self activateSession];
742
+ }
743
+ [self updateUnitWithRetry:@"audio_enabled"];
744
+ }];
745
+ }
746
+
747
+ - (void)audioSessionDidBeginInterruption:(RTCAudioSession *)session
748
+ {
749
+ [self onDeviceThread:^{
750
+ self->_interrupted = YES;
751
+ GxLog(@"interruption", @"begin");
752
+ [self updateUnit:@"interruption_begin"];
753
+ }];
754
+ }
755
+
756
+ - (void)audioSessionDidEndInterruption:(RTCAudioSession *)session shouldResumeSession:(BOOL)shouldResumeSession
757
+ {
758
+ [self onDeviceThread:^{
759
+ self->_interrupted = NO;
760
+ GxLog(@"interruption", [NSString stringWithFormat:@"end resume=%d", shouldResumeSession]);
761
+ [self updateUnitWithRetry:@"interruption_end"];
762
+ }];
763
+ }
764
+
765
+ - (void)audioSessionDidChangeRoute:(RTCAudioSession *)session
766
+ reason:(AVAudioSessionRouteChangeReason)reason
767
+ previousRoute:(AVAudioSessionRouteDescription *)previousRoute
768
+ {
769
+ [self onDeviceThread:^{
770
+ double rate = [AVAudioSession sharedInstance].sampleRate;
771
+ BOOL running = atomic_load(&self->_unitRunning) != 0;
772
+ GxLog(@"route", [NSString stringWithFormat:@"reason=%lu rate=%.0f unit_rate=%d running=%d", (unsigned long)reason,
773
+ rate, gIo.rate, running]);
774
+ if (running && rate > 0 && lround(rate) != gIo.rate) {
775
+ // New hardware rate (Bluetooth HFP, a wired headset): rebuild at it.
776
+ [self stopUnit:@"route_rate_change"];
777
+ [self updateUnitWithRetry:@"route_rate_change"];
778
+ } else if (running && self->_unitHasInput) {
779
+ [GxIosAudio captureStreamStartedWithRate:gIo.rate vpioAgc:@"unchanged"];
780
+ }
781
+ }];
782
+ }
783
+
784
+ - (void)audioSessionMediaServerReset:(RTCAudioSession *)session
785
+ {
786
+ [self onDeviceThread:^{
787
+ GxLog(@"mediaServerReset", nil);
788
+ [self stopUnit:@"media_server_reset"];
789
+ // RTCAudioSession keeps its activation count across a reset and re-activates
790
+ // itself: re-apply the configuration only (no second activation).
791
+ RTCAudioSession *s = [RTCAudioSession sharedInstance];
792
+ [s lockForConfiguration];
793
+ [s setConfiguration:[RTCAudioSessionConfiguration webRTCConfiguration] error:nil];
794
+ [s unlockForConfiguration];
795
+ [self updateUnitWithRetry:@"media_server_reset"];
796
+ }];
797
+ }
798
+
799
+ #pragma mark Mute releases the mic
800
+
801
+ - (void)setCaptureClosed:(BOOL)closed
802
+ {
803
+ int wasClosed = gx_gate_set_closed(&_captureClosed, closed);
804
+ GxLog(@"captureClosed", [NSString stringWithFormat:@"closed=%d was=%d initialized=%d", closed, wasClosed, self.isUsable]);
805
+ if (wasClosed == (closed ? 1 : 0)) {
806
+ return;
807
+ }
808
+ if (!gx_owner_any(&_ctl)) {
809
+ return; // applied when a unit next starts
810
+ }
811
+ [self onDeviceThread:^{
812
+ [self updateUnitWithRetry:closed ? @"mute_close" : @"mute_reopen"];
813
+ }];
814
+ }
815
+
816
+ - (void)releaseCaptureCloseOnStop
817
+ {
818
+ if (!gx_gate_release_on_stop(&_captureClosed)) {
819
+ return; // open (nothing to release) or already pending
820
+ }
821
+ GxLog(@"captureClosed", [NSString stringWithFormat:@"release_on_stop=1 initialized=%d", self.isUsable]);
822
+ if (!gx_owner_any(&_ctl)) {
823
+ gx_gate_recording_stopped(&_captureClosed); // no factory: nothing records
824
+ return;
825
+ }
826
+ // Already idle: open now (no input opens while WebRTC records nothing).
827
+ // Recording: stopRecording opens it.
828
+ [self onDeviceThread:^{
829
+ if (!self.isRecording && gx_gate_recording_stopped(&self->_captureClosed)) {
830
+ GxLog(@"captureClosed", @"released=1 (not recording)");
831
+ }
832
+ }];
833
+ }
834
+
835
+ #pragma mark Recorder state
836
+
837
+ - (NSDictionary<NSString *, id> *)recorderState
838
+ {
839
+ BOOL running = atomic_load(&_unitRunning) != 0;
840
+ BOOL input = atomic_load(&_unitInput) != 0;
841
+ return @{
842
+ @"recording" : @(self.isRecording && running && input),
843
+ @"captureClosed" : @(gx_gate_closed(&_captureClosed)),
844
+ // The muted publication ended: the close lasts until WebRTC stops recording.
845
+ @"captureReleasePending" : @(atomic_load(&_captureClosed) == GX_GATE_CLOSED_UNTIL_STOP),
846
+ @"recordingInitialized" : @(_recordingInitialized),
847
+ @"playing" : @(self.isPlaying),
848
+ @"engineRunning" : @(running),
849
+ // The microphone input is closed (no VPIO input unit).
850
+ @"microphoneMuted" : @(!input),
851
+ // 1 = restartEngine: a mute rebuilds the unit without input.
852
+ @"muteMode" : @1,
853
+ @"device" : @"gravix",
854
+ };
855
+ }
856
+
857
+ @end