react-native-webgpu 0.22.0 → 0.24.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 (165) hide show
  1. package/Package.swift +18 -129
  2. package/README.md +15 -2
  3. package/android/CMakeLists.txt +2 -1
  4. package/android/cpp/AndroidAnimationFrameSource.h +136 -0
  5. package/android/cpp/AndroidPlatformContext.h +65 -9
  6. package/android/cpp/cpp-adapter.cpp +148 -2
  7. package/android/src/main/java/com/webgpu/WebGPUModule.java +24 -7
  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 +2 -2
  12. package/android/src/main/java/com/webgpu/WebGPUView.java +19 -3
  13. package/android/src/main/java/com/webgpu/WebGPUViewPackage.java +2 -2
  14. package/android/src/newarch/com/webgpu/WebGPUNativeBufferViewManagerSpec.java +24 -0
  15. package/apple/AppleAnimationFrameSource.mm +208 -0
  16. package/apple/ApplePlatformContext.h +8 -1
  17. package/apple/ApplePlatformContext.mm +75 -2
  18. package/apple/NativeBufferFenceWait.mm +88 -0
  19. package/apple/WebGPUNativeBufferView.h +15 -0
  20. package/apple/WebGPUNativeBufferView.mm +200 -0
  21. package/binaries.json +53 -105
  22. package/cpp/dawn/common/ExternalTextureParams.h +3 -3
  23. package/cpp/dawn/include/dawn/dawn_proc.h +53 -0
  24. package/cpp/dawn/include/dawn/dawn_proc_table.h +329 -0
  25. package/cpp/dawn/include/dawn/dawn_thread_dispatch_proc.h +47 -0
  26. package/cpp/dawn/include/dawn/dawn_version.h +51 -0
  27. package/cpp/dawn/include/dawn/native/D3D11Backend.h +65 -0
  28. package/cpp/dawn/include/dawn/native/D3D12Backend.h +104 -0
  29. package/cpp/dawn/include/dawn/native/D3DBackend.h +56 -0
  30. package/cpp/dawn/include/dawn/native/DawnNative.h +375 -0
  31. package/cpp/dawn/include/dawn/native/MetalBackend.h +67 -0
  32. package/cpp/dawn/include/dawn/native/NullBackend.h +39 -0
  33. package/cpp/dawn/include/dawn/native/OpenGLBackend.h +89 -0
  34. package/cpp/dawn/include/dawn/native/VulkanBackend.h +199 -0
  35. package/cpp/dawn/include/dawn/native/WebGPUBackend.h +49 -0
  36. package/cpp/dawn/include/dawn/native/dawn_native_export.h +49 -0
  37. package/cpp/dawn/include/dawn/platform/DawnPlatform.h +210 -0
  38. package/cpp/dawn/include/dawn/platform/dawn_platform_export.h +49 -0
  39. package/cpp/dawn/include/dawn/replay/Replay.h +99 -0
  40. package/cpp/dawn/include/dawn/replay/dawn_replay_export.h +49 -0
  41. package/cpp/dawn/include/dawn/webgpu.h +5119 -0
  42. package/cpp/dawn/include/dawn/webgpu_cpp.h +10506 -0
  43. package/cpp/dawn/include/dawn/webgpu_cpp_print.h +2897 -0
  44. package/cpp/dawn/include/webgpu/webgpu.h +33 -0
  45. package/cpp/dawn/include/webgpu/webgpu_cpp.h +33 -0
  46. package/cpp/dawn/include/webgpu/webgpu_cpp_chained_struct.h +57 -0
  47. package/cpp/dawn/include/webgpu/webgpu_cpp_print.h +33 -0
  48. package/cpp/dawn/include/webgpu/webgpu_enum_class_bitmasks.h +163 -0
  49. package/cpp/dawn/include/webgpu/webgpu_glfw.h +88 -0
  50. package/cpp/rnwgpu/AnimationFrames.cpp +576 -0
  51. package/cpp/rnwgpu/AnimationFrames.h +233 -0
  52. package/cpp/rnwgpu/NativeBufferViewRegistry.cpp +396 -0
  53. package/cpp/rnwgpu/NativeBufferViewRegistry.h +163 -0
  54. package/cpp/rnwgpu/PlatformContext.h +21 -1
  55. package/cpp/rnwgpu/RNWebGPUManager.cpp +17 -4
  56. package/cpp/rnwgpu/SurfaceRegistry.h +2 -2
  57. package/cpp/rnwgpu/api/GPUAdapter.cpp +2 -2
  58. package/cpp/rnwgpu/api/GPUDevice.cpp +16 -131
  59. package/cpp/rnwgpu/api/GPUDevice.h +0 -18
  60. package/cpp/rnwgpu/api/GPUExternalTexture.cpp +35 -3
  61. package/cpp/rnwgpu/api/GPUExternalTexture.h +4 -4
  62. package/cpp/rnwgpu/api/GPUQueue.cpp +1 -1
  63. package/cpp/rnwgpu/api/GPUQueue.h +1 -1
  64. package/cpp/rnwgpu/api/GPUSharedFence.h +1 -0
  65. package/cpp/rnwgpu/api/GPUSharedTextureMemory.cpp +11 -5
  66. package/cpp/rnwgpu/api/GPUSharedTextureMemory.h +21 -2
  67. package/cpp/rnwgpu/api/GPUTexture.h +18 -0
  68. package/cpp/rnwgpu/api/NativeFrameFeatures.h +1 -1
  69. package/cpp/rnwgpu/api/NativeFrameImport.cpp +20 -17
  70. package/cpp/rnwgpu/api/NativeFrameImport.h +31 -20
  71. package/cpp/rnwgpu/api/RNWebGPU.h +206 -7
  72. package/cpp/rnwgpu/api/VideoFrame.h +5 -4
  73. package/cpp/rnwgpu/api/VideoFrameBlit.h +2 -2
  74. package/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h +21 -14
  75. package/cpp/rnwgpu/api/descriptors/GPUImageCopyExternalImage.h +1 -1
  76. package/cpp/rnwgpu/api/descriptors/GPUSharedTextureMemoryDescriptor.h +17 -9
  77. package/cpp/rnwgpu/async/RuntimeContext.cpp +21 -4
  78. package/cpp/rnwgpu/async/RuntimeContext.h +8 -0
  79. package/lib/commonjs/NativeBufferView.js +131 -0
  80. package/lib/commonjs/NativeBufferView.js.map +1 -0
  81. package/lib/commonjs/NativeBufferViewNativeComponent.js +10 -0
  82. package/lib/commonjs/NativeBufferViewNativeComponent.js.map +1 -0
  83. package/lib/commonjs/animationFrame.js +91 -0
  84. package/lib/commonjs/animationFrame.js.map +1 -0
  85. package/lib/commonjs/index.js +16 -1
  86. package/lib/commonjs/index.js.map +1 -1
  87. package/lib/commonjs/main/index.js +12 -0
  88. package/lib/commonjs/main/index.js.map +1 -1
  89. package/lib/commonjs/mock.js +30 -1
  90. package/lib/commonjs/mock.js.map +1 -1
  91. package/lib/commonjs/video.js +21 -7
  92. package/lib/commonjs/video.js.map +1 -1
  93. package/lib/module/NativeBufferView.js +122 -0
  94. package/lib/module/NativeBufferView.js.map +1 -0
  95. package/lib/module/NativeBufferViewNativeComponent.js +4 -0
  96. package/lib/module/NativeBufferViewNativeComponent.js.map +1 -0
  97. package/lib/module/animationFrame.js +83 -0
  98. package/lib/module/animationFrame.js.map +1 -0
  99. package/lib/module/index.js +1 -0
  100. package/lib/module/index.js.map +1 -1
  101. package/lib/module/main/index.js +1 -0
  102. package/lib/module/main/index.js.map +1 -1
  103. package/lib/module/mock.js +21 -0
  104. package/lib/module/mock.js.map +1 -1
  105. package/lib/module/video.js +17 -4
  106. package/lib/module/video.js.map +1 -1
  107. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts +48 -0
  108. package/lib/typescript/lib/commonjs/NativeBufferView.d.ts.map +1 -0
  109. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts +5 -0
  110. package/lib/typescript/lib/commonjs/NativeBufferViewNativeComponent.d.ts.map +1 -0
  111. package/lib/typescript/lib/commonjs/animationFrame.d.ts +54 -0
  112. package/lib/typescript/lib/commonjs/animationFrame.d.ts.map +1 -0
  113. package/lib/typescript/lib/commonjs/index.d.ts +2 -0
  114. package/lib/typescript/lib/commonjs/mock.d.ts +12 -0
  115. package/lib/typescript/lib/commonjs/mock.d.ts.map +1 -1
  116. package/lib/typescript/lib/commonjs/video.d.ts +9 -4
  117. package/lib/typescript/lib/commonjs/video.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/animationFrame.d.ts +3 -0
  123. package/lib/typescript/lib/module/animationFrame.d.ts.map +1 -0
  124. package/lib/typescript/lib/module/index.d.ts +1 -0
  125. package/lib/typescript/lib/module/main/index.d.ts +1 -0
  126. package/lib/typescript/lib/module/mock.d.ts +14 -0
  127. package/lib/typescript/lib/module/mock.d.ts.map +1 -1
  128. package/lib/typescript/lib/module/video.d.ts +4 -3
  129. package/lib/typescript/lib/module/video.d.ts.map +1 -1
  130. package/lib/typescript/react-native.config.d.ts +1 -0
  131. package/lib/typescript/src/NativeBufferView.d.ts +99 -0
  132. package/lib/typescript/src/NativeBufferView.d.ts.map +1 -0
  133. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts +13 -0
  134. package/lib/typescript/src/NativeBufferViewNativeComponent.d.ts.map +1 -0
  135. package/lib/typescript/src/animationFrame.d.ts +59 -0
  136. package/lib/typescript/src/animationFrame.d.ts.map +1 -0
  137. package/lib/typescript/src/index.d.ts +18 -8
  138. package/lib/typescript/src/index.d.ts.map +1 -1
  139. package/lib/typescript/src/main/index.d.ts +1 -0
  140. package/lib/typescript/src/main/index.d.ts.map +1 -1
  141. package/lib/typescript/src/mock.d.ts +11 -0
  142. package/lib/typescript/src/mock.d.ts.map +1 -1
  143. package/lib/typescript/src/types.d.ts +33 -32
  144. package/lib/typescript/src/types.d.ts.map +1 -1
  145. package/lib/typescript/src/video.d.ts +18 -6
  146. package/lib/typescript/src/video.d.ts.map +1 -1
  147. package/package.json +16 -6
  148. package/react-native-webgpu.podspec +47 -79
  149. package/react-native.config.js +9 -6
  150. package/scripts/apple-binaries-utils.sh +280 -0
  151. package/scripts/prepare-apple-binaries.sh +309 -0
  152. package/scripts/spm-plugin.js +130 -0
  153. package/src/NativeBufferView.tsx +199 -0
  154. package/src/NativeBufferViewNativeComponent.ts +20 -0
  155. package/src/animationFrame.ts +82 -0
  156. package/src/index.tsx +48 -42
  157. package/src/main/index.tsx +1 -0
  158. package/src/mock.ts +35 -0
  159. package/src/types.ts +62 -88
  160. package/src/video.ts +32 -12
  161. package/cpp/rnwgpu/api/GPUNativeBufferExternalTexture.h +0 -60
  162. package/cpp/rnwgpu/api/GPUNativeBufferTexture.h +0 -52
  163. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.cpp +0 -144
  164. package/cpp/rnwgpu/api/GPUNativeBufferWrapper.h +0 -143
  165. package/cpp/rnwgpu/api/descriptors/GPUNativeBufferTextureDescriptor.h +0 -55
