@onekeyfe/react-native-native-list 6.7.0-28 → 6.7.0-29

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.
@@ -26,6 +26,8 @@ import com.facebook.react.modules.network.OkHttpClientProvider
26
26
  import com.facebook.react.uimanager.ThemedReactContext
27
27
  import okhttp3.JavaNetCookieJar
28
28
  import org.json.JSONObject
29
+ import com.margelo.nitro.onekeyimage.OneKeyMediaPreviewCache
30
+ import java.util.UUID
29
31
 
30
32
  /**
31
33
  * Uses Media3 like native Video, but never starts playback or requests audio focus. A player
@@ -35,9 +37,10 @@ import org.json.JSONObject
35
37
  internal class NativeListMediaPreviewSlot(private val context: ThemedReactContext) {
36
38
  val view: FrameLayout = object : FrameLayout(context) {
37
39
  override fun onAttachedToWindow() { super.onAttachedToWindow(); observeViewport(); updateVisibility() }
38
- override fun onDetachedFromWindow() { stopObservingViewport(); releasePlayer(); super.onDetachedFromWindow() }
40
+ override fun onDetachedFromWindow() { stopObservingViewport(); cancelPreview(); super.onDetachedFromWindow() }
41
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh); updateVisibility() }
39
42
  override fun onWindowVisibilityChanged(visibility: Int) { super.onWindowVisibilityChanged(visibility); updateVisibility() }
40
- override fun onVisibilityAggregated(isVisible: Boolean) { super.onVisibilityAggregated(isVisible); if (isVisible) updateVisibility() else releasePlayer() }
43
+ override fun onVisibilityAggregated(isVisible: Boolean) { super.onVisibilityAggregated(isVisible); if (isVisible) updateVisibility() else cancelPreview() }
41
44
  }
42
45
  private val image = NativeListImageSlot(context)
43
46
  private val video = AspectRatioFrameLayout(context)
@@ -51,6 +54,10 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
51
54
  private var completion: ((Boolean) -> Unit)? = null
52
55
  private var pendingCompletion: Runnable? = null
53
56
  private var player: ExoPlayer? = null
57
+ private var subscription: OneKeyMediaPreviewCache.Subscription? = null
58
+ private var extractionLease: UUID? = null
59
+ private var requestedEdge: Int? = null
60
+ private val previewCache by lazy { OneKeyMediaPreviewCache.get(context) }
54
61
  private var resumeVideo: (() -> Unit)? = null
55
62
  private var viewportObserver: ViewTreeObserver? = null
56
63
  private val visibleRect = Rect()
@@ -99,7 +106,7 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
99
106
  val candidate = candidateGeneration
100
107
  resumeVideo = null
101
108
  stopObservingViewport()
102
- releasePlayer()
109
+ cancelPreview()
103
110
  if (attempt >= order.size) {
104
111
  result = false
105
112
  completion?.invoke(false)
@@ -133,8 +140,36 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
133
140
  val uri = source.optString("uri")
134
141
  if (uri.isBlank()) { finished(false); return }
135
142
  val headers = source.optJSONObject("headers")?.let { values -> values.keys().asSequence().associateWith { values.optString(it) } } ?: emptyMap()
143
+ val fitKey = if ((fit ?: source.optString("contentFit")) == "cover") "cover" else "contain"
136
144
  resumeVideo = start@{
137
- if (epoch != token || candidateGeneration != candidate || player != null) return@start
145
+ if (epoch != token || candidateGeneration != candidate || subscription != null || frame.drawable != null ||
146
+ video.width <= 0 || video.height <= 0) return@start
147
+ val edge = OneKeyMediaPreviewCache.targetEdge(maxOf(view.width, view.height))
148
+ requestedEdge = edge
149
+ subscription = previewCache.request(uri, headers, edge, fitKey, source.optString("cachePolicy", "memory-disk"),
150
+ onImage = { still ->
151
+ if (epoch == token && candidateGeneration == candidate) {
152
+ subscription = null
153
+ video.setAspectRatio(still.width.toFloat() / still.height)
154
+ frame.setImageBitmap(still); frame.visibility = View.VISIBLE
155
+ stopObservingViewport(); finished(true)
156
+ }
157
+ }, onExtract = { lease ->
158
+ if (epoch == token && candidateGeneration == candidate) {
159
+ extractionLease = lease
160
+ updateVisibility()
161
+ if (extractionLease == lease && requestedEdge == edge) startPlayer(uri, headers, token, candidate, edge, lease)
162
+ }
163
+ }, onRevoked = { extractionLease = null; releasePlayer() },
164
+ onFailure = {
165
+ if (epoch == token && candidateGeneration == candidate) { subscription = null; finished(false) }
166
+ })
167
+ }
168
+ observeViewport()
169
+ updateVisibility()
170
+ }
171
+
172
+ private fun startPlayer(uri: String, headers: Map<String, String>, token: Int, candidate: Int, edge: Int, lease: UUID) {
138
173
  playerGeneration++
139
174
  val generation = playerGeneration
140
175
  try {
@@ -158,10 +193,11 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
158
193
  next.addListener(object : Player.Listener {
159
194
  override fun onRenderedFirstFrame() {
160
195
  if (playerGeneration != generation) return
161
- finished(true, generation)
162
- captureFirstFrame(token, candidate, generation, FIRST_FRAME_CAPTURE_ATTEMPTS)
196
+ captureFirstFrame(token, candidate, generation, FIRST_FRAME_CAPTURE_ATTEMPTS, edge, lease)
197
+ }
198
+ override fun onPlayerError(error: PlaybackException) {
199
+ view.post { if (playerGeneration == generation) previewCache.fail(lease) }
163
200
  }
164
- override fun onPlayerError(error: PlaybackException) { if (playerGeneration == generation) finished(false, generation) }
165
201
  override fun onVideoSizeChanged(size: VideoSize) {
166
202
  if (playerGeneration == generation && size.height > 0) video.setAspectRatio(size.width * size.pixelWidthHeightRatio / size.height)
167
203
  }
@@ -170,39 +206,26 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
170
206
  next.prepare()
171
207
  next.pause()
172
208
  } catch (_: Exception) {
173
- releasePlayer()
174
- finished(false)
209
+ previewCache.fail(lease)
175
210
  }
176
- }
177
- observeViewport()
178
- updateVisibility()
179
211
  }
180
212
 
181
- /**
182
- * The rendered frame reaches the TextureView asynchronously, so a transparent copy is
183
- * retried on later frames. If no frame can be copied the paused player stays attached.
184
- */
185
- private fun captureFirstFrame(token: Int, candidate: Int, generation: Int, attemptsLeft: Int) {
213
+ /** TextureView requires UI access; request bounded pixels before background encoding. */
214
+ private fun captureFirstFrame(token: Int, candidate: Int, generation: Int, attemptsLeft: Int, edge: Int, lease: UUID) {
186
215
  view.postOnAnimation {
187
216
  if (epoch != token || candidateGeneration != candidate || playerGeneration != generation) return@postOnAnimation
188
- // Releasing first would make the queued success completion drop itself as stale.
189
- if (result != true) {
190
- captureFirstFrame(token, candidate, generation, attemptsLeft)
191
- return@postOnAnimation
192
- }
193
217
  val still = if (texture.isAvailable && texture.width > 0 && texture.height > 0) {
194
- runCatching { texture.getBitmap(texture.width, texture.height) }.getOrNull()
218
+ val scale = minOf(1.0, edge.toDouble() / maxOf(texture.width, texture.height))
219
+ runCatching { texture.getBitmap(maxOf(1, (texture.width * scale).toInt()), maxOf(1, (texture.height * scale).toInt())) }.getOrNull()
195
220
  } else null
196
221
  if (still == null || !hasVisiblePixels(still)) {
197
222
  still?.recycle()
198
- if (attemptsLeft > 1) captureFirstFrame(token, candidate, generation, attemptsLeft - 1)
223
+ if (attemptsLeft > 1) captureFirstFrame(token, candidate, generation, attemptsLeft - 1, edge, lease)
224
+ else previewCache.fail(lease)
199
225
  return@postOnAnimation
200
226
  }
201
- frame.setImageBitmap(still)
202
- frame.visibility = View.VISIBLE
203
- resumeVideo = null
204
- stopObservingViewport()
205
227
  releasePlayer()
228
+ previewCache.complete(lease, still)
206
229
  }
207
230
  }
208
231
 
@@ -213,7 +236,7 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
213
236
  }
