react-native-webgpu 0.22.0 → 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 (129) hide show
  1. package/README.md +15 -2
  2. package/android/CMakeLists.txt +2 -1
  3. package/android/cpp/AndroidAnimationFrameSource.h +136 -0
  4. package/android/cpp/AndroidPlatformContext.h +55 -0
  5. package/android/cpp/cpp-adapter.cpp +148 -2
  6. package/android/src/main/java/com/webgpu/WebGPUModule.java +21 -4
  7. package/android/src/main/java/com/webgpu/WebGPUNativeBufferView.java +370 -0
  8. package/android/src/main/java/com/webgpu/WebGPUNativeBufferViewManager.java +56 -0
  9. package/android/src/main/java/com/webgpu/WebGPUTextureView.java +21 -0
  10. package/android/src/main/java/com/webgpu/WebGPUVideoPlayer.java +1 -1
  11. package/android/src/main/java/com/webgpu/WebGPUView.java +19 -3
  12. package/android/src/main/java/com/webgpu/WebGPUViewPackage.java +2 -2
  13. package/android/src/newarch/com/webgpu/WebGPUNativeBufferViewManagerSpec.java +24 -0
  14. package/apple/AppleAnimationFrameSource.mm +208 -0
  15. package/apple/ApplePlatformContext.h +6 -0
  16. package/apple/ApplePlatformContext.mm +73 -0
  17. package/apple/NativeBufferFenceWait.mm +88 -0
  18. package/apple/WebGPUNativeBufferView.h +15 -0
  19. package/apple/WebGPUNativeBufferView.mm +200 -0
  20. package/cpp/rnwgpu/AnimationFrames.cpp +576 -0
  21. package/cpp/rnwgpu/AnimationFrames.h +233 -0
  22. package/cpp/rnwgpu/NativeBufferViewRegistry.cpp +396 -0
  23. package/cpp/rnwgpu/NativeBufferViewRegistry.h +163 -0
  24. package/cpp/rnwgpu/PlatformContext.h +20 -0
  25. package/cpp/rnwgpu/RNWebGPUManager.cpp +17 -4
  26. package/cpp/rnwgpu/api/GPUAdapter.cpp +1 -1
  27. package/cpp/rnwgpu/api/GPUDevice.cpp +16 -131
  28. package/cpp/rnwgpu/api/GPUDevice.h +0 -18
  29. package/cpp/rnwgpu/api/GPUExternalTexture.cpp +35 -3
  30. package/cpp/rnwgpu/api/GPUExternalTexture.h +4 -4
  31. package/cpp/rnwgpu/api/GPUQueue.cpp +1 -1
  32. package/cpp/rnwgpu/api/GPUQueue.h +1 -1
  33. package/cpp/rnwgpu/api/GPUSharedFence.h +1 -0
  34. package/cpp/rnwgpu/api/GPUSharedTextureMemory.cpp +11 -5
  35. package/cpp/rnwgpu/api/GPUSharedTextureMemory.h +21 -2
  36. package/cpp/rnwgpu/api/GPUTexture.h +18 -0
  37. package/cpp/rnwgpu/api/NativeFrameFeatures.h +1 -1
  38. package/cpp/rnwgpu/api/NativeFrameImport.cpp +20 -17
  39. package/cpp/rnwgpu/api/NativeFrameImport.h +31 -20
  40. package/cpp/rnwgpu/api/RNWebGPU.h +201 -3
  41. package/cpp/rnwgpu/api/VideoFrame.h +5 -4
  42. package/cpp/rnwgpu/api/VideoFrameBlit.h +2 -2
  43. package/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h +21 -14
  44. package/cpp/rnwgpu/api/descriptors/GPUImageCopyExternalImage.h +1 -1
  45. package/cpp/rnwgpu/api/descriptors/GPUSharedTextureMemoryDescriptor.h +17 -9
  46. package/cpp/rnwgpu/async/RuntimeContext.cpp +21 -4
  47. package/cpp/rnwgpu/async/RuntimeContext.h +8 -0
  48. package/lib/commonjs/NativeBufferView.js +131 -0
  49. package/lib/commonjs/NativeBufferView.js.map +1 -0
  50. package/lib/commonjs/NativeBufferViewNativeComponent.js +10 -0
  51. package/lib/commonjs/NativeBufferViewNativeComponent.js.map +1 -0
  52. package/lib/commonjs/animationFrame.js +91 -0
  53. package/lib/commonjs/animationFrame.js.map +1 -0
  54. package/lib/commonjs/index.js +16 -1
  55. package/lib/commonjs/index.js.map +1 -1
  56. package/lib/commonjs/main/index.js +12 -0
  57. package/lib/commonjs/main/index.js.map +1 -1
  58. package/lib/commonjs/mock.js +30 -1
  59. package/lib/commonjs/mock.js.map +1 -1
  60. package/lib/commonjs/video.js +14 -4
  61. package/lib/commonjs/video.js.map +1 -1
  62. package/lib/module/NativeBufferView.js +122 -0
  63. package/lib/module/NativeBufferView.js.map +1 -0
  64. package/lib/module/NativeBufferViewNativeComponent.js +4 -0
  65. package/lib/module/NativeBufferViewNativeComponent.js.map +1 -0
  66. package/lib/module/animationFrame.js +83 -0
  67. package/lib/module/animationFrame.js.map +1 -0
  68. package/lib/module/index.js +1 -0
  69. package/lib/module/index.js.map +1 -1
  70. package/lib/module/main/index.js +1 -0
  71. package/lib/module/main/index.js.map +1 -1
  72. package/lib/module/mock.js +21 -0
  73. package/lib/module/mock.js.map +1 -1
  74. package/lib/module/video.js +11 -2
  75. package/lib/module/video.js.map +1 -1
  76. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts +48 -0
  77. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts.map +1 -0
  78. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts +5 -0
  79. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts.map +1 -0
  80. package/lib/typescript/lib/commonjs/animationFrame.d.ts +54 -0
  81. package/lib/typescript/lib/commonjs/animationFrame.d.ts.map +1 -0
  82. package/lib/typescript/lib/commonjs/index.d.ts +2 -0
  83. package/lib/typescript/lib/commonjs/mock.d.ts +12 -0
  84. package/lib/typescript/lib/commonjs/mock.d.ts.map +1 -1
  85. package/lib/typescript/lib/commonjs/video.d.ts +3 -2
  86. package/lib/typescript/lib/commonjs/video.d.ts.map +1 -1
  87. package/lib/typescript/lib/module/NativeBufferView.d.ts +14 -0
  88. package/lib/typescript/lib/module/NativeBufferView.d.ts.map +1 -0
  89. package/lib/typescript/lib/module/NativeBufferViewNativeComponent.d.ts +3 -0
  90. package/lib/typescript/lib/module/NativeBufferViewNativeComponent.d.ts.map +1 -0
  91. package/lib/typescript/lib/module/animationFrame.d.ts +3 -0
  92. package/lib/typescript/lib/module/animationFrame.d.ts.map +1 -0
  93. package/lib/typescript/lib/module/index.d.ts +1 -0
  94. package/lib/typescript/lib/module/main/index.d.ts +1 -0
  95. package/lib/typescript/lib/module/mock.d.ts +14 -0
  96. package/lib/typescript/lib/module/mock.d.ts.map +1 -1
  97. package/lib/typescript/lib/module/video.d.ts +3 -2
  98. package/lib/typescript/lib/module/video.d.ts.map +1 -1
  99. package/lib/typescript/src/NativeBufferView.d.ts +99 -0
  100. package/lib/typescript/src/NativeBufferView.d.ts.map +1 -0
  101. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts +13 -0
  102. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts.map +1 -0
  103. package/lib/typescript/src/animationFrame.d.ts +59 -0
  104. package/lib/typescript/src/animationFrame.d.ts.map +1 -0
  105. package/lib/typescript/src/index.d.ts +18 -8
  106. package/lib/typescript/src/index.d.ts.map +1 -1
  107. package/lib/typescript/src/main/index.d.ts +1 -0
  108. package/lib/typescript/src/main/index.d.ts.map +1 -1
  109. package/lib/typescript/src/mock.d.ts +11 -0
  110. package/lib/typescript/src/mock.d.ts.map +1 -1
  111. package/lib/typescript/src/types.d.ts +32 -31
  112. package/lib/typescript/src/types.d.ts.map +1 -1
  113. package/lib/typescript/src/video.d.ts +12 -4
  114. package/lib/typescript/src/video.d.ts.map +1 -1
  115. package/package.json +7 -2
  116. package/react-native-webgpu.podspec +1 -1
  117. package/src/NativeBufferView.tsx +199 -0
  118. package/src/NativeBufferViewNativeComponent.ts +20 -0
  119. package/src/animationFrame.ts +82 -0
  120. package/src/index.tsx +45 -39
  121. package/src/main/index.tsx +1 -0
  122. package/src/mock.ts +35 -0
  123. package/src/types.ts +61 -87
  124. package/src/video.ts +20 -7
  125. package/cpp/rnwgpu/api/GPUNativeBufferExternalTexture.h +0 -60
  126. package/cpp/rnwgpu/api/GPUNativeBufferTexture.h +0 -52
  127. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.cpp +0 -144
  128. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.h +0 -143
  129. 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
 
