react-native-webgpu 0.23.0 → 0.25.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 (127) hide show
  1. package/Package.swift +18 -129
  2. package/android/CMakeLists.txt +1 -0
  3. package/android/cpp/AndroidPlatformContext.h +10 -9
  4. package/android/cpp/cpp-adapter.cpp +19 -96
  5. package/android/src/main/java/com/webgpu/BackingViewKind.java +5 -22
  6. package/android/src/main/java/com/webgpu/WebGPUAPI.java +0 -2
  7. package/android/src/main/java/com/webgpu/WebGPUModule.java +34 -3
  8. package/android/src/main/java/com/webgpu/WebGPUVideoPlayer.java +1 -1
  9. package/android/src/main/java/com/webgpu/WebGPUView.java +17 -34
  10. package/apple/ApplePlatformContext.h +2 -1
  11. package/apple/ApplePlatformContext.mm +2 -2
  12. package/apple/WebGPUModule.mm +22 -0
  13. package/binaries.json +53 -105
  14. package/cpp/dawn/common/ExternalTextureParams.h +3 -3
  15. package/cpp/dawn/include/dawn/dawn_proc.h +53 -0
  16. package/cpp/dawn/include/dawn/dawn_proc_table.h +329 -0
  17. package/cpp/dawn/include/dawn/dawn_thread_dispatch_proc.h +47 -0
  18. package/cpp/dawn/include/dawn/dawn_version.h +51 -0
  19. package/cpp/dawn/include/dawn/native/D3D11Backend.h +65 -0
  20. package/cpp/dawn/include/dawn/native/D3D12Backend.h +104 -0
  21. package/cpp/dawn/include/dawn/native/D3DBackend.h +56 -0
  22. package/cpp/dawn/include/dawn/native/DawnNative.h +375 -0
  23. package/cpp/dawn/include/dawn/native/MetalBackend.h +67 -0
  24. package/cpp/dawn/include/dawn/native/NullBackend.h +39 -0
  25. package/cpp/dawn/include/dawn/native/OpenGLBackend.h +89 -0
  26. package/cpp/dawn/include/dawn/native/VulkanBackend.h +199 -0
  27. package/cpp/dawn/include/dawn/native/WebGPUBackend.h +49 -0
  28. package/cpp/dawn/include/dawn/native/dawn_native_export.h +49 -0
  29. package/cpp/dawn/include/dawn/platform/DawnPlatform.h +210 -0
  30. package/cpp/dawn/include/dawn/platform/dawn_platform_export.h +49 -0
  31. package/cpp/dawn/include/dawn/replay/Replay.h +99 -0
  32. package/cpp/dawn/include/dawn/replay/dawn_replay_export.h +49 -0
  33. package/cpp/dawn/include/dawn/webgpu.h +5119 -0
  34. package/cpp/dawn/include/dawn/webgpu_cpp.h +10506 -0
  35. package/cpp/dawn/include/dawn/webgpu_cpp_print.h +2897 -0
  36. package/cpp/dawn/include/webgpu/webgpu.h +33 -0
  37. package/cpp/dawn/include/webgpu/webgpu_cpp.h +33 -0
  38. package/cpp/dawn/include/webgpu/webgpu_cpp_chained_struct.h +57 -0
  39. package/cpp/dawn/include/webgpu/webgpu_cpp_print.h +33 -0
  40. package/cpp/dawn/include/webgpu/webgpu_enum_class_bitmasks.h +163 -0
  41. package/cpp/dawn/include/webgpu/webgpu_glfw.h +88 -0
  42. package/cpp/rnwgpu/GpuPurge.cpp +86 -0
  43. package/cpp/rnwgpu/GpuPurge.h +66 -0
  44. package/cpp/rnwgpu/PlatformContext.h +1 -1
  45. package/cpp/rnwgpu/SurfaceRegistry.h +2 -612
  46. package/cpp/rnwgpu/api/GPUAdapter.cpp +1 -1
  47. package/cpp/rnwgpu/api/GPUDevice.cpp +59 -32
  48. package/cpp/rnwgpu/api/GPUDevice.h +49 -4
  49. package/cpp/rnwgpu/api/RNWebGPU.h +11 -4
  50. package/lib/commonjs/Canvas.js +8 -26
  51. package/lib/commonjs/Canvas.js.map +1 -1
  52. package/lib/commonjs/main/index.js +12 -0
  53. package/lib/commonjs/main/index.js.map +1 -1
  54. package/lib/commonjs/main/index.web.js +11 -0
  55. package/lib/commonjs/main/index.web.js.map +1 -1
  56. package/lib/commonjs/mock.js +4 -1
  57. package/lib/commonjs/mock.js.map +1 -1
  58. package/lib/commonjs/purgeGpuResources.js +29 -0
  59. package/lib/commonjs/purgeGpuResources.js.map +1 -0
  60. package/lib/commonjs/video.js +8 -4
  61. package/lib/commonjs/video.js.map +1 -1
  62. package/lib/module/Canvas.js +8 -26
  63. package/lib/module/Canvas.js.map +1 -1
  64. package/lib/module/main/index.js +1 -0
  65. package/lib/module/main/index.js.map +1 -1
  66. package/lib/module/main/index.web.js +1 -0
  67. package/lib/module/main/index.web.js.map +1 -1
  68. package/lib/module/mock.js +1 -0
  69. package/lib/module/mock.js.map +1 -1
  70. package/lib/module/purgeGpuResources.js +22 -0
  71. package/lib/module/purgeGpuResources.js.map +1 -0
  72. package/lib/module/video.js +6 -2
  73. package/lib/module/video.js.map +1 -1
  74. package/lib/typescript/lib/commonjs/Canvas.d.ts.map +1 -1
  75. package/lib/typescript/lib/commonjs/mock.d.ts +1 -0
  76. package/lib/typescript/lib/commonjs/mock.d.ts.map +1 -1
  77. package/lib/typescript/lib/commonjs/purgeGpuResources.d.ts +18 -0
  78. package/lib/typescript/lib/commonjs/purgeGpuResources.d.ts.map +1 -0
  79. package/lib/typescript/lib/commonjs/video.d.ts +6 -2
  80. package/lib/typescript/lib/commonjs/video.d.ts.map +1 -1
  81. package/lib/typescript/lib/module/Canvas.d.ts.map +1 -1
  82. package/lib/typescript/lib/module/main/index.d.ts +1 -0
  83. package/lib/typescript/lib/module/main/index.web.d.ts +1 -0
  84. package/lib/typescript/lib/module/mock.d.ts +1 -0
  85. package/lib/typescript/lib/module/mock.d.ts.map +1 -1
  86. package/lib/typescript/lib/module/purgeGpuResources.d.ts +2 -0
  87. package/lib/typescript/lib/module/purgeGpuResources.d.ts.map +1 -0
  88. package/lib/typescript/lib/module/video.d.ts +1 -1
  89. package/lib/typescript/lib/module/video.d.ts.map +1 -1
  90. package/lib/typescript/react-native.config.d.ts +1 -0
  91. package/lib/typescript/src/Canvas.d.ts +2 -12
  92. package/lib/typescript/src/Canvas.d.ts.map +1 -1
  93. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts +1 -1
  94. package/lib/typescript/src/WebGPUViewNativeComponent.d.ts.map +1 -1
  95. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts +1 -1
  96. package/lib/typescript/src/WebGPUViewNativeComponent.web.d.ts.map +1 -1
  97. package/lib/typescript/src/index.d.ts +3 -2
  98. package/lib/typescript/src/index.d.ts.map +1 -1
  99. package/lib/typescript/src/main/index.d.ts +1 -0
  100. package/lib/typescript/src/main/index.d.ts.map +1 -1
  101. package/lib/typescript/src/main/index.web.d.ts +1 -0
  102. package/lib/typescript/src/main/index.web.d.ts.map +1 -1
  103. package/lib/typescript/src/mock.d.ts +2 -1
  104. package/lib/typescript/src/mock.d.ts.map +1 -1
  105. package/lib/typescript/src/purgeGpuResources.d.ts +17 -0
  106. package/lib/typescript/src/purgeGpuResources.d.ts.map +1 -0
  107. package/lib/typescript/src/types.d.ts +1 -1
  108. package/lib/typescript/src/types.d.ts.map +1 -1
  109. package/lib/typescript/src/video.d.ts +7 -3
  110. package/lib/typescript/src/video.d.ts.map +1 -1
  111. package/package.json +10 -5
  112. package/react-native-webgpu.podspec +46 -78
  113. package/react-native.config.js +9 -6
  114. package/scripts/apple-binaries-utils.sh +280 -0
  115. package/scripts/prepare-apple-binaries.sh +309 -0
  116. package/scripts/spm-plugin.js +130 -0
  117. package/src/Canvas.tsx +12 -50
  118. package/src/WebGPUViewNativeComponent.ts +1 -1
  119. package/src/WebGPUViewNativeComponent.web.ts +1 -1
  120. package/src/index.tsx +5 -4
  121. package/src/main/index.tsx +1 -0
  122. package/src/main/index.web.tsx +1 -0
  123. package/src/mock.ts +2 -1
  124. package/src/purgeGpuResources.ts +21 -0
  125. package/src/types.ts +1 -1
  126. package/src/video.ts +12 -5
  127. package/android/src/main/java/com/webgpu/WebGPUHardwareBufferView.java +0 -278
