react-native-webgpu 0.24.0 → 0.26.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 (91) hide show
  1. package/README.md +9 -1
  2. package/android/CMakeLists.txt +1 -0
  3. package/android/cpp/cpp-adapter.cpp +19 -96
  4. package/android/src/main/java/com/webgpu/BackingViewKind.java +5 -22
  5. package/android/src/main/java/com/webgpu/WebGPUAPI.java +0 -2
  6. package/android/src/main/java/com/webgpu/WebGPUModule.java +31 -0
  7. package/android/src/main/java/com/webgpu/WebGPUView.java +17 -34
  8. package/apple/WebGPUModule.mm +22 -0
  9. package/cpp/rnwgpu/GpuPurge.cpp +86 -0
  10. package/cpp/rnwgpu/GpuPurge.h +66 -0
  11. package/cpp/rnwgpu/SurfaceRegistry.h +0 -610
  12. package/cpp/rnwgpu/api/GPUDevice.cpp +59 -32
  13. package/cpp/rnwgpu/api/GPUDevice.h +49 -4
  14. package/cpp/rnwgpu/api/RNWebGPU.h +29 -2
  15. package/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h +46 -0
  16. package/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h +21 -15
  17. package/lib/commonjs/Canvas.js +8 -26
  18. package/lib/commonjs/Canvas.js.map +1 -1
  19. package/lib/commonjs/index.js.map +1 -1
  20. package/lib/commonjs/main/index.js +12 -0
  21. package/lib/commonjs/main/index.js.map +1 -1
  22. package/lib/commonjs/main/index.web.js +11 -0
  23. package/lib/commonjs/main/index.web.js.map +1 -1
  24. package/lib/commonjs/mock.js +4 -1
  25. package/lib/commonjs/mock.js.map +1 -1
  26. package/lib/commonjs/purgeGpuResources.js +29 -0
  27. package/lib/commonjs/purgeGpuResources.js.map +1 -0
  28. package/lib/commonjs/video.js +1 -1
  29. package/lib/commonjs/video.js.map +1 -1
  30. package/lib/module/Canvas.js +8 -26
  31. package/lib/module/Canvas.js.map +1 -1
  32. package/lib/module/index.js.map +1 -1
  33. package/lib/module/main/index.js +1 -0
  34. package/lib/module/main/index.js.map +1 -1
  35. package/lib/module/main/index.web.js +1 -0
  36. package/lib/module/main/index.web.js.map +1 -1
  37. package/lib/module/mock.js +1 -0
  38. package/lib/module/mock.js.map +1 -1
  39. package/lib/module/purgeGpuResources.js +22 -0
  40. package/lib/module/purgeGpuResources.js.map +1 -0
  41. package/lib/module/video.js +1 -1
  42. package/lib/module/video.js.map +1 -1
  43. package/lib/typescript/lib/commonjs/Canvas.d.ts.map +1 -1
  44. package/lib/typescript/lib/commonjs/mock.d.ts +1 -0
  45. package/lib/typescript/lib/commonjs/mock.d.ts.map +1 -1
  46. package/lib/typescript/lib/commonjs/purgeGpuResources.d.ts +18 -0
  47. package/lib/typescript/lib/commonjs/purgeGpuResources.d.ts.map +1 -0
  48. package/lib/typescript/lib/commonjs/video.d.ts +1 -1
  49. package/lib/typescript/lib/commonjs/video.d.ts.map +1 -1
  50. package/lib/typescript/lib/module/Canvas.d.ts.map +1 -1
  51. package/lib/typescript/lib/module/main/index.d.ts +1 -0
  52. package/lib/typescript/lib/module/main/index.web.d.ts +1 -0
  53. package/lib/typescript/lib/module/mock.d.ts +1 -0
  54. package/lib/typescript/lib/module/mock.d.ts.map +1 -1
  55. package/lib/typescript/lib/module/purgeGpuResources.d.ts +2 -0
  56. package/lib/typescript/lib/module/purgeGpuResources.d.ts.map +1 -0
  57. package/lib/typescript/lib/module/video.d.ts +1 -1
  58. package/lib/typescript/lib/module/video.d.ts.map +1 -1
  59. package/lib/typescript/src/Canvas.d.ts +2 -12
  60. package/lib/typescript/src/Canvas.d.ts.map +1 -1
  61. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts +1 -1
  62. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts.map +1 -1
  63. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts +1 -1
  64. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  65. package/lib/typescript/src/index.d.ts +3 -2
  66. package/lib/typescript/src/index.d.ts.map +1 -1
  67. package/lib/typescript/src/main/index.d.ts +1 -0
  68. package/lib/typescript/src/main/index.d.ts.map +1 -1
  69. package/lib/typescript/src/main/index.web.d.ts +1 -0
  70. package/lib/typescript/src/main/index.web.d.ts.map +1 -1
  71. package/lib/typescript/src/mock.d.ts +2 -1
  72. package/lib/typescript/src/mock.d.ts.map +1 -1
  73. package/lib/typescript/src/purgeGpuResources.d.ts +17 -0
  74. package/lib/typescript/src/purgeGpuResources.d.ts.map +1 -0
  75. package/lib/typescript/src/types.d.ts +12 -0
  76. package/lib/typescript/src/types.d.ts.map +1 -1
  77. package/lib/typescript/src/video.d.ts +2 -2
  78. package/lib/typescript/src/video.d.ts.map +1 -1
  79. package/package.json +1 -1
  80. package/scripts/prepare-apple-binaries.sh +9 -3
  81. package/src/Canvas.tsx +12 -50
  82. package/src/WebGPUViewNativeComponent.ts +1 -1
  83. package/src/WebGPUViewNativeComponent.web.ts +1 -1
  84. package/src/index.tsx +6 -1
  85. package/src/main/index.tsx +1 -0
  86. package/src/main/index.web.tsx +1 -0
  87. package/src/mock.ts +2 -1
  88. package/src/purgeGpuResources.ts +21 -0
  89. package/src/types.ts +13 -0
  90. package/src/video.ts +6 -1
  91. package/android/src/main/java/com/webgpu/WebGPUHardwareBufferView.java +0 -278