@@ -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() {
@@ -212,12 +229,12 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
212
229
  private native void onViewSnapshotBuffer(long callback, HardwareBuffer buffer, int fenceFd);
213
230
 
214
231
  /**
215
- * Called from C++ (AndroidPlatformContext::createVideoPlayer) for
216
- * RNWebGPU.createVideoPlayer. Throws when the source cannot be opened; the
232
+ * Called from C++ (AndroidPlatformContext::createTestVideoPlayer) for
233
+ * RNWebGPU.createTestVideoPlayer. Throws when the source cannot be opened; the
217
234
  * caller turns the exception into a JS error.
218
235
  */
219
236
  @DoNotStrip
220
- WebGPUVideoPlayer createVideoPlayer(String source) {
237
+ WebGPUVideoPlayer createTestVideoPlayer(String source) {
221
238
  return new WebGPUVideoPlayer(getReactApplicationContext(), source);
222
239
  }
223
240
  }
@@ -0,0 +1,370 @@
1
+ package com.webgpu;
2
+
3
+ import android.annotation.SuppressLint;
4
+ import android.content.Context;
5
+ import android.graphics.Bitmap;
6
+ import android.graphics.Canvas;
7
+ import android.graphics.ColorSpace;
8
+ import android.graphics.Paint;
9
+ import android.graphics.Rect;
10
+ import android.hardware.HardwareBuffer;
11
+ import android.os.Build;
12
+ import android.os.Handler;
13
+ import android.os.Looper;
14
+ import android.util.Log;
15
+ import android.view.View;
16
+
17
+ import androidx.annotation.Keep;
18
+ import androidx.annotation.Nullable;
19
+ import androidx.annotation.RequiresApi;
20
+
21
+ import com.facebook.react.bridge.Arguments;
22
+ import com.facebook.react.bridge.ReactContext;
23
+ import com.facebook.react.bridge.WritableMap;
24
+ import com.facebook.react.uimanager.UIManagerHelper;
25
+ import com.facebook.react.uimanager.events.Event;
26
+ import com.facebook.react.uimanager.events.EventDispatcher;
27
+
28
+ import java.util.concurrent.atomic.AtomicBoolean;
29
+
30
+ /**
31
+ * NativeBufferView: displays a native buffer that JS presented
32
+ * (RNWebGPU.presentNativeBuffer), with no swap chain and no GPU device on the display side.
33
+ *
34
+ * <p>The contract: a buffer is never written again while it is displayed (the producer renders the
35
+ * next content into another buffer), and this view never allocates one. It reports its size in
36
+ * physical pixels (onPixelSizeChange) and draws whatever it is handed, scaled to its bounds by
37
+ * {@code resizeMode}, until the producer catches up with a buffer of the new size.
38
+ *
39
+ * <p>Native code waits for the buffer's fence off the UI thread (NativeBufferViewRegistry) and then
40
+ * wakes this view; it shows the buffer on the next vsync. API 29 and above: the buffer is drawn
41
+ * inline, zero-copy, through {@link Bitmap#wrapHardwareBuffer}, which takes its own reference on
42
+ * it. API 26 to 28: the pixels are read back into a regular Bitmap, and the buffer is free right
43
+ * after the copy.
44
+ */
45
+ @SuppressLint("ViewConstructor")
46
+ public class WebGPUNativeBufferView extends View {
47
+
48
+ private static final String TAG = "WebGPUNativeBufferView";
49
+
50
+ static final String PIXEL_SIZE_CHANGE_EVENT = "topPixelSizeChange";
51
+
52
+ // NativeBufferContent metadata written by nTakeContent.
53
+ private static final int INFO_SEQUENCE = 0;
54
+ private static final int INFO_WIDTH = 1;
55
+ private static final int INFO_HEIGHT = 2;
56
+ private static final int INFO_HALF_FLOAT = 3;
57
+ private static final int INFO_DISPLAY_P3 = 4;
58
+ private static final int INFO_OPAQUE = 5;
59
+ private static final int INFO_SIZE = 6;
60
+
61
+ private enum ResizeMode { STRETCH, CONTAIN, COVER, TOP_LEFT }
62
+
63
+ private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
64
+ private final Rect mSrc = new Rect();
65
+ private final Rect mDst = new Rect();
66
+ private final long[] mInfo = new long[INFO_SIZE];
67
+
68
+ // Native -> UI thread wake-up, coalesced into at most one pending consume().
69
+ private final Handler mMainHandler = new Handler(Looper.getMainLooper());
70
+ private final AtomicBoolean mConsumePosted = new AtomicBoolean(false);
71
+ private final Runnable mConsume = this::consume;
72
+
73
+ private int mViewId;
74
+ private long mSequence;
75
+ private ResizeMode mResizeMode = ResizeMode.STRETCH;
76
+ @Nullable private Bitmap mBitmap;
77
+ private int mReportedWidth;
78
+ private int mReportedHeight;
79
+
80
+ public WebGPUNativeBufferView(Context context) {
81
+ super(context);
82
+ setWillNotDraw(false);
83
+ }
84
+
85
+ // --- Props -------------------------------------------------------------------
86
+
87
+ public void setViewId(int viewId) {
88
+ if (viewId == mViewId) {
89
+ return;
90
+ }
91
+ if (mViewId != 0) {
92
+ nDetach(mViewId);
93
+ }
94
+ mViewId = viewId;
95
+ mSequence = 0;
96
+ if (viewId != 0) {
97
+ // Calls onNativeContentReady right away when content is already there.
98
+ nAttach(viewId);
99
+ }
100
+ }
101
+
102
+ public void setResizeMode(@Nullable String value) {
103
+ ResizeMode mode;
104
+ if ("contain".equals(value)) {
105
+ mode = ResizeMode.CONTAIN;
106
+ } else if ("cover".equals(value)) {
107
+ mode = ResizeMode.COVER;
108
+ } else if ("topLeft".equals(value)) {
109
+ mode = ResizeMode.TOP_LEFT;
110
+ } else {
111
+ mode = ResizeMode.STRETCH;
112
+ }
113
+ if (mode != mResizeMode) {
114
+ mResizeMode = mode;
115
+ invalidate();
116
+ }
117
+ }
118
+
119
+ // --- Size --------------------------------------------------------------------
120
+
121
+ @Override
122
+ protected void onSizeChanged(int w, int h, int oldw, int oldh) {
123
+ super.onSizeChanged(w, h, oldw, oldh);
124
+ // The size the producer should render at for a 1:1 display. Layout has
125
+ // already rounded it to whole pixels; JS gets exactly these numbers.
126
+ if (w > 0 && h > 0 && (w != mReportedWidth || h != mReportedHeight)) {
127
+ mReportedWidth = w;
128
+ mReportedHeight = h;
129
+ dispatchPixelSize(w, h);
130
+ }
131
+ }
132
+
133
+ private void dispatchPixelSize(int width, int height) {
134
+ Context context = getContext();
135
+ if (!(context instanceof ReactContext)) {
136
+ return;
137
+ }
138
+ ReactContext reactContext = (ReactContext) context;
139
+ EventDispatcher dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());
140
+ if (dispatcher != null) {
141
+ dispatcher.dispatchEvent(
142
+ new PixelSizeChangeEvent(UIManagerHelper.getSurfaceId(this), getId(), width, height));
143
+ }
144
+ }
145
+
146
+ // --- Content (UI thread, woken by native) ---------------------------------------
147
+
148
+ /** Called by native, from any thread, when new content is ready. */
149
+ @Keep
150
+ private void onNativeContentReady() {
151
+ if (mConsumePosted.compareAndSet(false, true)) {
152
+ mMainHandler.post(mConsume);
153
+ }
154
+ }
155
+
156
+ private void consume() {
157
+ mConsumePosted.set(false);
158
+ if (mViewId == 0) {
159
+ return;
160
+ }
161
+ HardwareBuffer buffer = nTakeContent(mViewId, mSequence, mInfo);
162
+ if (buffer == null) {
163
+ return;
164
+ }
165
+ mSequence = mInfo[INFO_SEQUENCE];
166
+ Bitmap bitmap;
167
+ try {
168
+ bitmap = toBitmap(buffer);
169
+ } finally {
170
+ // The Bitmap holds its own reference (or a copy below API 29).
171
+ buffer.close();
172
+ }
173
+ if (bitmap == null) {
174
+ return;
175
+ }
176
+ Bitmap previous = mBitmap;
177
+ mBitmap = bitmap;
178
+ invalidate();
179
+ // The display list recorded with the previous bitmap keeps its own native
180
+ // reference until it is replaced; this only drops ours.
181
+ if (previous != null && !previous.isRecycled()) {
182
+ previous.recycle();
183
+ }
184
+ }
185
+
186
+ @Nullable
187
+ private Bitmap toBitmap(HardwareBuffer buffer) {
188
+ final boolean halfFloat = mInfo[INFO_HALF_FLOAT] != 0;
189
+ final ColorSpace colorSpace = colorSpaceFor(halfFloat, mInfo[INFO_DISPLAY_P3] != 0);
190
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
191
+ return wrap(buffer, colorSpace);
192
+ }
193
+ return readBack(buffer, halfFloat, colorSpace);
194
+ }
195
+
196
+ @RequiresApi(api = Build.VERSION_CODES.Q)
197
+ @Nullable
198
+ private static Bitmap wrap(HardwareBuffer buffer, ColorSpace colorSpace) {
199
+ try {
200
+ Bitmap bitmap = Bitmap.wrapHardwareBuffer(buffer, colorSpace);
201
+ if (bitmap == null) {
202
+ Log.e(TAG, "Bitmap.wrapHardwareBuffer failed: the buffer needs GPU_SAMPLED_IMAGE usage");
203
+ }
204
+ return bitmap;
205
+ } catch (IllegalArgumentException e) {
206
+ Log.e(TAG, "Bitmap.wrapHardwareBuffer failed", e);
207
+ return null;
208
+ }
209
+ }
210
+
211
+ // Android 8 and 9: no wrapHardwareBuffer. The pixels are copied into a
212
+ // regular Bitmap (the buffer needs CPU_READ_RARELY usage, which
213
+ // createNativeBuffer adds there); the copy is free to go right after.
214
+ @Nullable
215
+ private Bitmap readBack(HardwareBuffer buffer, boolean halfFloat, ColorSpace colorSpace) {
216
+ final int width = (int) mInfo[INFO_WIDTH];
217
+ final int height = (int) mInfo[INFO_HEIGHT];
218
+ final boolean hasAlpha = mInfo[INFO_OPAQUE] == 0;
219
+ final Bitmap.Config config = halfFloat ? Bitmap.Config.RGBA_F16 : Bitmap.Config.ARGB_8888;
220
+ Bitmap bitmap;
221
+ try {
222
+ bitmap = Bitmap.createBitmap(width, height, config, hasAlpha, colorSpace);
223
+ } catch (IllegalArgumentException e) {
224
+ // Android 8 and 9 only take a linear color space for RGBA_F16 bitmaps.
225
+ Log.w(TAG, "no " + colorSpace.getName() + " bitmap for this format; colors may be off");
226
+ bitmap = Bitmap.createBitmap(width, height, config);
227
+ }
228
+ if (!nReadPixels(buffer, bitmap)) {
229
+ Log.e(TAG, "reading the buffer back failed (it needs CPU_READ_RARELY usage below API 29)");
230
+ bitmap.recycle();
231
+ return null;
232
+ }
233
+ return bitmap;
234
+ }
235
+
236
+ private static ColorSpace colorSpaceFor(boolean halfFloat, boolean displayP3) {
237
+ if (displayP3) {
238
+ return ColorSpace.get(ColorSpace.Named.DISPLAY_P3);
239
+ }
240
+ return ColorSpace.get(halfFloat ? ColorSpace.Named.EXTENDED_SRGB : ColorSpace.Named.SRGB);
241
+ }
242
+
243
+ // --- Draw --------------------------------------------------------------------
244
+
245
+ @Override
246
+ protected void onDraw(Canvas canvas) {
247
+ super.onDraw(canvas);
248
+ Bitmap bitmap = mBitmap;
249
+ if (bitmap == null || bitmap.isRecycled()) {
250
+ return;
251
+ }
252
+ final int bw = bitmap.getWidth();
253
+ final int bh = bitmap.getHeight();
254
+ final int vw = getWidth();
255
+ final int vh = getHeight();
256
+ if (bw <= 0 || bh <= 0 || vw <= 0 || vh <= 0) {
257
+ return;
258
+ }
259
+ // A buffer that lags the view size (mid-resize) is scaled, never blank.
260
+ switch (mResizeMode) {
261
+ case CONTAIN: {
262
+ final float scale = Math.min((float) vw / bw, (float) vh / bh);
263
+ final int dw = Math.round(bw * scale);
264
+ final int dh = Math.round(bh * scale);
265
+ mSrc.set(0, 0, bw, bh);
266
+ mDst.set((vw - dw) / 2, (vh - dh) / 2, (vw - dw) / 2 + dw, (vh - dh) / 2 + dh);
267
+ break;
268
+ }
269
+ case COVER: {
270
+ // Crop the source to the view's aspect ratio rather than clipping.
271
+ final float scale = Math.max((float) vw / bw, (float) vh / bh);
272
+ final int sw = Math.min(bw, Math.round(vw / scale));
273
+ final int sh = Math.min(bh, Math.round(vh / scale));
274
+ mSrc.set((bw - sw) / 2, (bh - sh) / 2, (bw - sw) / 2 + sw, (bh - sh) / 2 + sh);
275
+ mDst.set(0, 0, vw, vh);
276
+ break;
277
+ }
278
+ case TOP_LEFT: {
279
+ // No scaling: crop instead of blur.
280
+ final int w = Math.min(bw, vw);
281
+ final int h = Math.min(bh, vh);
282
+ mSrc.set(0, 0, w, h);
283
+ mDst.set(0, 0, w, h);
284
+ break;
285
+ }
286
+ case STRETCH:
287
+ default:
288
+ mSrc.set(0, 0, bw, bh);
289
+ mDst.set(0, 0, vw, vh);
290
+ break;
291
+ }
292
+ if (bitmap.getConfig() == Bitmap.Config.HARDWARE && !canvas.isHardwareAccelerated()) {
293
+ // A software canvas (a view capture with view.draw(new Canvas(bitmap)), a
294
+ // software layer) throws on a hardware bitmap: draw a copy of the pixels.
295
+ Bitmap copy = softwareCopy(bitmap);
296
+ if (copy != null) {
297
+ canvas.drawBitmap(copy, mSrc, mDst, mPaint);
298
+ copy.recycle();
299
+ }
300
+ return;
301
+ }
302
+ canvas.drawBitmap(bitmap, mSrc, mDst, mPaint);
303
+ }
304
+
305
+ // Reads the buffer back; null when the pixels can't be read (the capture
306
+ // then shows nothing for this view).
307
+ @Nullable
308
+ private static Bitmap softwareCopy(Bitmap hardware) {
309
+ try {
310
+ return hardware.copy(Bitmap.Config.ARGB_8888, false);
311
+ } catch (RuntimeException e) {
312
+ Log.w(TAG, "no software copy of the buffer for a software canvas", e);
313
+ return null;
314
+ }
315
+ }
316
+
317
+ // --- Lifecycle -----------------------------------------------------------------
318
+
319
+ /** RN dropped the view for good (WebGPUNativeBufferViewManager.onDropViewInstance). */
320
+ public void destroy() {
321
+ if (mViewId != 0) {
322
+ nDetach(mViewId);
323
+ mViewId = 0;
324
+ }
325
+ mMainHandler.removeCallbacks(mConsume);
326
+ mConsumePosted.set(false);
327
+ if (mBitmap != null && !mBitmap.isRecycled()) {
328
+ mBitmap.recycle();
329
+ }
330
+ mBitmap = null;
331
+ }
332
+
333
+ // --- Event -------------------------------------------------------------------
334
+
335
+ private static class PixelSizeChangeEvent extends Event<PixelSizeChangeEvent> {
336
+ private final int mWidth;
337
+ private final int mHeight;
338
+
339
+ PixelSizeChangeEvent(int surfaceId, int viewTag, int width, int height) {
340
+ super(surfaceId, viewTag);
341
+ mWidth = width;
342
+ mHeight = height;
343
+ }
344
+
345
+ @Override
346
+ public String getEventName() {
347
+ return PIXEL_SIZE_CHANGE_EVENT;
348
+ }
349
+
350
+ @Override
351
+ protected WritableMap getEventData() {
352
+ WritableMap data = Arguments.createMap();
353
+ data.putInt("width", mWidth);
354
+ data.putInt("height", mHeight);
355
+ return data;
356
+ }
357
+ }
358
+
359
+ // --- Native (cpp-adapter.cpp) ------------------------------------------------
360
+
361
+ private native void nAttach(int viewId);
362
+
363
+ private static native void nDetach(int viewId);
364
+
365
+ // The newest content after `afterSequence` as a HardwareBuffer the caller
366
+ // closes, or null; its metadata goes to `info` (see INFO_*).
367
+ private static native HardwareBuffer nTakeContent(int viewId, long afterSequence, long[] info);
368
+
369
+ private static native boolean nReadPixels(HardwareBuffer buffer, Bitmap bitmap);
370
+ }
@@ -0,0 +1,56 @@
1
+ package com.webgpu;
2
+
3
+ import androidx.annotation.NonNull;
4
+ import androidx.annotation.Nullable;
5
+
6
+ import com.facebook.react.common.MapBuilder;
7
+ import com.facebook.react.module.annotations.ReactModule;
8
+ import com.facebook.react.uimanager.ThemedReactContext;
9
+ import com.facebook.react.uimanager.annotations.ReactProp;
10
+
11
+ import java.util.Map;
12
+
13
+ @ReactModule(name = WebGPUNativeBufferViewManager.NAME)
14
+ public class WebGPUNativeBufferViewManager
15
+ extends WebGPUNativeBufferViewManagerSpec<WebGPUNativeBufferView> {
16
+
17
+ public static final String NAME = "WebGPUNativeBufferView";
18
+
19
+ @NonNull
20
+ @Override
21
+ public String getName() {
22
+ return NAME;
23
+ }
24
+
25
+ @NonNull
26
+ @Override
27
+ public WebGPUNativeBufferView createViewInstance(@NonNull ThemedReactContext context) {
28
+ return new WebGPUNativeBufferView(context);
29
+ }
30
+
31
+ @Override
32
+ public void onDropViewInstance(@NonNull WebGPUNativeBufferView view) {
33
+ super.onDropViewInstance(view);
34
+ view.destroy();
35
+ }
36
+
37
+ @Override
38
+ @ReactProp(name = "viewId")
39
+ public void setViewId(WebGPUNativeBufferView view, int value) {
40
+ view.setViewId(value);
41
+ }
42
+
43
+ @Override
44
+ @ReactProp(name = "resizeMode")
45
+ public void setResizeMode(WebGPUNativeBufferView view, @Nullable String value) {
46
+ view.setResizeMode(value);
47
+ }
48
+
49
+ @Nullable
50
+ @Override
51
+ public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
52
+ return MapBuilder.<String, Object>of(
53
+ WebGPUNativeBufferView.PIXEL_SIZE_CHANGE_EVENT,
54
+ MapBuilder.of("registrationName", "onPixelSizeChange"));
55
+ }
56
+ }