@@ -47,7 +47,6 @@ add_library(${PACKAGE_NAME} SHARED
47
47
  ../cpp/rnwgpu/api/GPUSharedFence.cpp
48
48
  ../cpp/rnwgpu/api/GPUSharedTextureMemory.cpp
49
49
  ../cpp/rnwgpu/api/GPUExternalTexture.cpp
50
- ../cpp/rnwgpu/api/GPUNativeBufferWrapper.cpp
51
50
  ../cpp/rnwgpu/api/NativeFrameImport.cpp
52
51
  ../cpp/rnwgpu/api/GPURenderBundleEncoder.cpp
53
52
  ../cpp/rnwgpu/api/GPURenderPassEncoder.cpp
@@ -57,6 +56,8 @@ add_library(${PACKAGE_NAME} SHARED
57
56
  ../cpp/rnwgpu/api/GPUComputePipeline.cpp
58
57
  ../cpp/rnwgpu/api/GPUCanvasContext.cpp
59
58
  ../cpp/rnwgpu/DawnBlobCache.cpp
59
+ ../cpp/rnwgpu/NativeBufferViewRegistry.cpp
60
+ ../cpp/rnwgpu/AnimationFrames.cpp
60
61
  ../cpp/rnwgpu/RNWebGPUManager.cpp
61
62
  ../cpp/rnwgpu/WebGPURuntime.cpp
62
63
  ../cpp/jsi/Promise.cpp
@@ -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
+ }
@@ -16,6 +16,7 @@ import com.facebook.proguard.annotations.DoNotStrip;
16
16
  import com.facebook.react.bridge.ReactApplicationContext;
17
17
  import com.facebook.react.bridge.JavaScriptContextHolder;
18
18
  import com.facebook.react.bridge.LifecycleEventListener;
19
+ import com.facebook.react.common.LifecycleState;
19
20
  import com.facebook.react.bridge.ReactMethod;
20
21
  import com.facebook.react.bridge.UIManager;
21
22
  import com.facebook.react.bridge.UiThreadUtil;
@@ -37,6 +38,8 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
37
38
  super(reactContext);
38
39
  // Initialize the C++ module
39
40
  initialize();
41
+ // Animation frames follow the host activity: resumed, or not.
42
+ setForegroundNative(reactContext.getLifecycleState() == LifecycleState.RESUMED);
40
43
  reactContext.addLifecycleEventListener(this);
41
44
  }