214
237
 
215
238
  private fun observeViewport() {
216
- if (viewportObserver != null || resumeVideo == null || !view.isAttachedToWindow) return
239
+ if (viewportObserver != null || resumeVideo == null || frame.drawable != null || !view.isAttachedToWindow) return
217
240
  view.viewTreeObserver.takeIf { it.isAlive }?.let {
218
241
  it.addOnScrollChangedListener(scrollListener)
219
242
  it.addOnGlobalLayoutListener(layoutListener)
@@ -230,6 +253,13 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
230
253
  viewportObserver = null
231
254
  }
232
255
  private fun updateVisibility() {
256
+ requestedEdge?.let { previous ->
257
+ if (video.width > 0 && video.height > 0 && OneKeyMediaPreviewCache.targetEdge(maxOf(view.width, view.height)) != previous) {
258
+ cancelPreview(); requestedEdge = null
259
+ frame.setImageDrawable(null); frame.visibility = View.GONE; result = null
260
+ observeViewport()
261
+ }
262
+ }
233
263
  var ancestor: View? = view
234
264
  var opaque = true
235
265
  while (ancestor != null) {
@@ -238,7 +268,11 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
238
268
  }
239
269
  if (opaque && view.isAttachedToWindow && view.windowVisibility == View.VISIBLE && view.isShown &&
240
270
  view.getGlobalVisibleRect(visibleRect) && !visibleRect.isEmpty) resumeVideo?.invoke()
241
- else releasePlayer()
271
+ else cancelPreview()
272
+ }
273
+ private fun cancelPreview() {
274
+ val previous = subscription; subscription = null
275
+ previewCache.cancel(previous); extractionLease = null; releasePlayer()
242
276
  }
243
277
  private fun releasePlayer() {
244
278
  playerGeneration++
@@ -251,11 +285,12 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
251
285
  pendingCompletion = null
252
286
  resumeVideo = null
253
287
  stopObservingViewport()
254
- releasePlayer()
288
+ cancelPreview()
255
289
  image.recycle()
256
290
  image.view.visibility = View.VISIBLE
257
291
  video.visibility = View.GONE
258
292
  video.setAspectRatio(0f)
293
+ requestedEdge = null
259
294
  frame.setImageDrawable(null)
260
295
  frame.visibility = View.GONE
261
296
  identity = null; result = null; completion = null
package/docs/SPEC.md CHANGED
@@ -1296,6 +1296,76 @@ disposal. Unit checks prove transition semantics, not rendered behavior.
1296
1296
 
1297
1297
  ## Native media preview probing
1298
1298
 
1299
+ ### Persistent first-frame revision — Source implemented; scoped iOS validation
1300
+
1301
+ This revision supersedes the cell-only frame retention, unbounded visible-player
1302
+ count and copy-failure retained-player behavior described in the baseline below.
1303
+ Image owns the native-only preview cache and extraction coordinator defined in
1304
+ its SPEC §6.3; NativeList retains the paused/muted player and view lifecycle.
1305
+ No public descriptor, JavaScript API or Web renderer behavior changes.
1306
+
1307
+ On reaching the video candidate, a visible slot queries permitted decoded memory
1308
+ and then disk before requesting extraction. A hit displays the still frame and
1309
+ creates no AVPlayer/ExoPlayer. Normal image candidates retain their original
1310
+ precedence and image cache; a video-cache hit MUST NOT bypass an earlier image
1311
+ candidate. Cache identity excludes row key and includes URI, canonical headers,
1312
+ bounded pixel tier, schema and capture fit. Recycle drops cell state, not the
1313
+ shared cached frame. Fit, orientation, black/transparent platform letterbox and
1314
+ row-owned tap behavior match a newly captured frame.
1315
+
1316
+ The media descriptor exposes URI, explicit headers, dimensions, fit and cache
1317
+ policy, with no cookie/session management API. Preview identity does not track
1318
+ ambient cookie sessions or automatically invalidate on cookie changes; media
1319
+ that requires that behavior is outside the supported preview-cache contract.
1320
+ Existing AVPlayer/Media3 networking and cookie handling remain unchanged. The
1321
+ cache does not promise that underlying network requests are cookie-free.
1322
+ Detaching an iOS view with no window MUST preserve its last pixel tier and captured
1323
+ still; only a real attached-window scale/layout change can invalidate that tier.
1324
+
1325
+ Slots subscribe only while visible, attached and foreground eligible. They
1326
+ cancel on invisibility, detach, background, recycle or identity/size change and
1327
+ release any owned player immediately. A same-key visible peer may take over;
1328
+ old owner, binding, candidate and player generations cannot attach a frame or
1329
+ complete a newer request. At most two flights extract concurrently, bounded by
1330
+ Image's queue and 10-second grant deadline. The existing six short copy attempts
1331
+ may run, but exhaustion now releases the player and advances/fails the candidate
1332
+ instead of retaining a paused player indefinitely. Success is emitted after a
1333
+ valid still exists, not solely when the player reports its first rendered frame.
1334
+ No failed extraction is cached. Disk-write failure still permits a successful
1335
+ still to display. A cached or newly copied still releases player and viewport
1336
+ observers, and ordinary text-only rebinding retains the current presentation.
1337
+
1338
+ The cache dimensions use actual view pixel size, capped to a 1024-pixel long edge
1339
+ and 1,048,576 pixels with source aspect ratio preserved. Empty layout defers work.
1340
+ iOS retains the CVPixelBuffer for bounded background CI conversion rather than
1341
+ building a full-resolution UIImage on the UI thread. Android performs a bounded
1342
+ TextureView copy on the UI thread and background encoding; its cached presentation
1343
+ must restore the aspect-ratio container after reuse. Source headers and URL/query
1344
+ text are not written into cache filenames, metadata or logs.
1345
+
1346
+ The production iOS video slot passed 14 simulator checks with a real H.264 MP4,
1347
+ including cold capture/player release, cross-cell/recycled memory reuse, disk
1348
+ reuse after memory clear and a layout-tier resize. Its harness substitutes only
1349
+ the unused image-candidate host; image-to-video fallback and full-app integration
1350
+ were not exercised. Android runtime and physical-device performance remain
1351
+ pending. The complete acceptance matrix adds warm cross-cell/recycled hits with
1352
+ zero new players, disk hits after memory clear and process restart, same-source
1353
+ deduplication, owner cancellation/transfer, concurrency and timeout bounds,
1354
+ clear-generation races, corrupt entry repair and all existing probing/lifecycle
1355
+ cases. Native tests and simulator evidence cannot establish device FPS or memory
1356
+ improvement; those require workload-specific measurements on target devices.
1357
+
1358
+ The final Android slot, including deferred Media3 error release, compiled in the
1359
+ consumer's normal native build and final incremental APK. Matching SDK/consumer
1360
+ source hashes and APK provenance were checked, and the App visibly started on
1361
+ the isolated emulator. This is build/startup acceptance, not Android video-frame
1362
+ or complete Home NFT route acceptance. A temporary Home probe lacked account
1363
+ context; a later diagnostic Dialog had an unexplained black capture. Neither is
1364
+ recorded as a passing NFT visual case. Further scrolling, frame-cache and
1365
+ memory/performance measurements are outside this PR's recorded acceptance scope.
1366
+
1367
+ ### Baseline before the persistent first-frame revision
1368
+
1299
1369
  Status: Source implemented; native runtime acceptance pending. `mediaTile.media`
1300
1370
  is an opt-in native-only preview descriptor: `{ source: ImageSource, probeOrder:
1301
1371
  ('image' | 'video')[] }`. The order contains one or two distinct candidates.
@@ -1,4 +1,5 @@
1
1
  import AVFoundation
2
+ import OneKeyImage
2
3
  import UIKit
3
4
 
4
5
  private final class NativeListPausedVideoView: UIView {
@@ -17,6 +18,18 @@ final class NativeListMediaPreviewSlot {
17
18
  private let image = NativeListImageSlot()
18
19
  private let video = NativeListPausedVideoView()
19
20
  private let frameView = UIImageView()
21
+ private final class PendingFrame {
22
+ private let lock = NSLock()
23
+ private var buffer: CVPixelBuffer?
24
+ init(_ buffer: CVPixelBuffer) { self.buffer = buffer }
25
+ func take() -> CVPixelBuffer? { lock.lock(); defer { lock.unlock() }; let value = buffer; buffer = nil; return value }
26
+ func cancel() { lock.lock(); buffer = nil; lock.unlock() }
27
+ }
28
+ private var pendingFrame: PendingFrame?
29
+ private var requestedEdge: Int?
30
+ private var subscription: OneKeyMediaPreviewCache.Subscription?
31
+ private var extractionLease: UUID?
32
+ private static let frameWorker = DispatchQueue(label: "onekey.native-list.frame", qos: .userInitiated)
20
33
  private var videoOutput: AVPlayerItemVideoOutput?
21
34
  private static let frameContext = CIContext(options: [.cacheIntermediates: false])
22
35
  private static let frameCaptureAttempts = 6
@@ -26,6 +39,7 @@ final class NativeListMediaPreviewSlot {
26
39
  private var playerGeneration = 0
27
40
  private var result: Bool?
28
41
  private var completion: ((Bool) -> Void)?
42
+ private(set) var createdPlayerCount = 0
29
43
  private var player: AVPlayer?
30
44
  private var itemObservation: NSKeyValueObservation?
31
45
  private var readyObservation: NSKeyValueObservation?
@@ -49,7 +63,7 @@ final class NativeListMediaPreviewSlot {
49
63
  video.onWindowChanged = { [weak self] in self?.observeViewport(); self?.updateVisibility() }
50
64
  video.onLayoutChanged = { [weak self] in self?.updateVisibility() }
51
65
  lifecycleObservers = [
52
- NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.releasePlayer() },
66
+ NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.cancelPreview() },
53
67
  NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.updateVisibility() },
54
68
  ]
55
69
  }
@@ -87,7 +101,7 @@ final class NativeListMediaPreviewSlot {
87
101
  let candidate = candidateGeneration
88
102
  resumeVideo = nil
89
103
  viewportObservations.removeAll()
90
- releasePlayer()
104
+ cancelPreview()
91
105
  guard attempt < order.count else {
92
106
  result = false
93
107
  completion?(false)
@@ -113,81 +127,108 @@ final class NativeListMediaPreviewSlot {
113
127
  image.view.isHidden = true
114
128
  video.isHidden = false
115
129
  guard let url = URL(string: source.string("uri")), !source.string("uri").isEmpty else { finished(false); return }
130
+ let headers = (source.dictionary("headers") ?? [:]).compactMapValues { $0 as? String }
131
+ let fitKey = coverFit(fit ?? source.string("contentFit"))
116
132
  resumeVideo = { [weak self] in
117
- guard let self, self.epoch == token, self.candidateGeneration == candidate, self.player == nil else { return }
118
- self.playerGeneration &+= 1
119
- let generation = self.playerGeneration
120
- let asset = AVURLAsset(url: url, options: ["AVURLAssetHTTPHeaderFieldsKey": source.dictionary("headers") ?? [:]])
121
- let item = AVPlayerItem(asset: asset)
122
- item.preferredForwardBufferDuration = 1
123
- let output = AVPlayerItemVideoOutput(pixelBufferAttributes: [
124
- kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
125
- ])
126
- item.add(output)
127
- self.videoOutput = output
128
- let player = AVPlayer(playerItem: item)
129
- player.isMuted = true
130
- player.pause()
131
- self.player = player
132
- self.video.playerLayer.player = player
133
- self.itemObservation = item.observe(\.status, options: [.initial, .new]) { [weak self] item, _ in
134
- DispatchQueue.main.async {
135
- guard let self, self.playerGeneration == generation else { return }
136
- if item.status == .failed { finished(false) }
137
- }
138
- }
139
- self.readyObservation = self.video.playerLayer.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weak self] layer, _ in
140
- DispatchQueue.main.async {
141
- guard let self, self.playerGeneration == generation else { return }
142
- guard layer.isReadyForDisplay else { return }
133
+ guard let self, self.epoch == token, self.candidateGeneration == candidate,
134
+ self.subscription == nil, self.frameView.image == nil, !self.video.bounds.isEmpty else { return }
135
+ let edge = OneKeyMediaPreviewCache.targetEdge(max(self.video.bounds.width, self.video.bounds.height) * (self.video.window?.screen.scale ?? 1))
136
+ self.requestedEdge = edge
137
+ self.subscription = OneKeyMediaPreviewCache.shared.request(uri: url.absoluteString, headers: headers,
138
+ edge: edge, fit: fitKey, policy: source.string("cachePolicy", default: "memory-disk"),
139
+ onImage: { [weak self] still in
140
+ guard let self, self.epoch == token, self.candidateGeneration == candidate else { return }
141
+ self.subscription = nil
142
+ self.frameView.image = still; self.frameView.isHidden = false
143
+ self.viewportObservations.removeAll()
143
144
  finished(true)
144
- self.captureFirstFrame(generation: generation, attemptsLeft: Self.frameCaptureAttempts)
145
- }
146
- }
145
+ }, onExtract: { [weak self] lease in
146
+ guard let self, self.epoch == token, self.candidateGeneration == candidate else { return }
147
+ self.extractionLease = lease
148
+ self.updateVisibility()
149
+ guard self.extractionLease == lease, self.requestedEdge == edge else { return }
150
+ self.startPlayer(url: url, headers: headers, edge: edge, lease: lease)
151
+ }, onRevoked: { [weak self] in
152
+ self?.extractionLease = nil; self?.pendingFrame?.cancel(); self?.pendingFrame = nil; self?.releasePlayer()
153
+ },
154
+ onFailure: { [weak self] in
155
+ guard let self, self.epoch == token, self.candidateGeneration == candidate else { return }
156
+ self.subscription = nil; finished(false)
157
+ })
147
158
  }
148
159
  observeViewport()
149
160
  updateVisibility()
150
161
  }
151
162
 
152
- /// A paused item may not have handed its preroll frame to the output yet, so copying retries
153
- /// on later runloop turns. If no frame arrives the paused player stays attached.
154
- private func captureFirstFrame(generation: Int, attemptsLeft: Int) {
163
+ private func coverFit(_ fit: String) -> String { fit == "cover" ? "cover" : "contain" }
164
+
165
+ private func startPlayer(url: URL, headers: [String: String], edge: Int, lease: UUID) {
166
+ createdPlayerCount += 1
167
+ self.playerGeneration &+= 1
168
+ let generation = self.playerGeneration
169
+ let asset = AVURLAsset(url: url, options: ["AVURLAssetHTTPHeaderFieldsKey": headers])
170
+ let item = AVPlayerItem(asset: asset)
171
+ item.preferredForwardBufferDuration = 1
172
+ let output = AVPlayerItemVideoOutput(pixelBufferAttributes: [
173
+ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
174
+ ])
175
+ item.add(output)
176
+ self.videoOutput = output
177
+ let player = AVPlayer(playerItem: item)
178
+ player.isMuted = true
179
+ player.pause()
180
+ self.player = player
181
+ self.video.playerLayer.player = player
182
+ self.itemObservation = item.observe(\.status, options: [.initial, .new]) { [weak self] item, _ in
183
+ DispatchQueue.main.async {
184
+ guard let self, self.playerGeneration == generation else { return }
185
+ if item.status == .failed { OneKeyMediaPreviewCache.shared.fail(lease) }
186
+ }
187
+ }
188
+ self.readyObservation = self.video.playerLayer.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weak self] layer, _ in
189
+ DispatchQueue.main.async {
190
+ guard let self, self.playerGeneration == generation, layer.isReadyForDisplay else { return }
191
+ self.readyObservation = nil
192
+ self.captureFirstFrame(generation: generation, attemptsLeft: Self.frameCaptureAttempts, edge: edge, lease: lease)
193
+ }
194
+ }
195
+ }
196
+
197
+ /// Capture only the buffer on UI; CI normalizes orientation and size on a worker.
198
+ private func captureFirstFrame(generation: Int, attemptsLeft: Int, edge: Int, lease: UUID) {
155
199
  guard playerGeneration == generation, let player, let item = player.currentItem, let output = videoOutput else { return }
156
200
  let time = item.currentTime()
157
- if let buffer = output.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil),
158
- let still = Self.frameContext.createCGImage(CIImage(cvPixelBuffer: buffer), from: CGRect(
159
- x: 0, y: 0, width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer))) {
160
- let transform = item.tracks.lazy.compactMap(\.assetTrack).first { $0.mediaType == .video }?.preferredTransform
161
- frameView.image = UIImage(cgImage: still, scale: 1, orientation: Self.orientation(transform))
162
- frameView.isHidden = false
163
- resumeVideo = nil
164
- viewportObservations.removeAll()
201
+ if let buffer = output.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil) {
202
+ let transform = item.tracks.lazy.compactMap(\.assetTrack).first { $0.mediaType == .video }?.preferredTransform ?? .identity
165
203
  releasePlayer()
204
+ let pending = PendingFrame(buffer)
205
+ pendingFrame = pending
206
+ Self.frameWorker.async { [weak self] in
207
+ guard let buffer = pending.take() else { return }
208
+ var image = CIImage(cvPixelBuffer: buffer).transformed(by: transform)
209
+ let origin = image.extent.origin
210
+ image = image.transformed(by: CGAffineTransform(translationX: -origin.x, y: -origin.y))
211
+ let scale = min(1, CGFloat(edge) / max(image.extent.width, image.extent.height))
212
+ image = image.transformed(by: CGAffineTransform(scaleX: scale, y: scale))
213
+ let still = Self.frameContext.createCGImage(image, from: image.extent).map { UIImage(cgImage: $0) }
214
+ DispatchQueue.main.async {
215
+ guard let self, self.extractionLease == lease else { return }
216
+ if let still { OneKeyMediaPreviewCache.shared.complete(lease, image: still) }
217
+ else { OneKeyMediaPreviewCache.shared.fail(lease) }
218
+ }
219
+ }
166
220
  return
167
221
  }
