react-native-skia-webgpu-video 0.0.0-stage → 0.1.0-beta.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 (236) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +303 -2
  3. package/android/BUILD_VALIDATION.md +62 -0
  4. package/android/CMakeLists.txt +99 -0
  5. package/android/build-validation.json +262 -0
  6. package/android/build.gradle +185 -0
  7. package/android/cpp/EncoderTargets.cpp +226 -0
  8. package/android/cpp/EncoderTargets.h +70 -0
  9. package/android/cpp/JNIHelpers.cpp +15 -0
  10. package/android/cpp/JNIHelpers.h +20 -0
  11. package/android/cpp/NativeEventDispatcher.cpp +59 -0
  12. package/android/cpp/NativeEventDispatcher.h +31 -0
  13. package/android/cpp/NativeHardwareBuffer.cpp +397 -0
  14. package/android/cpp/NativeHardwareBuffer.h +34 -0
  15. package/android/cpp/NativeRgbaBuffer.cpp +45 -0
  16. package/android/cpp/NativeRgbaBuffer.h +9 -0
  17. package/android/cpp/ReturnedVideoFrames.h +37 -0
  18. package/android/cpp/RgbaFrameLease.h +53 -0
  19. package/android/cpp/VideoCapabilities.cpp +87 -0
  20. package/android/cpp/VideoCapabilities.h +44 -0
  21. package/android/cpp/VideoComposition.cpp +170 -0
  22. package/android/cpp/VideoComposition.h +36 -0
  23. package/android/cpp/VideoCompositionFramesExtractor.cpp +82 -0
  24. package/android/cpp/VideoCompositionFramesExtractor.h +48 -0
  25. package/android/cpp/VideoCompositionFramesExtractorHostObject.cpp +230 -0
  26. package/android/cpp/VideoCompositionFramesExtractorHostObject.h +42 -0
  27. package/android/cpp/VideoCompositionFramesExtractorSyncHostObject.cpp +133 -0
  28. package/android/cpp/VideoCompositionFramesExtractorSyncHostObject.h +46 -0
  29. package/android/cpp/VideoEncoderHostObject.cpp +318 -0
  30. package/android/cpp/VideoEncoderHostObject.h +76 -0
  31. package/android/cpp/VideoFrame.cpp +293 -0
  32. package/android/cpp/VideoFrame.h +27 -0
  33. package/android/cpp/VideoPlayer.cpp +96 -0
  34. package/android/cpp/VideoPlayer.h +52 -0
  35. package/android/cpp/VideoPlayerHostObject.cpp +225 -0
  36. package/android/cpp/VideoPlayerHostObject.h +43 -0
  37. package/android/cpp/cpp-adapter.cpp +316 -0
  38. package/android/gradle.properties +5 -0
  39. package/android/instrumentation-inventory.json +178 -0
  40. package/android/proguard-rules.pro +4 -0
  41. package/android/src/main/AndroidManifest.xml +2 -0
  42. package/android/src/main/java/com/azzapp/rnskv/AudioCompositionExporter.java +537 -0
  43. package/android/src/main/java/com/azzapp/rnskv/AudioCompositionPlayer.java +321 -0
  44. package/android/src/main/java/com/azzapp/rnskv/BufferLifetime.java +55 -0
  45. package/android/src/main/java/com/azzapp/rnskv/DecodeRequests.java +100 -0
  46. package/android/src/main/java/com/azzapp/rnskv/DecoderWindow.java +55 -0
  47. package/android/src/main/java/com/azzapp/rnskv/EGLResourcesHolder.java +132 -0
  48. package/android/src/main/java/com/azzapp/rnskv/EGLUtils.java +225 -0
  49. package/android/src/main/java/com/azzapp/rnskv/FrameSize.java +50 -0
  50. package/android/src/main/java/com/azzapp/rnskv/GLFrameExtractor.java +510 -0
  51. package/android/src/main/java/com/azzapp/rnskv/JNIHelpers.java +12 -0
  52. package/android/src/main/java/com/azzapp/rnskv/NativeEventDispatcher.java +25 -0
  53. package/android/src/main/java/com/azzapp/rnskv/NativeHardwareBuffer.java +62 -0
  54. package/android/src/main/java/com/azzapp/rnskv/NativeRgbaBuffer.java +35 -0
  55. package/android/src/main/java/com/azzapp/rnskv/ReactNativeSkiaVideoModule.java +45 -0
  56. package/android/src/main/java/com/azzapp/rnskv/ReactNativeSkiaVideoPackage.java +43 -0
  57. package/android/src/main/java/com/azzapp/rnskv/ReactNativeSkiaVideoSpec.java +9 -0
  58. package/android/src/main/java/com/azzapp/rnskv/RgbaBufferAllocator.java +83 -0
  59. package/android/src/main/java/com/azzapp/rnskv/RgbaLayout.java +33 -0
  60. package/android/src/main/java/com/azzapp/rnskv/SurfaceOutputPolicy.java +13 -0
  61. package/android/src/main/java/com/azzapp/rnskv/TextureRenderer.java +150 -0
  62. package/android/src/main/java/com/azzapp/rnskv/TimeHelpers.java +11 -0
  63. package/android/src/main/java/com/azzapp/rnskv/VideoCapabilities.java +354 -0
  64. package/android/src/main/java/com/azzapp/rnskv/VideoComposition.java +147 -0
  65. package/android/src/main/java/com/azzapp/rnskv/VideoCompositionDecoder.java +772 -0
  66. package/android/src/main/java/com/azzapp/rnskv/VideoCompositionFramesExtractor.java +354 -0
  67. package/android/src/main/java/com/azzapp/rnskv/VideoCompositionFramesExtractorSync.java +241 -0
  68. package/android/src/main/java/com/azzapp/rnskv/VideoCompositionItemDecoder.java +492 -0
  69. package/android/src/main/java/com/azzapp/rnskv/VideoEncoder.java +639 -0
  70. package/android/src/main/java/com/azzapp/rnskv/VideoFrame.java +74 -0
  71. package/android/src/main/java/com/azzapp/rnskv/VideoPlayer.java +361 -0
  72. package/cpp/RNSVCheckedSizes.h +54 -0
  73. package/cpp/RNSVEventEmitter.cpp +199 -0
  74. package/cpp/RNSVEventEmitter.h +31 -0
  75. package/cpp/RNSVHostObject.cpp +79 -0
  76. package/cpp/RNSVHostObject.h +67 -0
  77. package/cpp/RNSVMemoryBudget.cpp +68 -0
  78. package/cpp/RNSVMemoryBudget.h +100 -0
  79. package/cpp/RNSVRuntimeLifecycleMonitor.cpp +88 -0
  80. package/cpp/RNSVRuntimeLifecycleMonitor.h +33 -0
  81. package/docs/ANDROID_DEVICE_306.md +95 -0
  82. package/docs/ANDROID_EXPORT_CACHE_306.md +48 -0
  83. package/docs/ANDROID_MEMORY_RETENTION_306.md +67 -0
  84. package/docs/BENCHMARKS.md +368 -0
  85. package/docs/IOS_DEVICE_TESTS.md +115 -0
  86. package/docs/IOS_SIMULATOR_TESTS.md +74 -0
  87. package/docs/MIGRATION.md +82 -0
  88. package/docs/NATIVE_MEMORY_INVESTIGATION_306.md +88 -0
  89. package/docs/PERFORMANCE_AB_IPHONE_303.md +196 -0
  90. package/docs/PERFORMANCE_AB_SIMULATOR.md +135 -0
  91. package/docs/PERFORMANCE_AB_SOAK_SIMULATOR.md +84 -0
  92. package/docs/PERFORMANCE_IPHONE_306_OPTIMIZATION.md +76 -0
  93. package/docs/PERFORMANCE_SIMULATOR.md +89 -0
  94. package/docs/PERFORMANCE_SIMULATOR_INITIAL.md +96 -0
  95. package/docs/PERFORMANCE_SOAK_IPHONE_303.md +41 -0
  96. package/docs/UPSTREAM_NOTES.md +188 -0
  97. package/docs/assets/banner.svg +26 -0
  98. package/examples/webgpu-overlay.ts +147 -0
  99. package/ios/AVAssetTrackUtils.h +24 -0
  100. package/ios/AudioCompositionUtils.h +27 -0
  101. package/ios/AudioCompositionUtils.mm +113 -0
  102. package/ios/DecoderWindow.h +52 -0
  103. package/ios/NativeResourceStats.h +32 -0
  104. package/ios/RNSVColorSpace.h +50 -0
  105. package/ios/RNSVJSIUtils.h +46 -0
  106. package/ios/RNSVScopedPixelBuffer.h +17 -0
  107. package/ios/RNSVVideoPlayer.h +46 -0
  108. package/ios/RNSVVideoPlayer.mm +410 -0
  109. package/ios/ReactNativeSkiaVideo.h +8 -0
  110. package/ios/ReactNativeSkiaVideo.mm +310 -0
  111. package/ios/SeekPolicy.h +27 -0
  112. package/ios/VideoComposition.h +148 -0
  113. package/ios/VideoCompositionFramesExtractorHostObject.h +105 -0
  114. package/ios/VideoCompositionFramesExtractorHostObject.mm +686 -0
  115. package/ios/VideoCompositionFramesExtractorSyncHostObject.h +37 -0
  116. package/ios/VideoCompositionFramesExtractorSyncHostObject.mm +168 -0
  117. package/ios/VideoCompositionItemDecoder.h +60 -0
  118. package/ios/VideoCompositionItemDecoder.mm +480 -0
  119. package/ios/VideoEncoderHostObject.h +83 -0
  120. package/ios/VideoEncoderHostObject.mm +706 -0
  121. package/ios/VideoFrame.h +66 -0
  122. package/ios/VideoFrame.mm +108 -0
  123. package/ios/VideoPlayerHostObject.h +52 -0
  124. package/ios/VideoPlayerHostObject.mm +332 -0
  125. package/lib/module/NativeReactNativeSkiaVideo.js +5 -0
  126. package/lib/module/NativeReactNativeSkiaVideo.js.map +1 -0
  127. package/lib/module/RNSkiaVideoModule.js +20 -0
  128. package/lib/module/RNSkiaVideoModule.js.map +1 -0
  129. package/lib/module/canvas.js +18 -0
  130. package/lib/module/canvas.js.map +1 -0
  131. package/lib/module/exportCache.js +22 -0
  132. package/lib/module/exportCache.js.map +1 -0
  133. package/lib/module/exportFrames.js +338 -0
  134. package/lib/module/exportFrames.js.map +1 -0
  135. package/lib/module/exportQueue.js +52 -0
  136. package/lib/module/exportQueue.js.map +1 -0
  137. package/lib/module/exportTarget.js +137 -0
  138. package/lib/module/exportTarget.js.map +1 -0
  139. package/lib/module/exportVideoComposition.js +492 -0
  140. package/lib/module/exportVideoComposition.js.map +1 -0
  141. package/lib/module/frameInterop.js +532 -0
  142. package/lib/module/frameInterop.js.map +1 -0
  143. package/lib/module/gpu.js +222 -0
  144. package/lib/module/gpu.js.map +1 -0
  145. package/lib/module/gpuDevice.js +54 -0
  146. package/lib/module/gpuDevice.js.map +1 -0
  147. package/lib/module/index.js +36 -0
  148. package/lib/module/index.js.map +1 -0
  149. package/lib/module/memory.js +38 -0
  150. package/lib/module/memory.js.map +1 -0
  151. package/lib/module/package.json +1 -0
  152. package/lib/module/previewLifecycle.js +52 -0
  153. package/lib/module/previewLifecycle.js.map +1 -0
  154. package/lib/module/runtimeYield.js +10 -0
  155. package/lib/module/runtimeYield.js.map +1 -0
  156. package/lib/module/types.js +4 -0
  157. package/lib/module/types.js.map +1 -0
  158. package/lib/module/utils/useEventListener.js +18 -0
  159. package/lib/module/utils/useEventListener.js.map +1 -0
  160. package/lib/module/videoCompositionPlayer.js +348 -0
  161. package/lib/module/videoCompositionPlayer.js.map +1 -0
  162. package/lib/module/videoFrameImage.js +185 -0
  163. package/lib/module/videoFrameImage.js.map +1 -0
  164. package/lib/module/videoPlayer.js +172 -0
  165. package/lib/module/videoPlayer.js.map +1 -0
  166. package/lib/module/yuvBlit.js +299 -0
  167. package/lib/module/yuvBlit.js.map +1 -0
  168. package/lib/typescript/package.json +1 -0
  169. package/lib/typescript/src/NativeReactNativeSkiaVideo.d.ts +7 -0
  170. package/lib/typescript/src/NativeReactNativeSkiaVideo.d.ts.map +1 -0
  171. package/lib/typescript/src/RNSkiaVideoModule.d.ts +4 -0
  172. package/lib/typescript/src/RNSkiaVideoModule.d.ts.map +1 -0
  173. package/lib/typescript/src/canvas.d.ts +4 -0
  174. package/lib/typescript/src/canvas.d.ts.map +1 -0
  175. package/lib/typescript/src/exportCache.d.ts +6 -0
  176. package/lib/typescript/src/exportCache.d.ts.map +1 -0
  177. package/lib/typescript/src/exportFrames.d.ts +57 -0
  178. package/lib/typescript/src/exportFrames.d.ts.map +1 -0
  179. package/lib/typescript/src/exportQueue.d.ts +5 -0
  180. package/lib/typescript/src/exportQueue.d.ts.map +1 -0
  181. package/lib/typescript/src/exportTarget.d.ts +28 -0
  182. package/lib/typescript/src/exportTarget.d.ts.map +1 -0
  183. package/lib/typescript/src/exportVideoComposition.d.ts +68 -0
  184. package/lib/typescript/src/exportVideoComposition.d.ts.map +1 -0
  185. package/lib/typescript/src/frameInterop.d.ts +17 -0
  186. package/lib/typescript/src/frameInterop.d.ts.map +1 -0
  187. package/lib/typescript/src/gpu.d.ts +39 -0
  188. package/lib/typescript/src/gpu.d.ts.map +1 -0
  189. package/lib/typescript/src/gpuDevice.d.ts +11 -0
  190. package/lib/typescript/src/gpuDevice.d.ts.map +1 -0
  191. package/lib/typescript/src/index.d.ts +21 -0
  192. package/lib/typescript/src/index.d.ts.map +1 -0
  193. package/lib/typescript/src/memory.d.ts +25 -0
  194. package/lib/typescript/src/memory.d.ts.map +1 -0
  195. package/lib/typescript/src/previewLifecycle.d.ts +22 -0
  196. package/lib/typescript/src/previewLifecycle.d.ts.map +1 -0
  197. package/lib/typescript/src/runtimeYield.d.ts +4 -0
  198. package/lib/typescript/src/runtimeYield.d.ts.map +1 -0
  199. package/lib/typescript/src/types.d.ts +631 -0
  200. package/lib/typescript/src/types.d.ts.map +1 -0
  201. package/lib/typescript/src/utils/useEventListener.d.ts +5 -0
  202. package/lib/typescript/src/utils/useEventListener.d.ts.map +1 -0
  203. package/lib/typescript/src/videoCompositionPlayer.d.ts +85 -0
  204. package/lib/typescript/src/videoCompositionPlayer.d.ts.map +1 -0
  205. package/lib/typescript/src/videoFrameImage.d.ts +60 -0
  206. package/lib/typescript/src/videoFrameImage.d.ts.map +1 -0
  207. package/lib/typescript/src/videoPlayer.d.ts +99 -0
  208. package/lib/typescript/src/videoPlayer.d.ts.map +1 -0
  209. package/lib/typescript/src/yuvBlit.d.ts +50 -0
  210. package/lib/typescript/src/yuvBlit.d.ts.map +1 -0
  211. package/package.json +154 -4
  212. package/patches/react-native-skia+3.7.0.patch +502 -0
  213. package/react-native-skia-webgpu-video.podspec +35 -0
  214. package/scripts/apply-skia-canvas-patch.mjs +48 -0
  215. package/scripts/skia-canvas-patch.json +291 -0
  216. package/src/NativeReactNativeSkiaVideo.ts +8 -0
  217. package/src/RNSkiaVideoModule.ts +27 -0
  218. package/src/canvas.ts +22 -0
  219. package/src/exportCache.ts +27 -0
  220. package/src/exportFrames.ts +421 -0
  221. package/src/exportQueue.ts +65 -0
  222. package/src/exportTarget.ts +179 -0
  223. package/src/exportVideoComposition.ts +718 -0
  224. package/src/frameInterop.ts +684 -0
  225. package/src/gpu.ts +290 -0
  226. package/src/gpuDevice.ts +80 -0
  227. package/src/index.tsx +45 -0
  228. package/src/memory.ts +48 -0
  229. package/src/previewLifecycle.ts +60 -0
  230. package/src/runtimeYield.ts +6 -0
  231. package/src/types.ts +661 -0
  232. package/src/utils/useEventListener.ts +22 -0
  233. package/src/videoCompositionPlayer.ts +520 -0
  234. package/src/videoFrameImage.ts +205 -0
  235. package/src/videoPlayer.ts +318 -0
  236. package/src/yuvBlit.ts +331 -0
