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
@@ -0,0 +1,208 @@
1
+ #include "AnimationFrames.h"
2
+
3
+ #import "RNWGUIKit.h"
4
+ #import <QuartzCore/QuartzCore.h>
5
+ #import <React/RCTUtils.h>
6
+
7
+ #include <atomic>
8
+ #include <memory>
9
+
10
+ namespace rnwgpu {
11
+ class AppleAnimationFrameSource;
12
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource();
13
+ } // namespace rnwgpu
14
+
15
+ // The display link's target. A CADisplayLink retains its target, and the
16
+ // source outlives it anyway: the target borrows the source.
17
+ @interface RNWGAnimationFrameTarget : NSObject
18
+ - (instancetype)initWithSource:(rnwgpu::AppleAnimationFrameSource *)source;
19
+ - (void)onFrame:(CADisplayLink *)link;
20
+ @end
21
+
22
+ namespace rnwgpu {
23
+
24
+ #if !TARGET_OS_OSX
25
+
26
+ /**
27
+ * The display's frames on iOS: a CADisplayLink on a run loop thread of its
28
+ * own, so that a busy main thread never delays them, asking for the highest
29
+ * rate the display has. React Native's own display link sets no frame rate
30
+ * range, which keeps it at 60 Hz on a ProMotion iPhone. (The app must still
31
+ * opt in to more than 60 Hz on iPhone with CADisableMinimumFrameDurationOnPhone
32
+ * in its Info.plist.)
33
+ *
34
+ * A request is delivered at the next frame of the link. The link keeps running
35
+ * between requests, and only pauses after kIdleFramesBeforePause frames
36
+ * without one: pausing it at every frame and unpausing it at the next request
37
+ * reads to the system as a link that keeps stopping, which it does not run at
38
+ * 120 Hz. The frame time is the link's timestamp, moved from its clock to
39
+ * std::chrono::steady_clock. The thread lives as long as the process.
40
+ */
41
+ class AppleAnimationFrameSource : public AnimationFrameSource {
42
+ public:
43
+ static std::shared_ptr<AppleAnimationFrameSource> shared() {
44
+ static std::shared_ptr<AppleAnimationFrameSource> source = create();
45
+ return source;
46
+ }
47
+
48
+ void requestFrame() override {
49
+ _wanted.store(true);
50
+ // Paired with onFrame(), which stores _paused before it reads _wanted:
51
+ // either it sees this request, or this sees the link paused.
52
+ if (_paused.load()) {
53
+ unpause();
54
+ }
55
+ }
56
+
57
+ // The link's thread.
58
+ void onFrame(CADisplayLink *link) {
59
+ if (!_wanted.exchange(false)) {
60
+ if (++_idleFrames >= kIdleFramesBeforePause) {
61
+ link.paused = YES;
62
+ _paused.store(true);
63
+ if (_wanted.load()) {
64
+ unpause();
65
+ }
66
+ }
67
+ return;
68
+ }
69
+ _idleFrames = 0;
70
+ const CFTimeInterval age = CACurrentMediaTime() - link.timestamp;
71
+ const int64_t ageNanos = age > 0 ? static_cast<int64_t>(age * 1e9) : 0;
72
+ deliverFrame(AnimationFrameDispatcher::nowNanos() - ageNanos);
73
+ }
74
+
75
+ private:
76
+ AppleAnimationFrameSource() = default;
77
+
78
+ static std::shared_ptr<AppleAnimationFrameSource> create() {
79
+ auto source = std::shared_ptr<AppleAnimationFrameSource>(
80
+ new AppleAnimationFrameSource());
81
+ auto *raw = source.get();
82
+ dispatch_semaphore_t ready = dispatch_semaphore_create(0);
83
+ NSThread *thread = [[NSThread alloc] initWithBlock:^{
84
+ RNWGAnimationFrameTarget *target =
85
+ [[RNWGAnimationFrameTarget alloc] initWithSource:raw];
86
+ CADisplayLink *link =
87
+ [CADisplayLink displayLinkWithTarget:target
88
+ selector:@selector(onFrame:)];
89
+ if (@available(iOS 15.0, tvOS 15.0, *)) {
90
+ // Up to what the display can do: the system lowers it as it sees fit
91
+ // (Low Power Mode, a display that has no more).
92
+ link.preferredFrameRateRange = CAFrameRateRangeMake(60, 120, 120);
93
+ }
94
+ link.paused = YES;
95
+ [link addToRunLoop:[NSRunLoop currentRunLoop]
96
+ forMode:NSRunLoopCommonModes];
97
+ raw->_link = link;
98
+ raw->_runLoop = CFRunLoopGetCurrent();
99
+ CFRetain(raw->_runLoop);
100
+ dispatch_semaphore_signal(ready);
101
+ // The display link is a source of the run loop: it keeps running.
102
+ for (;;) {
103
+ @autoreleasepool {
104
+ [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
105
+ beforeDate:[NSDate distantFuture]];
106
+ }
107
+ }
108
+ }];
109
+ thread.name = @"RNWebGPU Frames";
110
+ thread.qualityOfService = NSQualityOfServiceUserInteractive;
111
+ [thread start];
112
+ dispatch_semaphore_wait(ready, DISPATCH_TIME_FOREVER);
113
+ return source;
114
+ }
115
+
116
+ // Any thread: the link runs again from its next frame.
117
+ void unpause() {
118
+ CFRunLoopPerformBlock(_runLoop, kCFRunLoopCommonModes, ^{
119
+ if (_paused.exchange(false)) {
120
+ _link.paused = NO;
121
+ }
122
+ });
123
+ CFRunLoopWakeUp(_runLoop);
124
+ }
125
+
126
+ static constexpr int kIdleFramesBeforePause = 8;
127
+
128
+ CADisplayLink *_link = nil;
129
+ CFRunLoopRef _runLoop = nullptr;
130
+ std::atomic<bool> _wanted{false};
131
+ std::atomic<bool> _paused{true};
132
+ // The link's thread only.
133
+ int _idleFrames = 0;
134
+ };
135
+
136
+ // Whether the app is in the foreground and active (see
137
+ // AnimationFrameDispatcher::setForeground): false from the moment it starts to
138
+ // resign active (a lock, a swipe home, an incoming call; the inactive and
139
+ // background states of iOS) until it is active again. The display link does
140
+ // not stop on its own when the app goes to the background: it runs on until
141
+ // the system suspends the app, a second or so of frames whose GPU work iOS
142
+ // refuses.
143
+ static void observeApplicationState() {
144
+ static dispatch_once_t once;
145
+ dispatch_once(&once, ^{
146
+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
147
+ [center addObserverForName:UIApplicationWillResignActiveNotification
148
+ object:nil
149
+ queue:nil
150
+ usingBlock:^(NSNotification *) {
151
+ AnimationFrameDispatcher::shared().setForeground(false);
152
+ }];
153
+ [center addObserverForName:UIApplicationDidBecomeActiveNotification
154
+ object:nil
155
+ queue:nil
156
+ usingBlock:^(NSNotification *) {
157
+ AnimationFrameDispatcher::shared().setForeground(true);
158
+ }];
159
+ // The state now, which is the main thread's to read. An app extension has
160
+ // no application: it stays in the foreground.
161
+ dispatch_async(dispatch_get_main_queue(), ^{
162
+ UIApplication *application = RCTSharedApplication();
163
+ if (application != nil &&
164
+ application.applicationState != UIApplicationStateActive) {
165
+ AnimationFrameDispatcher::shared().setForeground(false);
166
+ }
167
+ });
168
+ });
169
+ }
170
+
171
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource() {
172
+ observeApplicationState();
173
+ return AppleAnimationFrameSource::shared();
174
+ }
175
+
176
+ #else
177
+
178
+ // macOS: none for now. Each runtime keeps its own requestAnimationFrame.
179
+ class AppleAnimationFrameSource : public AnimationFrameSource {
180
+ public:
181
+ void requestFrame() override {}
182
+ void onFrame(CADisplayLink *) {}
183
+ };
184
+
185
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource() {
186
+ return nullptr;
187
+ }
188
+
189
+ #endif
190
+
191
+ } // namespace rnwgpu
192
+
193
+ @implementation RNWGAnimationFrameTarget {
194
+ rnwgpu::AppleAnimationFrameSource *_source;
195
+ }
196
+
197
+ - (instancetype)initWithSource:(rnwgpu::AppleAnimationFrameSource *)source {
198
+ if ((self = [super init])) {
199
+ _source = source;
200
+ }
201
+ return self;
202
+ }
203
+
204
+ - (void)onFrame:(CADisplayLink *)link {
205
+ _source->onFrame(link);
206
+ }
207
+
208
+ @end
@@ -45,6 +45,10 @@ public:
45
45
  VideoFrameHandle createTestVideoFrame(uint32_t width, uint32_t height,
46
46
  VideoPixelFormat format) override;