168
- guard attemptsLeft > 1 else { return }
169
- // An exact seek re-delivers the paused preroll frame to newly attached outputs.
170
- if attemptsLeft == Self.frameCaptureAttempts {
171
- player.seek(to: time, toleranceBefore: .zero, toleranceAfter: .zero)
172
- }
222
+ guard attemptsLeft > 1 else { OneKeyMediaPreviewCache.shared.fail(lease); return }
223
+ if attemptsLeft == Self.frameCaptureAttempts { player.seek(to: time, toleranceBefore: .zero, toleranceAfter: .zero) }
173
224
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
174
- self?.captureFirstFrame(generation: generation, attemptsLeft: attemptsLeft - 1)
175
- }
176
- }
177
-
178
- private static func orientation(_ transform: CGAffineTransform?) -> UIImage.Orientation {
179
- guard let transform else { return .up }
180
- switch (transform.a, transform.b, transform.c, transform.d) {
181
- case (0, 1, -1, 0): return .right
182
- case (0, -1, 1, 0): return .left
183
- case (-1, 0, 0, -1): return .down
184
- default: return .up
225
+ self?.captureFirstFrame(generation: generation, attemptsLeft: attemptsLeft - 1, edge: edge, lease: lease)
185
226
  }
186
227
  }
187
228
 
