react-native-webgpu 0.21.4 → 0.23.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 (170) hide show
  1. package/README.md +15 -2
  2. package/android/CMakeLists.txt +10 -8
  3. package/android/build.gradle +111 -20
  4. package/android/cpp/AndroidAnimationFrameSource.h +136 -0
  5. package/android/cpp/AndroidPlatformContext.h +55 -0
  6. package/android/cpp/cpp-adapter.cpp +148 -2
  7. package/android/src/main/java/com/webgpu/WebGPUModule.java +21 -4
  8. package/android/src/main/java/com/webgpu/WebGPUNativeBufferView.java +370 -0
  9. package/android/src/main/java/com/webgpu/WebGPUNativeBufferViewManager.java +56 -0
  10. package/android/src/main/java/com/webgpu/WebGPUTextureView.java +21 -0
  11. package/android/src/main/java/com/webgpu/WebGPUVideoPlayer.java +1 -1
  12. package/android/src/main/java/com/webgpu/WebGPUView.java +19 -3
  13. package/android/src/main/java/com/webgpu/WebGPUViewManager.java +10 -0
  14. package/android/src/main/java/com/webgpu/WebGPUViewPackage.java +2 -2
  15. package/android/src/newarch/com/webgpu/WebGPUNativeBufferViewManagerSpec.java +24 -0
  16. package/apple/AppleAnimationFrameSource.mm +208 -0
  17. package/apple/ApplePlatformContext.h +6 -0
  18. package/apple/ApplePlatformContext.mm +73 -0
  19. package/apple/MetalLayerColorSpace.h +17 -0
  20. package/apple/MetalLayerColorSpace.mm +36 -57
  21. package/apple/MetalView.h +4 -0
  22. package/apple/MetalView.mm +14 -0
  23. package/apple/NativeBufferFenceWait.mm +88 -0
  24. package/apple/RNWGUIKit.h +4 -1
  25. package/apple/WebGPUModule.mm +26 -1
  26. package/apple/WebGPUNativeBufferView.h +15 -0
  27. package/apple/WebGPUNativeBufferView.mm +200 -0
  28. package/apple/WebGPUView.h +2 -1
  29. package/apple/WebGPUView.mm +6 -0
  30. package/binaries.json +156 -0
  31. package/cpp/jsi/NativeObject.h +12 -5
  32. package/cpp/rnwgpu/AnimationFrames.cpp +576 -0
  33. package/cpp/rnwgpu/AnimationFrames.h +233 -0
  34. package/cpp/rnwgpu/CanvasColorSpace.h +16 -0
  35. package/cpp/rnwgpu/NativeBufferViewRegistry.cpp +396 -0
  36. package/cpp/rnwgpu/NativeBufferViewRegistry.h +163 -0
  37. package/cpp/rnwgpu/PlatformContext.h +20 -0
  38. package/cpp/rnwgpu/RNWebGPUManager.cpp +17 -4
  39. package/cpp/rnwgpu/SurfaceRegistry.h +26 -30
  40. package/cpp/rnwgpu/api/GPUAdapter.cpp +1 -1
  41. package/cpp/rnwgpu/api/GPUCanvasContext.cpp +41 -3
  42. package/cpp/rnwgpu/api/GPUCanvasContext.h +7 -3
  43. package/cpp/rnwgpu/api/GPUDevice.cpp +16 -131
  44. package/cpp/rnwgpu/api/GPUDevice.h +0 -18
  45. package/cpp/rnwgpu/api/GPUExternalTexture.cpp +35 -3
  46. package/cpp/rnwgpu/api/GPUExternalTexture.h +4 -4
  47. package/cpp/rnwgpu/api/GPUQueue.cpp +1 -1
  48. package/cpp/rnwgpu/api/GPUQueue.h +1 -1
  49. package/cpp/rnwgpu/api/GPUSharedFence.h +1 -0
  50. package/cpp/rnwgpu/api/GPUSharedTextureMemory.cpp +11 -5
  51. package/cpp/rnwgpu/api/GPUSharedTextureMemory.h +21 -2
  52. package/cpp/rnwgpu/api/GPUTexture.h +18 -0
  53. package/cpp/rnwgpu/api/NativeFrameFeatures.h +1 -1
  54. package/cpp/rnwgpu/api/NativeFrameImport.cpp +20 -17
  55. package/cpp/rnwgpu/api/NativeFrameImport.h +31 -20
  56. package/cpp/rnwgpu/api/RNWebGPU.h +201 -3
  57. package/cpp/rnwgpu/api/VideoFrame.h +5 -4
  58. package/cpp/rnwgpu/api/VideoFrameBlit.h +2 -2
  59. package/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h +21 -14
  60. package/cpp/rnwgpu/api/descriptors/GPUImageCopyExternalImage.h +1 -1
  61. package/cpp/rnwgpu/api/descriptors/GPUSharedTextureMemoryDescriptor.h +17 -9
  62. package/cpp/rnwgpu/async/RuntimeContext.cpp +21 -4
  63. package/cpp/rnwgpu/async/RuntimeContext.h +8 -0
  64. package/lib/commonjs/Canvas.js +33 -1
  65. package/lib/commonjs/Canvas.js.map +1 -1
  66. package/lib/commonjs/NativeBufferView.js +131 -0
  67. package/lib/commonjs/NativeBufferView.js.map +1 -0
  68. package/lib/commonjs/NativeBufferViewNativeComponent.js +10 -0
  69. package/lib/commonjs/NativeBufferViewNativeComponent.js.map +1 -0
  70. package/lib/commonjs/WebGPUViewNativeComponent.js.map +1 -1
  71. package/lib/commonjs/WebGPUViewNativeComponent.web.js +2 -0
  72. package/lib/commonjs/WebGPUViewNativeComponent.web.js.map +1 -1
  73. package/lib/commonjs/animationFrame.js +91 -0
  74. package/lib/commonjs/animationFrame.js.map +1 -0
  75. package/lib/commonjs/index.js +16 -1
  76. package/lib/commonjs/index.js.map +1 -1
  77. package/lib/commonjs/main/index.js +12 -0
  78. package/lib/commonjs/main/index.js.map +1 -1
  79. package/lib/commonjs/mock.js +30 -1
  80. package/lib/commonjs/mock.js.map +1 -1
  81. package/lib/commonjs/video.js +14 -4
  82. package/lib/commonjs/video.js.map +1 -1
  83. package/lib/module/Canvas.js +33 -1
  84. package/lib/module/Canvas.js.map +1 -1
  85. package/lib/module/NativeBufferView.js +122 -0
  86. package/lib/module/NativeBufferView.js.map +1 -0
  87. package/lib/module/NativeBufferViewNativeComponent.js +4 -0
  88. package/lib/module/NativeBufferViewNativeComponent.js.map +1 -0
  89. package/lib/module/WebGPUViewNativeComponent.js.map +1 -1
  90. package/lib/module/WebGPUViewNativeComponent.web.js +2 -0
  91. package/lib/module/WebGPUViewNativeComponent.web.js.map +1 -1
  92. package/lib/module/animationFrame.js +83 -0
  93. package/lib/module/animationFrame.js.map +1 -0
  94. package/lib/module/index.js +1 -0
  95. package/lib/module/index.js.map +1 -1
  96. package/lib/module/main/index.js +1 -0
  97. package/lib/module/main/index.js.map +1 -1
  98. package/lib/module/mock.js +21 -0
  99. package/lib/module/mock.js.map +1 -1
  100. package/lib/module/video.js +11 -2
  101. package/lib/module/video.js.map +1 -1
  102. package/lib/typescript/lib/commonjs/Canvas.d.ts +3 -1
  103. package/lib/typescript/lib/commonjs/Canvas.d.ts.map +1 -1
  104. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts +48 -0
  105. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts.map +1 -0
  106. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts +5 -0
  107. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts.map +1 -0
  108. package/lib/typescript/lib/commonjs/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  109. package/lib/typescript/lib/commonjs/animationFrame.d.ts +54 -0
  110. package/lib/typescript/lib/commonjs/animationFrame.d.ts.map +1 -0
  111. package/lib/typescript/lib/commonjs/index.d.ts +2 -0
  112. package/lib/typescript/lib/commonjs/mock.d.ts +12 -0
  113. package/lib/typescript/lib/commonjs/mock.d.ts.map +1 -1
  114. package/lib/typescript/lib/commonjs/video.d.ts +3 -2
  115. package/lib/typescript/lib/commonjs/video.d.ts.map +1 -1
  116. package/lib/typescript/lib/module/Canvas.d.ts +3 -1
  117. package/lib/typescript/lib/module/Canvas.d.ts.map +1 -1
  118. package/lib/typescript/lib/module/NativeBufferView.d.ts +14 -0
  119. package/lib/typescript/lib/module/NativeBufferView.d.ts.map +1 -0
  120. package/lib/typescript/lib/module/NativeBufferViewNativeComponent.d.ts +3 -0
  121. package/lib/typescript/lib/module/NativeBufferViewNativeComponent.d.ts.map +1 -0
  122. package/lib/typescript/lib/module/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  123. package/lib/typescript/lib/module/animationFrame.d.ts +3 -0
  124. package/lib/typescript/lib/module/animationFrame.d.ts.map +1 -0
  125. package/lib/typescript/lib/module/index.d.ts +1 -0
  126. package/lib/typescript/lib/module/main/index.d.ts +1 -0
  127. package/lib/typescript/lib/module/mock.d.ts +14 -0
  128. package/lib/typescript/lib/module/mock.d.ts.map +1 -1
  129. package/lib/typescript/lib/module/video.d.ts +3 -2
  130. package/lib/typescript/lib/module/video.d.ts.map +1 -1
  131. package/lib/typescript/src/Canvas.d.ts +17 -1
  132. package/lib/typescript/src/Canvas.d.ts.map +1 -1
  133. package/lib/typescript/src/NativeBufferView.d.ts +99 -0
  134. package/lib/typescript/src/NativeBufferView.d.ts.map +1 -0
  135. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts +13 -0
  136. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts.map +1 -0
  137. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts +2 -0
  138. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts.map +1 -1
  139. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts +2 -0
  140. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  141. package/lib/typescript/src/animationFrame.d.ts +59 -0
  142. package/lib/typescript/src/animationFrame.d.ts.map +1 -0
  143. package/lib/typescript/src/index.d.ts +18 -8
  144. package/lib/typescript/src/index.d.ts.map +1 -1
  145. package/lib/typescript/src/main/index.d.ts +1 -0
  146. package/lib/typescript/src/main/index.d.ts.map +1 -1
  147. package/lib/typescript/src/mock.d.ts +11 -0
  148. package/lib/typescript/src/mock.d.ts.map +1 -1
  149. package/lib/typescript/src/types.d.ts +32 -31
  150. package/lib/typescript/src/types.d.ts.map +1 -1
  151. package/lib/typescript/src/video.d.ts +12 -4
  152. package/lib/typescript/src/video.d.ts.map +1 -1
  153. package/package.json +8 -2
  154. package/react-native-webgpu.podspec +1 -1
  155. package/src/Canvas.tsx +67 -1
  156. package/src/NativeBufferView.tsx +199 -0
  157. package/src/NativeBufferViewNativeComponent.ts +20 -0
  158. package/src/WebGPUViewNativeComponent.ts +4 -0
  159. package/src/WebGPUViewNativeComponent.web.ts +6 -0
  160. package/src/animationFrame.ts +82 -0
  161. package/src/index.tsx +45 -39
  162. package/src/main/index.tsx +1 -0
  163. package/src/mock.ts +35 -0
  164. package/src/types.ts +61 -87
  165. package/src/video.ts +20 -7
  166. package/cpp/rnwgpu/api/GPUNativeBufferExternalTexture.h +0 -60
  167. package/cpp/rnwgpu/api/GPUNativeBufferTexture.h +0 -52
  168. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.cpp +0 -144
  169. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.h +0 -143
  170. package/cpp/rnwgpu/api/descriptors/GPUNativeBufferTextureDescriptor.h +0 -55
