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,195 @@
1
+ // Copyright (c) 2024-2026 Gravity Compile. MIT License; see LICENSE.
2
+
3
+ #if canImport(CoreML)
4
+ import CoreML
5
+ import Foundation
6
+
7
+ /// DeepFilterNet3 streaming model on Core ML (standard: bundled; LL: downloaded).
8
+ ///
9
+ /// Interface (dfn3-spike release manifest, `interface`): 48 kHz mono, 480
10
+ /// float32 samples in -> 480 out per call, in order. Every input except
11
+ /// `input_frame` / `gx_dft_cos` / `gx_dft_sin` is a state; output
12
+ /// `new_<name>` is fed back as `<name>` next frame. Core ML models have no
13
+ /// `new_analysis_mem`: the next frame's `analysis_mem` is this frame's input.
14
+ /// The STFT runs inside the model as matmuls against the two DFT tables
15
+ /// (computed once here); the ERB front end inside the model is fp32.
16
+ ///
17
+ /// Real-time path: two pre-allocated state sets (inputs of one = output
18
+ /// backings of the other, swapped every frame), pre-built feature values and
19
+ /// one MLPredictionOptions per parity, so a frame copies 2 x 480 floats and
20
+ /// calls `prediction`. Core ML may still allocate internally; the gx_ns
21
+ /// watchdog (frame time) and the benchmark gate cover that.
22
+ @available(iOS 16.0, macOS 13.0, *)
23
+ final class GxNsDfn3CoreML: GxNsStudioEngine {
24
+ let name: String
25
+ let modelSha256: String
26
+ let latencySamples: Int32
27
+
28
+ private let model: MLModel
29
+ private let frame: MLMultiArray
30
+ private let sets: [StateSet] // [0], [1]
31
+ private let providers: [Provider]
32
+ private let options: [MLPredictionOptions]
33
+ private var parity = 0
34
+ private let stateNames: [String]
35
+
36
+ private final class StateSet {
37
+ var arrays: [String: MLMultiArray] = [:]
38
+ var enhanced: MLMultiArray!
39
+ }
40
+
41
+ private final class Provider: NSObject, MLFeatureProvider {
42
+ let featureNames: Set<String>
43
+ let values: [String: MLFeatureValue]
44
+ init(_ values: [String: MLFeatureValue]) {
45
+ self.values = values
46
+ featureNames = Set(values.keys)
47
+ }
48
+ func featureValue(for featureName: String) -> MLFeatureValue? { values[featureName] }
49
+ }
50
+
51
+ /// Loads a compiled model (.mlmodelc). Off the audio thread.
52
+ init(compiledModel url: URL, name: String, modelSha256: String, latencySamples: Int32,
53
+ computeUnits: MLComputeUnits = .cpuOnly) throws {
54
+ let cfg = MLModelConfiguration()
55
+ cfg.computeUnits = computeUnits
56
+ model = try MLModel(contentsOf: url, configuration: cfg)
57
+ self.name = name
58
+ self.modelSha256 = modelSha256
59
+ self.latencySamples = latencySamples
60
+
61
+ let inputs = model.modelDescription.inputDescriptionsByName
62
+ let outputs = model.modelDescription.outputDescriptionsByName
63
+ func shape(_ d: MLFeatureDescription?) throws -> [NSNumber] {
64
+ guard let c = d?.multiArrayConstraint else { throw Self.error("model I/O is not a multi-array") }
65
+ return c.shape
66
+ }
67
+ guard inputs["input_frame"] != nil, inputs["gx_dft_cos"] != nil, inputs["gx_dft_sin"] != nil,
68
+ outputs["enhanced_audio_frame"] != nil, inputs["analysis_mem"] != nil
69
+ else { throw Self.error("unexpected DFN3 model interface") }
70
+
71
+ frame = try MLMultiArray(shape: try shape(inputs["input_frame"]), dataType: .float32)
72
+ let (cosT, sinT) = try Self.dftTables(shape: try shape(inputs["gx_dft_cos"]))
73
+
74
+ let names = inputs.keys.filter { !["input_frame", "gx_dft_cos", "gx_dft_sin"].contains($0) }.sorted()
75
+ stateNames = names
76
+ var builtSets: [StateSet] = []
77
+ for _ in 0 ..< 2 {
78
+ let s = StateSet()
79
+ for n in names { s.arrays[n] = try MLMultiArray(shape: try shape(inputs[n]), dataType: .float32) }
80
+ s.enhanced = try MLMultiArray(shape: try shape(outputs["enhanced_audio_frame"]), dataType: .float32)
81
+ builtSets.append(s)
82
+ }
83
+ sets = builtSets
84
+ for n in names where n != "analysis_mem" {
85
+ guard outputs["new_\(n)"] != nil else { throw Self.error("missing output new_\(n)") }
86
+ }
87
+
88
+ var provs: [Provider] = []
89
+ var opts: [MLPredictionOptions] = []
90
+ for p in 0 ..< 2 {
91
+ let cur = builtSets[p], next = builtSets[1 - p]
92
+ var values: [String: MLFeatureValue] = [
93
+ "input_frame": MLFeatureValue(multiArray: frame),
94
+ "gx_dft_cos": MLFeatureValue(multiArray: cosT),
95
+ "gx_dft_sin": MLFeatureValue(multiArray: sinT),
96
+ ]
97
+ for n in names { values[n] = MLFeatureValue(multiArray: cur.arrays[n]!) }
98
+ provs.append(Provider(values))
99
+ var backings: [String: Any] = ["enhanced_audio_frame": next.enhanced!]
100
+ for n in names where n != "analysis_mem" { backings["new_\(n)"] = next.arrays[n]! }
101
+ let o = MLPredictionOptions()
102
+ o.outputBackings = backings
103
+ opts.append(o)
104
+ }
105
+ providers = provs
106
+ options = opts
107
+ reset()
108
+ }
109
+
110
+ func process(_ out: UnsafeMutablePointer<Float>, _ input: UnsafePointer<Float>, _ count: Int32) -> Int32 {
111
+ let n = Int(count)
112
+ guard n == frame.count else { return -2 }
113
+ let p = parity
114
+ let fptr = frame.dataPointer.assumingMemoryBound(to: Float.self)
115
+ fptr.update(from: input, count: n)
116
+ do {
117
+ let result = try autoreleasepool { try model.prediction(from: providers[p], options: options[p]) }
118
+ let next = sets[1 - p]
119
+ // Output backings are normally honoured; copy from the result if not.
120
+ if let enhanced = result.featureValue(for: "enhanced_audio_frame")?.multiArrayValue, enhanced !== next.enhanced {
121
+ guard Self.copyOut(enhanced, to: out, count: n) else { return -3 }
122
+ for name in stateNames where name != "analysis_mem" {
123
+ if let v = result.featureValue(for: "new_\(name)")?.multiArrayValue, let dst = next.arrays[name], v !== dst {
124
+ Self.copy(v, into: dst)
125
+ }
126
+ }
127
+ } else {
128
+ out.update(from: next.enhanced.dataPointer.assumingMemoryBound(to: Float.self), count: n)
129
+ }
130
+ next.arrays["analysis_mem"]!.dataPointer.assumingMemoryBound(to: Float.self).update(from: input, count: n)
131
+ parity = 1 - p
132
+ return 0
133
+ } catch {
134
+ return -1
135
+ }
136
+ }
137
+
138
+ func reset() {
139
+ for s in sets {
140
+ for (_, a) in s.arrays { memset(a.dataPointer, 0, a.count * MemoryLayout<Float>.size) }
141
+ if let e = s.arrays["erb_norm_state"] { Self.linspace(e, -60, -90) }
142
+ if let b = s.arrays["band_unit_norm_state"] { Self.linspace(b, 0.001, 0.0001) }
143
+ }
144
+ parity = 0
145
+ }
146
+
147
+ // MARK: helpers
148
+
149
+ private static func linspace(_ a: MLMultiArray, _ from: Float, _ to: Float) {
150
+ let n = a.count
151
+ let p = a.dataPointer.assumingMemoryBound(to: Float.self)
152
+ for i in 0 ..< n { p[i] = n == 1 ? from : from + (to - from) * Float(i) / Float(n - 1) }
153
+ }
154
+
155
+ private static func copyOut(_ a: MLMultiArray, to out: UnsafeMutablePointer<Float>, count: Int) -> Bool {
156
+ guard a.count == count else { return false }
157
+ switch a.dataType {
158
+ case .float32: out.update(from: a.dataPointer.assumingMemoryBound(to: Float.self), count: count)
159
+ default: for i in 0 ..< count { out[i] = a[i].floatValue }
160
+ }
161
+ return true
162
+ }
163
+
164
+ private static func copy(_ src: MLMultiArray, into dst: MLMultiArray) {
165
+ if src.dataType == .float32, src.count == dst.count {
166
+ memcpy(dst.dataPointer, src.dataPointer, dst.count * MemoryLayout<Float>.size)
167
+ } else {
168
+ let d = dst.dataPointer.assumingMemoryBound(to: Float.self)
169
+ for i in 0 ..< min(src.count, dst.count) { d[i] = src[i].floatValue }
170
+ }
171
+ }
172
+
173
+ /// cos/sin(2*pi*((n*k) mod N)/N), n < N, k < N/2+1 (shape [N, N/2+1]).
174
+ static func dftTables(shape: [NSNumber]) throws -> (MLMultiArray, MLMultiArray) {
175
+ guard shape.count == 2 else { throw error("unexpected DFT table shape") }
176
+ let rows = shape[0].intValue, cols = shape[1].intValue
177
+ let c = try MLMultiArray(shape: shape, dataType: .float32)
178
+ let s = try MLMultiArray(shape: shape, dataType: .float32)
179
+ let cp = c.dataPointer.assumingMemoryBound(to: Float.self)
180
+ let sp = s.dataPointer.assumingMemoryBound(to: Float.self)
181
+ for n in 0 ..< rows {
182
+ for k in 0 ..< cols {
183
+ let a = Double((n * k) % rows) * (2 * Double.pi / Double(rows))
184
+ cp[n * cols + k] = Float(cos(a))
185
+ sp[n * cols + k] = Float(sin(a))
186
+ }
187
+ }
188
+ return (c, s)
189
+ }
190
+
191
+ static func error(_ msg: String) -> NSError {
192
+ NSError(domain: "GravixNS", code: 1, userInfo: [NSLocalizedDescriptionKey: msg])
193
+ }
194
+ }
195
+ #endif
@@ -0,0 +1,237 @@
1
+ // Copyright (c) 2024-2026 Gravity Compile. MIT License; see LICENSE.
2
+
3
+ import Foundation
4
+ @_implementationOnly import gxns
5
+ #if canImport(CoreML)
6
+ import CoreML
7
+ #endif
8
+
9
+ /// A studio (external) noise suppression engine plugged into the gx_ns core
10
+ /// through `gx_ns_set_external_engine` (plan §2, §4). The core feeds it one
11
+ /// 10 ms block: 480 samples at 48 kHz in [-1, 1] scale.
12
+ ///
13
+ /// `process` runs on the real-time capture thread: no allocation, no locks,
14
+ /// no Objective-C bridging that allocates. Return 0 on success; anything else
15
+ /// makes the core fall back to RNNoise at once (reason `ext_error`).
16
+ protocol GxNsStudioEngine: AnyObject {
17
+ /// Short engine id for logs, e.g. "dfn3-coreml-fp16nn".
18
+ var name: String { get }
19
+ /// Model SHA-256 (benchmark cache key), or "" when unknown.
20
+ var modelSha256: String { get }
21
+ /// Algorithmic delay at 48 kHz (DFN3 standard: 1440 samples = 30 ms).
22
+ var latencySamples: Int32 { get }
23
+ func process(_ out: UnsafeMutablePointer<Float>, _ input: UnsafePointer<Float>, _ count: Int32) -> Int32
24
+ /// Clears the streaming state (route change). Audio thread or idle.
25
+ func reset()
26
+ }
27
+
28
+ /// Holds the engine for the C trampolines (`user` pointer). Retained by the
29
+ /// processor while attached and until the audio thread has moved past it.
30
+ final class GxNsStudioBox {
31
+ let engine: GxNsStudioEngine
32
+ init(_ engine: GxNsStudioEngine) { self.engine = engine }
33
+
34
+ func cEngine() -> gx_ns_external_engine {
35
+ gx_ns_external_engine(
36
+ process: { user, out, input, n in
37
+ guard let user, let out, let input else { return -1 }
38
+ let box = Unmanaged<GxNsStudioBox>.fromOpaque(user).takeUnretainedValue()
39
+ return box.engine.process(out, input, n)
40
+ },
41
+ reset: { user in
42
+ guard let user else { return }
43
+ Unmanaged<GxNsStudioBox>.fromOpaque(user).takeUnretainedValue().engine.reset()
44
+ },
45
+ user: Unmanaged.passUnretained(self).toOpaque(),
46
+ latency_samples: engine.latencySamples
47
+ )
48
+ }
49
+ }
50
+
51
+ /// Where studio engines come from.
52
+ ///
53
+ /// - std (default): DeepFilterNet3 standard, Core ML int8-linear / fp16
54
+ /// compute with the ERB front end fp32 (DFN3_SPIKE.md §1/§3), BUNDLED as a
55
+ /// precompiled `gxns_dfn3.mlmodelc` (resource bundle `gravix_rtc_ns` with
56
+ /// CocoaPods, the target's resource bundle with SwiftPM). 30 ms latency.
57
+ /// - ll: DeepFilterNet3 low-latency (10 ms), downloaded on demand
58
+ /// (GxNsStudioPack: SHA-256 compiled in, URL from config).
59
+ /// Core ML mlprogram iOS16: studio needs iOS 16+.
60
+ enum GxNsStudioEngines {
61
+ static let bundledModelName = "gxns_dfn3"
62
+ /// SHA-256 of the release dfn3_std_int8.mlpackage.zip the bundled model was compiled from.
63
+ static let bundledModelSha256 = "29c4d6b4951d10123798bafe7560de993f4b712ccf8f9dc269cce88487f9485b"
64
+ static let bundledLatency: Int32 = 1440 // 30 ms at 48 kHz (10 ms window overlap + 20 ms lookahead)
65
+
66
+ /// URL of the bundled compiled model, if it was shipped.
67
+ static func bundledModelURL() -> URL? {
68
+ var bundles: [Bundle] = []
69
+ #if SWIFT_PACKAGE
70
+ bundles.append(Bundle.module)
71
+ #endif
72
+ for base in [Bundle(for: GxNsStudioBox.self), Bundle.main] {
73
+ if let sub = base.url(forResource: "gravix_rtc_ns", withExtension: "bundle"), let b = Bundle(url: sub) {
74
+ bundles.append(b)
75
+ }
76
+ bundles.append(base)
77
+ }
78
+ for bundle in bundles {
79
+ if let url = bundle.url(forResource: bundledModelName, withExtension: "mlmodelc") { return url }
80
+ if let url = bundle.url(forResource: bundledModelName, withExtension: "mlmodelc", subdirectory: "ns") { return url }
81
+ }
82
+ return nil
83
+ }
84
+
85
+ /// Loads the bundled standard engine. Off the audio thread.
86
+ static func loadBundled(computeUnits: String?) -> (engine: GxNsStudioEngine?, reason: String) {
87
+ guard #available(iOS 16.0, macOS 13.0, *) else { return (nil, "static_old_os") }
88
+ guard let url = bundledModelURL() else { return (nil, "dfn3_not_bundled") }
89
+ do {
90
+ let e = try GxNsDfn3CoreML(compiledModel: url, name: "dfn3-std-coreml", modelSha256: bundledModelSha256,
91
+ latencySamples: bundledLatency, computeUnits: units(computeUnits))
92
+ return (e, "ok")
93
+ } catch {
94
+ return (nil, "dfn3_load_failed")
95
+ }
96
+ }
97
+
98
+ /// Loads a compiled downloaded pack model. Off the audio thread.
99
+ static func loadCompiled(_ url: URL, spec: GxNsStudioPack.Spec, computeUnits: String?) -> (engine: GxNsStudioEngine?, reason: String) {
100
+ guard #available(iOS 16.0, macOS 13.0, *) else { return (nil, "static_old_os") }
101
+ do {
102
+ let e = try GxNsDfn3CoreML(compiledModel: url, name: spec.id, modelSha256: spec.sha256,
103
+ latencySamples: spec.latencySamples, computeUnits: units(computeUnits))
104
+ return (e, "ok")
105
+ } catch {
106
+ return (nil, "pack_load_failed")
107
+ }
108
+ }
109
+
110
+ #if canImport(CoreML)
111
+ static func units(_ s: String?) -> MLComputeUnits {
112
+ switch s {
113
+ case "cpuAndNeuralEngine": if #available(iOS 16.0, macOS 13.0, *) { return .cpuAndNeuralEngine } else { return .cpuOnly }
114
+ case "cpuAndGpu": return .cpuAndGPU
115
+ case "all": return .all
116
+ default: return .cpuOnly // spike: CPU_ONLY fastest; ANE jitter unmeasured (Phase 5)
117
+ }
118
+ }
119
+ #endif
120
+ }
121
+
122
+ /// First-run benchmark (plan §4): 20 warm-up + 200 timed blocks on a
123
+ /// background thread while RNNoise keeps running; the engine is attached only
124
+ /// if p95 < the limit and the output is sane (corrupt model check).
125
+ enum GxNsBenchmark {
126
+ struct Result {
127
+ let p95Us: Int
128
+ let maxUs: Int
129
+ let outputOk: Bool
130
+ let frames: Int
131
+ var quietInDb: Double = 0
132
+ var quietOutDb: Double = 0
133
+ }
134
+
135
+ /// The synthetic speech-like block generator (voiced harmonic stack +
136
+ /// white noise, ~-20 dBFS before `scale`).
137
+ private struct Gen {
138
+ var seed: UInt32 = 0x9E37_79B9
139
+ var phase: Double = 0
140
+ mutating func fill(_ x: inout [Float], scale: Double) {
141
+ for k in 0 ..< x.count {
142
+ seed = seed &* 1_664_525 &+ 1_013_904_223
143
+ let noise = (Double(seed >> 8) / Double(1 << 24) - 0.5) * 0.1
144
+ phase += 2 * Double.pi * 180 / 48000
145
+ let voiced = 0.06 * (sin(phase) + 0.5 * sin(2 * phase) + 0.25 * sin(3 * phase))
146
+ x[k] = Float((voiced + noise) * scale)
147
+ }
148
+ }
149
+ }
150
+
151
+ /// Quiet-mic check (device run 2026-10-21: DFN3 erased a quiet iPhone mic):
152
+ /// speech-like input at -45 dBFS, lifted by the core's pre-gain for that
153
+ /// level, must keep its energy through the engine (out >= in - 6 dB).
154
+ static func quietCheck(_ engine: GxNsStudioEngine, blocks: Int = 150) -> (inDb: Double, outDb: Double, ok: Bool) {
155
+ let n = Int(GX_NS_BLOCK)
156
+ var input = [Float](repeating: 0, count: n)
157
+ var output = [Float](repeating: 0, count: n)
158
+ // the generator's RMS at scale 1 (measured once over 1 s)
159
+ var probe = Gen()
160
+ var acc = 0.0
161
+ for _ in 0 ..< 100 { probe.fill(&input, scale: 1); for v in input { acc += Double(v) * Double(v) } }
162
+ let rms1 = 10 * log10(acc / Double(100 * n) + 1e-20)
163
+ let quietDb = -45.0
164
+ let scaleDb = quietDb - rms1 + Double(gx_ns_pregain_for_level(Float(quietDb)))
165
+ let scale = pow(10, scaleDb / 20)
166
+ var gen = Gen()
167
+ var ie = 0.0, oe = 0.0
168
+ engine.reset()
169
+ for i in 0 ..< blocks {
170
+ gen.fill(&input, scale: scale)
171
+ let rc = input.withUnsafeBufferPointer { inp in
172
+ output.withUnsafeMutableBufferPointer { out in engine.process(out.baseAddress!, inp.baseAddress!, Int32(n)) }
173
+ }
174
+ if rc != 0 { engine.reset(); return (0, -120, false) }
175
+ if i >= 10 { // past the engine's latency
176
+ for k in 0 ..< n {
177
+ ie += Double(input[k]) * Double(input[k])
178
+ oe += Double(output[k]) * Double(output[k])
179
+ }
180
+ }
181
+ }
182
+ engine.reset()
183
+ let cnt = Double((blocks - 10) * n)
184
+ let inDb = 10 * log10(ie / cnt + 1e-20), outDb = 10 * log10(oe / cnt + 1e-20)
185
+ return (inDb, outDb, outDb.isFinite && outDb >= inDb - 6)
186
+ }
187
+
188
+ static func run(_ engine: GxNsStudioEngine, warmup: Int = 20, frames: Int = 200) -> Result {
189
+ let n = Int(GX_NS_BLOCK)
190
+ var input = [Float](repeating: 0, count: n)
191
+ var output = [Float](repeating: 0, count: n)
192
+ var times = [Int]()
193
+ times.reserveCapacity(frames)
194
+ var seed: UInt32 = 0x9E37_79B9
195
+ var phase: Double = 0
196
+ var inEnergy: Double = 0
197
+ var outEnergy: Double = 0
198
+ var finite = true
199
+ engine.reset()
200
+ for i in 0 ..< (warmup + frames) {
201
+ // Voiced-like harmonic stack + white noise (~-20 dBFS): the real
202
+ // speech clip arrives with the pack (Phase 3).
203
+ for k in 0 ..< n {
204
+ seed = seed &* 1_664_525 &+ 1_013_904_223
205
+ let noise = (Double(seed >> 8) / Double(1 << 24) - 0.5) * 0.1
206
+ phase += 2 * Double.pi * 180 / 48000
207
+ let voiced = 0.06 * (sin(phase) + 0.5 * sin(2 * phase) + 0.25 * sin(3 * phase))
208
+ input[k] = Float(voiced + noise)
209
+ }
210
+ let t0 = DispatchTime.now().uptimeNanoseconds
211
+ let rc = input.withUnsafeBufferPointer { inp in
212
+ output.withUnsafeMutableBufferPointer { out in
213
+ engine.process(out.baseAddress!, inp.baseAddress!, Int32(n))
214
+ }
215
+ }
216
+ let us = Int((DispatchTime.now().uptimeNanoseconds - t0) / 1000)
217
+ if rc != 0 { return Result(p95Us: Int.max, maxUs: us, outputOk: false, frames: i) }
218
+ if i >= warmup {
219
+ times.append(us)
220
+ for k in 0 ..< n {
221
+ let o = Double(output[k])
222
+ if !o.isFinite { finite = false }
223
+ outEnergy += o * o
224
+ inEnergy += Double(input[k]) * Double(input[k])
225
+ }
226
+ }
227
+ }
228
+ engine.reset()
229
+ times.sort()
230
+ let p95 = times.isEmpty ? Int.max : times[min(times.count - 1, Int(Double(times.count) * 0.95))]
231
+ // Sane output: finite, not silent, not louder than the input + 6 dB.
232
+ let ratio = inEnergy > 0 ? outEnergy / inEnergy : 0
233
+ let q = quietCheck(engine)
234
+ let ok = finite && ratio > 1e-6 && ratio < 4 && q.ok
235
+ return Result(p95Us: p95, maxUs: times.last ?? 0, outputOk: ok, frames: frames, quietInDb: q.inDb, quietOutDb: q.outDb)
236
+ }
237
+ }
@@ -0,0 +1,212 @@
1
+ // Copyright (c) 2024-2026 Gravity Compile. MIT License; see LICENSE.
2
+
3
+ import Compression
4
+ import CryptoKit
5
+ import Foundation
6
+ #if canImport(CoreML)
7
+ import CoreML
8
+ #endif
9
+
10
+ /// Downloadable studio pack (DFN3 low-latency, Core ML) — plan §3 Phase 3 item 16.
11
+ ///
12
+ /// The URL is configuration (`studioLlUrl`); the SHA-256 and size are compiled
13
+ /// into the SDK (release manifest `download/ll/manifest.json`), so a CDN or
14
+ /// app-provided file can only ever deliver this exact model. Flow:
15
+ /// download -> verify size + SHA-256 -> unzip (.mlpackage) -> MLModel.compileModel
16
+ /// -> cache `<Application Support>/gravix_ns/<sha>/model.mlmodelc`; the next
17
+ /// run uses the cache without network.
18
+ enum GxNsStudioPack {
19
+ struct Spec {
20
+ let id: String
21
+ let sha256: String
22
+ let bytes: Int
23
+ let latencySamples: Int32
24
+ }
25
+
26
+ /// dfn3_ll_int8.mlpackage.zip, release 0.1.0-spike (2026-10-21).
27
+ static let ll = Spec(
28
+ id: "dfn3-ll-coreml-int8",
29
+ sha256: "293304adbdde9165585babb31407af7fda87e2c10677873f3f44de9d22342168",
30
+ bytes: 9_044_104,
31
+ latencySamples: 480
32
+ )
33
+
34
+ enum Download: String {
35
+ case never, unmeteredIdle, any
36
+ }
37
+
38
+ static func cacheRoot() throws -> URL {
39
+ let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask,
40
+ appropriateFor: nil, create: true)
41
+ let dir = base.appendingPathComponent("gravix_ns", isDirectory: true)
42
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
43
+ var values = URLResourceValues()
44
+ values.isExcludedFromBackup = true
45
+ var d = dir
46
+ try? d.setResourceValues(values)
47
+ return dir
48
+ }
49
+
50
+ /// Compiled model already in the cache?
51
+ static func cachedModel(_ spec: Spec) -> URL? {
52
+ guard let root = try? cacheRoot() else { return nil }
53
+ let url = root.appendingPathComponent(spec.sha256, isDirectory: true).appendingPathComponent("model.mlmodelc")
54
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
55
+ }
56
+
57
+ /// Downloads (if allowed), verifies, unzips, compiles and caches. Blocking:
58
+ /// call on a background queue. `remote` may be https:// or file://.
59
+ @available(iOS 16.0, macOS 13.0, *)
60
+ static func ensure(_ spec: Spec, remote: URL?, policy: Download,
61
+ log: (String) -> Void) throws -> URL {
62
+ if let cached = cachedModel(spec) { log("pack src=cache sha=ok id=\(spec.id)"); return cached }
63
+ guard policy != .never else { throw error("download_never") }
64
+ guard let remote else { throw error("no_url") }
65
+ let t0 = Date()
66
+ let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("gxns-\(UUID().uuidString)", isDirectory: true)
67
+ try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
68
+ defer { try? FileManager.default.removeItem(at: tmp) }
69
+
70
+ let zip = tmp.appendingPathComponent("pack.zip")
71
+ try fetch(remote, to: zip, unmeteredOnly: policy == .unmeteredIdle)
72
+ try verify(zip, spec)
73
+ let unpacked = tmp.appendingPathComponent("unzipped", isDirectory: true)
74
+ try GxNsZip.extract(zip, to: unpacked)
75
+ guard let pkg = try FileManager.default.contentsOfDirectory(at: unpacked, includingPropertiesForKeys: nil)
76
+ .first(where: { $0.pathExtension == "mlpackage" })
77
+ else { throw error("no_mlpackage") }
78
+ #if canImport(CoreML)
79
+ let compiled = try MLModel.compileModel(at: pkg)
80
+ #else
81
+ throw error("no_coreml")
82
+ #endif
83
+ let dstDir = try cacheRoot().appendingPathComponent(spec.sha256, isDirectory: true)
84
+ try? FileManager.default.removeItem(at: dstDir)
85
+ try FileManager.default.createDirectory(at: dstDir, withIntermediateDirectories: true)
86
+ let dst = dstDir.appendingPathComponent("model.mlmodelc")
87
+ try FileManager.default.moveItem(at: compiled, to: dst)
88
+ log("pack src=\(remote.isFileURL ? "file" : "cdn") sha=ok id=\(spec.id) bytes=\(spec.bytes) +\(Int(Date().timeIntervalSince(t0) * 1000))ms")
89
+ return dst
90
+ }
91
+
92
+ static func verify(_ file: URL, _ spec: Spec) throws {
93
+ let size = (try FileManager.default.attributesOfItem(atPath: file.path)[.size] as? NSNumber)?.intValue ?? -1
94
+ guard size == spec.bytes else { throw error("size_mismatch got=\(size)") }
95
+ guard try sha256(file) == spec.sha256 else { throw error("sha_mismatch") }
96
+ }
97
+
98
+ static func sha256(_ file: URL) throws -> String {
99
+ let h = try FileHandle(forReadingFrom: file)
100
+ defer { try? h.close() }
101
+ var hasher = SHA256()
102
+ while true {
103
+ let chunk = h.readData(ofLength: 1 << 20)
104
+ if chunk.isEmpty { break }
105
+ hasher.update(data: chunk)
106
+ }
107
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
108
+ }
109
+
110
+ private static func fetch(_ remote: URL, to dst: URL, unmeteredOnly: Bool) throws {
111
+ if remote.isFileURL {
112
+ try FileManager.default.copyItem(at: remote, to: dst)
113
+ return
114
+ }
115
+ guard remote.scheme == "https" else { throw error("https_only") }
116
+ let cfg = URLSessionConfiguration.ephemeral
117
+ cfg.allowsExpensiveNetworkAccess = !unmeteredOnly
118
+ cfg.allowsConstrainedNetworkAccess = !unmeteredOnly
119
+ cfg.timeoutIntervalForResource = 300
120
+ let session = URLSession(configuration: cfg)
121
+ defer { session.finishTasksAndInvalidate() }
122
+ let done = DispatchSemaphore(value: 0)
123
+ var failure: Error?
124
+ session.downloadTask(with: remote) { tmp, resp, err in
125
+ defer { done.signal() }
126
+ if let err { failure = err; return }
127
+ guard let http = resp as? HTTPURLResponse, http.statusCode == 200, let tmp else {
128
+ failure = GxNsStudioPack.error("http_\((resp as? HTTPURLResponse)?.statusCode ?? -1)"); return
129
+ }
130
+ do { try FileManager.default.moveItem(at: tmp, to: dst) } catch { failure = error }
131
+ }.resume()
132
+ done.wait()
133
+ if let failure { throw failure }
134
+ }
135
+
136
+ static func error(_ msg: String) -> NSError {
137
+ NSError(domain: "GravixNS.pack", code: 1, userInfo: [NSLocalizedDescriptionKey: msg])
138
+ }
139
+ }
140
+
141
+ /// Minimal .zip reader (stored + deflate, no zip64/encryption) for the
142
+ /// studio pack; iOS has no public unzip API. Rejects absolute paths and "..".
143
+ enum GxNsZip {
144
+ static func extract(_ zip: URL, to dir: URL) throws {
145
+ let data = try Data(contentsOf: zip, options: .mappedIfSafe)
146
+ func u16(_ o: Int) -> Int { Int(data[o]) | Int(data[o + 1]) << 8 }
147
+ func u32(_ o: Int) -> Int { u16(o) | u16(o + 2) << 16 }
148
+ // End of central directory (last 22 + comment bytes).
149
+ var eocd = -1
150
+ var i = data.count - 22
151
+ while i >= max(0, data.count - 22 - 65535) {
152
+ if u32(i) == 0x0605_4B50 { eocd = i; break }
153
+ i -= 1
154
+ }
155
+ guard eocd >= 0 else { throw GxNsStudioPack.error("zip_no_eocd") }
156
+ let entries = u16(eocd + 10)
157
+ var p = u32(eocd + 16)
158
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
159
+ for _ in 0 ..< entries {
160
+ guard p + 46 <= data.count, u32(p) == 0x0201_4B50 else { throw GxNsStudioPack.error("zip_bad_cd") }
161
+ let flags = u16(p + 8), method = u16(p + 10)
162
+ let csize = u32(p + 20), usize = u32(p + 24)
163
+ let nlen = u16(p + 28), xlen = u16(p + 30), clen = u16(p + 32)
164
+ let local = u32(p + 42)
165
+ guard let name = String(data: data[(p + 46) ..< (p + 46 + nlen)], encoding: .utf8) else {
166
+ throw GxNsStudioPack.error("zip_bad_name")
167
+ }
168
+ p += 46 + nlen + xlen + clen
169
+ guard flags & 1 == 0 else { throw GxNsStudioPack.error("zip_encrypted") }
170
+ guard !name.hasPrefix("/"), !name.split(separator: "/").contains("..") else {
171
+ throw GxNsStudioPack.error("zip_bad_path")
172
+ }
173
+ if name.hasPrefix("__MACOSX/") || name.split(separator: "/").last?.hasPrefix("._") == true { continue }
174
+ let target = dir.appendingPathComponent(name)
175
+ if name.hasSuffix("/") {
176
+ try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
177
+ continue
178
+ }
179
+ try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
180
+ guard u32(local) == 0x0403_4B50 else { throw GxNsStudioPack.error("zip_bad_local") }
181
+ let start = local + 30 + u16(local + 26) + u16(local + 28)
182
+ guard start + csize <= data.count else { throw GxNsStudioPack.error("zip_truncated") }
183
+ let body = data[start ..< (start + csize)]
184
+ let out: Data
185
+ switch method {
186
+ case 0:
187
+ out = Data(body)
188
+ case 8:
189
+ out = try inflate(Data(body), size: usize)
190
+ default:
191
+ throw GxNsStudioPack.error("zip_method_\(method)")
192
+ }
193
+ guard out.count == usize else { throw GxNsStudioPack.error("zip_size") }
194
+ try out.write(to: target)
195
+ }
196
+ }
197
+
198
+ /// Raw DEFLATE (COMPRESSION_ZLIB is RFC 1951 without a header).
199
+ private static func inflate(_ src: Data, size: Int) throws -> Data {
200
+ if size == 0 { return Data() }
201
+ var dst = Data(count: size)
202
+ let n = dst.withUnsafeMutableBytes { d in
203
+ src.withUnsafeBytes { s in
204
+ compression_decode_buffer(d.bindMemory(to: UInt8.self).baseAddress!, size,
205
+ s.bindMemory(to: UInt8.self).baseAddress!, src.count,
206
+ nil, COMPRESSION_ZLIB)
207
+ }
208
+ }
209
+ guard n == size else { throw GxNsStudioPack.error("zip_inflate") }
210
+ return dst
211
+ }
212
+ }