@blotch/angular-lynx-native 22.3.0 → 22.3.2

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 (100) hide show
  1. package/README.md +41 -15
  2. package/dist/android/project.d.ts +90 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +369 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +13 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/generate.d.ts +17 -1
  12. package/dist/generate.d.ts.map +1 -1
  13. package/dist/generate.js +12 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -1
  17. package/dist/ios/build.d.ts.map +1 -1
  18. package/dist/ios/build.js +8 -2
  19. package/dist/ios/frameworks.d.ts +6 -5
  20. package/dist/ios/frameworks.d.ts.map +1 -1
  21. package/dist/ios/frameworks.js +46 -15
  22. package/dist/ios/project.d.ts +173 -11
  23. package/dist/ios/project.d.ts.map +1 -1
  24. package/dist/ios/project.js +767 -33
  25. package/dist/options.d.ts +143 -2
  26. package/dist/options.d.ts.map +1 -1
  27. package/dist/options.js +127 -0
  28. package/dist/permissions.d.ts +18 -1
  29. package/dist/permissions.d.ts.map +1 -1
  30. package/dist/permissions.js +63 -3
  31. package/package.json +1 -1
  32. package/templates/android/README.md +37 -2
  33. package/templates/android/angular-lynx.properties +2 -0
  34. package/templates/android/app/build.gradle.kts +70 -1
  35. package/templates/android/app/src/main/AndroidManifest.xml +24 -3
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +376 -6
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +25 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +168 -0
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +6 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +47 -3
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  65. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  66. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  67. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  68. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  69. package/templates/android/build.gradle.kts +1 -1
  70. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  71. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  72. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  73. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  74. package/templates/ios/App/AngularLynxVideo.h +37 -0
  75. package/templates/ios/App/AngularLynxVideo.m +435 -0
  76. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  77. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  78. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  79. package/templates/ios/App/AppDelegate.swift +34 -2
  80. package/templates/ios/App/AppleSignInButton.swift +106 -0
  81. package/templates/ios/App/AppleSignInModule.swift +222 -0
  82. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  83. package/templates/ios/App/BiometricsModule.swift +256 -0
  84. package/templates/ios/App/BluetoothModule.swift +1086 -0
  85. package/templates/ios/App/CalendarModule.swift +158 -0
  86. package/templates/ios/App/FilePickerModule.swift +240 -0
  87. package/templates/ios/App/HapticsModule.swift +90 -0
  88. package/templates/ios/App/Info.plist +2 -0
  89. package/templates/ios/App/LynxViewController.swift +210 -6
  90. package/templates/ios/App/MotionModule.swift +430 -0
  91. package/templates/ios/App/NfcModule.swift +346 -0
  92. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  93. package/templates/ios/App/ShareTargetModule.swift +150 -0
  94. package/templates/ios/App/ShellModule.swift +17 -0
  95. package/templates/ios/App/StoreReviewModule.swift +61 -0
  96. package/templates/ios/App/TrackingModule.swift +121 -0
  97. package/templates/ios/App/WifiModule.swift +237 -0
  98. package/templates/ios/App/XElementRegistry.swift +13 -3
  99. package/templates/ios/ShareExtension/Info.plist +42 -0
  100. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,676 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.graphics.Bitmap