42
45
 
@@ -47,15 +50,19 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
47
50
  }
48
51
 
49
52
  @Override
50
- public void onHostResume() {}
53
+ public void onHostResume() {
54
+ setForegroundNative(true);
55
+ }
51
56
 
52
57
  /**
53
- * The app is going to the background: the last moment to write what Dawn's
54
- * pipeline caches hold before the process may be killed (see
55
- * GPUDevice::flushPipelineCaches).
58
+ * The app is going to the background: no animation frames until it is back
59
+ * (see AnimationFrameDispatcher::setForeground), and the last moment to
60
+ * write what Dawn's pipeline caches hold before the process may be killed
61
+ * (see GPUDevice::flushPipelineCaches).
56
62
  */
57
63
  @Override
58
64
  public void onHostPause() {
65
+ setForegroundNative(false);
59
66
  flushPipelineCaches();
60
67
  }
61
68
 
@@ -65,6 +72,16 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
65
72
  @DoNotStrip
66
73
  private native void flushPipelineCaches();
67
74
 
75
+ /**
76
+ * Whether the app is in the foreground: the host activity is resumed (see
77
+ * AnimationFrameDispatcher::setForeground). An AChoreographer sends its
78
+ * frames to a paused app as well: without this, a requestAnimationFrame
79
+ * loop would keep rendering in the background, which one on React Native's
80
+ * own does not (JavaTimerManager.onHostPause).
81
+ */
82
+ @DoNotStrip
83
+ private static native void setForegroundNative(boolean foreground);
84
+
68
85
  @OptIn(markerClass = FrameworkAPI.class)
69
86
  @ReactMethod(isBlockingSynchronousMethod = true)
70
87
  public boolean install() {