188
229
  private func observeViewport() {
189
230
  viewportObservations.removeAll()
190
- guard resumeVideo != nil, video.window != nil else { return }
231
+ guard resumeVideo != nil, frameView.image == nil, video.window != nil else { return }
191
232
  var ancestor = video.superview
192
233
  while let current = ancestor {
193
234
  if let scrollView = current as? UIScrollView {
@@ -223,8 +264,24 @@ final class NativeListMediaPreviewSlot {
223
264
  }
224
265
 
225
266
  private func updateVisibility() {
267
+ if let requestedEdge, let window = video.window, !video.bounds.isEmpty {
268
+ let edge = OneKeyMediaPreviewCache.targetEdge(max(video.bounds.width, video.bounds.height) * window.screen.scale)
269
+ if edge != requestedEdge {
270
+ cancelPreview(); self.requestedEdge = nil
271
+ frameView.image = nil; frameView.isHidden = true; result = nil
272
+ observeViewport()
273
+ }
274
+ }
226
275
  if Self.intersectsViewport(video) && UIApplication.shared.applicationState == .active { resumeVideo?() }
227
- else { releasePlayer() }
276
+ else { cancelPreview() }
277
+ }
278
+ private func cancelPreview() {
279
+ let previous = subscription
280
+ subscription = nil
281
+ OneKeyMediaPreviewCache.shared.cancel(previous)
282
+ extractionLease = nil
283
+ pendingFrame?.cancel(); pendingFrame = nil
284
+ releasePlayer()
228
285
  }
229
286
  private func releasePlayer() {
230
287
  playerGeneration &+= 1
@@ -241,10 +298,11 @@ final class NativeListMediaPreviewSlot {
241
298
  candidateGeneration &+= 1
242
299
  resumeVideo = nil
243
300
  viewportObservations.removeAll()
244
- releasePlayer()
301
+ cancelPreview()
245
302
  image.recycle()
246
303
  image.view.isHidden = false
247
304
  video.isHidden = true
305
+ requestedEdge = nil
248
306
  frameView.image = nil
249
307
  frameView.isHidden = true
250
308
  identity = nil
@@ -252,6 +310,9 @@ final class NativeListMediaPreviewSlot {
252
310
  completion = nil
253
311
  }
254
312
  deinit {
313
+ pendingFrame?.cancel()
314
+ let pending = subscription
315
+ DispatchQueue.main.async { OneKeyMediaPreviewCache.shared.cancel(pending) }
255
316
  lifecycleObservers.forEach(NotificationCenter.default.removeObserver)
256
317
  player?.pause()
257
318
  player?.replaceCurrentItem(with: nil)
@@ -57,7 +57,7 @@ final class NativeListMediaFrameCaptureTests: XCTestCase {
57
57
 
58
58
  var loaded: Bool?
59
59
  slot.bind(["uri": url.absoluteString], key: "video", probeOrder: ["video"]) { loaded = $0 }
60
- XCTAssertTrue(slot.hasLivePlayer, "A visible tile starts one paused player")
60
+ // The cache lookup precedes player creation and can complete asynchronously.
61
61
  let deadline = Date().addingTimeInterval(10)
62
62
  while slot.capturedFrame == nil, Date() < deadline {
63
63
  RunLoop.main.run(until: Date().addingTimeInterval(0.05))
@@ -68,13 +68,38 @@ final class NativeListMediaFrameCaptureTests: XCTestCase {
68
68
  XCTAssertFalse(slot.hasLivePlayer)
69
69
 
70
70
  // Leaving and re-entering the viewport keeps the still without rebuilding a player.
71
+ let playersBeforeDetach = slot.createdPlayerCount
71
72
  slot.view.removeFromSuperview()
73
+ XCTAssertTrue(slot.capturedFrame === frame, "Detaching has no replacement screen scale")
74
+ XCTAssertEqual(slot.createdPlayerCount, playersBeforeDetach)
72
75
  window.rootViewController?.view.addSubview(slot.view)
73
76
  slot.bind(["uri": url.absoluteString], key: "video", probeOrder: ["video"])
77
+ XCTAssertTrue(slot.capturedFrame === frame, "The same window retains the same tier")
78
+ XCTAssertEqual(slot.createdPlayerCount, playersBeforeDetach)
74
79
  XCTAssertFalse(slot.hasLivePlayer)
75
80
  XCTAssertNotNil(slot.capturedFrame)
76
81
  slot.recycle()
77
82
  XCTAssertNil(slot.capturedFrame)
83
+ let coldPlayers = slot.createdPlayerCount
84
+ slot.bind(["uri": url.absoluteString], key: "different-row", probeOrder: ["video"])
85
+ let warmDeadline = Date().addingTimeInterval(3)
86
+ while slot.capturedFrame == nil, Date() < warmDeadline {
87
+ RunLoop.main.run(until: Date().addingTimeInterval(0.01))
88
+ }
89
+ XCTAssertNotNil(slot.capturedFrame)
90
+ XCTAssertEqual(slot.createdPlayerCount, coldPlayers, "Recycled row reuses the cached still")
91
+ let second = NativeListMediaPreviewSlot()
92
+ second.view.frame = CGRect(x: 120, y: 0, width: 120, height: 120)
93
+ window.rootViewController?.view.addSubview(second.view)
94
+ second.view.layoutIfNeeded()
95
+ second.bind(["uri": url.absoluteString], key: "another-cell", probeOrder: ["video"])
96
+ let crossCellDeadline = Date().addingTimeInterval(3)
97
+ while second.capturedFrame == nil, Date() < crossCellDeadline {
98
+ RunLoop.main.run(until: Date().addingTimeInterval(0.01))
99
+ }
100
+ XCTAssertNotNil(second.capturedFrame)
101
+ XCTAssertEqual(second.createdPlayerCount, 0, "A different cell uses shared cached pixels")
102
+ second.recycle(); slot.recycle()
78
103
  }
79
104
 
80
105
  /// A 64×48, ten-frame H.264 MP4 (generated with AVAssetWriter on macOS); the simulator
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-native-list",
3
- "version": "6.7.0-28",
3
+ "version": "6.7.0-29",
4
4
  "description": "Template-driven native RecyclerView and UICollectionView for React Native",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./lib/module/index.js",