47
47
 
48
+ VideoFrameHandle createNativeBuffer(uint32_t width, uint32_t height,
49
+ wgpu::TextureFormat format,
50
+ bool displayP3) override;
51
+
48
52
  std::unique_ptr<IVideoPlayer>
49
53
  createVideoPlayer(const std::string &path, VideoPixelFormat format) override;
50
54
 
@@ -54,6 +58,8 @@ public:
54
58
 
55
59
  std::function<void(void *)> retainNativeWindow(void *window) override;
56
60
 
61
+ std::shared_ptr<AnimationFrameSource> makeAnimationFrameSource() override;
62
+
57
63
  private:
58
64
  ViewLookup _viewLookup;
59
65
  BlobManagerLookup _blobManagerLookup;
@@ -547,6 +547,14 @@ ApplePlatformContext::createVideoPlayer(const std::string &path,
547
547
  return createAppleVideoPlayer(path, format);
548
548
  }
549
549
 
550
+ // AppleAnimationFrameSource.mm
551
+ std::shared_ptr<AnimationFrameSource> makeAppleAnimationFrameSource();
552
+
553
+ std::shared_ptr<AnimationFrameSource>
554
+ ApplePlatformContext::makeAnimationFrameSource() {
555
+ return makeAppleAnimationFrameSource();
556
+ }
557
+
550
558
  std::string ApplePlatformContext::writeTestVideoFile() {
551
559
  return writeAppleTestVideoFile();
552
560
  }