package/Package.swift CHANGED
@@ -1,134 +1,21 @@
1
1
  // swift-tools-version: 6.0
2
- //
3
- // SwiftPM manifest for react-native-webgpu. iOS only.
4
- // Additive: the CocoaPods podspec remains the supported default.
5
- //
6
- // React Native 0.87+ references a library that ships its own Package.swift
7
- // through a symlink at <app>/ios/build/generated/autolinking/libs/<name>, and
8
- // resolves the relative paths below against that symlink. They are the same
9
- // for every standard app, because the symlink location is. Earlier React
10
- // Native releases have no SwiftPM autolinking: keep CocoaPods there.
11
-
2
+ // Optional RN 0.87.1+ SwiftPM integration; CocoaPods remains the default.
3
+ // The autolinking plugin registers this manifest through libs/ReactNativeWebGPU
4
+ // and creates a neighboring link-settings package. Headers ship in npm; an
5
+ // Xcode phase prepares only the selected SDK's Dawn archive before app linking.
12
6
  import Foundation
13
7
  import PackageDescription
14
8
 
15
- // Absolute location of this package. Xcode passes the autolinking symlink as
16
- // the package directory, so resolve it before deriving sibling paths.
17
- let packageRoot = URL(fileURLWithPath: Context.packageDirectory)
18
- .resolvingSymlinksInPath().path
19
- let sibling = { (relative: String) -> String in
20
- URL(fileURLWithPath: "\(packageRoot)/\(relative)").standardized.path
21
- }
22
- // A node package next to this one: a sibling in the consumer's node_modules,
23
- // or under this monorepo's root.
24
- let nodePackage = { (name: String) -> String? in
25
- ["../\(name)", "../../node_modules/\(name)"]
26
- .map(sibling)
27
- .first { FileManager.default.fileExists(atPath: "\($0)/package.json") }
28
- }
29
- let readJSON = { (path: String) -> [String: Any]? in
30
- guard let data = FileManager.default.contents(atPath: path) else { return nil }
31
- return try? JSONSerialization.jsonObject(with: data) as? [String: Any]
32
- }
33
-
34
- // Dawn, the WebGPU implementation, comes from the react-native-webgpu-dawn npm
35
- // package this package depends on: an xcframework with the `webgpu/` and
36
- // `dawn/` headers embedded in every slice, which SwiftPM exposes to dependents
37
- // without any search path. react-native-skia's Graphite backend links the
38
- // same package, so an app installing both contains exactly one Dawn.
39
- guard let dawnPath = nodePackage("react-native-webgpu-dawn") else {
40
- // Reached when the dependency was skipped at install time, which SwiftPM
41
- // would otherwise report as an unresolvable dependency path.
42
- fatalError(
43
- """
44
- react-native-webgpu-dawn was not found next to react-native-webgpu. It ships \
45
- the Dawn binaries this package links against. Reinstall dependencies.
46
- """)
47
- }
48
- let ownPackage = readJSON("\(packageRoot)/package.json") ?? [:]
49
- let dawnVersion =
50
- (readJSON("\(dawnPath)/package.json")?["version"] as? String) ?? "unknown"
51
-
52
- // Skia Graphite and WebGPU must link the exact same Dawn, or the pair links
53
- // fine and crashes at runtime. react-native-skia's podspec enforces this at
54
- // `pod install` time; a Swift package has no install hook, so the same check
55
- // runs here, at manifest evaluation. SwiftPM caches evaluations, so after
56
- // changing either package's Dawn reset the package caches (File > Packages >
57
- // Reset Package Caches) if this does not re-run.
58
- //
59
- // A react-native-skia that depends on react-native-webgpu-dawn itself must
60
- // resolve the same version as this package: the copy nested under it when the
61
- // package manager could not hoist it, else the one next to it (Node's
62
- // resolution, which react-native-skia's podspec compares too). A workspace
63
- // that resolves the package to one version for both (yarn `resolutions`, npm
64
- // `overrides`) passes while react-native-skia's own pin lags behind a Dawn
65
- // bump: the app then contains that one Dawn. Older Graphite builds
66
- // (react-native-skia 3.0.x) vendor their own Dawn and record its release tag
67
- // at libs/.dawn-version in their binary packages; this package's `dawn` field
68
- // names the release that Dawn is interchangeable with.
69
- if let skiaPath = nodePackage("react-native-skia"),
70
- let skiaPackage = readJSON("\(skiaPath)/package.json"),
71
- let skiaDawnPin = (skiaPackage["dependencies"] as? [String: String])?["react-native-webgpu-dawn"]
72
- {
73
- let skiaDawnPath = [
74
- "\(skiaPath)/node_modules/react-native-webgpu-dawn",
75
- "\(skiaPath)/../react-native-webgpu-dawn",
76
- ].first { FileManager.default.fileExists(atPath: "\($0)/package.json") }
77
- let skiaDawn =
78
- skiaDawnPath.flatMap { readJSON("\($0)/package.json")?["version"] as? String } ?? skiaDawnPin
79
- if skiaDawn != dawnVersion {
80
- fatalError(
81
- """
82
- react-native-webgpu: Dawn version mismatch. This package links \
83
- react-native-webgpu-dawn \(dawnVersion) but react-native-skia resolves \
84
- \(skiaDawn) (it depends on \(skiaDawnPin)). Align the two packages so the \
85
- app contains exactly one Dawn.
86
- """)
87
- }
88
- } else {
89
- let dawnReleaseTag =
90
- "dawn-\((ownPackage["dawn"] as? String ?? "").replacingOccurrences(of: "/", with: "-"))"
91
- // The graphite packages are normally hoisted next to this package, but may
92
- // be nested under react-native-skia when the package manager cannot hoist
93
- // them. The v2 Graphite previews (e.g. @shopify/react-native-skia@2.12.0-next.1)
94
- // keep the marker in their own libs/. Every marker found is checked.
95
- let skiaDawnMarkers = [
96
- "react-native-skia-graphite-apple-ios/libs/.dawn-version",
97
- "react-native-skia-graphite-apple-macos/libs/.dawn-version",
98
- "react-native-skia/node_modules/react-native-skia-graphite-apple-ios/libs/.dawn-version",
99
- "react-native-skia/node_modules/react-native-skia-graphite-apple-macos/libs/.dawn-version",
100
- "@shopify/react-native-skia/libs/.dawn-version",
101
- ].flatMap { marker in
102
- [
103
- sibling("../\(marker)"), // consumer: sibling in node_modules
104
- sibling("../../node_modules/\(marker)"), // this monorepo
105
- ]
106
- }
107
- for marker in skiaDawnMarkers {
108
- guard let data = FileManager.default.contents(atPath: marker),
109
- let skiaDawn = String(data: data, encoding: .utf8)?
110
- .trimmingCharacters(in: .whitespacesAndNewlines)
111
- else { continue }
112
- if skiaDawn != dawnReleaseTag {
113
- fatalError(
114
- """
115
- react-native-webgpu: Dawn version mismatch. This package links \
116
- react-native-webgpu-dawn \(dawnVersion) (\(dawnReleaseTag)) but the \
117
- react-native-skia Graphite binaries (\(marker)) link \(skiaDawn). Align \
118
- the two packages so the app contains exactly one Dawn.
119
- """)
120
- }
121
- }
9
+ // SwiftPM discovers resources even with explicit sources. Limit discovery to
10
+ // native directories, excluding JS dependencies and build products automatically.
11
+ let packageDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
12
+ let nativeDirectories: Set<String> = ["apple", "cpp"]
13
+ let excludedPaths = try FileManager.default.contentsOfDirectory(atPath: packageDirectory.path).filter {
14
+ !nativeDirectories.contains($0)
122
15
  }
123
16
 
124
- // Unlike a native Xcode target, SwiftPM doesn't generate an implicit
125
- // per-target header map, so quoted includes only resolve within the
126
- // including file's own directory. The sources use bare cross-directory
127
- // includes (e.g. apple/WebGPUModule.h includes "RNWebGPUManager.h" from
128
- // cpp/rnwgpu), so every directory that's the target of one of those bare
129
- // includes has to be listed explicitly here. The "webgpu/..." and "dawn/..."
130
- // includes resolve through the Dawn xcframework's embedded headers.
131
- // Keep in sync with header_dirs in react-native-webgpu.podspec.
17
+ // Bare includes need each internal directory explicitly, including the bundled
18
+ // source/generated Dawn headers. Keep this catalog aligned with the podspec.
132
19
  let internalHeaderDirs = [
133
20
  "apple",
134
21
  "cpp",
@@ -137,6 +24,7 @@ let internalHeaderDirs = [
137
24
  "cpp/rnwgpu/api",
138
25
  "cpp/rnwgpu/api/descriptors",
139
26
  "cpp/rnwgpu/async",
27
+ "cpp/dawn/include",
140
28
  ]
141
29
 
142
30
  let package = Package(
@@ -145,7 +33,7 @@ let package = Package(
145
33
  // target's. React Native's generated Autolinked aggregate hardcodes iOS 15.0
146
34
  // (react-native#58379 derives it from the app instead), so this must not
147
35
  // exceed 15.0; a lower floor is always accepted.
148
- platforms: [.iOS(.v15)],
36
+ platforms: [.iOS(.v15), .tvOS(.v15), .macOS(.v14)],
149
37
  products: [
150
38
  // Autolinking looks this name up verbatim; react-native.config.js pins it.
151
39
  .library(name: "ReactNativeWebGPU", targets: ["ReactNativeWebGPU"])
@@ -153,7 +41,7 @@ let package = Package(
153
41
  dependencies: [
154
42
  .package(name: "React-GeneratedCode", path: "../../../ios"),
155
43
  .package(name: "ReactNative", path: "../../../../xcframeworks"),
156
- .package(path: dawnPath),
44
+ .package(name: "ReactNativeWebGPUBinaries", path: "../../ReactNativeWebGPUBinaries"),
157
45
  ],
158
46
  targets: [
159
47
  .target(
@@ -164,12 +52,13 @@ let package = Package(
164
52
  .product(name: "ReactNativeDependenciesHeaders", package: "ReactNative"),
165
53
  // RNWgpuViewSpec, generated by the app's codegen run.
166
54
  .product(name: "ReactAppHeaders", package: "React-GeneratedCode"),
167
- .product(name: "react-native-webgpu-dawn", package: "react-native-webgpu-dawn"),
55
+ .product(name: "ReactNativeWebGPUBinaries", package: "ReactNativeWebGPUBinaries"),
168
56
  ],
169
57
  // apple/ and cpp/ have no common ancestor below the package root, and
170
58
  // .headerSearchPath cannot escape the target path.
171
59
  path: ".",
172
- // Explicit, so SwiftPM never walks node_modules, lib or android.
60
+ exclude: excludedPaths,
61
+ // Compile only native implementations; Dawn itself is already prebuilt.
173
62
  sources: ["apple", "cpp/jsi", "cpp/rnwgpu"],
174
63
  // SwiftPM requires a public headers directory inside the target and
175
64
  // defaults to "include", which this package does not have.
@@ -56,6 +56,7 @@ add_library(${PACKAGE_NAME} SHARED
56
56
  ../cpp/rnwgpu/api/GPUComputePipeline.cpp
57
57
  ../cpp/rnwgpu/api/GPUCanvasContext.cpp
58
58
  ../cpp/rnwgpu/DawnBlobCache.cpp
59
+ ../cpp/rnwgpu/GpuPurge.cpp
59
60
  ../cpp/rnwgpu/NativeBufferViewRegistry.cpp
60
61
  ../cpp/rnwgpu/AnimationFrames.cpp
61
62
  ../cpp/rnwgpu/RNWebGPUManager.cpp
@@ -479,36 +479,37 @@ public:
479
479
  // the frames are sampled through importExternalTexture (see
480
480
  // WebGPUVideoPlayer.java).
481
481
  std::unique_ptr<IVideoPlayer>
482
- createVideoPlayer(const std::string &path,
483
- VideoPixelFormat /*format*/) override {
482
+ createTestVideoPlayer(const std::string &path,
483
+ VideoPixelFormat /*format*/) override {
484
484
  if (!_module) {
485
- throw std::runtime_error("createVideoPlayer: the WebGPU module is gone");
485
+ throw std::runtime_error(
486
+ "createTestVideoPlayer: the WebGPU module is gone");
486
487
  }
487
488
  jni::Environment::ensureCurrentThreadIsAttached();
488
489
  JNIEnv *env = facebook::jni::Environment::current();
489
490
  if (!env) {
490
491
  throw std::runtime_error(
491
- "createVideoPlayer: couldn't get the JNI environment");
492
+ "createTestVideoPlayer: couldn't get the JNI environment");
492
493
  }
493
494
  jclass moduleClass = env->GetObjectClass(_module);
494
495
  jmethodID method =
495
- env->GetMethodID(moduleClass, "createVideoPlayer",
496
+ env->GetMethodID(moduleClass, "createTestVideoPlayer",
496
497
  "(Ljava/lang/String;)Lcom/webgpu/WebGPUVideoPlayer;");
497
498
  env->DeleteLocalRef(moduleClass);
498
499
  if (!method) {
499
500
  env->ExceptionClear();
500
- throw std::runtime_error(
501
- "createVideoPlayer: WebGPUModule.createVideoPlayer not found");
501
+ throw std::runtime_error("createTestVideoPlayer: "
502
+ "WebGPUModule.createTestVideoPlayer not found");
502
503
  }
503
504
  jstring jPath = env->NewStringUTF(path.c_str());
504
505
  jobject player = env->CallObjectMethod(_module, method, jPath);
505
506
  env->DeleteLocalRef(jPath);
506
507
  if (env->ExceptionCheck()) {
507
- throw std::runtime_error("createVideoPlayer: " +
508
+ throw std::runtime_error("createTestVideoPlayer: " +
508
509
  describeAndClearJavaException(env));
509
510
  }
510
511
  if (player == nullptr) {
511
- throw std::runtime_error("createVideoPlayer: no player was created");
512
+ throw std::runtime_error("createTestVideoPlayer: no player was created");
512
513
  }
513
514
  auto result = std::make_unique<AndroidVideoPlayer>(env, player);
514
515
  env->DeleteLocalRef(player);
@@ -25,6 +25,7 @@
25
25
  #include "DawnBlobCache.h"
26
26
  #include "GPUCanvasContext.h"
27
27
  #include "GPUDevice.h"
28
+ #include "GpuPurge.h"
28
29
  #include "NativeBufferViewRegistry.h"
29
30
  #include "RNWebGPUManager.h"
30
31
  #include "WebGPURuntime.h"
@@ -70,6 +71,21 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */,
70
71
  rnwgpu::GPUDevice::flushPipelineCaches();
71
72
  }
72
73
 
74
+ // WebGPUModule's ComponentCallbacks2 (UI thread): what the system says about
75
+ // memory, as it says it. GpuPurge decides what calls for a purge.
76
+ extern "C" JNIEXPORT void JNICALL
77
+ Java_com_webgpu_WebGPUModule_onLowMemoryNative(JNIEnv * /* env */,
78
+ jclass /* clazz */) {
79
+ rnwgpu::GpuPurge::onLowMemory();
80
+ }
81
+
82
+ extern "C" JNIEXPORT void JNICALL
83
+ Java_com_webgpu_WebGPUModule_onTrimMemoryNative(JNIEnv * /* env */,
84
+ jclass /* clazz */,
85
+ jint level) {
86
+ rnwgpu::GpuPurge::onTrimMemory(level);
87
+ }
88
+
73
89
  // WebGPUModule.onHostResume and onHostPause (UI thread): animation frames
74
90
  // follow the host activity, resumed or not.
75
91
  extern "C" JNIEXPORT void JNICALL
@@ -198,9 +214,9 @@ extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUView_onSurfaceChanged(
198
214
  namespace {
199
215
 
200
216
  // Weak handle on a Java view and one of its no-argument methods, for native
201
- // threads to call into it: the fence waiter wakes a WebGPUHardwareBufferView
202
- // when a frame is ready, the presenting thread tells a SurfaceView it is
203
- // animating (AnimationReporter). Holding the view weakly means a view that RN
217
+ // threads to call into it: native wakes a WebGPUNativeBufferView when new
218
+ // content is ready, the presenting thread tells a SurfaceView it is animating
219
+ // (AnimationReporter). Holding the view weakly means a view that RN
204
220
  // has dropped is not kept alive by a SurfaceInfo that outlives it (the
205
221
  // registry keeps the SurfaceInfo until onDropViewInstance).
206
222
  struct WeakViewCall {
@@ -416,99 +432,6 @@ extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUView_onViewDestroyed(
416
432
  registry.removeSurfaceInfo(contextId);
417
433
  }
418
434
 
419
- // --- WebGPUHardwareBufferView (AHB-pool presentation)
420
- // ---------------------------------
421
-
422
- // Turn on pool mode for this context. dpW/dpH is the canvas-client (dp) size;
423
- // the native pool buffers are sized from the canvas drawing buffer lazily.
424
- extern "C" JNIEXPORT void JNICALL
425
- Java_com_webgpu_WebGPUHardwareBufferView_nEnablePool(JNIEnv *env, jobject thiz,
426
- jint contextId, jint dpW,
427
- jint dpH) {
428
- auto &registry = rnwgpu::SurfaceRegistry::getInstance();
429
- auto info = registry.getSurfaceInfoOrCreate(
430
- contextId, rnwgpu::WebGPURuntime::shared().instance(),
431
- static_cast<int>(dpW), static_cast<int>(dpH));
432
- auto waker = std::make_shared<WeakViewCall>(env, thiz, "onNativeFrameReady");
433
- info->setPoolFrameReadyCallback([waker]() { (*waker)(); });
434
- info->enablePool(static_cast<int>(dpW), static_cast<int>(dpH));
435
- }
436
-
437
- // Keep the canvas-client (dp) size in sync on resize.
438
- extern "C" JNIEXPORT void JNICALL
439
- Java_com_webgpu_WebGPUHardwareBufferView_nSetClientSize(JNIEnv *env,
440
- jobject thiz,
441
- jint contextId,
442
- jint dpW, jint dpH) {
443
- auto &registry = rnwgpu::SurfaceRegistry::getInstance();
444
- auto info = registry.getSurfaceInfo(contextId);
445
- if (info != nullptr) {
446
- info->setPoolClientSize(static_cast<int>(dpW), static_cast<int>(dpH));
447
- }
448
- }
449
-
450
- // The HardwareBuffer backing a (generation, slot), for the view to wrap in a
451
- // Bitmap. Returns null for a retired generation.
452
- extern "C" JNIEXPORT jobject JNICALL
453
- Java_com_webgpu_WebGPUHardwareBufferView_nGetHardwareBuffer(
454
- JNIEnv *env, jobject thiz, jint contextId, jint generation, jint slot) {
455
- auto &registry = rnwgpu::SurfaceRegistry::getInstance();
456
- auto info = registry.getSurfaceInfo(contextId);
457
- if (info == nullptr) {
458
- return nullptr;
459
- }
460
- void *ahb = info->poolBufferForDisplay(static_cast<uint32_t>(generation),
461
- static_cast<int>(slot));
462
- if (ahb == nullptr) {
463
- return nullptr;
464
- }
465
- // toHardwareBuffer acquires its own ref for the returned jobject; the pool
466
- // keeps the underlying buffer alive independently.
467
- return AHardwareBuffer_toHardwareBuffer(env,
468
- static_cast<AHardwareBuffer *>(ahb));
469
- }
470
-
471
- // Latest signaled frame ready to display, encoded (generation << 32 | slot), or
472
- // -1 when nothing is new. Called on the UI thread after onNativeFrameReady.
473
- extern "C" JNIEXPORT jlong JNICALL
474
- Java_com_webgpu_WebGPUHardwareBufferView_nPollReady(JNIEnv *env, jobject thiz,
475
- jint contextId) {
476
- auto &registry = rnwgpu::SurfaceRegistry::getInstance();
477
- auto info = registry.getSurfaceInfo(contextId);
478
- if (info == nullptr) {
479
- return -1;
480
- }
481
- return info->poolPollReady();
482
- }
483
-
484
- // The view is done displaying (and holding) a slot; return it to the pool.
485
- extern "C" JNIEXPORT void JNICALL
486
- Java_com_webgpu_WebGPUHardwareBufferView_nReleaseSlot(JNIEnv *env, jobject thiz,
487
- jint contextId,
488
- jint generation,
489
- jint slot) {
490
- auto &registry = rnwgpu::SurfaceRegistry::getInstance();
491
- auto info = registry.getSurfaceInfo(contextId);
492
- if (info != nullptr) {
493
- info->poolReleaseSlot(static_cast<uint32_t>(generation),
494
- static_cast<int>(slot));
495
- }
496
- }
497
-
498
- // View detached / hidden: keep the canvas alive by falling back to an offscreen
499
- // texture (mirrors switchToOffscreenSurface for the surface path).
500
- extern "C" JNIEXPORT void JNICALL
501
- Java_com_webgpu_WebGPUHardwareBufferView_nSwitchToOffscreen(JNIEnv *env,
502
- jobject thiz,
503
- jint contextId) {
504
- auto &registry = rnwgpu::SurfaceRegistry::getInstance();
505
- auto info = registry.getSurfaceInfo(contextId);
506
- if (info != nullptr) {
507
- info->setPoolFrameReadyCallback(nullptr);
508
- info->switchToOffscreen();
509
- }
510
- }
511
-
512
435
  // --- WebGPUNativeBufferView
513
436
  // ------------------------------------------------------
514
437
 
@@ -4,35 +4,18 @@ import androidx.annotation.Nullable;
4
4
 
5
5
  /**
6
6
  * The Android view a WebGPUView draws into, see WebGPUView.updateView(), and
7
- * the rules the props resolve by. The JS side (Canvas.tsx) mirrors them to
8
- * warn in development.
7
+ * the rule the prop resolves by. The JS side (Canvas.tsx) mirrors it to warn
8
+ * in development.
9
9
  */
10
10
  enum BackingViewKind {
11
11
  SURFACE_VIEW,
12
- TEXTURE_VIEW,
13
- HARDWARE_BUFFER_VIEW;
12
+ TEXTURE_VIEW;
14
13
 
15
- /**
16
- * The kind the androidBackingView prop names; a TextureView by default. A
17
- * HardwareBufferView (a plain View drawing AHardwareBuffers inline) needs
18
- * Android 10: below it, the request falls back to a TextureView, which
19
- * composites the same way, and the JS side warns about it in development.
20
- */
21
- static BackingViewKind fromBackingView(@Nullable String backingView, boolean hardwareBufferSupported) {
14
+ /** The kind the androidBackingView prop names; a TextureView by default. */
15
+ static BackingViewKind fromBackingView(@Nullable String backingView) {
22
16
  if ("SurfaceView".equals(backingView)) {
23
17
  return SURFACE_VIEW;
24
18
  }
25
- if ("HardwareBufferView".equals(backingView) && hardwareBufferSupported) {
26
- return HARDWARE_BUFFER_VIEW;
27
- }
28
19
  return TEXTURE_VIEW;
29
20
  }
30
-
31
- /**
32
- * Whether the canvas composites as opaque: what the prop asks for, except
33
- * that a HardwareBufferView always composites with alpha.
34
- */
35
- static boolean resolveOpaque(BackingViewKind kind, boolean opaque) {
36
- return opaque && kind != HARDWARE_BUFFER_VIEW;
37
- }
38
21
  }
@@ -22,6 +22,4 @@ public interface WebGPUAPI {
22
22
  );
23
23
 
24
24
  void surfaceOffscreen();
25
-
26
- int getContextId();
27
25
  }
@@ -1,5 +1,7 @@
1
1
  package com.webgpu;
2
2
 
3
+ import android.content.ComponentCallbacks2;
4
+ import android.content.res.Configuration;
3
5
  import android.graphics.Bitmap;
4
6
  import android.hardware.HardwareBuffer;
5
7
  import android.os.Build;
@@ -34,6 +36,25 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
34
36
  System.loadLibrary("react-native-webgpu"); // Load the C++ library
35
37
  }
36
38
 
39
+ // What the system says about memory goes to the native side as it comes,
40
+ // which decides when the GPU memory nothing uses goes back to the system
41
+ // (see GpuPurge).
42
+ private final ComponentCallbacks2 mComponentCallbacks =
43
+ new ComponentCallbacks2() {
44
+ @Override
45
+ public void onConfigurationChanged(Configuration newConfig) {}
46
+
47
+ @Override
48
+ public void onLowMemory() {
49
+ onLowMemoryNative();
50
+ }
51
+
52
+ @Override
53
+ public void onTrimMemory(int level) {
54
+ onTrimMemoryNative(level);
55
+ }
56
+ };
57
+
37
58
  public WebGPUModule(ReactApplicationContext reactContext) {
38
59
  super(reactContext);
39
60
  // Initialize the C++ module
@@ -41,11 +62,15 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
41
62
  // Animation frames follow the host activity: resumed, or not.
42
63
  setForegroundNative(reactContext.getLifecycleState() == LifecycleState.RESUMED);
43
64
  reactContext.addLifecycleEventListener(this);
65
+ reactContext.getApplicationContext().registerComponentCallbacks(mComponentCallbacks);
44
66
  }
45
67
 
46
68
  @Override
47
69
  public void invalidate() {
48
70
  getReactApplicationContext().removeLifecycleEventListener(this);
71
+ getReactApplicationContext()
72
+ .getApplicationContext()
73
+ .unregisterComponentCallbacks(mComponentCallbacks);
49
74
  super.invalidate();
50
75
  }
51
76
 
@@ -72,6 +97,12 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
72
97
  @DoNotStrip
73
98
  private native void flushPipelineCaches();
74
99
 
100
+ @DoNotStrip
101
+ private static native void onLowMemoryNative();
102
+
103
+ @DoNotStrip
104
+ private static native void onTrimMemoryNative(int level);
105
+
75
106
  /**
76
107
  * Whether the app is in the foreground: the host activity is resumed (see
77
108
  * AnimationFrameDispatcher::setForeground). An AChoreographer sends its
@@ -229,12 +260,12 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
229
260
  private native void onViewSnapshotBuffer(long callback, HardwareBuffer buffer, int fenceFd);
230
261
 
231
262
  /**
232
- * Called from C++ (AndroidPlatformContext::createVideoPlayer) for
233
- * RNWebGPU.createVideoPlayer. Throws when the source cannot be opened; the
263
+ * Called from C++ (AndroidPlatformContext::createTestVideoPlayer) for
264
+ * RNWebGPU.createTestVideoPlayer. Throws when the source cannot be opened; the
234
265
  * caller turns the exception into a JS error.
235
266
  */
236
267
  @DoNotStrip
237
- WebGPUVideoPlayer createVideoPlayer(String source) {
268
+ WebGPUVideoPlayer createTestVideoPlayer(String source) {
238
269
  return new WebGPUVideoPlayer(getReactApplicationContext(), source);
239
270
  }
240
271
  }
@@ -112,7 +112,7 @@ public class WebGPUVideoPlayer {
112
112
  mp.setDataSource(context, uri);
113
113
  } catch (IOException | IllegalArgumentException | SecurityException e) {
114
114
  mp.release();
115
- throw new RuntimeException("createVideoPlayer: cannot open " + source, e);
115
+ throw new RuntimeException("createTestVideoPlayer: cannot open " + source, e);
116
116
  }
117
117
  mp.setLooping(loop);
118
118
  mp.prepareAsync();
@@ -13,9 +13,8 @@ import com.facebook.react.uimanager.ThemedReactContext;
13
13
  import com.facebook.react.views.view.ReactViewGroup;
14
14
 
15
15
  /**
16
- * The Android view behind <Canvas>. It is backed by a TextureView, a
17
- * SurfaceView or a HardwareBufferView, named by the androidBackingView prop
18
- * and created once, from the props of the first transaction, for the life of
16
+ * The Android view behind <Canvas>. It is backed by a TextureView or a
17
+ * SurfaceView, named by the androidBackingView prop and created once, from the props of the first transaction, for the life of
19
18
  * the view (see updateView()).
20
19
  */
21
20
  public class WebGPUView extends ReactViewGroup implements WebGPUAPI {
@@ -36,8 +35,8 @@ public class WebGPUView extends ReactViewGroup implements WebGPUAPI {
36
35
  private View mView = null;
37
36
  @Nullable
38
37
  private BackingViewKind mKind = null;
39
- // Only a SurfaceView votes: a TextureView or HardwareBufferView is
40
- // composited into the window, which votes for it.
38
+ // Only a SurfaceView votes: a TextureView is composited into the window,
39
+ // which votes for it.
41
40
  private final SurfaceFrameRateVote mFrameRateVote = new SurfaceFrameRateVote(
42
41
  this, idleAfterNanos -> releaseFrameRateVoteIfIdle(mContextId, idleAfterNanos));
43
42
 
@@ -46,9 +45,9 @@ public class WebGPUView extends ReactViewGroup implements WebGPUAPI {
46
45
  // ReactViewGroup disables clipChildren (RN overflow is handled with canvas
47
46
  // clipping instead). Android copies the parent's clipChildren into each
48
47
  // child's RenderNode.clipToBounds, and HWUI treats a damaged node without
49
- // it as unbounded damage (RenderNode::damageSelf). The TextureView and
50
- // HardwareBufferView children invalidate on every frame, so without this
51
- // every non-opaque canvas frame repaints the whole window. Our only child
48
+ // it as unbounded damage (RenderNode::damageSelf). A TextureView child
49
+ // invalidates on every frame, so without this every non-opaque canvas
50
+ // frame repaints the whole window. Our only child
52
51
  // exactly fills this view, so clipping it changes nothing visually.
53
52
  setClipChildren(true);
54
53
  }
@@ -76,8 +75,7 @@ public class WebGPUView extends ReactViewGroup implements WebGPUAPI {
76
75
  warnIgnoredOnceMounted("android.backingView");
77
76
  return;
78
77
  }
79
- boolean hardwareBufferSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
80
- mBackingView = BackingViewKind.fromBackingView(value, hardwareBufferSupported);
78
+ mBackingView = BackingViewKind.fromBackingView(value);
81
79
  }
82
80
 
83
81
  public void setOpaque(boolean value) {
@@ -139,32 +137,22 @@ public class WebGPUView extends ReactViewGroup implements WebGPUAPI {
139
137
  // not carry. A canvas that needs another backing view is remounted instead,
140
138
  // and is off screen for a frame or two until the new view draws its first
141
139
  // frame. Later transactions apply the opacity in place (the setters decide
142
- // what else is taken); WebGPUHardwareBufferView always composites with
143
- // alpha, so there it is a no-op.
140
+ // what else is taken).
144
141
  public void updateView() {
145
142
  if (mKind != null) {
146
- boolean opaque = BackingViewKind.resolveOpaque(mKind, mOpaque);
147
143
  if (mKind == BackingViewKind.TEXTURE_VIEW) {
148
- ((WebGPUTextureView) mView).setOpaque(opaque);
149
- } else if (mKind == BackingViewKind.SURFACE_VIEW) {
150
- ((WebGPUSurfaceView) mView).setOpaque(opaque);
144
+ ((WebGPUTextureView) mView).setOpaque(mOpaque);
145
+ } else {
146
+ ((WebGPUSurfaceView) mView).setOpaque(mOpaque);
151
147
  }
152
148
  return;
153
149
  }
154
- BackingViewKind kind = mBackingView;
155
- mKind = kind;
156
- boolean opaque = BackingViewKind.resolveOpaque(kind, mOpaque);
150
+ mKind = mBackingView;
157
151
  Context ctx = getContext();
158
- switch (kind) {
159
- case HARDWARE_BUFFER_VIEW:
160
- mView = new WebGPUHardwareBufferView(ctx, this);
161
- break;
162
- case TEXTURE_VIEW:
163
- mView = new WebGPUTextureView(ctx, this, opaque);
164
- break;
165
- default:
166
- mView = new WebGPUSurfaceView(ctx, this, mZOrderOnTop, mZOrderMediaOverlay, opaque);
167
- break;
152
+ if (mKind == BackingViewKind.TEXTURE_VIEW) {
153
+ mView = new WebGPUTextureView(ctx, this, mOpaque);
154
+ } else {
155
+ mView = new WebGPUSurfaceView(ctx, this, mZOrderOnTop, mZOrderMediaOverlay, mOpaque);
168
156
  }
169
157
  addView(mView);
170
158
  // ReactViewGroup.requestLayout() is a deliberate no-op, so addView outside
@@ -234,11 +222,6 @@ public class WebGPUView extends ReactViewGroup implements WebGPUAPI {
234
222
  }
235
223
  }
236
224
 
237
- @Override
238
- public int getContextId() {
239
- return mContextId;
240
- }
241
-
242
225
  /**
243
226
  * Called from WebGPUViewManager.onDropViewInstance when React removes this
244
227
  * view: the view dies with its Canvas, so it retires the registry entry.
@@ -50,7 +50,8 @@ public:
50
50
  bool displayP3) override;
51
51
 
52
52
  std::unique_ptr<IVideoPlayer>
53
- createVideoPlayer(const std::string &path, VideoPixelFormat format) override;
53
+ createTestVideoPlayer(const std::string &path,
54
+ VideoPixelFormat format) override;
54
55
 
55
56
  std::string writeTestVideoFile() override;
56
57
 
@@ -542,8 +542,8 @@ VideoFrameHandle ApplePlatformContext::loadVideoFrame(const std::string &path) {
542
542
  }
543
543
 
544
544
  std::unique_ptr<IVideoPlayer>
545
- ApplePlatformContext::createVideoPlayer(const std::string &path,
546
- VideoPixelFormat format) {
545
+ ApplePlatformContext::createTestVideoPlayer(const std::string &path,
546
+ VideoPixelFormat format) {
547
547
  return createAppleVideoPlayer(path, format);
548
548
  }
549
549