package/README.md CHANGED
@@ -1,8 +1,21 @@
1
1
  # React Native WebGPU
2
2
 
3
- WebGPU for React Native, powered by Dawn.
3
+ [![CI](https://github.com/wcandillon/react-native-webgpu/actions/workflows/ci.yml/badge.svg)](https://github.com/wcandillon/react-native-webgpu/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/react-native-webgpu.svg?style=flat)](https://www.npmjs.com/package/react-native-webgpu)
4
5
 
5
- [wcandillon.github.io/react-native-webgpu](https://wcandillon.github.io/react-native-webgpu/)
6
+ <div align="center">
7
+ <img alt="React Native WebGPU Logo" src="https://firebasestorage.googleapis.com/v0/b/start-react-native.appspot.com/o/webgpu.png?alt=media&token=98a41d89-3915-468c-8c8d-9f41c8110f94" width="450">
8
+ </div>
9
+
10
+ WebGPU for React Native, powered by Dawn. See [Documentation](https://wcandillon.github.io/react-native-webgpu/).
11
+
12
+ ## Platinum Sponsors
13
+
14
+ <div align="center">
15
+ <a href="https://expo.dev/" target="_blank" rel="sponsored">
16
+ <img width="80" height="80" alt="Expo" src="https://github.com/user-attachments/assets/33f7d710-2bcc-444e-b1dd-d1288c2a0bc4" />
17
+ </a>
18
+ </div>
6
19
 
7
20
  ## Getting Started
8
21
 
@@ -17,15 +17,16 @@ else()
17
17
  add_definitions(-DRNF_ENABLE_LOGS=0)
18
18
  endif()
19
19
 
20
- # Dawn comes from the react-native-webgpu-dawn npm package (DAWN_DIR is passed
21
- # by build.gradle): the shared library per ABI and the headers.
20
+ # Dawn is in DAWN_DIR, passed by build.gradle: the directory its
21
+ # prepareDawnBinaries task extracts the released archives into, with the shared
22
+ # library per ABI and the headers under include/. It is not required to be
23
+ # there yet: Android Studio configures this project when it syncs, before any
24
+ # task has run. Gradle is what guarantees the files, and verifies them, before
25
+ # the library is built.
22
26
  if(NOT DAWN_DIR)
23
- message(FATAL_ERROR "react-native-webgpu: DAWN_DIR is not set (the react-native-webgpu-dawn package directory)")
24
- endif()
25
- set (WEBGPU_LIBS_PATH "${DAWN_DIR}/libs/android/${ANDROID_ABI}")
26
- if(NOT EXISTS "${WEBGPU_LIBS_PATH}/libwebgpu_dawn.so")
27
- message(FATAL_ERROR "react-native-webgpu: libwebgpu_dawn.so not found at ${WEBGPU_LIBS_PATH}. Reinstall dependencies (yarn install / npm install).")
27
+ message(FATAL_ERROR "react-native-webgpu: DAWN_DIR is not set (the directory holding the Dawn binaries)")
28
28
  endif()
29
+ set (WEBGPU_LIBS_PATH "${DAWN_DIR}/${ANDROID_ABI}")
29
30
 
30
31
  find_package(ReactAndroid REQUIRED CONFIG)
31
32
  find_package(fbjni REQUIRED CONFIG)
@@ -46,7 +47,6 @@ add_library(${PACKAGE_NAME} SHARED
46
47
  ../cpp/rnwgpu/api/GPUSharedFence.cpp
47
48
  ../cpp/rnwgpu/api/GPUSharedTextureMemory.cpp
48
49
  ../cpp/rnwgpu/api/GPUExternalTexture.cpp
49
- ../cpp/rnwgpu/api/GPUNativeBufferWrapper.cpp
50
50
  ../cpp/rnwgpu/api/NativeFrameImport.cpp
51
51
  ../cpp/rnwgpu/api/GPURenderBundleEncoder.cpp
52
52
  ../cpp/rnwgpu/api/GPURenderPassEncoder.cpp
@@ -56,6 +56,8 @@ add_library(${PACKAGE_NAME} SHARED
56
56
  ../cpp/rnwgpu/api/GPUComputePipeline.cpp
57
57
  ../cpp/rnwgpu/api/GPUCanvasContext.cpp
58
58
  ../cpp/rnwgpu/DawnBlobCache.cpp
59
+ ../cpp/rnwgpu/NativeBufferViewRegistry.cpp
60
+ ../cpp/rnwgpu/AnimationFrames.cpp
59
61
  ../cpp/rnwgpu/RNWebGPUManager.cpp
60
62
  ../cpp/rnwgpu/WebGPURuntime.cpp
61
63
  ../cpp/jsi/Promise.cpp
@@ -45,27 +45,27 @@ static def findNodeModules(baseDir) {
45
45
 
46
46
  def nodeModules = findNodeModules(projectDir)
47
47
 
48
- // Resolve a node package directory using Node's own module resolution
49
- // (mirrors `require.resolve(pkg/package.json)`).
50
- static def resolveNodePackage(packageName, baseDir) {
51
- def script = "process.stdout.write(require('path').dirname(require.resolve('${packageName}/package.json')))"
52
- def proc = ["node", "-e", script].execute(null, baseDir)
53
- proc.waitFor()
54
- if (proc.exitValue() != 0) {
55
- throw new GradleException(
56
- "react-native-webgpu: Could not resolve the '${packageName}' package. " +
57
- "Make sure dependencies are installed (yarn install / npm install).\n" + proc.err.text
58
- )
59
- }
60
- return proc.text.trim()
61
- }
48
+ // Dawn, the WebGPU implementation, is an asset of the GitHub release
49
+ // binaries-<version> of react-native-skia: one archive per ABI holding
50
+ // <abi>/libwebgpu_dawn.so, and one holding the headers under include/.
51
+ // binaries.json pins that version and the sha256 of every asset. Gradle
52
+ // downloads the archives of the ABIs being built as dependencies (see the
53
+ // repository and prepareDawnBinaries below), so they sit in the Gradle user
54
+ // home cache like any other dependency, and prepareDawnBinaries extracts them
55
+ // into build/binaries. react-native-skia's Graphite backend links the Dawn of
56
+ // the same release, so an app installing both contains exactly one Dawn.
57
+ def binaries = new groovy.json.JsonSlurper().parse(file("${projectDir}/../binaries.json"))
58
+ def dawnDir = file("${buildDir}/binaries")
59
+ logger.warn("react-native-webgpu: Dawn ${binaries.version} in ${dawnDir}")
62
60
 
63
- // Dawn, the WebGPU implementation, ships in the react-native-webgpu-dawn npm
64
- // package this package depends on: libs/android/<abi>/libwebgpu_dawn.so and
65
- // the headers under include/. react-native-skia's Graphite backend links the
66
- // same package, so an app installing both contains exactly one Dawn.
67
- def dawnDir = resolveNodePackage('react-native-webgpu-dawn', projectDir)
68
- logger.warn("react-native-webgpu: Dawn from ${dawnDir}")
61
+ // Where the releases are downloaded from: <url>/binaries-<version>/<asset>.
62
+ // A mirror, or a directory (file:///...) for builds without network access,
63
+ // is set with the reactNativeSkiaBinariesUrl Gradle property or the
64
+ // REACT_NATIVE_SKIA_BINARIES_URL environment variable, the ones
65
+ // react-native-skia reads too.
66
+ def binariesUrl = (project.findProperty('reactNativeSkiaBinariesUrl')
67
+ ?: System.getenv('REACT_NATIVE_SKIA_BINARIES_URL')
68
+ ?: 'https://github.com/wcandillon/react-native-skia/releases/download').toString()
69
69
 
70
70
  def getExtOrDefault(name) {
71
71
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["Wgpu_" + name]
@@ -167,12 +167,103 @@ android {
167
167
  repositories {
168
168
  mavenCentral()
169
169
  google()
170
+ // The assets of the binaries-<version> releases, as a repository: Gradle
171
+ // then caches them in its user home and resolves them offline. Only this
172
+ // group is looked up here, and it is looked up nowhere else.
173
+ exclusiveContent {
174
+ forRepository {
175
+ ivy {
176
+ name = "ReactNativeSkiaBinaries"
177
+ url = uri(binariesUrl)
178
+ patternLayout {
179
+ artifact "binaries-[revision]/[module](-[classifier]).[ext]"
180
+ }
181
+ metadataSources { artifact() }
182
+ }
183
+ }
184
+ filter { includeGroup "react-native-skia-binaries" }
185
+ }
170
186
  }
171
187
 
188
+ configurations {
189
+ dawnBinaries {
190
+ canBeConsumed = false
191
+ transitive = false
192
+ }
193
+ }
194
+
195
+ // sha256 → asset, for the archives this build downloads.
196
+ def binaryChecksums = [:]
197
+ def dawnBinary = { String module, String abi ->
198
+ def name = abi == null ? "${module}.zip".toString() : "${module}-${abi}.zip".toString()
199
+ def asset = binaries.assets[name]
200
+ if (asset == null) {
201
+ throw new GradleException("react-native-webgpu: binaries ${binaries.version} have no ${name}.")
202
+ }
203
+ binaryChecksums[asset.sha256.toString()] = name
204
+ return "react-native-skia-binaries:${module}:${binaries.version}" + (abi == null ? "" : ":${abi}") + "@zip"
205
+ }
172
206
 
173
207
  dependencies {
174
208
  // For < 0.71, this will be from the local maven repo
175
209
  // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
176
210
  //noinspection GradleDynamicVersion
177
211
  implementation "com.facebook.react:react-native:+"
212
+
213
+ dawnBinaries dawnBinary('dawn-headers', null)
214
+ reactNativeArchitectures().each { abi ->
215
+ dawnBinaries dawnBinary('dawn-android', abi)
216
+ }
217
+ }
218
+
219
+ // Extracts the downloaded archives into build/binaries (<abi>/ and include/),
220
+ // where CMake reads them from, once each matches the sha256 binaries.json pins
221
+ // for it.
222
+ def prepareDawnBinaries = tasks.register('prepareDawnBinaries') {
223
+ def archives = configurations.dawnBinaries
224
+ def checksums = binaryChecksums
225
+ def destination = dawnDir
226
+ def version = binaries.version
227
+ inputs.files(archives)
228
+ inputs.property('checksums', checksums)
229
+ outputs.dir(destination)
230
+ doLast {
231
+ destination.deleteDir()
232
+ destination.mkdirs()
233
+ def root = destination.canonicalPath + File.separator
234
+ def pending = new HashMap(checksums)
235
+ archives.files.each { File archive ->
236
+ def digest = java.security.MessageDigest.getInstance('SHA-256')
237
+ archive.eachByte(1 << 20) { buffer, read -> digest.update(buffer, 0, read) }
238
+ def sha256 = digest.digest().encodeHex().toString()
239
+ if (pending.remove(sha256) == null) {
240
+ throw new GradleException(
241
+ "react-native-webgpu: ${archive} (sha256 ${sha256}) is not one of the " +
242
+ "archives of binaries ${version}: its checksum is not in binaries.json. " +
243
+ "Build with --refresh-dependencies to download it again.")
244
+ }
245
+ new java.util.zip.ZipFile(archive).withCloseable { zip ->
246
+ Collections.list(zip.entries()).each { entry ->
247
+ def target = new File(destination, entry.name)
248
+ if (!target.canonicalPath.startsWith(root)) {
249
+ throw new GradleException(
250
+ "react-native-webgpu: ${archive.name} has an entry outside of the archive: ${entry.name}")
251
+ }
252
+ if (entry.directory) {
253
+ target.mkdirs()
254
+ } else {
255
+ target.parentFile.mkdirs()
256
+ zip.getInputStream(entry).withCloseable { input ->
257
+ target.withOutputStream { output -> output << input }
258
+ }
259
+ }
260
+ }
261
+ }
262
+ }
263
+ if (!pending.isEmpty()) {
264
+ throw new GradleException(
265
+ "react-native-webgpu: archives missing from binaries ${version}: ${pending.values().join(', ')}")
266
+ }
267
+ }
178
268
  }
269
+ preBuild.dependsOn(prepareDawnBinaries)
@@ -0,0 +1,136 @@
1
+ #pragma once
2
+
3
+ #include <android/choreographer.h>
4
+ #include <android/log.h>
5
+ #include <android/looper.h>
6
+ #include <dlfcn.h>
7
+ #include <pthread.h>
8
+
9
+ #include <atomic>
10
+ #include <cstdint>
11
+ #include <future>
12
+ #include <memory>
13
+ #include <thread>
14
+
15
+ #include "AnimationFrames.h"
16
+
17
+ namespace rnwgpu {
18
+
19
+ /**
20
+ * The display's frames on Android: an AChoreographer on a looper thread of its
21
+ * own, so that a busy main thread or JS thread never delays them. A request
22
+ * from any thread sets a flag and wakes the looper, which posts one frame
23
+ * callback; the frame time is the choreographer's, on CLOCK_MONOTONIC (the
24
+ * clock of std::chrono::steady_clock). The thread lives as long as the
25
+ * process.
26
+ */
27
+ class AndroidAnimationFrameSource : public AnimationFrameSource {
28
+ public:
29
+ // The process's source, made on first use (its thread then runs for the
30
+ // life of the process); null when the thread gets no choreographer. A
31
+ // reload asks again and gets the same one.
32
+ static std::shared_ptr<AndroidAnimationFrameSource> shared() {
33
+ static std::shared_ptr<AndroidAnimationFrameSource> source = create();
34
+ return source;
35
+ }
36
+
37
+ void requestFrame() override {
38
+ _wanted.store(true, std::memory_order_release);
39
+ ALooper_wake(_looper);
40
+ }
41
+
42
+ private:
43
+ AndroidAnimationFrameSource() = default;
44
+
45
+ static std::shared_ptr<AndroidAnimationFrameSource> create() {
46
+ auto source = std::shared_ptr<AndroidAnimationFrameSource>(
47
+ new AndroidAnimationFrameSource());
48
+ // Shared with the thread, which may still be inside set_value() when
49
+ // get() returns here.
50
+ auto ready = std::make_shared<std::promise<ALooper *>>();
51
+ auto looperFuture = ready->get_future();
52
+ // The thread borrows the source, which shared() keeps for the life of the
53
+ // process (when the thread fails, it returns before this returns).
54
+ auto *raw = source.get();
55
+ std::thread([raw, ready]() { raw->run(*ready); }).detach();
56
+ source->_looper = looperFuture.get();
57
+ if (source->_looper == nullptr) {
58
+ return nullptr;
59
+ }
60
+ return source;
61
+ }
62
+
63
+ using FrameCallback64 = void (*)(int64_t, void *);
64
+ using PostFrameCallback64 = void (*)(AChoreographer *, FrameCallback64,
65
+ void *);
66
+
67
+ void run(std::promise<ALooper *> &ready) {
68
+ pthread_setname_np(pthread_self(), "RNWebGPU Frames");
69
+ ALooper *looper = ALooper_prepare(0);
70
+ _choreographer = AChoreographer_getInstance();
71
+ if (looper == nullptr || _choreographer == nullptr) {
72
+ __android_log_print(ANDROID_LOG_WARN, "RNWebGPU",
73
+ "No choreographer on the animation frame thread: "
74
+ "requestAnimationFrame falls back to the runtime's.");
75
+ ready.set_value(nullptr);
76
+ return;
77
+ }
78
+ ALooper_acquire(looper);
79
+ // API 29; the library builds for API 26.
80
+ _postFrameCallback64 = reinterpret_cast<PostFrameCallback64>(
81
+ dlsym(RTLD_DEFAULT, "AChoreographer_postFrameCallback64"));
82
+ ready.set_value(looper);
83
+ for (;;) {
84
+ ALooper_pollOnce(-1, nullptr, nullptr, nullptr);
85
+ if (_wanted.exchange(false, std::memory_order_acq_rel) && !_posted) {
86
+ post();
87
+ }
88
+ }
89
+ }
90
+
91
+ // Looper thread.
92
+ void post() {
93
+ _posted = true;
94
+ if (_postFrameCallback64 != nullptr) {
95
+ _postFrameCallback64(
96
+ _choreographer,
97
+ [](int64_t frameTimeNanos, void *data) {
98
+ static_cast<AndroidAnimationFrameSource *>(data)->onFrame(
99
+ frameTimeNanos);
100
+ },
101
+ this);
102
+ return;
103
+ }
104
+ #pragma clang diagnostic push
105
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
106
+ // The entry point of API 24: its frame time is a long, 32 bits on a
107
+ // 32-bit device, so the clock is read instead there.
108
+ AChoreographer_postFrameCallback(
109
+ _choreographer,
110
+ [](long frameTimeNanos, void *data) {
111
+ static_cast<AndroidAnimationFrameSource *>(data)->onFrame(
112
+ sizeof(long) >= sizeof(int64_t)
113
+ ? static_cast<int64_t>(frameTimeNanos)
114
+ : AnimationFrameDispatcher::nowNanos());
115
+ },
116
+ this);
117
+ #pragma clang diagnostic pop
118
+ }
119
+
120
+ // Looper thread.
121
+ void onFrame(int64_t frameTimeNanos) {
122
+ _posted = false;
123
+ deliverFrame(frameTimeNanos);
124
+ // A request made while the frame was delivered (on this thread, or
125
+ // another) is in _wanted, and its wake is pending: the loop posts it.
126
+ }
127
+
128
+ ALooper *_looper = nullptr;
129
+ AChoreographer *_choreographer = nullptr;
130
+ PostFrameCallback64 _postFrameCallback64 = nullptr;
131
+ std::atomic<bool> _wanted{false};
132
+ // Looper thread only.
133
+ bool _posted = false;
134
+ };
135
+
136
+ } // namespace rnwgpu
@@ -1,5 +1,6 @@
1
1
  #pragma once
2
2
 
3
+ #include <android/api-level.h>
3
4
  #include <android/bitmap.h>
4
5
  #include <android/data_space.h>
5
6
  #include <android/hardware_buffer.h>
@@ -17,6 +18,7 @@
17
18
 
18
19
  #include "webgpu/webgpu_cpp.h"
19
20
 
21
+ #include "AndroidAnimationFrameSource.h"
20
22
  #include "AndroidColorSpace.h"
21
23
  #include "AndroidVideoPlayer.h"
22
24
  #include "PlatformContext.h"
@@ -424,6 +426,55 @@ public:
424
426
  return handle;
425
427
  }
426
428
 
429
+ // A buffer Dawn imports as a render target (GPU_COLOR_OUTPUT) and HWUI
430
+ // samples (GPU_SAMPLED_IMAGE, Bitmap.wrapHardwareBuffer). Below API 29,
431
+ // where a NativeBufferView reads the pixels back instead, it is CPU
432
+ // readable too; only there, as CPU usage can force a linear layout on some
433
+ // drivers.
434
+ VideoFrameHandle createNativeBuffer(uint32_t width, uint32_t height,
435
+ wgpu::TextureFormat format,
436
+ bool displayP3) override {
437
+ uint32_t ahbFormat;
438
+ switch (format) {
439
+ case wgpu::TextureFormat::RGBA8Unorm:
440
+ ahbFormat = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
441
+ break;
442
+ case wgpu::TextureFormat::RGBA16Float:
443
+ ahbFormat = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
444
+ break;
445
+ default:
446
+ throw std::runtime_error(
447
+ "createNativeBuffer: unsupported format on Android (expected "
448
+ "'rgba8unorm' or 'rgba16float')");
449
+ }
450
+ AHardwareBuffer_Desc desc = {};
451
+ desc.width = width;
452
+ desc.height = height;
453
+ desc.layers = 1;
454
+ desc.format = ahbFormat;
455
+ desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
456
+ AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT;
457
+ if (android_get_device_api_level() < 29) {
458
+ desc.usage |= AHARDWAREBUFFER_USAGE_CPU_READ_RARELY;
459
+ }
460
+ AHardwareBuffer *buffer = nullptr;
461
+ int err = AHardwareBuffer_allocate(&desc, &buffer);
462
+ if (err != 0 || !buffer) {
463
+ throw std::runtime_error(
464
+ "createNativeBuffer: AHardwareBuffer_allocate failed (" +
465
+ std::to_string(err) + ")");
466
+ }
467
+ VideoFrameHandle handle;
468
+ handle.handle = static_cast<void *>(buffer);
469
+ handle.width = width;
470
+ handle.height = height;
471
+ handle.colorSpace.primaries = displayP3
472
+ ? wgpu::ColorSpacePrimariesDawn::DisplayP3
473
+ : wgpu::ColorSpacePrimariesDawn::SRGB;
474
+ handle.deleter = [buffer]() { AHardwareBuffer_release(buffer); };
475
+ return handle;
476
+ }
477
+
427
478
  // The decoder writes its native YUV layout whatever format is requested:
428
479
  // the frames are sampled through importExternalTexture (see
429
480
  // WebGPUVideoPlayer.java).
@@ -464,6 +515,10 @@ public:
464
515
  return result;
465
516
  }
466
517
 
518
+ std::shared_ptr<AnimationFrameSource> makeAnimationFrameSource() override {
519
+ return AndroidAnimationFrameSource::shared();
520
+ }
521
+
467
522
  std::string writeTestVideoFile() override {
468
523
  // TODO: implement using MediaCodec (H.264 encoder) or MediaMuxer.
469
524
  throw std::runtime_error(
@@ -21,9 +21,11 @@
21
21
  #include <webgpu/webgpu_cpp.h>
22
22
 
23
23
  #include "AndroidPlatformContext.h"
24
+ #include "AnimationFrames.h"
24
25
  #include "DawnBlobCache.h"
25
26
  #include "GPUCanvasContext.h"
26
27
  #include "GPUDevice.h"
28
+ #include "NativeBufferViewRegistry.h"
27
29
  #include "RNWebGPUManager.h"
28
30
  #include "WebGPURuntime.h"
29
31
 
@@ -50,7 +52,8 @@ extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_initializeNative(
50
52
  auto jsCallInvoker{
51
53
  facebook::jni::alias_ref<facebook::react::CallInvokerHolder::javaobject>{
52
54
  reinterpret_cast<facebook::react::CallInvokerHolder::javaobject>(
53
- jsCallInvokerHolder)} -> cthis()->getCallInvoker()};
55
+ jsCallInvokerHolder)} -> cthis()
56
+ ->getCallInvoker()};
54
57
  auto platformContext = std::make_shared<rnwgpu::AndroidPlatformContext>(
55
58
  globalBlobModule, globalModule);
56
59
  manager = std::make_shared<rnwgpu::RNWebGPUManager>(runtime, jsCallInvoker,
@@ -67,6 +70,16 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */,
67
70
  rnwgpu::GPUDevice::flushPipelineCaches();
68
71
  }
69
72
 
73
+ // WebGPUModule.onHostResume and onHostPause (UI thread): animation frames
74
+ // follow the host activity, resumed or not.
75
+ extern "C" JNIEXPORT void JNICALL
76
+ Java_com_webgpu_WebGPUModule_setForegroundNative(JNIEnv * /* env */,
77
+ jclass /* clazz */,
78
+ jboolean foreground) {
79
+ rnwgpu::AnimationFrameDispatcher::shared().setForeground(foreground ==
80
+ JNI_TRUE);
81
+ }
82
+
70
83
  // Completion of WebGPUModule.snapshotView (UI thread). Reclaims the callbacks
71
84
  // handed to Java and delivers either the bitmap's pixels or the error.
72
85
  extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_onViewSnapshot(
@@ -306,7 +319,7 @@ void setAnimationReporter(int contextId,
306
319
 
307
320
  extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUView_onSurfaceCreate(
308
321
  JNIEnv *env, jobject thiz, jobject jSurface, jint contextId, jfloat width,
309
- jfloat height, jboolean reportAnimation) {
322
+ jfloat height, jboolean reportAnimation, jboolean latchOnMainThread) {
310
323
  if (manager == nullptr) {
311
324
  return;
312
325
  }
@@ -334,6 +347,22 @@ extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUView_onSurfaceCreate(
334
347
  setAnimationReporter(contextId, reporter);
335
348
  info->setFramePresentedCallback(
336
349
  [reporter]() { reporter->onFramePresented(); });
350
+ } else if (latchOnMainThread) {
351
+ // A TextureView learns of a new frame through a message on the main
352
+ // looper, which runs after the frame being drawn: a frame presented on
353
+ // the main thread (the Reanimated UI runtime, during the Choreographer's
354
+ // animation callbacks) would only show at the draw after, which halves
355
+ // the frame rate. Tell the view right away, before this draw
356
+ // (WebGPUView.onFramePresentedOnMainThread). Other threads present
357
+ // between draws, where the message is in time.
358
+ setAnimationReporter(contextId, nullptr);
359
+ auto latch = std::make_shared<WeakViewCall>(env, thiz,
360
+ "onFramePresentedOnMainThread");
361
+ info->setFramePresentedCallback([latch]() {
362
+ if (gettid() == getpid()) {
363
+ (*latch)();
364
+ }
365
+ });
337
366
  } else {
338
367
  setAnimationReporter(contextId, nullptr);
339
368
  info->setFramePresentedCallback(nullptr);
@@ -479,3 +508,120 @@ Java_com_webgpu_WebGPUHardwareBufferView_nSwitchToOffscreen(JNIEnv *env,
479
508
  info->switchToOffscreen();
480
509
  }
481
510
  }
511
+
512
+ // --- WebGPUNativeBufferView
513
+ // ------------------------------------------------------
514
+
515
+ // The view attaches to its registry entry: native wakes it
516
+ // (onNativeContentReady) whenever new content is ready, and right away when
517
+ // there is some already.
518
+ extern "C" JNIEXPORT void JNICALL
519
+ Java_com_webgpu_WebGPUNativeBufferView_nAttach(JNIEnv *env, jobject thiz,
520
+ jint viewId) {
521
+ auto waker =
522
+ std::make_shared<WeakViewCall>(env, thiz, "onNativeContentReady");
523
+ rnwgpu::NativeBufferViewRegistry::getInstance().setListener(
524
+ static_cast<int>(viewId), [waker]() { (*waker)(); });
525
+ }
526
+
527
+ // RN dropped the view for good.
528
+ extern "C" JNIEXPORT void JNICALL
529
+ Java_com_webgpu_WebGPUNativeBufferView_nDetach(JNIEnv * /* env */,
530
+ jclass /* clazz */,
531
+ jint viewId) {
532
+ rnwgpu::NativeBufferViewRegistry::getInstance().detachView(
533
+ static_cast<int>(viewId));
534
+ }
535
+
536
+ // The newest content presented after `afterSequence`, as a HardwareBuffer
537
+ // (with a reference of its own, closed by the caller), or null when there is
538
+ // nothing new. `info` receives { sequence, width, height, halfFloat,
539
+ // displayP3, opaque }. UI thread.
540
+ extern "C" JNIEXPORT jobject JNICALL
541
+ Java_com_webgpu_WebGPUNativeBufferView_nTakeContent(JNIEnv *env,
542
+ jclass /* clazz */,
543
+ jint viewId,
544
+ jlong afterSequence,
545
+ jlongArray info) {
546
+ uint64_t sequence = 0;
547
+ auto content = rnwgpu::NativeBufferViewRegistry::getInstance().content(
548
+ static_cast<int>(viewId), &sequence);
549
+ if (!content || sequence <= static_cast<uint64_t>(afterSequence)) {
550
+ return nullptr;
551
+ }
552
+ auto *buffer = static_cast<AHardwareBuffer *>(content->buffer());
553
+ AHardwareBuffer_Desc desc{};
554
+ AHardwareBuffer_describe(buffer, &desc);
555
+ const jlong values[] = {
556
+ static_cast<jlong>(sequence),
557
+ static_cast<jlong>(desc.width),
558
+ static_cast<jlong>(desc.height),
559
+ desc.format == AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT ? 1 : 0,
560
+ content->colorSpace() == rnwgpu::NativeBufferColorSpace::DisplayP3 ? 1
561
+ : 0,
562
+ desc.format == AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM ? 1 : 0,
563
+ };
564
+ env->SetLongArrayRegion(info, 0, 6, values);
565
+ return AHardwareBuffer_toHardwareBuffer(env, buffer);
566
+ }
567
+
568
+ // Android 8 and 9: copies the buffer's pixels into `bitmap` (same size, and
569
+ // ARGB_8888 for an 8-bit buffer, RGBA_F16 for a half-float one; both lay the
570
+ // channels out in RGBA order). The buffer's fence has signaled already.
571
+ extern "C" JNIEXPORT jboolean JNICALL
572
+ Java_com_webgpu_WebGPUNativeBufferView_nReadPixels(JNIEnv *env,
573
+ jclass /* clazz */,
574
+ jobject hardwareBuffer,
575
+ jobject bitmap) {
576
+ AHardwareBuffer *buffer =
577
+ AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer);
578
+ if (buffer == nullptr) {
579
+ return JNI_FALSE;
580
+ }
581
+ AHardwareBuffer_Desc desc{};
582
+ AHardwareBuffer_describe(buffer, &desc);
583
+ AndroidBitmapInfo info{};
584
+ if (AndroidBitmap_getInfo(env, bitmap, &info) !=
585
+ ANDROID_BITMAP_RESULT_SUCCESS ||
586
+ info.width != desc.width || info.height != desc.height) {
587
+ return JNI_FALSE;
588
+ }
589
+ const bool halfFloat =
590
+ desc.format == AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
591
+ if (info.format != (halfFloat ? ANDROID_BITMAP_FORMAT_RGBA_F16
592
+ : ANDROID_BITMAP_FORMAT_RGBA_8888)) {
593
+ return JNI_FALSE;
594
+ }
595
+ const size_t bytesPerPixel = halfFloat ? 8 : 4;
596
+ void *src = nullptr;
597
+ if (AHardwareBuffer_lock(buffer, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, -1,
598
+ nullptr, &src) != 0 ||
599
+ src == nullptr) {
600
+ return JNI_FALSE;
601
+ }
602
+ void *dst = nullptr;
603
+ if (AndroidBitmap_lockPixels(env, bitmap, &dst) !=
604
+ ANDROID_BITMAP_RESULT_SUCCESS ||
605
+ dst == nullptr) {
606
+ AHardwareBuffer_unlock(buffer, nullptr);
607
+ return JNI_FALSE;
608
+ }
609
+ const bool opaque = desc.format == AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM;
610
+ const size_t rowBytes = static_cast<size_t>(desc.width) * bytesPerPixel;
611
+ // The buffer's stride is in pixels, the bitmap's in bytes.
612
+ const size_t srcStride = static_cast<size_t>(desc.stride) * bytesPerPixel;
613
+ for (uint32_t y = 0; y < desc.height; ++y) {
614
+ auto *dstRow = static_cast<uint8_t *>(dst) + y * info.stride;
615
+ std::memcpy(dstRow, static_cast<const uint8_t *>(src) + y * srcStride,
616
+ rowBytes);
617
+ if (opaque) {
618
+ // The X channel is undefined.
619
+ for (uint32_t x = 0; x < desc.width; ++x) {
620
+ dstRow[x * 4 + 3] = 0xFF;
621
+ }
622
+ }
623
+ }
624
+ AndroidBitmap_unlockPixels(env, bitmap);
625
+ AHardwareBuffer_unlock(buffer, nullptr);
626
+ return JNI_TRUE;
627
+ }