@@ -685,4 +693,69 @@ ApplePlatformContext::createTestVideoFrame(uint32_t width, uint32_t height,
685
693
  return handle;
686
694
  }
687
695
 
696
+ // An IOSurface-backed pixel buffer that Dawn imports as a render target and
697
+ // Core Animation displays as layer contents (NativeBufferView). The surface is
698
+ // tagged with its color space (kIOSurfaceColorSpace), which Core Animation
699
+ // reads; untagged surfaces are taken as sRGB.
700
+ VideoFrameHandle
701
+ ApplePlatformContext::createNativeBuffer(uint32_t width, uint32_t height,
702
+ wgpu::TextureFormat format,
703
+ bool displayP3) {
704
+ OSType pixelFormat;
705
+ CFStringRef colorSpaceName;
706
+ switch (format) {
707
+ case wgpu::TextureFormat::BGRA8Unorm:
708
+ pixelFormat = kCVPixelFormatType_32BGRA;
709
+ colorSpaceName = displayP3 ? kCGColorSpaceDisplayP3 : kCGColorSpaceSRGB;
710
+ break;
711
+ case wgpu::TextureFormat::RGBA16Float:
712
+ pixelFormat = kCVPixelFormatType_64RGBAHalf;
713
+ colorSpaceName =
714
+ displayP3 ? kCGColorSpaceExtendedDisplayP3 : kCGColorSpaceExtendedSRGB;
715
+ break;
716
+ default:
717
+ throw std::runtime_error(
718
+ "createNativeBuffer: unsupported format on Apple platforms (expected "
719
+ "'bgra8unorm' or 'rgba16float')");
720
+ }
721
+ NSDictionary *attrs = @{
722
+ (NSString *)kCVPixelBufferIOSurfacePropertiesKey : @{},
723
+ (NSString *)kCVPixelBufferMetalCompatibilityKey : @YES,
724
+ };
725
+ CVPixelBufferRef pixelBuffer = NULL;
726
+ CVReturn err =
727
+ CVPixelBufferCreate(kCFAllocatorDefault, width, height, pixelFormat,
728
+ (__bridge CFDictionaryRef)attrs, &pixelBuffer);
729
+ if (err != kCVReturnSuccess || !pixelBuffer) {
730
+ throw std::runtime_error(
731
+ "createNativeBuffer: CVPixelBufferCreate failed (" +
732
+ std::to_string(err) + ")");
733
+ }
734
+ IOSurfaceRef ioSurface = CVPixelBufferGetIOSurface(pixelBuffer);
735
+ if (!ioSurface) {
736
+ CFRelease(pixelBuffer);
737
+ throw std::runtime_error(
738
+ "createNativeBuffer: pixel buffer is not IOSurface-backed");
739
+ }
740
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(colorSpaceName);
741
+ if (colorSpace != NULL) {
742
+ CFPropertyListRef plist = CGColorSpaceCopyPropertyList(colorSpace);
743
+ if (plist != NULL) {
744
+ IOSurfaceSetValue(ioSurface, kIOSurfaceColorSpace, plist);
745
+ CFRelease(plist);
746
+ }
747
+ CGColorSpaceRelease(colorSpace);
748
+ }
749
+
750
+ VideoFrameHandle handle;
751
+ handle.handle = (void *)ioSurface;
752
+ handle.width = width;
753
+ handle.height = height;
754
+ handle.colorSpace.primaries = displayP3
755
+ ? wgpu::ColorSpacePrimariesDawn::DisplayP3
756
+ : wgpu::ColorSpacePrimariesDawn::SRGB;
757
+ handle.deleter = [pixelBuffer]() { CFRelease(pixelBuffer); };
758
+ return handle;
759
+ }
760
+
688
761
  } // namespace rnwgpu