@@ -0,0 +1,520 @@
1
+ import { getVideoCanvas } from "./canvas";
2
+ import type { SkCanvas, SkImage, SkSurface } from "react-native-skia";
3
+ import { BlendMode, Skia } from "react-native-skia";
4
+ import {
5
+ useSharedValue,
6
+ useFrameCallback,
7
+ runOnUI,
8
+ type DerivedValue,
9
+ type SharedValue,
10
+ } from "react-native-reanimated";
11
+ import { useCallback, useEffect, useRef, useState } from "react";
12
+ import type {
13
+ FrameDrawer,
14
+ VideoFrame,
15
+ VideoComposition,
16
+ VideoCompositionFramesExtractor,
17
+ } from "./types";
18
+ import RNSkiaVideoModule from "./RNSkiaVideoModule";
19
+ import useEventListener from "./utils/useEventListener";
20
+ import { PixelRatio } from "react-native";
21
+ import { scheduleOnRN } from "react-native-worklets";
22
+ import { ownVideoFrames, releaseVideoFrameImage } from "./frameInterop";
23
+ import { frameByteSize, reserveVideoMemory } from "./memory";
24
+ import { disposePreviewResources } from "./previewLifecycle";
25
+
26
+ type UseVideoCompositionPlayerOptions<T = undefined> = {
27
+ /**
28
+ * The video composition to play.
29
+ * if null, the composition player won't be created.
30
+ */
31
+ composition: VideoComposition | null;
32
+ /**
33
+ * The function used to draw the composition frames.
34
+ */
35
+ drawFrame: FrameDrawer<T>;
36
+ /**
37
+ * A function that is called before drawing each frame.
38
+ * the return value will be passed to the drawFrame function as context.
39
+ */
40
+ beforeDrawFrame?: () => T;
41
+ /**
42
+ * A function that is called after drawing each frame.
43
+ * the context returned by the beforeDrawFrame function will be passed to this function.
44
+ * This function can be used to clean up resources allocated during the drawFrame function.
45
+ */
46
+ afterDrawFrame?: (context: T) => void;
47
+ /**
48
+ * The width of rendered frames.
49
+ */
50
+ width: number;
51
+ /**
52
+ * The height of rendered frames.
53
+ */
54
+ height: number;
55
+ /**
56
+ * Whether the composition should start playing automatically.
57
+ */
58
+ autoPlay?: boolean;
59
+ /**
60
+ * Weather the composition should loop.
61
+ */
62
+ isLooping?: boolean;
63
+ /**
64
+ * Whether to keep calling `drawFrame` at every vsync while playback is
65
+ * paused. By default a paused player only redraws when the composition time
66
+ * or the decoded frames change (a seek, the frame that follows it), which
67
+ * saves GPU time and battery. Enable it if `drawFrame` depends on values
68
+ * that change while paused, an overlay being dragged for instance.
69
+ *
70
+ * Or the shared values `drawFrame` reads: a paused player then redraws only
71
+ * when one of them is replaced, besides the time, the frames, the size or
72
+ * `drawFrame` itself. An idle editor stops redrawing at every vsync.
73
+ * @default false
74
+ */
75
+ drawWhenPaused?: boolean | SharedValue<unknown>[];
76
+ /**
77
+ * Callback that is called when the composition is ready to play.
78
+ */
79
+ onReadyToPlay?: () => void;
80
+ /**
81
+ * Callback that is called when the composition playback completes.
82
+ */
83
+ onComplete?: () => void;
84
+ /**
85
+ * Callback that is called when an error occurs.
86
+ * @param error the error that occurred.
87
+ * @param retry a function that can be called to retry the operation.
88
+ */
89
+ onError?: (error: any, retry: () => void) => void;
90
+ };
91
+
92
+ type VideoCompositionPlayerController = Pick<
93
+ VideoCompositionFramesExtractor,
94
+ "currentTime" | "play" | "pause" | "seekTo" | "isPlaying"
95
+ >;
96
+
97
+ type UseVideoCompositionPlayerReturnType = {
98
+ /**
99
+ * The current drawn frame of the video composition.
100
+ */
101
+ currentFrame: DerivedValue<SkImage | null>;
102
+ /**
103
+ * The video player controller.
104
+ */
105
+ player: VideoCompositionPlayerController | null;
106
+ };
107
+
108
+ /**
109
+ * A hook that creates a video composition player.
110
+ */
111
+ export const useVideoComposition = <T = undefined>({
112
+ composition,
113
+ drawFrame,
114
+ beforeDrawFrame,
115
+ afterDrawFrame,
116
+ width,
117
+ height,
118
+ autoPlay = false,
119
+ isLooping = false,
120
+ drawWhenPaused = false,
121
+ onReadyToPlay,
122
+ onComplete,
123
+ onError,
124
+ }: UseVideoCompositionPlayerOptions<T>): UseVideoCompositionPlayerReturnType => {
125
+ const [failedComposition, setFailedComposition] =
126
+ useState<VideoComposition | null>(null);
127
+ const isErrored = composition !== null && failedComposition === composition;
128
+ const [session, setSession] = useState<{
129
+ extractor: VideoCompositionFramesExtractor;
130
+ generation: number;
131
+ composition: VideoComposition;
132
+ } | null>(null);
133
+ const framesExtractor = session?.extractor ?? null;
134
+ const generation = session?.generation ?? 0;
135
+ const nextGeneration = useRef(0);
136
+ const activeOnRN = useRef(0);
137
+ // HostObject JS wrappers are recreated across runtimes; compare numbers.
138
+ const activeGeneration = useSharedValue(0);
139
+ const frameGeneration = useSharedValue(0);
140
+ const sourcesGeneration = useSharedValue(0);
141
+ const currentFrame = useSharedValue<SkImage | null>(null);
142
+ const pendingSnapshot = useSharedValue<SkImage | null>(null);
143
+ // Reanimated interprets a function assigned to `.value` as an animation
144
+ // factory. Keep the teardown callback inside an ordinary value instead.
145
+ const pendingAfterDraw = useSharedValue<{ run: () => void } | null>(null);
146
+ const previousSources = useSharedValue<Record<string, VideoFrame>>({});
147
+ const onCreationError = useRef(onError);
148
+ onCreationError.current = onError;
149
+ useEffect(() => {
150
+ if (!composition || isErrored) {
151
+ setSession(null);
152
+ return;
153
+ }
154
+ let created: VideoCompositionFramesExtractor;
155
+ try {
156
+ created =
157
+ RNSkiaVideoModule.createVideoCompositionFramesExtractor(composition);
158
+ } catch (error) {
159
+ setFailedComposition(composition);
160
+ onCreationError.current?.(error, () => setFailedComposition(null));
161
+ return;
162
+ }
163
+ const createdGeneration = ++nextGeneration.current;
164
+ activeOnRN.current = createdGeneration;
165
+ activeGeneration.value = createdGeneration;
166
+ setSession({
167
+ extractor: created,
168
+ generation: createdGeneration,
169
+ composition,
170
+ });
171
+ return () => {
172
+ if (activeOnRN.current === createdGeneration) {
173
+ activeOnRN.current = 0;
174
+ activeGeneration.value = 0;
175
+ }
176
+ runOnUI(() => {
177
+ "worklet";
178
+ if (
179
+ frameGeneration.value === createdGeneration ||
180
+ sourcesGeneration.value === createdGeneration
181
+ )
182
+ releasePreview(created);
183
+ else {
184
+ const failure = disposePreviewResources({ native: created });
185
+ if (failure.failed)
186
+ console.warn(
187
+ "Video preview cleanup failed; resources remain accounted until native runtime teardown",
188
+ failure.error,
189
+ );
190
+ }
191
+ })();
192
+ };
193
+ }, [
194
+ composition,
195
+ isErrored,
196
+ activeGeneration,
197
+ currentFrame,
198
+ previousSources,
199
+ frameGeneration,
200
+ sourcesGeneration,
201
+ pendingSnapshot,
202
+ pendingAfterDraw,
203
+ ]);
204
+
205
+ const retry = useCallback(() => {
206
+ setFailedComposition(null);
207
+ }, []);
208
+
209
+ const errorHandler = useCallback(
210
+ (error: any) => {
211
+ if (generation !== activeOnRN.current) return;
212
+ activeOnRN.current = 0;
213
+ activeGeneration.value = 0;
214
+ setFailedComposition(session!.composition);
215
+ onCreationError.current?.(error, retry);
216
+ },
217
+ [retry, generation, activeGeneration, session],
218
+ );
219
+
220
+ useEffect(() => {
221
+ if (framesExtractor) {
222
+ framesExtractor.isLooping = isLooping;
223
+ }
224
+ }, [framesExtractor, isLooping]);
225
+
226
+ const isCurrentSession = useCallback(
227
+ () => generation !== 0 && generation === activeOnRN.current,
228
+ [generation],
229
+ );
230
+ useEventListener(framesExtractor, "ready", onReadyToPlay, isCurrentSession);
231
+ useEventListener(framesExtractor, "complete", onComplete, isCurrentSession);
232
+ useEventListener(framesExtractor, "error", errorHandler, isCurrentSession);
233
+ useEffect(() => {
234
+ if (!framesExtractor) return;
235
+ runOnUI(() => {
236
+ "worklet";
237
+ if (activeGeneration.value !== generation) return;
238
+ try {
239
+ framesExtractor.prepare();
240
+ } catch (error) {
241
+ activeGeneration.value = 0;
242
+ scheduleOnRN(errorHandler, error);
243
+ }
244
+ })();
245
+ }, [framesExtractor, activeGeneration, generation, errorHandler]);
246
+
247
+ useEffect(() => {
248
+ if (autoPlay) {
249
+ framesExtractor?.play();
250
+ }
251
+ }, [framesExtractor, autoPlay]);
252
+
253
+ const surfaceSharedValue = useSharedValue<SkSurface | null>(null);
254
+ const canvasSharedValue = useSharedValue<SkCanvas | null>(null);
255
+ const surfaceReservation = useSharedValue(0);
256
+ const surfaceWidth = useSharedValue(0);
257
+ const surfaceHeight = useSharedValue(0);
258
+ const releasePreview = (native?: { dispose: () => void }) => {
259
+ "worklet";
260
+ const resources = {
261
+ surface: surfaceSharedValue.value,
262
+ canvas: canvasSharedValue.value,
263
+ images: [currentFrame.value, pendingSnapshot.value],
264
+ frames: Object.values(previousSources.value),
265
+ reservation: surfaceReservation.value,
266
+ afterDraw: pendingAfterDraw.value?.run,
267
+ native,
268
+ };
269
+ // Remove consumers before attempting a drain. A thrown drain must never
270
+ // leave teardown callbacks able to recycle these same resources later.
271
+ currentFrame.value = null;
272
+ pendingSnapshot.value = null;
273
+ pendingAfterDraw.value = null;
274
+ frameGeneration.value = 0;
275
+ previousSources.value = {};
276
+ sourcesGeneration.value = 0;
277
+ surfaceSharedValue.value = null;
278
+ canvasSharedValue.value = null;
279
+ surfaceReservation.value = 0;
280
+ surfaceWidth.value = 0;
281
+ surfaceHeight.value = 0;
282
+ const failure = disposePreviewResources(resources);
283
+ if (failure.failed)
284
+ console.warn(
285
+ "Video preview cleanup failed; resources remain accounted until native runtime teardown",
286
+ failure.error,
287
+ );
288
+ };
289
+ // Frames version and composition time of the last drawn image, to skip
290
+ // redrawing an unchanged picture while paused.
291
+ const lastDrawnFramesVersion = useSharedValue(-1);
292
+ const lastDrawnTime = useSharedValue(-1);
293
+ const lastDrawnInputs = useSharedValue<unknown[] | null>(null);
294
+ // A new drawFrame can draw something else from the same time and frames.
295
+ useEffect(() => {
296
+ lastDrawnTime.value = -1;
297
+ }, [drawFrame, lastDrawnTime]);
298
+ const pixelRatio = PixelRatio.get();
299
+
300
+ // Release the offscreen surface with the hook that made it. Without this a
301
+ // caller that mounts and unmounts the player repeatedly — a player inside a
302
+ // modal, say — leaks a full size texture per cycle. runOnUI because this
303
+ // effect is declared before the frame callback below, and so its cleanup runs
304
+ // before the callback is unregistered.
305
+ useEffect(
306
+ () => () => {
307
+ runOnUI(() => {
308
+ "worklet";
309
+ releasePreview();
310
+ })();
311
+ },
312
+ [
313
+ surfaceSharedValue,
314
+ canvasSharedValue,
315
+ surfaceReservation,
316
+ surfaceWidth,
317
+ surfaceHeight,
318
+ currentFrame,
319
+ pendingSnapshot,
320
+ pendingAfterDraw,
321
+ frameGeneration,
322
+ previousSources,
323
+ sourcesGeneration,
324
+ ],
325
+ );
326
+
327
+ useFrameCallback(() => {
328
+ "worklet";
329
+ if (!framesExtractor || activeGeneration.value !== generation) {
330
+ return;
331
+ }
332
+ try {
333
+ const pixelWidth = Math.floor(width * pixelRatio);
334
+ const pixelHeight = Math.floor(height * pixelRatio);
335
+
336
+ // Layout can report zero or NaN before the player is measured. Avoid
337
+ // native surface allocation until the dimensions are valid.
338
+ if (
339
+ !(pixelWidth > 0) ||
340
+ !(pixelHeight > 0) ||
341
+ !isFinite(pixelWidth) ||
342
+ !isFinite(pixelHeight)
343
+ ) {
344
+ return;
345
+ }
346
+
347
+ // Pull the frames decoded since the last vsync first: it is cheap when
348
+ // nothing new arrived, and it is what lets a paused player pick up the
349
+ // frame of a seek.
350
+ const frames = ownVideoFrames(framesExtractor.decodeCompositionFrames());
351
+ for (const [key, previous] of Object.entries(previousSources.value)) {
352
+ if (!frames[key] || frames[key]!.producerId !== previous.producerId)
353
+ releaseVideoFrameImage(previous);
354
+ }
355
+ previousSources.value = frames;
356
+ sourcesGeneration.value = generation;
357
+ const currentTime = framesExtractor.currentTime;
358
+ const framesVersion = framesExtractor.framesVersion;
359
+ const inputs = Array.isArray(drawWhenPaused) ? drawWhenPaused : null;
360
+ let inputsSame = true;
361
+ if (inputs) {
362
+ const last = lastDrawnInputs.value;
363
+ if (!last || last.length !== inputs.length) inputsSame = false;
364
+ else {
365
+ for (let i = 0; i < inputs.length; i++) {
366
+ if (inputs[i]!.value !== last[i]) {
367
+ inputsSame = false;
368
+ break;
369
+ }
370
+ }
371
+ }
372
+ }
373
+ if (
374
+ drawWhenPaused !== true &&
375
+ inputsSame &&
376
+ !framesExtractor.isPlaying &&
377
+ currentFrame.value !== null &&
378
+ frameGeneration.value === generation &&
379
+ framesVersion === lastDrawnFramesVersion.value &&
380
+ currentTime === lastDrawnTime.value &&
381
+ surfaceWidth.value === pixelWidth &&
382
+ surfaceHeight.value === pixelHeight
383
+ ) {
384
+ // Paused with nothing new: the image on screen is still exact, and
385
+ // redrawing it at every vsync would only burn GPU time and battery.
386
+ return;
387
+ }
388
+
389
+ let surface: SkSurface | null = surfaceSharedValue.value;
390
+
391
+ if (
392
+ !surface ||
393
+ surfaceWidth.value !== pixelWidth ||
394
+ surfaceHeight.value !== pixelHeight
395
+ ) {
396
+ // width and height can change while the player stays mounted — laying the
397
+ // stage out for a different aspect ratio calls the hook with new
398
+ // dimensions and the same surface. Drawing the new size into the old
399
+ // texture and then declaring the result to be the new size stretches the
400
+ // picture by the ratio between them, so the surface is re-keyed on its
401
+ // dimensions the way exportVideoComposition already re-keys its own.
402
+ const retired = {
403
+ images: [currentFrame.value, pendingSnapshot.value],
404
+ surface,
405
+ canvas: canvasSharedValue.value,
406
+ reservation: surfaceReservation.value,
407
+ afterDraw: pendingAfterDraw.value?.run,
408
+ };
409
+ currentFrame.value = null;
410
+ pendingSnapshot.value = null;
411
+ pendingAfterDraw.value = null;
412
+ canvasSharedValue.value = null;
413
+ surfaceSharedValue.value = null;
414
+ surfaceReservation.value = 0;
415
+ const retiredFailure = disposePreviewResources(retired);
416
+ if (retiredFailure.failed) throw retiredFailure.error;
417
+ // Surface + immutable snapshot/COW backing while replacing the preview.
418
+ const reservation = reserveVideoMemory(
419
+ frameByteSize(pixelWidth, pixelHeight) * 2,
420
+ "composition preview",
421
+ );
422
+ surfaceReservation.value = reservation;
423
+ try {
424
+ surface = Skia.Surface.MakeOffscreen(pixelWidth, pixelHeight);
425
+ surfaceSharedValue.value = surface;
426
+ if (!surface) throw new Error("Cannot allocate preview surface");
427
+ canvasSharedValue.value = getVideoCanvas(surface);
428
+ surfaceWidth.value = pixelWidth;
429
+ surfaceHeight.value = pixelHeight;
430
+ } catch (error) {
431
+ // The ordinary session cleanup owns partial allocation state too.
432
+ // Preserve the setup error and keep its reservation reachable.
433
+ throw error;
434
+ }
435
+ }
436
+ if (!surface) {
437
+ console.warn("Failed to create surface");
438
+ return;
439
+ }
440
+
441
+ const canvas = canvasSharedValue.value!;
442
+ // Cleared as the export clears it: a drawFrame that leaves part of the
443
+ // canvas alone showed the previous frames there, and not in the export.
444
+ canvas.drawColor(Skia.Color("#00000000"), BlendMode.Clear);
445
+ const context = beforeDrawFrame?.() as T;
446
+ const drawn = {
447
+ submitted: false,
448
+ failed: false,
449
+ error: undefined as unknown,
450
+ };
451
+ const releaseContext = () => {
452
+ "worklet";
453
+ afterDrawFrame?.(context);
454
+ };
455
+ pendingAfterDraw.value = { run: releaseContext };
456
+ try {
457
+ drawFrame({
458
+ canvas,
459
+ context,
460
+ videoComposition: composition!,
461
+ currentTime,
462
+ frames,
463
+ width: pixelWidth,
464
+ height: pixelHeight,
465
+ });
466
+ const previous = currentFrame.value;
467
+ const next = surface.makeImageSnapshot(
468
+ undefined,
469
+ previous ?? undefined,
470
+ );
471
+ if (next !== previous) pendingSnapshot.value = next;
472
+ surface.flush(true);
473
+ drawn.submitted = true;
474
+ frameGeneration.value = generation;
475
+ if (next === previous) currentFrame.modify(undefined, true);
476
+ else {
477
+ currentFrame.value = next;
478
+ previous?.dispose();
479
+ }
480
+ pendingSnapshot.value = null;
481
+ } catch (error) {
482
+ drawn.failed = true;
483
+ drawn.error = error;
484
+ } finally {
485
+ // A drawer can throw after recording commands that sample resources
486
+ // from context. Submit and wait before the caller releases them.
487
+ if (!drawn.submitted) {
488
+ try {
489
+ surface.flush(true);
490
+ drawn.submitted = true;
491
+ } catch (error) {
492
+ if (!drawn.failed) drawn.error = error;
493
+ drawn.failed = true;
494
+ }
495
+ }
496
+ if (drawn.submitted) {
497
+ pendingAfterDraw.value = null;
498
+ try {
499
+ releaseContext();
500
+ } catch (error) {
501
+ if (!drawn.failed) drawn.error = error;
502
+ drawn.failed = true;
503
+ }
504
+ }
505
+ }
506
+ if (drawn.failed) throw drawn.error;
507
+ lastDrawnFramesVersion.value = framesVersion;
508
+ lastDrawnTime.value = currentTime;
509
+ if (inputs) lastDrawnInputs.value = inputs.map((input) => input.value);
510
+ } catch (error) {
511
+ activeGeneration.value = 0;
512
+ scheduleOnRN(errorHandler, error);
513
+ }
514
+ }, true);
515
+
516
+ return {
517
+ currentFrame,
518
+ player: framesExtractor,
519
+ };
520
+ };