@@ -2,18 +2,13 @@
2
2
 
3
3
  #include <algorithm>
4
4
  #include <atomic>
5
- #include <cerrno>
6
- #include <chrono>
7
- #include <condition_variable>
8
5
  #include <cstdint>
9
- #include <deque>
10
6
  #include <functional>
11
7
  #include <memory>
12
8
  #include <mutex>
13
9
  #include <optional>
14
10
  #include <shared_mutex>
15
11
  #include <stdexcept>
16
- #include <thread>
17
12
  #include <unordered_map>
18
13
  #include <utility>
19
14
  #include <vector>
@@ -23,13 +18,6 @@
23
18
  #include "CanvasColorSpace.h"
24
19
  #include "WebGPURuntime.h"
25
20
 
26
- #if defined(__ANDROID__)
27
- #include <android/hardware_buffer.h>
28
- #include <android/log.h>
29
- #include <poll.h>
30
- #include <unistd.h>
31
- #endif
32
-
33
21
  #ifdef __APPLE__
34
22
  namespace dawn::native::metal {
35
23
  void WaitForCommandsToBeScheduled(WGPUDevice device);
@@ -55,64 +43,6 @@ struct Size {
55
43
  // CAMetalLayer on Apple platforms). May run on any thread.
56
44
  using NativeSurfaceReleaser = std::function<void(void *)>;
57
45
 
58
- #if defined(__ANDROID__)
59
- // --- AHB-pool presentation mode (WebGPUNativeBufferView)
60
- // -----------------------------
61
- //
62
- // A third presentation backend (besides the on-screen wgpu::Surface swapchain
63
- // and the offscreen texture). WebGPU renders into a small pool of native
64
- // AHardwareBuffers imported as Dawn SharedTextureMemory; the view draws each
65
- // finished buffer inline via Bitmap.wrapHardwareBuffer so it behaves like a
66
- // normal RN view. The pool is sized from the JS canvas drawing buffer
67
- // (_canvas->getWidth()/Height()) and reallocated when that changes, exactly
68
- // like the swapchain, so the canvas texture always matches the app's other
69
- // attachments (e.g. its depth texture).
70
-
71
- #define RNWGPU_LOG_TAG "WebGPUNativeBufferView"
72
- // Failure / anomaly reporting only (never per-frame).
73
- #define RNWGPU_POOL_WARN(...) \
74
- __android_log_print(ANDROID_LOG_WARN, RNWGPU_LOG_TAG, __VA_ARGS__)
75
-
76
- enum class SlotState : uint8_t {
77
- Free, // available for poolGetCurrentTexture
78
- Rendering, // BeginAccess done, JS rendering into it
79
- Presented, // EndAccess done, fence(s) queued for the waiter
80
- Ready, // fence signaled, awaiting UI pickup
81
- Displayed, // handed to the consumer, held until released (held-ring)
82
- };
83
-
84
- struct PoolSlot {
85
- AHardwareBuffer *ahb = nullptr; // owned by the pool (allocated natively)
86
- wgpu::SharedTextureMemory memory = nullptr;
87
- wgpu::Texture texture = nullptr;
88
- SlotState state = SlotState::Free;
89
- };
90
-
91
- // One generation of the pool (one buffer size). Reference-counted (shared_ptr)
92
- // so an in-flight render / present / ready slot keeps the whole generation
93
- // alive across a resize. The destructor frees every AHB and tears down the Dawn
94
- // imports. The Java side keeps its own ref (via wrapHardwareBuffer) for
95
- // anything it is still drawing, so a generation can be freed here without
96
- // disturbing a frame still on screen.
97
- struct AHBPool {
98
- std::vector<PoolSlot> slots;
99
- uint32_t generation = 0;
100
- int width = 0;
101
- int height = 0;
102
-
103
- ~AHBPool() {
104
- for (auto &slot : slots) {
105
- slot.texture = nullptr;
106
- slot.memory = nullptr;
107
- if (slot.ahb != nullptr) {
108
- AHardwareBuffer_release(slot.ahb);
109
- slot.ahb = nullptr;
110
- }
111
- }
112
- }
113
- };
114
- #endif
115
-
116
46
  // Bridges the asynchronous native surface lifecycle (surfaces appear and
117
47
  // disappear on the platform UI thread) with the synchronous WebGPU canvas API
118
48
  // (the JS render loop must always be able to acquire a texture).
@@ -161,16 +91,6 @@ public:
161
91
  _releaseSurfaceOnUnconfigure(releaseSurfaceOnUnconfigure) {}
162
92
 
163
93
  ~SurfaceInfo() {
164
- #if defined(__ANDROID__)
165
- // Stop the fence waiter before any pool generation is freed.
166
- stopWaiter();
167
- {
168
- std::lock_guard<std::mutex> poolLock(_poolMutex);
169
- _presentQueue.clear();
170
- poolResetLocked();
171
- _poolDevice = nullptr;
172
- }
173
- #endif
174
94
  // Drop the Dawn objects before releasing the native surfaces they borrow.
175
95
  _surface = nullptr;
176
96
  #if defined(__ANDROID__)
@@ -358,20 +278,6 @@ public:
358
278
  _config.presentMode = wgpu::PresentMode::Fifo;
359
279
  _texture = nullptr;
360
280
  _frameEpoch++;
361
- #if defined(__ANDROID__)
362
- {
363
- std::lock_guard<std::mutex> poolLock(_poolMutex);
364
- if (_poolDevice.Get() != _config.device.Get()) {
365
- // Buffers imported for another device cannot be reused.
366
- poolResetLocked();
367
- }
368
- _poolDevice = _config.device;
369
- _poolFormat = _config.format;
370
- _poolUsage = _config.usage;
371
- // A new device may support AHB sharing even if the previous one did not.
372
- _poolUnsupported = false;
373
- }
374
- #endif
375
281
  if (_releaseSurfaceOnUnconfigure && !_surface && _nativeSurface) {
376
282
  // unconfigure() destroyed the surface; make a new one for the window.
377
283
  recreateSurfaceLocked();
@@ -413,13 +319,6 @@ public:
413
319
  _viewFormats.clear();
414
320
  _acquiredFromSurface = false;
415
321
  _frameEpoch++;
416
- #if defined(__ANDROID__)
417
- {
418
- std::lock_guard<std::mutex> poolLock(_poolMutex);
419
- poolResetLocked();
420
- _poolDevice = nullptr;
421
- }
422
- #endif
423
322
  }
424
323
 
425
324
  bool isConfigured() {
@@ -447,16 +346,6 @@ public:
447
346
  void releaseSurfaceForDevice(const wgpu::Device &device) {
448
347
  #if defined(__ANDROID__)
449
348
  std::unique_lock<std::shared_mutex> lock(_mutex);
450
- {
451
- // The pool's SharedTextureMemory imports belong to the device too: drop
452
- // them while it is alive. The next getCurrentTexture() after a configure
453
- // with a live device reallocates the pool.
454
- std::lock_guard<std::mutex> poolLock(_poolMutex);
455
- if (_poolDevice && _poolDevice.Get() == device.Get()) {
456
- poolResetLocked();
457
- _poolDevice = nullptr;
458
- }
459
- }
460
349
  if (!_surface || !_surfaceDevice || _surfaceDevice.Get() != device.Get()) {
461
350
  return;
462
351
  }
@@ -475,13 +364,6 @@ public:
475
364
  // otherwise (see RNWebGPU::destroyContext).
476
365
  bool hasNativeSurface() {
477
366
  std::shared_lock<std::shared_mutex> lock(_mutex);
478
- #if defined(__ANDROID__)
479
- // A WebGPUNativeBufferView in pool mode owns presentation the same way a
480
- // surface-backed view does, and retires the entry on its own teardown.
481
- if (_poolMode.load()) {
482
- return true;
483
- }
484
- #endif
485
367
  return _nativeSurface != nullptr || _hasPendingAttach;
486
368
  }
487
369
 
@@ -494,37 +376,6 @@ public:
494
376
  // Start-of-frame boundary; a new acquire supersedes any previous frame
495
377
  // that never presented.
496
378
  applyPendingAttach(/* supersedeInFlightFrame = */ true);
497
- #if defined(__ANDROID__)
498
- if (_poolMode.load()) {
499
- // The pool tracks the drawing buffer (_config.width/height, kept in sync
500
- // with canvas.width/height by reconfigure()), like the swapchain, so the
501
- // canvas texture always matches the app's other attachments.
502
- int poolW = 0;
503
- int poolH = 0;
504
- {
505
- std::shared_lock<std::shared_mutex> lock(_mutex);
506
- if (_config.device != nullptr) {
507
- poolW = static_cast<int>(_config.width);
508
- poolH = static_cast<int>(_config.height);
509
- }
510
- }
511
- poolResize(poolW, poolH);
512
- if (auto texture = poolGetCurrentTexture()) {
513
- std::unique_lock<std::shared_mutex> lock(_mutex);
514
- _frameInFlight = true;
515
- _acquiredFromSurface = false;
516
- _frameEpoch++;
517
- if (frameEpoch) {
518
- *frameEpoch = _frameEpoch;
519
- }
520
- return texture;
521
- }
522
- // No slot available (pool not allocated yet, unsupported device, view
523
- // detached mid-frame, or a free-slot timeout): fall through to the
524
- // offscreen fallback so the render loop survives; this frame is simply
525
- // not shown.
526
- }
527
- #endif
528
379
  std::unique_lock<std::shared_mutex> lock(_mutex);
529
380
  if (_config.device == nullptr) {
530
381
  throw std::runtime_error(
@@ -571,13 +422,6 @@ public:
571
422
  // acquire failure) are dropped. This is also the end-of-frame boundary: it
572
423
  // adopts a surface that attached while the frame was in flight.
573
424
  void presentFrame() {
574
- #if defined(__ANDROID__)
575
- if (_poolMode.load()) {
576
- // Ends access on the pool slot and hands it to the fence waiter; the
577
- // view picks it up once its render-complete fence signals.
578
- poolPresent();
579
- }
580
- #endif
581
425
  #ifdef __APPLE__
582
426
  // Ensure command buffers are scheduled before presenting. Read the device
583
427
  // under a shared lock, then wait without holding it (the wait can block).
@@ -631,119 +475,6 @@ public:
631
475
  }
632
476
 
633
477
  #if defined(__ANDROID__)
634
- // --- AHB-pool API (called from the JNI layer, see cpp-adapter.cpp) ---------
635
-
636
- // Turn on pool mode for this context. dpW/dpH is the canvas-client (dp) size
637
- // reported to JS via getSize(); the actual buffers are sized in pool px from
638
- // the canvas drawing buffer in poolResize().
639
- void enablePool(int dpW, int dpH) {
640
- {
641
- std::unique_lock<std::shared_mutex> lock(_mutex);
642
- _width = dpW;
643
- _height = dpH;
644
- }
645
- std::lock_guard<std::mutex> poolLock(_poolMutex);
646
- _poolMode.store(true);
647
- _shutdown = false;
648
- }
649
-
650
- // Set the canvas-client (dp) size without changing pool mode. Keeps getSize()
651
- // (and thus the JS canvas.clientWidth/Height) in sync on resize.
652
- void setPoolClientSize(int dpW, int dpH) {
653
- std::unique_lock<std::shared_mutex> lock(_mutex);
654
- _width = dpW;
655
- _height = dpH;
656
- }
657
-
658
- // (Re)allocate the pool to match the canvas drawing buffer (px). Called from
659
- // getCurrentTexture() on the rendering thread before acquiring a slot, so the
660
- // canvas texture size always tracks the app's other attachments.
661
- void poolResize(int pxW, int pxH) {
662
- std::lock_guard<std::mutex> poolLock(_poolMutex);
663
- if (!_poolMode.load() || _poolDevice == nullptr || pxW <= 0 || pxH <= 0) {
664
- return;
665
- }
666
- if (_pool != nullptr && _pool->width == pxW && _pool->height == pxH) {
667
- return;
668
- }
669
- if (_poolUnsupported) {
670
- return;
671
- }
672
- if (!_poolDevice.HasFeature(
673
- wgpu::FeatureName::SharedTextureMemoryAHardwareBuffer)) {
674
- _poolUnsupported = true;
675
- RNWGPU_POOL_WARN("device lacks SharedTextureMemoryAHardwareBuffer; the "
676
- "transparent canvas cannot present and stays blank");
677
- return;
678
- }
679
- auto pool = allocatePoolLocked(pxW, pxH);
680
- if (pool == nullptr) {
681
- return;
682
- }
683
- _pool = pool;
684
- _pools[pool->generation] = pool;
685
- // Keep current + previous generation (in-flight frames of the previous size
686
- // may still be on screen during the cross-fade); drop anything older.
687
- for (auto it = _pools.begin(); it != _pools.end();) {
688
- if (it->first + 1 < pool->generation) {
689
- it = _pools.erase(it);
690
- } else {
691
- ++it;
692
- }
693
- }
694
- _freeCv.notify_all();
695
- }
696
-
697
- // Latest signaled frame awaiting display, encoded as (generation << 32 |
698
- // slot). Returns -1 when there is nothing new. Marks the slot Displayed so
699
- // the producer will not re-render into it until releaseSlot() is called.
700
- // Called on the UI thread after the frame-ready wake-up.
701
- int64_t poolPollReady() {
702
- std::lock_guard<std::mutex> poolLock(_poolMutex);
703
- if (_readySlot < 0 || _readyPool == nullptr) {
704
- return -1;
705
- }
706
- int idx = _readySlot;
707
- uint32_t gen = _readyPool->generation;
708
- _readyPool->slots[idx].state = SlotState::Displayed;
709
- _readyPool = nullptr;
710
- _readySlot = -1;
711
- return (static_cast<int64_t>(gen) << 32) | static_cast<uint32_t>(idx);
712
- }
713
-
714
- // The AHardwareBuffer backing a (generation, slot), for the consumer to wrap
715
- // in a Bitmap. Returns nullptr for a retired generation. Called on the UI
716
- // thread; the JNI layer converts it to a HardwareBuffer jobject.
717
- void *poolBufferForDisplay(uint32_t gen, int slot) {
718
- std::lock_guard<std::mutex> poolLock(_poolMutex);
719
- auto it = _pools.find(gen);
720
- if (it == _pools.end() || slot < 0 ||
721
- slot >= static_cast<int>(it->second->slots.size())) {
722
- return nullptr;
723
- }
724
- return it->second->slots[slot].ahb;
725
- }
726
-
727
- // The consumer is done displaying (and holding) a slot: return it to the free
728
- // list so the producer may render into it again. No-op for a retired
729
- // generation (those buffers are never reused). Called on the UI thread.
730
- void poolReleaseSlot(uint32_t gen, int idx) {
731
- std::lock_guard<std::mutex> poolLock(_poolMutex);
732
- if (_pool != nullptr && _pool->generation == gen && idx >= 0 &&
733
- idx < static_cast<int>(_pool->slots.size())) {
734
- _pool->slots[idx].state = SlotState::Free;
735
- _freeCv.notify_one();
736
- }
737
- }
738
-
739
- // Invoked from the waiter thread (never under _poolMutex) each time a new
740
- // frame becomes ready, so the consumer can wake up instead of polling every
741
- // vsync. Pass nullptr to unregister.
742
- void setPoolFrameReadyCallback(std::function<void()> cb) {
743
- std::lock_guard<std::mutex> poolLock(_poolMutex);
744
- _poolFrameReady = std::move(cb);
745
- }
746
-
747
478
  // Invoked from the presenting thread (never under _mutex) after each frame
748
479
  // presentFrame() shows on the attached surface; the blit of the last
749
480
  // offscreen frame onto a newly attached surface does not count. The view
@@ -759,42 +490,8 @@ private:
759
490
  void detach(bool createFallbackTexture) {
760
491
  void *releasedSurfaces[2] = {nullptr, nullptr};
761
492
  NativeSurfaceReleaser releasers[2];
762
- #if defined(__ANDROID__)
763
- // Destroyed outside the lock: it releases a JNI reference.
764
- std::function<void()> releasedFrameReady;
765
- #endif
766
493
  {
767
494
  std::unique_lock<std::shared_mutex> lock(_mutex);
768
- #if defined(__ANDROID__)
769
- // Leaving pool mode (the WebGPUNativeBufferView detached): drop the
770
- // pool. A configured context keeps rendering into the offscreen
771
- // fallback, exactly like the surface path.
772
- if (_poolMode.load()) {
773
- _poolMode.store(false);
774
- {
775
- std::lock_guard<std::mutex> poolLock(_poolMutex);
776
- // A frame between getCurrentTexture and present still has an open
777
- // BeginAccess; end it and queue it so the waiter drains its fences
778
- // before the generation is freed (presentFrame() no-ops for it
779
- // because pool mode is already off).
780
- if (_renderPool != nullptr && _currentRenderSlot >= 0 &&
781
- _renderPool->slots[_currentRenderSlot].state ==
782
- SlotState::Rendering) {
783
- poolQueuePresentLocked();
784
- }
785
- // _presentQueue is intentionally left alone: the waiter still has
786
- // to wait on the queued fences before the generations they pin can
787
- // be released; it discards them on publish (no live pool).
788
- poolResetLocked();
789
- releasedFrameReady = std::move(_poolFrameReady);
790
- _poolFrameReady = nullptr;
791
- }
792
- if (createFallbackTexture && _config.device != nullptr && !_texture) {
793
- _texture = createOffscreenTextureLocked();
794
- }
795
- _frameEpoch++;
796
- }
797
- #endif
798
495
  // The platform is tearing surfaces down; a not-yet-adopted attach is
799
496
  // stale, cancel it.
800
497
  if (_hasPendingAttach) {
@@ -963,281 +660,6 @@ private:
963
660
  }
964
661
  }
965
662
 
966
- #if defined(__ANDROID__)
967
- // Drop every pool generation and the ready / in-flight slot bookkeeping.
968
- // Caller holds _poolMutex. Generations pinned by a queued present survive
969
- // through their PendingPresent until the waiter is done with them.
970
- void poolResetLocked() {
971
- _pool = nullptr;
972
- _pools.clear();
973
- _readyPool = nullptr;
974
- _readySlot = -1;
975
- _renderPool = nullptr;
976
- _currentRenderSlot = -1;
977
- _freeCv.notify_all();
978
- }
979
-
980
- // Allocate + import one generation of the pool. Caller holds _poolMutex.
981
- std::shared_ptr<AHBPool> allocatePoolLocked(int w, int h) {
982
- auto pool = std::make_shared<AHBPool>();
983
- pool->generation = ++_genCounter;
984
- pool->width = w;
985
- pool->height = h;
986
- pool->slots.resize(kPoolSize);
987
- for (auto &slot : pool->slots) {
988
- AHardwareBuffer_Desc desc = {};
989
- desc.width = static_cast<uint32_t>(w);
990
- desc.height = static_cast<uint32_t>(h);
991
- desc.layers = 1;
992
- desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
993
- desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
994
- AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT;
995
- int err = AHardwareBuffer_allocate(&desc, &slot.ahb);
996
- if (err != 0 || slot.ahb == nullptr) {
997
- RNWGPU_POOL_WARN("AHardwareBuffer_allocate failed (%d) %dx%d", err, w,
998
- h);
999
- return nullptr;
1000
- }
1001
- wgpu::SharedTextureMemoryDescriptor memDesc{};
1002
- wgpu::SharedTextureMemoryAHardwareBufferDescriptor ahbDesc{};
1003
- ahbDesc.handle = slot.ahb;
1004
- memDesc.nextInChain = &ahbDesc;
1005
- slot.memory = _poolDevice.ImportSharedTextureMemory(&memDesc);
1006
- // A failed import yields a non-null Dawn error object, so probing the
1007
- // properties is the actual validity check.
1008
- wgpu::SharedTextureMemoryProperties props{};
1009
- if (slot.memory == nullptr ||
1010
- slot.memory.GetProperties(&props) != wgpu::Status::Success) {
1011
- RNWGPU_POOL_WARN("ImportSharedTextureMemory failed (%dx%d)", w, h);
1012
- return nullptr;
1013
- }
1014
- // The AHB is rgba8unorm; the pool cannot honor another configured format.
1015
- // The canvas is configured rgba8unorm on Android (the preferred format),
1016
- // so this only fires for apps hardcoding e.g. bgra8unorm.
1017
- if (_poolFormat != wgpu::TextureFormat::Undefined &&
1018
- _poolFormat != wgpu::TextureFormat::RGBA8Unorm) {
1019
- RNWGPU_POOL_WARN("configured canvas format %d is not supported by the "
1020
- "transparent canvas; using rgba8unorm (use "
1021
- "navigator.gpu.getPreferredCanvasFormat())",
1022
- static_cast<int>(_poolFormat));
1023
- }
1024
- // Honor the configured usage flags as far as the imported memory allows.
1025
- wgpu::TextureUsage wanted =
1026
- _poolUsage | wgpu::TextureUsage::RenderAttachment;
1027
- wgpu::TextureUsage usage = wanted & props.usage;
1028
- if (usage != wanted) {
1029
- RNWGPU_POOL_WARN("configured canvas usage 0x%llx narrowed to 0x%llx "
1030
- "(unsupported by the transparent canvas buffers)",
1031
- static_cast<unsigned long long>(wanted),
1032
- static_cast<unsigned long long>(usage));
1033
- }
1034
- wgpu::TextureDescriptor texDesc{};
1035
- texDesc.format = props.format;
1036
- texDesc.usage = usage;
1037
- texDesc.size.width = static_cast<uint32_t>(w);
1038
- texDesc.size.height = static_cast<uint32_t>(h);
1039
- slot.texture = slot.memory.CreateTexture(&texDesc);
1040
- slot.state = SlotState::Free;
1041
- }
1042
- return pool;
1043
- }
1044
-
1045
- wgpu::Texture poolGetCurrentTexture() {
1046
- std::unique_lock<std::mutex> lock(_poolMutex);
1047
- // Per the WebGPU spec, getCurrentTexture returns the same texture until the
1048
- // frame is presented; a repeat call must not consume another slot.
1049
- if (_renderPool != nullptr && _currentRenderSlot >= 0) {
1050
- return _renderPool->slots[_currentRenderSlot].texture;
1051
- }
1052
- if (_pool == nullptr) {
1053
- return nullptr; // allocation failed / unsupported (already reported)
1054
- }
1055
- auto pool = _pool;
1056
- int idx = -1;
1057
- // Bounded wait: if no slot frees up (e.g. a wedged fence), skip the frame
1058
- // instead of parking the JS/worklet thread forever.
1059
- bool ready = _freeCv.wait_for(lock, std::chrono::seconds(1), [&]() {
1060
- if (_shutdown || pool != _pool) {
1061
- return true; // pool replaced or shutting down: bail out
1062
- }
1063
- for (size_t i = 0; i < pool->slots.size(); i++) {
1064
- if (pool->slots[i].state == SlotState::Free) {
1065
- idx = static_cast<int>(i);
1066
- return true;
1067
- }
1068
- }
1069
- return false;
1070
- });
1071
- if (!ready) {
1072
- RNWGPU_POOL_WARN("poolGetCurrentTexture: timed out waiting for a free "
1073
- "slot; skipping frame");
1074
- return nullptr;
1075
- }
1076
- if (idx < 0 || _shutdown || pool != _pool) {
1077
- return nullptr;
1078
- }
1079
- auto &slot = pool->slots[idx];
1080
- slot.state = SlotState::Rendering;
1081
- _renderPool = pool;
1082
- _currentRenderSlot = idx;
1083
- poolBeginAccess(slot);
1084
- return slot.texture;
1085
- }
1086
-
1087
- void poolPresent() {
1088
- std::lock_guard<std::mutex> lock(_poolMutex);
1089
- if (_currentRenderSlot < 0 || _renderPool == nullptr) {
1090
- return;
1091
- }
1092
- poolQueuePresentLocked();
1093
- }
1094
-
1095
- // Ends access on the in-flight render slot and hands it (with its fences) to
1096
- // the waiter. Caller holds _poolMutex and guarantees _renderPool /
1097
- // _currentRenderSlot are valid.
1098
- void poolQueuePresentLocked() {
1099
- auto pool = _renderPool;
1100
- int idx = _currentRenderSlot;
1101
- auto &slot = pool->slots[idx];
1102
-
1103
- wgpu::SharedTextureMemoryEndAccessState state{};
1104
- wgpu::SharedTextureMemoryVkImageLayoutEndState vkLayout{};
1105
- state.nextInChain = &vkLayout;
1106
- slot.memory.EndAccess(slot.texture, &state);
1107
-
1108
- std::vector<wgpu::SharedFence> fences;
1109
- fences.reserve(state.fenceCount);
1110
- for (size_t i = 0; i < state.fenceCount; i++) {
1111
- fences.push_back(state.fences[i]);
1112
- }
1113
-
1114
- slot.state = SlotState::Presented;
1115
- _presentQueue.push_back({pool, idx, std::move(fences)});
1116
- _renderPool = nullptr;
1117
- _currentRenderSlot = -1;
1118
- startWaiterLocked();
1119
- _presentCv.notify_one();
1120
- }
1121
-
1122
- void poolBeginAccess(PoolSlot &slot) {
1123
- wgpu::SharedTextureMemoryBeginAccessDescriptor desc{};
1124
- desc.initialized = false; // canvas contents are fully redrawn each frame
1125
- desc.concurrentRead = false;
1126
- desc.fenceCount = 0;
1127
- desc.fences = nullptr;
1128
- desc.signaledValues = nullptr;
1129
- wgpu::SharedTextureMemoryVkImageLayoutBeginState vkLayout{};
1130
- vkLayout.oldLayout = 0;
1131
- vkLayout.newLayout = 0;
1132
- desc.nextInChain = &vkLayout;
1133
- slot.memory.BeginAccess(slot.texture, &desc);
1134
- }
1135
-
1136
- void startWaiterLocked() {
1137
- if (_waiterRunning) {
1138
- return;
1139
- }
1140
- _waiterRunning = true;
1141
- _waiter = std::thread([this]() { waiterLoop(); });
1142
- }
1143
-
1144
- void stopWaiter() {
1145
- {
1146
- std::lock_guard<std::mutex> lock(_poolMutex);
1147
- _shutdown = true;
1148
- _presentCv.notify_all();
1149
- _freeCv.notify_all();
1150
- }
1151
- if (_waiter.joinable()) {
1152
- _waiter.join();
1153
- }
1154
- _waiterRunning = false;
1155
- }
1156
-
1157
- // Blocks on each presented frame's render-complete fence (off the UI and JS
1158
- // threads), then publishes it as the latest ready slot. This is the rigorous
1159
- // acquire-side wait: HWUI only samples a buffer after the UI thread picks it
1160
- // up via poolPollReady, which happens strictly after this wait returns.
1161
- void waiterLoop() {
1162
- while (true) {
1163
- PendingPresent pending;
1164
- {
1165
- std::unique_lock<std::mutex> lock(_poolMutex);
1166
- _presentCv.wait(lock,
1167
- [&]() { return _shutdown || !_presentQueue.empty(); });
1168
- if (_shutdown && _presentQueue.empty()) {
1169
- return;
1170
- }
1171
- pending = std::move(_presentQueue.front());
1172
- _presentQueue.pop_front();
1173
- }
1174
-
1175
- // Wait outside the lock. Each fd is owned by its SharedFence and closed
1176
- // when `pending.fences` is destroyed at the end of this iteration, so we
1177
- // never dup / double-close (avoids the fdsan abort, see
1178
- // GPUSharedFence.cpp).
1179
- for (auto &fence : pending.fences) {
1180
- wgpu::SharedFenceExportInfo info{};
1181
- wgpu::SharedFenceSyncFDExportInfo fdInfo{};
1182
- info.nextInChain = &fdInfo;
1183
- fence.ExportInfo(&info);
1184
- if (info.type != wgpu::SharedFenceType::SyncFD) {
1185
- // fdInfo was not populated (its default handle 0 is NOT a fence fd);
1186
- // we have no way to wait on this fence type.
1187
- RNWGPU_POOL_WARN("waiter: unexpected shared fence type %d, cannot "
1188
- "wait for render completion",
1189
- static_cast<int>(info.type));
1190
- continue;
1191
- }
1192
- if (fdInfo.handle >= 0) {
1193
- // Sync-fence fds become readable (POLLIN) when signaled; poll()
1194
- // avoids any libsync linkage concern. Poll in bounded slices so
1195
- // teardown (which flips _shutdown) cannot hang here on a wedged GPU.
1196
- struct pollfd pfd;
1197
- pfd.fd = fdInfo.handle;
1198
- pfd.events = POLLIN;
1199
- while (!_shutdown.load()) {
1200
- pfd.revents = 0;
1201
- int r = poll(&pfd, 1, 100);
1202
- if (r > 0) {
1203
- break; // signaled (or POLLERR): stop waiting
1204
- }
1205
- if (r < 0 && errno != EINTR) {
1206
- break; // real poll error; EINTR just retries
1207
- }
1208
- }
1209
- }
1210
- }
1211
-
1212
- std::function<void()> frameReady;
1213
- {
1214
- std::lock_guard<std::mutex> lock(_poolMutex);
1215
- // Pool torn down (switchToOffscreen) while this frame was in flight:
1216
- // discard it now that its fences have been drained. Publishing it would
1217
- // pin the retired generation forever (nothing polls anymore).
1218
- if (_pool == nullptr) {
1219
- continue;
1220
- }
1221
- // Supersede a still-unclaimed ready frame: drop it back to Free if it
1222
- // belongs to the live pool (a retired pool is simply discarded).
1223
- if (_readyPool != nullptr && _readySlot >= 0) {
1224
- if (_readyPool == _pool) {
1225
- _readyPool->slots[_readySlot].state = SlotState::Free;
1226
- _freeCv.notify_one();
1227
- }
1228
- }
1229
- pending.pool->slots[pending.slot].state = SlotState::Ready;
1230
- _readyPool = pending.pool;
1231
- _readySlot = pending.slot;
1232
- frameReady = _poolFrameReady;
1233
- }
1234
- if (frameReady) {
1235
- frameReady(); // outside the lock: it calls into Java
1236
- }
1237
- }
1238
- }
1239
- #endif
1240
-
1241
663
  mutable std::shared_mutex _mutex;
1242
664
  #if defined(__ANDROID__)
1243
665
  // DAWN_WORKAROUND_DEVICE_DESTROY_BEFORE_SURFACE_RELEASE
@@ -1291,40 +713,8 @@ private:
1291
713
  bool _releaseSurfaceOnUnconfigure = false;
1292
714
 
1293
715
  #if defined(__ANDROID__)
1294
- // Pool state. Guarded by _poolMutex (never nested under _mutex while
1295
- // blocking).
1296
- struct PendingPresent {
1297
- std::shared_ptr<AHBPool> pool;
1298
- int slot;
1299
- std::vector<wgpu::SharedFence> fences;
1300
- };
1301
-
1302
- static constexpr int kPoolSize =
1303
- 5; // 2 held + 1 rendering + 1 waiting + 1 ready
1304
-
1305
716
  // See setFramePresentedCallback(); read under _mutex, called outside it.
1306
717
  std::function<void()> _framePresented;
1307
-
1308
- std::atomic<bool> _poolMode{false};
1309
- std::mutex _poolMutex;
1310
- std::condition_variable _freeCv; // a slot returned to Free
1311
- std::condition_variable _presentCv; // a frame was queued for the waiter
1312
- wgpu::Device _poolDevice = nullptr;
1313
- wgpu::TextureFormat _poolFormat = wgpu::TextureFormat::Undefined;
1314
- wgpu::TextureUsage _poolUsage = wgpu::TextureUsage::RenderAttachment;
1315
- bool _poolUnsupported = false; // device lacks AHB shared-texture support
1316
- std::shared_ptr<AHBPool> _pool; // current generation
1317
- std::unordered_map<uint32_t, std::shared_ptr<AHBPool>> _pools; // gen -> pool
1318
- std::shared_ptr<AHBPool> _renderPool; // generation of the in-flight render
1319
- int _currentRenderSlot = -1;
1320
- std::shared_ptr<AHBPool> _readyPool; // generation of the latest ready frame
1321
- int _readySlot = -1;
1322
- std::deque<PendingPresent> _presentQueue;
1323
- std::thread _waiter;
1324
- bool _waiterRunning = false;
1325
- std::atomic<bool> _shutdown{false};
1326
- uint32_t _genCounter = 0;
1327
- std::function<void()> _poolFrameReady; // consumer wake-up, see setter
1328
718
  #endif
1329
719
  };
1330
720