@@ -0,0 +1,88 @@
1
+ #import <Foundation/Foundation.h>
2
+ #import <Metal/Metal.h>
3
+
4
+ #include <atomic>
5
+ #include <memory>
6
+ #include <utility>
7
+
8
+ #include "NativeBufferViewRegistry.h"
9
+
10
+ namespace rnwgpu {
11
+
12
+ namespace {
13
+
14
+ // A fence that has not signaled after this long belongs to work that will
15
+ // never finish (a lost device): the buffer is dropped, as on Android.
16
+ constexpr int64_t kTimeoutSeconds = 10;
17
+
18
+ // One wait, finished by whichever comes first: the event's notification or
19
+ // the timeout. Metal cannot cancel a notification, so after a timeout the
20
+ // listener keeps its block (and this small object) until the event signals,
21
+ // possibly never; the fence and the buffer captured by `done` are released
22
+ // when the wait finishes. ANGLE's Metal sync (SyncMtl.mm) makes the same
23
+ // trade-off.
24
+ struct PendingFenceWait {
25
+ wgpu::SharedFence fence;
26
+ std::function<void(bool)> done;
27
+ std::atomic<bool> finished{false};
28
+
29
+ void finish(bool signaled) {
30
+ if (finished.exchange(true)) {
31
+ return;
32
+ }
33
+ auto callback = std::move(done);
34
+ fence = nullptr;
35
+ if (!signaled) {
36
+ NSLog(@"[WebGPU] presentNativeBuffer: the fence did not signal within "
37
+ @"%lld s; the buffer is dropped",
38
+ kTimeoutSeconds);
39
+ }
40
+ callback(signaled);
41
+ }
42
+ };
43
+
44
+ } // namespace
45
+
46
+ // The MTLSharedEvent behind a Dawn fence, waited on with a listener: no
47
+ // thread blocks. The notification and the timeout run on a private serial
48
+ // queue.
49
+ void waitForSharedFence(wgpu::SharedFence fence, uint64_t signaledValue,
50
+ std::function<void(bool)> done) {
51
+ wgpu::SharedFenceExportInfo info{};
52
+ wgpu::SharedFenceMTLSharedEventExportInfo mtlInfo{};
53
+ info.nextInChain = &mtlInfo;
54
+ fence.ExportInfo(&info);
55
+ id<MTLSharedEvent> event = (__bridge id<MTLSharedEvent>)mtlInfo.sharedEvent;
56
+ if (info.type != wgpu::SharedFenceType::MTLSharedEvent || event == nil) {
57
+ NSLog(@"[WebGPU] presentNativeBuffer: the fence is not an MTLSharedEvent; "
58
+ @"the buffer is dropped");
59
+ done(false);
60
+ return;
61
+ }
62
+ if (event.signaledValue >= signaledValue) {
63
+ done(true);
64
+ return;
65
+ }
66
+ static dispatch_queue_t queue = dispatch_queue_create(
67
+ "com.webgpu.NativeBufferView.fence", DISPATCH_QUEUE_SERIAL);
68
+ static MTLSharedEventListener *listener =
69
+ [[MTLSharedEventListener alloc] initWithDispatchQueue:queue];
70
+ // Holds the fence (which keeps the event, and Dawn's view of it, alive)
71
+ // until the wait finishes.
72
+ auto pending = std::make_shared<PendingFenceWait>();
73
+ pending->fence = std::move(fence);
74
+ pending->done = std::move(done);
75
+ [event
76
+ notifyListener:listener
77
+ atValue:signaledValue
78
+ block:^(id<MTLSharedEvent> /* event */, uint64_t /* value */) {
79
+ pending->finish(true);
80
+ }];
81
+ dispatch_after(
82
+ dispatch_time(DISPATCH_TIME_NOW, kTimeoutSeconds * NSEC_PER_SEC), queue,
83
+ ^{
84
+ pending->finish(false);
85
+ });
86
+ }
87
+
88
+ } // namespace rnwgpu
@@ -0,0 +1,15 @@
1
+ #pragma once
2
+
3
+ // RNWGUIKit selects AppKit for native macOS and UIKit for other Apple targets.
4
+ #import "RNWGUIKit.h"
5
+ #import <React/RCTViewComponentView.h>
6
+
7
+ NS_ASSUME_NONNULL_BEGIN
8
+
9
+ // NativeBufferView: displays an IOSurface that JS presented
10
+ // (RNWebGPU.presentNativeBuffer) as layer contents, with no swap chain and no
11
+ // GPU device on the display side. See NativeBufferViewRegistry.h.
12
+ @interface WebGPUNativeBufferView : RCTViewComponentView
13
+ @end
14
+
15
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,200 @@
1
+ #import "WebGPUNativeBufferView.h"
2
+
3
+ #import <QuartzCore/QuartzCore.h>
4
+
5
+ #import <react/renderer/components/RNWgpuViewSpec/ComponentDescriptors.h>
6
+ #import <react/renderer/components/RNWgpuViewSpec/EventEmitters.h>
7
+ #import <react/renderer/components/RNWgpuViewSpec/Props.h>
8
+ #import <react/renderer/components/RNWgpuViewSpec/RCTComponentViewHelpers.h>
9
+
10
+ #import <React/RCTFabricComponentsPlugins.h>
11
+
12
+ #include <cmath>
13
+ #include <memory>
14
+
15
+ #include "NativeBufferViewRegistry.h"
16
+
17
+ using namespace facebook::react;
18
+
19
+ static const std::shared_ptr<const WebGPUNativeBufferViewProps> &
20
+ defaultNativeBufferViewProps() {
21
+ static const auto props =
22
+ std::make_shared<const WebGPUNativeBufferViewProps>();
23
+ return props;
24
+ }
25
+
26
+ static NSString *gravityForResizeMode(WebGPUNativeBufferViewResizeMode mode) {
27
+ switch (mode) {
28
+ case WebGPUNativeBufferViewResizeMode::Contain:
29
+ return kCAGravityResizeAspect;
30
+ case WebGPUNativeBufferViewResizeMode::Cover:
31
+ return kCAGravityResizeAspectFill;
32
+ case WebGPUNativeBufferViewResizeMode::TopLeft:
33
+ #if !TARGET_OS_OSX
34
+ // The gravity constants assume a bottom-left origin; UIKit layers have
35
+ // a top-left one, so "bottom" is the top edge on screen.
36
+ return kCAGravityBottomLeft;
37
+ #else
38
+ return kCAGravityTopLeft;
39
+ #endif
40
+ case WebGPUNativeBufferViewResizeMode::Stretch:
41
+ default:
42
+ return kCAGravityResize;
43
+ }
44
+ }
45
+
46
+ @implementation WebGPUNativeBufferView {
47
+ // Shows the IOSurface as its layer's contents. A subview rather than this
48
+ // view's own layer, which keeps React Native's background and borders.
49
+ RNWGPlatformView *_surfaceView;
50
+ int _viewId;
51
+ // The registry sequence number of what is shown, 0 for nothing.
52
+ uint64_t _sequence;
53
+ int _reportedWidth;
54
+ int _reportedHeight;
55
+ }
56
+
57
+ + (ComponentDescriptorProvider)componentDescriptorProvider {
58
+ return concreteComponentDescriptorProvider<
59
+ WebGPUNativeBufferViewComponentDescriptor>();
60
+ }
61
+
62
+ - (instancetype)initWithFrame:(CGRect)frame {
63
+ if (self = [super initWithFrame:frame]) {
64
+ // updateProps: casts _props to WebGPUNativeBufferViewProps, so it must
65
+ // hold that type from the start (see WebGPUView).
66
+ _props = defaultNativeBufferViewProps();
67
+ _surfaceView = [RNWGPlatformView new];
68
+ #if TARGET_OS_OSX
69
+ _surfaceView.wantsLayer = YES;
70
+ #else
71
+ _surfaceView.userInteractionEnabled = NO;
72
+ #endif
73
+ CALayer *layer = _surfaceView.layer;
74
+ layer.contentsGravity = kCAGravityResize;
75
+ layer.masksToBounds = YES;
76
+ self.contentView = _surfaceView;
77
+ }
78
+ return self;
79
+ }
80
+
81
+ - (void)dealloc {
82
+ if (_viewId != 0) {
83
+ rnwgpu::NativeBufferViewRegistry::getInstance().detachView(_viewId);
84
+ }
85
+ }
86
+
87
+ - (void)prepareForRecycle {
88
+ [super prepareForRecycle];
89
+ [self attachToViewId:0];
90
+ [self setSurfaceContents:nil];
91
+ _reportedWidth = 0;
92
+ _reportedHeight = 0;
93
+ // Reset to the default props (viewId == 0) so the next mount attaches.
94
+ _props = defaultNativeBufferViewProps();
95
+ }
96
+
97
+ - (void)updateProps:(const Props::Shared &)props
98
+ oldProps:(const Props::Shared &)oldProps {
99
+ const auto &oldViewProps =
100
+ *std::static_pointer_cast<const WebGPUNativeBufferViewProps>(_props);
101
+ const auto &newViewProps =
102
+ *std::static_pointer_cast<const WebGPUNativeBufferViewProps>(props);
103
+
104
+ if (newViewProps.viewId != oldViewProps.viewId) {
105
+ [self attachToViewId:newViewProps.viewId];
106
+ }
107
+ NSString *gravity = gravityForResizeMode(newViewProps.resizeMode);
108
+ if (![_surfaceView.layer.contentsGravity isEqualToString:gravity]) {
109
+ [CATransaction begin];
110
+ [CATransaction setDisableActions:YES];
111
+ _surfaceView.layer.contentsGravity = gravity;
112
+ [CATransaction commit];
113
+ }
114
+
115
+ [super updateProps:props oldProps:oldProps];
116
+ }
117
+
118
+ - (void)updateEventEmitter:(const EventEmitter::Shared &)eventEmitter {
119
+ [super updateEventEmitter:eventEmitter];
120
+ [self reportPixelSize];
121
+ }
122
+
123
+ - (void)updateLayoutMetrics:(const LayoutMetrics &)layoutMetrics
124
+ oldLayoutMetrics:(const LayoutMetrics &)oldLayoutMetrics {
125
+ [super updateLayoutMetrics:layoutMetrics oldLayoutMetrics:oldLayoutMetrics];
126
+ // With the screen scale, a buffer of the reported size maps 1:1 to pixels,
127
+ // and topLeft shows it unscaled.
128
+ _surfaceView.layer.contentsScale = layoutMetrics.pointScaleFactor;
129
+ [self reportPixelSize];
130
+ }
131
+
132
+ // onPixelSizeChange: the size the producer should render at for a 1:1
133
+ // display. Layout frames are already on the pixel grid; the rounding only
134
+ // absorbs floating point error, the same rounding as Android's.
135
+ - (void)reportPixelSize {
136
+ const auto scale = _layoutMetrics.pointScaleFactor;
137
+ const auto size = _layoutMetrics.frame.size;
138
+ const int width = static_cast<int>(std::lround(size.width * scale));
139
+ const int height = static_cast<int>(std::lround(size.height * scale));
140
+ if (width <= 0 || height <= 0 || _eventEmitter == nullptr ||
141
+ (width == _reportedWidth && height == _reportedHeight)) {
142
+ return;
143
+ }
144
+ _reportedWidth = width;
145
+ _reportedHeight = height;
146
+ std::static_pointer_cast<const WebGPUNativeBufferViewEventEmitter>(
147
+ _eventEmitter)
148
+ ->onPixelSizeChange({.width = width, .height = height});
149
+ }
150
+
151
+ // Main thread.
152
+ - (void)attachToViewId:(int)viewId {
153
+ auto &registry = rnwgpu::NativeBufferViewRegistry::getInstance();
154
+ if (_viewId != 0) {
155
+ registry.detachView(_viewId);
156
+ }
157
+ _viewId = viewId;
158
+ _sequence = 0;
159
+ if (viewId == 0) {
160
+ return;
161
+ }
162
+ // Called from any thread (the fence listener's queue, the JS thread)
163
+ // when content is ready, and right away when there is some already.
164
+ __weak WebGPUNativeBufferView *weakSelf = self;
165
+ registry.setListener(viewId, [weakSelf]() {
166
+ dispatch_async(dispatch_get_main_queue(), ^{
167
+ [weakSelf consumeContent];
168
+ });
169
+ });
170
+ }
171
+
172
+ // Main thread: shows the newest content, if it is newer than what is shown.
173
+ // Present on change, no frame pacing: Core Animation shows it on the next
174
+ // vsync, and retains the IOSurface for as long as it does.
175
+ - (void)consumeContent {
176
+ if (_viewId == 0) {
177
+ return;
178
+ }
179
+ uint64_t sequence = 0;
180
+ auto content = rnwgpu::NativeBufferViewRegistry::getInstance().content(
181
+ _viewId, &sequence);
182
+ if (content == nullptr || sequence <= _sequence) {
183
+ return;
184
+ }
185
+ _sequence = sequence;
186
+ [self setSurfaceContents:(__bridge id)content->buffer()];
187
+ }
188
+
189
+ - (void)setSurfaceContents:(nullable id)contents {
190
+ [CATransaction begin];
191
+ [CATransaction setDisableActions:YES];
192
+ _surfaceView.layer.contents = contents;
193
+ [CATransaction commit];
194
+ }
195
+
196
+ Class<RCTComponentViewProtocol> WebGPUNativeBufferViewCls(void) {
197
+ return WebGPUNativeBufferView.class;
198
+ }
199
+
200
+ @end