4
+ import android.net.Uri
5
+ import android.os.Handler
6
+ import android.os.HandlerThread
7
+ import android.os.Looper
8
+ import android.view.PixelCopy
9
+ import android.view.SurfaceHolder
10
+ import android.view.SurfaceView
11
+ import androidx.media3.common.C
12
+ import androidx.media3.common.MediaItem
13
+ import androidx.media3.common.Player
14
+ import androidx.media3.common.VideoSize
15
+ import androidx.media3.ui.PlayerView
16
+ import com.lynx.tasm.behavior.Behavior
17
+ import com.lynx.tasm.behavior.LynxContext
18
+ import com.lynx.tasm.behavior.LynxProp
19
+ import com.lynx.tasm.behavior.ui.LynxUI
20
+ import com.lynx.xelement.video.LynxUIVideo
21
+ import java.nio.ByteBuffer
22
+ import java.nio.ByteOrder
23
+ import java.util.concurrent.CountDownLatch
24
+ import java.util.concurrent.TimeUnit
25
+ import java.util.concurrent.atomic.AtomicInteger
26
+ import java.util.concurrent.atomic.AtomicReference
27
+ import kotlin.math.roundToInt
28
+
29
+ /**
30
+ * The `video` element: XElement's, with frames the canvas contexts can read,
31
+ * so a 2D canvas can draw a video (`drawImage()`, `createPattern()`) and a
32
+ * WebGL canvas upload it (`texImage2D()`, three.js's VideoTexture), as a
33
+ * browser's HTMLVideoElement can. See
34
+ * packages/runtime/src/lib/canvas/video-element.ts.
35
+ *
36
+ * XElement's player (media3's ExoPlayer) draws its frames into its
37
+ * PlayerView's SurfaceView, whose pixels the app can't read directly. So the
38
+ * element registers itself in the canvas registry under its `video-id`,
39
+ * which the runtime sets, as a canvas's context is registered, and its
40
+ * snapshot copies the frame showing now out of the surface with PixelCopy.
41
+ * The contexts then read a video as they read another canvas, by its id
42
+ * (`{ canvas: id }`), so the pixels never travel through JavaScript.
43
+ *
44
+ * The surface is there only while the video is laid out with a size. While
45
+ * it isn't (`display: none`), the player draws into a VideoFrameTarget
46
+ * instead, a texture the shell owns, which the snapshot reads, so a hidden
47
+ * video is drawn as a browser's is (issue #726). When the view has a surface
48
+ * again, the player goes back to it. One that's only out of sight (behind
49
+ * other elements, or `opacity: 0`) keeps its surface.
50
+ *
51
+ * The player saying it drew a frame into the target doesn't mean the target
52
+ * has one (issue #805), so `bindfirstframe` waits for the target's frame,
53
+ * and a frame that doesn't come is drawn again: see checkTargetFrame.
54
+ *
55
+ * A read is done on another thread (PixelCopy's, or the target's), which the
56
+ * engine thread waits for, but not for long, and on CI's software-drawn
57
+ * emulator a busy moment outlasts the wait (issues #806 and #817). So the
58
+ * element keeps the last frame a read copied, and a read that doesn't come
59
+ * in time hands that over instead of nothing: late, as a browser's can be,
60
+ * rather than blank. `bindfirstframe` also waits until a first frame is
61
+ * kept, so a draw from the event always has one: see frameReady.
62
+ */
63
+ class VideoUI(context: LynxContext) : LynxUIVideo(context), CanvasContext {
64
+ private var videoId: String? = null
65
+
66
+ /** A frame's size, published whole, so a reader never mixes two frames'. */
67
+ private data class FrameSize(val width: Int, val height: Int)
68
+
69
+ // The player's frame, as its listener tells it on the UI thread, read on
70
+ // Lynx's engine thread.
71
+ @Volatile
72
+ private var frame = FrameSize(0, 0)
73
+
74
+ /** The view's surface has a frame of the player's. */
75
+ @Volatile
76
+ private var hasFrame = false
77
+
78
+ /**
79
+ * Where the snapshot reads from when it isn't the view: the target the
80
+ * player draws into while the view has no surface, and still after it
81
+ * goes back to the view, until the view has a frame of its own.
82
+ */
83
+ @Volatile
84
+ private var readTarget: VideoFrameTarget? = null
85
+
86
+ // The UI thread's: the target, once made, whether one is being made,
87
+ // whether the player draws into it now, and whether the element is gone.
88
+ private var target: VideoFrameTarget? = null
89
+ private var makingTarget = false
90
+ private var drawingOffscreen = false
91
+ private var destroyed = false
92
+
93
+ /**
94
+ * XElement's first-frame event (its duration), held back while the
95
+ * player draws into the target and the target has no frame yet, so the
96
+ * app never hears of a frame it can't read.
97
+ */
98
+ private var heldFirstFrame: Long? = null
99
+
100
+ /** The source the held first-frame event is for. */
101
+ private var heldSource: Uri? = null
102
+
103
+ /** How many times the frame was drawn again since the player last went to the target. */
104
+ private var redraws = 0
105
+
106
+ /** Checks the target got the frame the player says it drew: see checkTargetFrame. */
107
+ private val frameCheck = Runnable { checkTargetFrame() }
108
+
109
+ /** A frame a read copied: the source it's of, and the read's place in order. */
110
+ private class KeptFrame(val image: DecodedImage, val source: Int, val order: Int)
111
+
112
+ /**
113
+ * Counts the player's sources, so a frame kept from the last one is never
114
+ * handed out as this one's.
115
+ */
116
+ @Volatile
117
+ private var source = 0
118
+
119
+ /** Numbers the reads, so one that lands late never replaces a newer frame. */
120
+ private val reads = AtomicInteger()
121
+
122
+ /**
123
+ * The newest frame a read copied, on any thread: what a read that doesn't
124
+ * come in time hands over.
125
+ */
126
+ private val keptFrame = AtomicReference<KeptFrame?>(null)
127
+
128
+ // The UI thread's: whether a first frame is being read to keep, and the
129
+ // try that is, so one given up on or forgotten does nothing when it lands.
130
+ private var keeping = false
131
+ private var keepTry = 0
132
+
133
+ /**
134
+ * Sends a held first-frame event without a kept frame, when the read
135
+ * meant to keep one hasn't landed in KEEP_WAIT_MS.
136
+ */
137
+ private val keepGiveUp = Runnable {
138
+ keepTry++
139
+ keeping = false
140
+ releaseFirstFrame()
141
+ }
142
+
143
+ private val mainHandler = Handler(Looper.getMainLooper())
144
+
145
+ private val playerView: PlayerView?
146
+ get() = view as? PlayerView
147
+
148
+ private val surfaceView: SurfaceView?
149
+ get() = playerView?.videoSurfaceView as? SurfaceView
150
+
151
+ /**
152
+ * Follows the view's surface beside the player's own callback.
153
+ *
154
+ * When the surface goes, the player is given the target only after
155
+ * every callback has run. SurfaceView calls a copy of its callback list,
156
+ * and once drawInView() has given the player the view again, the
157
+ * player's callback comes after this one. Were the target given here,
158
+ * setVideoSurface() would take the player's callback off the holder but
159
+ * not out of that copy, and it would still run, see the holder's surface
160
+ * as the player's output (setVideoSurface() doesn't clear media3's
161
+ * `surfaceHolderSurfaceIsVideoOutput`) and set the output to null,
162
+ * leaving a hidden video with nowhere to draw. Posted, the target comes
163
+ * after the player has let go of the view's surface, which it does
164
+ * before its callback returns, so the surface is never drawn into after
165
+ * it's gone.
166
+ */
167
+ private val surfaceCallback = object : SurfaceHolder.Callback {
168
+ override fun surfaceCreated(holder: SurfaceHolder) = drawInView()
169
+
170
+ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
171
+
172
+ override fun surfaceDestroyed(holder: SurfaceHolder) {
173
+ mainHandler.post {
174
+ // Unless the view was shown again in the meantime.
175
+ if (surfaceView?.holder?.surface?.isValid != true) drawOffscreen()
176
+ }
177
+ }
178
+ }
179
+
180
+ private val listener = object : Player.Listener {
181
+ override fun onVideoSizeChanged(videoSize: VideoSize) {
182
+ // The size the frame is shown at: its pixels stretched by their
183
+ // aspect ratio, and turned as the player turns them.
184
+ val ratio = if (videoSize.pixelWidthHeightRatio > 0f) videoSize.pixelWidthHeightRatio else 1f
185
+ var width = (videoSize.width * ratio).roundToInt()
186
+ var height = videoSize.height
187
+ if (videoSize.unappliedRotationDegrees % 180 != 0) {
188
+ width = height.also { height = width }
189
+ }
190
+ frame = FrameSize(width, height)
191
+ }
192
+
193
+ override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
194
+ // A new source has nothing to draw until its first frame, as in a
195
+ // browser, and the frame kept from the last one isn't its.
196
+ hasFrame = false
197
+ target?.reset()
198
+ forgetKeptFrame()
199
+ // A held first-frame event is the last source's: XElement sends
200
+ // the new one's itself (its setSrc lets it send another). XElement's
201
+ // `stop` and `play` clear the items (a transition to null) and
202
+ // add the same one back without that, so the event is kept
203
+ // through an empty transition and for the same source.
204
+ if (mediaItem == null) {
205
+ // Nothing plays until `play`, so a pending check would only
206
+ // send the held event with no frame: the next frame drawn
207
+ // starts a check again.
208
+ mainHandler.removeCallbacks(frameCheck)
209
+ } else if (mediaItem.localConfiguration?.uri != heldSource) {
210
+ heldFirstFrame = null
211
+ // A new source gets its own redraws.
212
+ redraws = 0
213
+ }
214
+ }
215
+
216
+ override fun onRenderedFirstFrame() {
217
+ // The player draws a first frame again after `stop` and `play`,
218
+ // which clear and rebuild its item, but XElement sends
219
+ // `onFirstFrame` only once: the frame is there again from here.
220
+ // It also tells of the first frame on each new surface, so once
221
+ // it's back in the view, the view is read again.
222
+ if (drawingOffscreen) expectTargetFrame() else frameRendered()
223
+ }
224
+ }
225
+
226
+ init {
227
+ // Here rather than in createView(), which LynxBaseUI's constructor
228
+ // calls before this class's properties are set. XElement's view gives
229
+ // its PlayerView its player on the UI thread, in a post when this
230
+ // isn't it, so the listener goes on after.
231
+ mainHandler.post { attachPlayer() }
232
+ }
233
+
234
+ /** Listens to the player and the view's surface, on the UI thread. */
235
+ private fun attachPlayer() {
236
+ val player = playerView?.player ?: return
237
+ player.addListener(listener)
238
+ val holder = surfaceView?.holder ?: return
239
+ holder.addCallback(surfaceCallback)
240
+ // A video laid out with no size (`display: none`) never has a surface.
241
+ if (!holder.surface.isValid) drawOffscreen()
242
+ }
243
+
244
+ /**
245
+ * Has the player draw into the target while the view has no surface: it
246
+ * drops every frame without one, and a hidden video has a frame to read
247
+ * in a browser.
248
+ */
249
+ private fun drawOffscreen() {
250
+ val player = playerView?.player ?: return
251
+ if (drawingOffscreen || destroyed) return
252
+ val offscreen = target
253
+ if (offscreen == null) {
254
+ makeTarget()
255
+ return
256
+ }
257
+ // A frame from the last time it was drawn into isn't the one showing.
258
+ offscreen.reset()
259
+ hasFrame = false
260
+ readTarget = offscreen
261
+ drawingOffscreen = true
262
+ redraws = 0
263
+ // The player renders the next frame here even while paused (it does
264
+ // for each new surface), and tells of it with onRenderedFirstFrame.
265
+ player.setVideoSurface(offscreen.surface)
266
+ }
267
+
268
+ /**
269
+ * Makes the target, off the UI thread, and draws into it once it's made
270
+ * if the view still has no surface. A video that's shown checks before
271
+ * its first layout too, so it may make one it won't draw into; it keeps
272
+ * it for when it's hidden.
273
+ */
274
+ private fun makeTarget() {
275
+ if (makingTarget) return
276
+ makingTarget = true
277
+ VideoFrameTarget.create { made ->
278
+ mainHandler.post {
279
+ makingTarget = false
280
+ if (destroyed) {
281
+ made?.release()
282
+ return@post
283
+ }
284
+ target = made ?: return@post
285
+ made.onFrame = { mainHandler.post { targetFrameCame(made) } }
286
+ if (surfaceView?.holder?.surface?.isValid != true) drawOffscreen()
287
+ }
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Gives the player back the view's surface: setVideoSurface() stopped
293
+ * the player following it, and setVideoSurfaceView() follows it again.
294
+ * The target is still read until the view has a frame.
295
+ */
296
+ private fun drawInView() {
297
+ if (!drawingOffscreen) return
298
+ val player = playerView?.player ?: return
299
+ drawingOffscreen = false
300
+ // The view's first frame sends a held first-frame event now, in
301
+ // frameRendered(): the target's no longer what the app reads.
302
+ mainHandler.removeCallbacks(frameCheck)
303
+ player.setVideoSurfaceView(surfaceView)
304
+ }
305
+
306
+ /** The player drew a frame on the view's surface, or XElement says it did. */
307
+ private fun frameRendered() {
308
+ if (drawingOffscreen) return
309
+ hasFrame = true
310
+ readTarget = null
311
+ frameReady()
312
+ }
313
+
314
+ /**
315
+ * The player says it drew a frame into the target. It may not have come:
316
+ * see checkTargetFrame, which runs unless it does.
317
+ */
318
+ private fun expectTargetFrame() {
319
+ if (target?.frameIsCurrent() == true) {
320
+ targetFrameCame(target)
321
+ return
322
+ }
323
+ mainHandler.removeCallbacks(frameCheck)
324
+ mainHandler.postDelayed(frameCheck, FRAME_WAIT_MS)
325
+ }
326
+
327
+ /** The target has a frame since the player last went to it. */
328
+ private fun targetFrameCame(from: VideoFrameTarget?) {
329
+ // The post can come after a reset (a new source, or the player going
330
+ // back to the target) forgot the frame it was for: the check that's
331
+ // pending then still runs.
332
+ if (from == null || from !== target || !from.frameIsCurrent()) return
333
+ mainHandler.removeCallbacks(frameCheck)
334
+ redraws = 0
335
+ frameReady()
336
+ }
337
+
338
+ /**
339
+ * The frame showing now can be read: a frame of this source is kept, then
340
+ * a held first-frame event goes out. The read that keeps it runs on its
341
+ * own thread, which nothing waits for, so a busy moment only makes the
342
+ * event late; without it, the app's draw at the event waited 250 ms for
343
+ * the first read and drew nothing when that ran out (issues #806 and
344
+ * #817). A video that already has a frame kept (shown again, say) sends
345
+ * the event at once. A source shown after `stop` and `play` keeps one
346
+ * too, with no event, so its reads have one to fall back on.
347
+ */
348
+ private fun frameReady() {
349
+ if (destroyed) return
350
+ if (keptFrame.get()?.source == source) {
351
+ releaseFirstFrame()
352
+ return
353
+ }
354
+ if (keeping) return
355
+ keeping = true
356
+ mainHandler.postDelayed(keepGiveUp, KEEP_WAIT_MS)
357
+ readToKeep(++keepTry, KEEP_TRIES)
358
+ }
359
+
360
+ /**
361
+ * Starts the read frameReady keeps, `tries` times at most: a copy can
362
+ * fail just after the player says it drew the frame, before the frame
363
+ * reaches the surface, so one that lands with nothing is tried again.
364
+ * One that can't start (no size yet, or no surface) sends the event at
365
+ * once, as before.
366
+ */
367
+ private fun readToKeep(attempt: Int, tries: Int) {
368
+ if (attempt != keepTry) return
369
+ val (width, height) = frame
370
+ val started = width > 0 && height > 0 &&
371
+ readFrame(width, height) { image -> mainHandler.post { frameKept(attempt, tries, image != null) } }
372
+ if (!started) finishKeeping(attempt)
373
+ }
374
+
375
+ /** The read readToKeep started landed, with a frame or without. */
376
+ private fun frameKept(attempt: Int, tries: Int, kept: Boolean) {
377
+ if (attempt != keepTry) return
378
+ if (!kept && tries > 1) {
379
+ mainHandler.postDelayed({ readToKeep(attempt, tries - 1) }, KEEP_RETRY_MS)
380
+ return
381
+ }
382
+ finishKeeping(attempt)
383
+ }
384
+
385
+ /**
386
+ * Sends the held event, with a frame kept or, after the last try,
387
+ * without one, as it went out before.
388
+ */
389
+ private fun finishKeeping(attempt: Int) {
390
+ if (attempt != keepTry) return
391
+ keeping = false
392
+ mainHandler.removeCallbacks(keepGiveUp)
393
+ releaseFirstFrame()
394
+ }
395
+
396
+ /** Forgets the kept frame and any read that's keeping one, on the UI thread. */
397
+ private fun forgetKeptFrame() {
398
+ source++
399
+ keptFrame.set(null)
400
+ keepTry++
401
+ keeping = false
402
+ mainHandler.removeCallbacks(keepGiveUp)
403
+ }
404
+
405
+ /**
406
+ * The player said it drew a frame into the target a while ago, and the
407
+ * target still has none. The frame was lost on its way: the decoder
408
+ * started on a surface of media3's own (the target is made off the UI
409
+ * thread, so it can come after), and a frame it decoded there before the
410
+ * switch fails to queue on the target (`queueBuffer failed: -32` in
411
+ * logcat), though media3 counts it as drawn. A paused player draws
412
+ * nothing more, so the video would have no frame until it plays (issue
413
+ * #805). Seeking to where it is draws the frame there again, decoded
414
+ * after the switch, as a paused player does after any seek. ExoPlayer
415
+ * ignores a seek to the position it's at, so it seeks a millisecond away
416
+ * first and straight back: the second is a real seek, to the frame the
417
+ * video shows. A seek makes XElement send `bindbuffering`, which only
418
+ * this rare case pays for.
419
+ * After a few tries, the app hears of the first frame anyway, as it did
420
+ * before the target.
421
+ */
422
+ private fun checkTargetFrame() {
423
+ val offscreen = target
424
+ val player = playerView?.player
425
+ if (destroyed || !drawingOffscreen || offscreen == null || offscreen.frameIsCurrent() ||
426
+ player == null || player.playbackState == Player.STATE_IDLE || redraws >= MAX_REDRAWS
427
+ ) {
428
+ // A frame that came after all is kept first, as any is.
429
+ if (offscreen?.frameIsCurrent() == true) frameReady() else releaseFirstFrame()
430
+ return
431
+ }
432
+ redraws++
433
+ val position = player.currentPosition
434
+ val duration = player.duration
435
+ val away = if (duration != C.TIME_UNSET && position + 1 > duration) position - 1 else position + 1
436
+ player.seekTo(away.coerceAtLeast(0))
437
+ player.seekTo(position)
438
+ // In case the seek draws nothing either, it's checked again.
439
+ mainHandler.postDelayed(frameCheck, FRAME_WAIT_MS)
440
+ }
441
+
442
+ /** Sends the first-frame event held back for the target's frame, if there is one. */
443
+ private fun releaseFirstFrame() {
444
+ val durationMs = heldFirstFrame ?: return
445
+ heldFirstFrame = null
446
+ if (!destroyed) super.onFirstFrame(durationMs)
447
+ }
448
+
449
+ /**
450
+ * The player drew its first frame: XElement's element sends
451
+ * `bindfirstframe` from here, so the frame is there for a canvas before
452
+ * the app hears of it. That waits for a copy of the frame to be kept
453
+ * (frameReady), and while the player draws into the target, for the
454
+ * target to have the frame first.
455
+ */
456
+ override fun onFirstFrame(durationMs: Long) {
457
+ heldFirstFrame = durationMs
458
+ heldSource = playerView?.player?.currentMediaItem?.localConfiguration?.uri
459
+ when {
460
+ !drawingOffscreen -> frameRendered()
461
+ target?.frameIsCurrent() == true -> frameReady()
462
+ else -> expectTargetFrame()
463
+ }
464
+ }
465
+
466
+ override val canvasId: String
467
+ get() = videoId ?: ""
468
+
469
+ /** A video shows itself in its own view: there's nothing to attach. */
470
+ override fun attachView(canvas: CanvasUI?) {}
471
+
472
+ override fun surfaceChanged() {}
473
+
474
+ /** Only an OffscreenCanvas is transferred: a video has nothing to clear. */
475
+ override fun clearForTransfer() {}
476
+
477
+ /**
478
+ * The size of the frame showing now, in pixels, or 0 by 0 while there's
479
+ * no frame to copy (before the first, or before the first on the
480
+ * player's new surface): the runtime's `videoWidth` and `videoHeight`
481
+ * (the module's `videoSize`), and the size the snapshot is copied at.
482
+ */
483
+ fun frameSize(): Pair<Int, Int> {
484
+ val (width, height) = frame
485
+ if (width <= 0 || height <= 0) return 0 to 0
486
+ val offscreen = readTarget
487
+ val readable = if (offscreen != null) {
488
+ offscreen.hasFrame()
489
+ } else {
490
+ hasFrame && surfaceView?.holder?.surface?.isValid == true
491
+ }
492
+ return if (readable) width to height else 0 to 0
493
+ }
494
+
495
+ /**
496
+ * The frame showing now, as RGBA rows top to bottom, or null without one.
497
+ * The read waits READ_TIMEOUT_MS at most, on Lynx's engine thread; one
498
+ * that doesn't come in time, or fails, hands over the newest frame kept
499
+ * instead (issues #806 and #817). Each is a copy of its own, since a
500
+ * caller may work on the pixels in place (createImageBitmap()'s flip).
501
+ */
502
+ override fun snapshot(): DecodedImage? {
503
+ val (width, height) = frameSize()
504
+ if (width == 0) return null
505
+ val done = CountDownLatch(1)
506
+ val read = AtomicReference<DecodedImage?>(null)
507
+ val started = readFrame(width, height) { image ->
508
+ read.set(image)
509
+ done.countDown()
510
+ }
511
+ if (started && done.await(READ_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
512
+ read.get()?.let { return it.copy() }
513
+ }
514
+ val kept = keptFrame.get() ?: return null
515
+ if (kept.source != source || kept.image.width != width || kept.image.height != height) return null
516
+ return kept.image.copy()
517
+ }
518
+
519
+ /**
520
+ * Reads the frame showing now at `width` by `height`, from the target or
521
+ * the view's surface, on a thread of the read's own, which nothing it
522
+ * waits on waits on: keeps it, then hands it to `done` there (null for a
523
+ * read that failed). False if the read couldn't start.
524
+ */
525
+ private fun readFrame(width: Int, height: Int, done: (DecodedImage?) -> Unit): Boolean {
526
+ val from = source
527
+ val order = reads.incrementAndGet()
528
+ val landed: (DecodedImage?) -> Unit = { image ->
529
+ if (image != null && source == from) {
530
+ val kept = KeptFrame(image, from, order)
531
+ // A read can land after a newer one: it never replaces that.
532
+ while (true) {
533
+ val old = keptFrame.get()
534
+ if (old != null && old.source == from && old.order > order) break
535
+ if (keptFrame.compareAndSet(old, kept)) break
536
+ }
537
+ }
538
+ done(image)
539
+ }
540
+ val offscreen = readTarget
541
+ if (offscreen != null) {
542
+ offscreen.read(width, height, landed)
543
+ return true
544
+ }
545
+ return copyView(width, height, landed)
546
+ }
547
+
548
+ /**
549
+ * Copies the view's surface with PixelCopy, which answers on a thread of
550
+ * its own (the engine thread may be waiting for it, and the UI thread on
551
+ * the engine thread), and hands the pixels to `done` there. False if the
552
+ * copy couldn't start.
553
+ */
554
+ private fun copyView(width: Int, height: Int, done: (DecodedImage?) -> Unit): Boolean {
555
+ val surfaceView = surfaceView ?: return false
556
+ if (!surfaceView.holder.surface.isValid) return false
557
+ val bitmap = try {
558
+ Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
559
+ } catch (_: OutOfMemoryError) {
560
+ return false
561
+ }
562
+ try {
563
+ PixelCopy.request(surfaceView, bitmap, { copied ->
564
+ // The RenderThread is done with the bitmap only here, however
565
+ // long it took: freeing it while the copy is queued aborts the
566
+ // app there ("cannot access an invalid/free'd bitmap"), as
567
+ // CI's software-drawn emulator showed, so it's freed here.
568
+ val image = if (copied == PixelCopy.SUCCESS) pixelsOf(bitmap) else null
569
+ bitmap.recycle()
570
+ done(image)
571
+ }, copyHandler)
572
+ } catch (_: IllegalArgumentException) {
573
+ // The surface went between the check and the copy.
574
+ bitmap.recycle()
575
+ return false
576
+ }
577
+ return true
578
+ }
579
+
580
+ /** A copied frame's pixels, as RGBA rows top to bottom. */
581
+ private fun pixelsOf(bitmap: Bitmap): DecodedImage? {
582
+ val pixels = try {
583
+ ByteBuffer.allocateDirect(bitmap.width * bitmap.height * 4).order(ByteOrder.nativeOrder())
584
+ } catch (_: OutOfMemoryError) {
585
+ return null
586
+ }
587
+ // ARGB_8888 is R, G, B, A in memory; a video frame is opaque, so
588
+ // premultiplied or not, its colors are the same.
589
+ bitmap.copyPixelsToBuffer(pixels)
590
+ pixels.rewind()
591
+ return DecodedImage(pixels, bitmap.width, bitmap.height, true)
592
+ }
593
+
594
+ @LynxProp(name = "video-id")
595
+ fun setVideoId(value: String?) {
596
+ if (value == videoId) return
597
+ videoId?.let { old -> if (CanvasRegistry.context(old) === this) CanvasRegistry.setContext(old, null) }
598
+ videoId = value
599
+ value?.let { CanvasRegistry.setContext(it, this) }
600
+ }
601
+
602
+ override fun destroy() {
603
+ videoId?.let { id -> if (CanvasRegistry.context(id) === this) CanvasRegistry.setContext(id, null) }
604
+ val detach = Runnable {
605
+ val player = playerView?.player
606
+ player?.removeListener(listener)
607
+ surfaceView?.holder?.removeCallback(surfaceCallback)
608
+ mainHandler.removeCallbacks(frameCheck)
609
+ forgetKeptFrame()
610
+ heldFirstFrame = null
611
+ readTarget = null
612
+ target?.let { offscreen ->
613
+ // The player lets go of the target's surface (and waits for
614
+ // its decoder to) before the target lets go of the texture
615
+ // behind it.
616
+ if (drawingOffscreen) player?.clearVideoSurface(offscreen.surface)
617
+ offscreen.release()
618
+ }
619
+ target = null
620
+ drawingOffscreen = false
621
+ destroyed = true
622
+ }
623
+ // Before XElement's destroy releases the player, which it does at
624
+ // once on the UI thread.
625
+ if (Looper.myLooper() == Looper.getMainLooper()) detach.run() else mainHandler.post(detach)
626
+ super.destroy()
627
+ }
628
+
629
+ companion object {
630
+ /**
631
+ * How long a snapshot waits for its read, which blocks Lynx's engine
632
+ * thread meanwhile. A read takes a few milliseconds on a phone, but a
633
+ * copy waits behind whatever the RenderThread is drawing, which takes
634
+ * far longer on an emulator drawing in software, and either thread
635
+ * can be starved there for seconds. One that doesn't come in time
636
+ * hands over the frame kept last.
637
+ */
638
+ private const val READ_TIMEOUT_MS = 250L
639
+
640
+ /**
641
+ * How long a held first-frame event waits for its frame to be kept.
642
+ * A copy lands in milliseconds on a phone; CI's emulator has stalled
643
+ * for 2.3 seconds. Past this, the event goes out without one.
644
+ */
645
+ private const val KEEP_WAIT_MS = 5000L
646
+
647
+ /** How many reads a first frame gets to be kept, when they land with nothing. */
648
+ private const val KEEP_TRIES = 5
649
+
650
+ /** How long after a read that landed with nothing the next starts. */
651
+ private const val KEEP_RETRY_MS = 100L
652
+
653
+ /**
654
+ * How long after the player says it drew a frame into the target the
655
+ * target should have it. A frame reaches it in a few milliseconds;
656
+ * this leaves room for an emulator drawing in software, and a frame
657
+ * that comes later only costs a redraw.
658
+ */
659
+ private const val FRAME_WAIT_MS = 500L
660
+
661
+ /** How many times a frame that didn't reach the target is drawn again. */
662
+ private const val MAX_REDRAWS = 3
663
+
664
+ private val copyHandler: Handler by lazy {
665
+ Handler(HandlerThread("AngularLynxVideoCopy").apply { start() }.looper)
666
+ }
667
+
668
+ /**
669
+ * Replaces XElement's `video` behavior: MainActivity adds it after
670
+ * XElement's, and the last behavior added for a tag wins.
671
+ */
672
+ fun behavior(): Behavior = object : Behavior("video") {
673
+ override fun createUI(context: LynxContext): LynxUI<*> = VideoUI(context)
674
+ }
675
+ }
676
+ }