@g9tm/lynxcontrols-native 2.7.3 → 2.8.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.
@@ -39,6 +39,9 @@ val androidxSqlite = "2.7.1"
39
39
  fun g9Feature(name: String): Boolean = (findProperty("g9native.$name") as String?)?.trim()?.toBoolean() ?: true
40
40
  val withMedia3 = g9Feature("media3")
41
41
  val withSqlite = g9Feature("sqlite")
42
+ // <g9-protected-video> (2.8.0): Media3's HLS module, opt-in (`g9native.hls=true`) so other hosts' APKs do not grow. A
43
+ // host that already ships media3-exoplayer-hls needs nothing; the element is compiled either way.
44
+ val withHls = (findProperty("g9native.hls") as String?)?.trim()?.toBoolean() ?: false
42
45
 
43
46
  dependencies {
44
47
  compileOnly("org.lynxsdk.lynx:lynx:$lynx")
@@ -60,6 +63,8 @@ dependencies {
60
63
  // <g9-video> (video/G9VideoUI.kt): ExoPlayer drawing into a TextureView. Google Maven only.
61
64
  if (withMedia3) implementation("androidx.media3:media3-exoplayer:1.8.0")
62
65
  else compileOnly("androidx.media3:media3-exoplayer:1.8.0")
66
+ if (withHls) implementation("androidx.media3:media3-exoplayer-hls:1.8.0")
67
+ else compileOnly("androidx.media3:media3-exoplayer-hls:1.8.0")
63
68
  // G9ImageModule (image/): EXIF orientation and the keepMetadata copy (GPS, dates, camera) onto JPEG / PNG / WebP.
64
69
  implementation("androidx.exifinterface:exifinterface:1.4.1")
65
70
 
@@ -11,6 +11,7 @@ import android.view.View
11
11
  import android.view.WindowManager
12
12
  import android.view.inputmethod.InputMethodManager
13
13
  import com.g9lynx.g9native.generated.G9HostModuleSpec
14
+ import com.g9lynx.g9native.host.G9SecureWindow
14
15
  import com.g9lynx.g9native.host.core.G9PreferenceBackend
15
16
  import com.g9lynx.g9native.host.core.G9PreferencesCore
16
17
  import com.g9lynx.g9native.host.core.G9SafeAreaCore
@@ -26,6 +27,8 @@ import com.lynx.tasm.behavior.LynxContext
26
27
  */
27
28
  @LynxNativeModule(name = "G9HostModule")
28
29
  class G9HostModule(private val lynxContext: LynxContext) : G9HostModuleSpec(lynxContext) {
30
+ /** This page's screen-protection hold in the window's shared FLAG_SECURE (G9SecureWindow, 2.8.0). */
31
+ private val pageHold = Any()
29
32
  private val main = Handler(Looper.getMainLooper())
30
33
 
31
34
  private val preferences: G9PreferencesCore by lazy {
@@ -161,11 +164,9 @@ class G9HostModule(private val lynxContext: LynxContext) : G9HostModuleSpec(lynx
161
164
  return
162
165
  }
163
166
  main.post {
164
- if (!activity.isFinishing) {
165
- if (on) activity.window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
166
- else activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
167
- }
168
- G9Bridge.reply(callback, G9PreferencesCore.ok(mapOf("blocked" to on, "captured" to false)))
167
+ // shared with every <g9-protected-video> on screen (2.8.0): the page letting go keeps a playing video protected
168
+ val blocked = if (activity.isFinishing) false else G9SecureWindow.hold(activity, pageHold, on)
169
+ G9Bridge.reply(callback, G9PreferencesCore.ok(mapOf("blocked" to (on && blocked), "captured" to false)))
169
170
  }
170
171
  }
171
172
 
@@ -0,0 +1,28 @@
1
+ package com.g9lynx.g9native.host
2
+
3
+ import android.app.Activity
4
+ import android.view.WindowManager
5
+ import com.g9lynx.g9native.host.core.G9SecureHolds
6
+
7
+ /**
8
+ * The activity window's FLAG_SECURE, shared by everything that protects the screen (2.8.0): the page's
9
+ * `useG9ScreenProtection` (through G9HostModule.screenProtection) and each `<g9-protected-video>` on screen. The flag is
10
+ * on while any holder holds it (screenshots, recordings and mirroring show the window black; the recents thumbnail is
11
+ * blank). Main thread.
12
+ */
13
+ object G9SecureWindow {
14
+ private val holds = G9SecureHolds<Activity>()
15
+
16
+ /** [holder] holds (or lets go of) [activity]'s protection; returns whether the window is now secure. */
17
+ @JvmStatic
18
+ fun hold(activity: Activity, holder: Any, on: Boolean): Boolean {
19
+ val secure = holds.set(activity, holder, on)
20
+ if (activity.isFinishing || activity.isDestroyed) {
21
+ holds.forget(activity)
22
+ return false
23
+ }
24
+ if (secure) activity.window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
25
+ else activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
26
+ return secure
27
+ }
28
+ }
@@ -0,0 +1,26 @@
1
+ package com.g9lynx.g9native.host.core
2
+
3
+ /**
4
+ * Who keeps a window protected (2.8.0): FLAG_SECURE stays on while ANY holder holds it — the page's screen-protection
5
+ * hold (G9HostModule.screenProtection) and every `<g9-protected-video>` on screen — so one letting go never uncovers
6
+ * another. Keyed by window (an activity), holders by identity. Pure Kotlin for the JVM suite; main thread only.
7
+ */
8
+ class G9SecureHolds<W : Any> {
9
+ private val holders = HashMap<W, MutableSet<Any>>()
10
+
11
+ /** Adds or removes [holder] for [window]; true when the window must now be secure. */
12
+ fun set(window: W, holder: Any, on: Boolean): Boolean {
13
+ val set = holders.getOrPut(window) { mutableSetOf() }
14
+ if (on) set.add(holder) else set.remove(holder)
15
+ if (set.isEmpty()) holders.remove(window)
16
+ return set.isNotEmpty()
17
+ }
18
+
19
+ /** Whether [window] has a holder. */
20
+ fun held(window: W): Boolean = holders[window]?.isNotEmpty() == true
21
+
22
+ /** Forgets a window that is gone (an activity destroyed). */
23
+ fun forget(window: W) {
24
+ holders.remove(window)
25
+ }
26
+ }
@@ -0,0 +1,434 @@
1
+ package com.g9lynx.g9native.video
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.content.ContextWrapper
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import android.util.Log
9
+ import android.view.SurfaceView
10
+ import android.view.View
11
+ import android.widget.FrameLayout
12
+ import androidx.annotation.OptIn
13
+ import androidx.media3.common.AudioAttributes
14
+ import androidx.media3.common.C
15
+ import androidx.media3.common.MediaItem
16
+ import androidx.media3.common.MimeTypes
17
+ import androidx.media3.common.PlaybackException
18
+ import androidx.media3.common.Player
19
+ import androidx.media3.common.VideoSize
20
+ import androidx.media3.common.util.UnstableApi
21
+ import androidx.media3.datasource.DataSource
22
+ import androidx.media3.datasource.DefaultHttpDataSource
23
+ import androidx.media3.datasource.HttpDataSource
24
+ import androidx.media3.exoplayer.ExoPlayer
25
+ import androidx.media3.exoplayer.hls.HlsMediaSource
26
+ import com.g9lynx.g9native.host.G9SecureWindow
27
+ import com.g9lynx.g9native.video.core.G9ProtectedVideoProps
28
+ import com.lynx.react.bridge.Dynamic
29
+ import com.lynx.react.bridge.ReadableType
30
+ import com.lynx.tasm.behavior.Behavior
31
+ import com.lynx.tasm.behavior.LynxContext
32
+ import com.lynx.tasm.behavior.LynxProp
33
+ import com.lynx.tasm.behavior.ui.LynxUI
34
+ import com.lynx.tasm.event.LynxDetailEvent
35
+
36
+ /**
37
+ * `<g9-protected-video>` on Android (2.8.0, G9Hub Plan-V8 row 145; Hub's `G9ProtectedVideoUI` brought into the library).
38
+ * A Media3 ExoPlayer plays a signed HLS playlist — AES-128 segments are decrypted by the HLS extractor, and every URL
39
+ * (the key's included) is signed, so no headers are needed — fetching through the host's network stack
40
+ * ([G9ProtectedVideo.dataSourceFactory]: the app's pinned OkHttp client through `OkHttpDataSource.Factory`, say).
41
+ * Nothing is cached to disk or downloaded, and there is no picture-in-picture. It draws into a secure SurfaceView and,
42
+ * while on screen, holds the window's FLAG_SECURE ([G9SecureWindow], shared with `useG9ScreenProtection`): screenshots,
43
+ * recordings and mirroring show black.
44
+ *
45
+ * Attributes (text; a boolean or a number is turned into the same text): `src` (https, or http to a local-network
46
+ * host), `paused` ("true" default / "false"), `seek` (seconds; each new value seeks — "<seconds>|<nonce>" seeks to the
47
+ * same second again), `rate` ("1", "1.5"… 0.25 – 4), `muted`, `fit` ("contain" default | "cover"), `protect-window`
48
+ * ("true" default; "false" leaves the window's flag to the page). Events: `status` `{state:
49
+ * loading|ready|playing|paused|buffering|ended|error, position, duration, error?, captured: false}` on every state
50
+ * change; `progress` `{position, duration, buffered}` about once a second while playing (and after a seek). The player
51
+ * is released when the element is destroyed or its `src` changes, and pauses while the view is off screen (the app in
52
+ * the background). Register it with [G9ProtectedVideoBehaviors] (needs `g9native.hls=true`). Main thread.
53
+ */
54
+ @OptIn(UnstableApi::class)
55
+ class G9ProtectedVideoUI(context: LynxContext) : LynxUI<G9ProtectedVideoView>(context) {
56
+ private val main = Handler(Looper.getMainLooper())
57
+ private var player: ExoPlayer? = null
58
+
59
+ private var src: String? = null
60
+ private var preparedSrc: String? = null
61
+ private var paused = true
62
+ private var seekValue: String? = null
63
+ private var appliedSeek: String? = null
64
+ private var rate = 1f
65
+ private var muted = false
66
+ private var cover = false
67
+ private var protectWindow = true
68
+
69
+ private var state = ""
70
+ private var readySeen = false
71
+ private var failure: String? = null
72
+ private var holding: Activity? = null
73
+
74
+ private val ticker =
75
+ object : Runnable {
76
+ override fun run() {
77
+ val p = player ?: return
78
+ progress()
79
+ if (p.isPlaying) main.postDelayed(this, PROGRESS_MS)
80
+ }
81
+ }
82
+
83
+ private val listener =
84
+ object : Player.Listener {
85
+ override fun onPlaybackStateChanged(playbackState: Int) {
86
+ if (playbackState == Player.STATE_READY && !readySeen) {
87
+ readySeen = true
88
+ setState("ready")
89
+ }
90
+ if (playbackState == Player.STATE_ENDED) progress()
91
+ report()
92
+ }
93
+
94
+ override fun onIsPlayingChanged(isPlaying: Boolean) {
95
+ main.removeCallbacks(ticker)
96
+ if (isPlaying) main.post(ticker)
97
+ report()
98
+ }
99
+
100
+ override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) = report()
101
+
102
+ override fun onPlayerError(error: PlaybackException) = fail(describe(error))
103
+
104
+ override fun onVideoSizeChanged(videoSize: VideoSize) {
105
+ mView.setVideoSize(videoSize.width * videoSize.pixelWidthHeightRatio, videoSize.height.toFloat())
106
+ }
107
+ }
108
+
109
+ override fun createView(context: Context): G9ProtectedVideoView =
110
+ G9ProtectedVideoView(context).also { view ->
111
+ view.onShownChanged = {
112
+ applyWindow()
113
+ applyPlayback()
114
+ }
115
+ }
116
+
117
+ @LynxProp(name = "src")
118
+ fun setSrc(value: Dynamic?) {
119
+ src = text(value)
120
+ }
121
+
122
+ @LynxProp(name = "paused")
123
+ fun setPaused(value: Dynamic?) {
124
+ paused = G9ProtectedVideoProps.flag(text(value), fallback = true)
125
+ }
126
+
127
+ @LynxProp(name = "seek")
128
+ fun setSeek(value: Dynamic?) {
129
+ seekValue = text(value)
130
+ }
131
+
132
+ @LynxProp(name = "rate")
133
+ fun setRate(value: Dynamic?) {
134
+ rate = G9ProtectedVideoProps.rate(text(value))
135
+ }
136
+
137
+ @LynxProp(name = "muted")
138
+ fun setMuted(value: Dynamic?) {
139
+ muted = G9ProtectedVideoProps.flag(text(value), fallback = false)
140
+ }
141
+
142
+ @LynxProp(name = "fit")
143
+ fun setFit(value: Dynamic?) {
144
+ cover = G9ProtectedVideoProps.cover(text(value))
145
+ }
146
+
147
+ @LynxProp(name = "protect-window")
148
+ fun setProtectWindow(value: Dynamic?) {
149
+ protectWindow = G9ProtectedVideoProps.flag(text(value), fallback = true)
150
+ }
151
+
152
+ override fun onPropsUpdated() {
153
+ super.onPropsUpdated()
154
+ mView.cover = cover
155
+ applyWindow()
156
+ if (src != preparedSrc) prepare()
157
+ val p = player ?: return
158
+ p.videoScalingMode = if (cover) C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING else C.VIDEO_SCALING_MODE_SCALE_TO_FIT
159
+ p.volume = if (muted) 0f else 1f
160
+ p.setPlaybackSpeed(rate)
161
+ val seek = seekValue
162
+ if (seek != null && seek != appliedSeek) {
163
+ appliedSeek = seek
164
+ G9ProtectedVideoProps.seekSeconds(seek)?.let(::seekTo)
165
+ }
166
+ applyPlayback()
167
+ }
168
+
169
+ override fun destroy() {
170
+ release()
171
+ letGoOfWindow()
172
+ super.destroy()
173
+ }
174
+
175
+ private fun prepare() {
176
+ release()
177
+ preparedSrc = src
178
+ readySeen = false
179
+ failure = null
180
+ appliedSeek = null
181
+ state = ""
182
+ val raw = src ?: return
183
+ val uri = G9ProtectedVideoProps.usableSource(raw)
184
+ if (uri == null) {
185
+ fail("invalid-src: not an https URL (plain http only to a local-network host)")
186
+ return
187
+ }
188
+ setState("loading")
189
+ val exo =
190
+ ExoPlayer.Builder(lynxContext)
191
+ .setMediaSourceFactory(HlsMediaSource.Factory(G9ProtectedVideo.dataSource()))
192
+ .setAudioAttributes(
193
+ AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),
194
+ // handleAudioFocus
195
+ true,
196
+ )
197
+ .setHandleAudioBecomingNoisy(true)
198
+ .build()
199
+ exo.addListener(listener)
200
+ exo.setVideoSurfaceView(mView.surface)
201
+ exo.setMediaItem(MediaItem.Builder().setUri(uri).setMimeType(MimeTypes.APPLICATION_M3U8).build())
202
+ exo.prepare()
203
+ player = exo
204
+ }
205
+
206
+ private fun release() {
207
+ main.removeCallbacks(ticker)
208
+ val p = player ?: return
209
+ player = null
210
+ preparedSrc = null
211
+ p.removeListener(listener)
212
+ p.clearVideoSurfaceView(mView.surface)
213
+ p.release()
214
+ }
215
+
216
+ /** Holds the window's FLAG_SECURE while on screen (unless `protect-window="false"`). */
217
+ private fun applyWindow() {
218
+ val want = protectWindow && mView.shown
219
+ if (want && holding == null) {
220
+ val activity = activityOf(lynxContext) ?: return
221
+ holding = activity
222
+ G9SecureWindow.hold(activity, this, true)
223
+ } else if (!want) {
224
+ letGoOfWindow()
225
+ }
226
+ }
227
+
228
+ private fun letGoOfWindow() {
229
+ val activity = holding ?: return
230
+ holding = null
231
+ G9SecureWindow.hold(activity, this, false)
232
+ }
233
+
234
+ /** Plays when the page wants it and the view is on screen; else pauses. */
235
+ private fun applyPlayback() {
236
+ val p = player ?: return
237
+ val play = !paused && mView.shown && failure == null
238
+ if (play && p.playbackState == Player.STATE_ENDED) p.seekTo(0)
239
+ p.playWhenReady = play
240
+ report()
241
+ }
242
+
243
+ private fun seekTo(seconds: Double) {
244
+ val p = player ?: return
245
+ val duration = p.duration
246
+ val ms = (seconds * 1000).toLong().coerceAtLeast(0)
247
+ p.seekTo(if (duration != C.TIME_UNSET && duration > 0) ms.coerceAtMost(duration) else ms)
248
+ progress()
249
+ }
250
+
251
+ private fun fail(message: String) {
252
+ Log.w(TAG, "protected video: $message")
253
+ failure = message
254
+ player?.playWhenReady = false
255
+ setState("error")
256
+ }
257
+
258
+ /** The state from the player: one `status` event per change. */
259
+ private fun report() {
260
+ if (failure != null) return
261
+ val p = player ?: return
262
+ setState(
263
+ G9ProtectedVideoProps.state(
264
+ readySeen = readySeen,
265
+ ended = p.playbackState == Player.STATE_ENDED,
266
+ playing = p.isPlaying,
267
+ buffering = p.playbackState == Player.STATE_BUFFERING,
268
+ playWhenReady = p.playWhenReady,
269
+ current = state,
270
+ ),
271
+ )
272
+ }
273
+
274
+ private fun setState(next: String) {
275
+ if (next == state) return
276
+ state = next
277
+ val detail = hashMapOf<String, Any>("state" to next, "position" to position(), "duration" to duration(), "captured" to false)
278
+ failure?.takeIf { next == "error" }?.let { detail["error"] = it }
279
+ send("status", detail)
280
+ }
281
+
282
+ private fun progress() {
283
+ val p = player ?: return
284
+ send("progress", hashMapOf("position" to position(), "duration" to duration(), "buffered" to seconds(p.bufferedPosition)))
285
+ }
286
+
287
+ private fun position(): Double = seconds(player?.currentPosition ?: 0L)
288
+
289
+ private fun duration(): Double = seconds(player?.duration ?: C.TIME_UNSET)
290
+
291
+ private fun seconds(ms: Long): Double = if (ms == C.TIME_UNSET || ms <= 0) 0.0 else ms / 1000.0
292
+
293
+ /** Lynx writes into the detail map: always a fresh mutable map (as G9VideoUI). */
294
+ private fun send(name: String, detail: HashMap<String, Any>) {
295
+ lynxContext.eventEmitter.sendCustomEvent(LynxDetailEvent(sign, name, detail))
296
+ }
297
+
298
+ private companion object {
299
+ const val TAG = "G9Lynx"
300
+ const val PROGRESS_MS = 1000L
301
+
302
+ fun activityOf(context: Context?): Activity? {
303
+ var c = context
304
+ while (c is ContextWrapper) {
305
+ if (c is Activity) return c
306
+ c = c.baseContext
307
+ }
308
+ return null
309
+ }
310
+
311
+ fun text(value: Dynamic?): String? {
312
+ if (value == null || value.isNull) return null
313
+ return when (value.type) {
314
+ ReadableType.String -> value.asString()
315
+ ReadableType.Boolean -> value.asBoolean().toString()
316
+ ReadableType.Int -> value.asInt().toString()
317
+ ReadableType.Long -> value.asLong().toString()
318
+ ReadableType.Number -> value.asDouble().toString()
319
+ else -> null
320
+ }
321
+ }
322
+
323
+ /** `<code name>: <message>`, with the HTTP status of a refused request (an expired signed URL is a 403). */
324
+ fun describe(error: PlaybackException): String {
325
+ var cause: Throwable? = error.cause
326
+ while (cause != null) {
327
+ if (cause is HttpDataSource.InvalidResponseCodeException) return "${error.errorCodeName}: http ${cause.responseCode}"
328
+ cause = cause.cause
329
+ }
330
+ return "${error.errorCodeName}: ${error.message ?: error.errorCodeName}"
331
+ }
332
+ }
333
+ }
334
+
335
+ /**
336
+ * The element's view: a secure SurfaceView (left out of screenshots and recordings by the system), letterboxed for
337
+ * `contain` and full size for `cover` (the player then crops). [shown]: on screen in a visible window.
338
+ */
339
+ class G9ProtectedVideoView(context: Context) : FrameLayout(context) {
340
+ val surface = SurfaceView(context).apply { setSecure(true) }
341
+ private var videoW = 0f
342
+ private var videoH = 0f
343
+
344
+ /** Called when [shown] changed. */
345
+ var onShownChanged: (() -> Unit)? = null
346
+
347
+ var shown = false
348
+ private set(value) {
349
+ if (field == value) return
350
+ field = value
351
+ onShownChanged?.invoke()
352
+ }
353
+
354
+ var cover = false
355
+ set(value) {
356
+ if (field == value) return
357
+ field = value
358
+ requestLayout()
359
+ }
360
+
361
+ init {
362
+ setBackgroundColor(android.graphics.Color.BLACK)
363
+ addView(surface, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
364
+ }
365
+
366
+ fun setVideoSize(width: Float, height: Float) {
367
+ if (width == videoW && height == videoH) return
368
+ videoW = width
369
+ videoH = height
370
+ requestLayout()
371
+ }
372
+
373
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
374
+ val w = right - left
375
+ val h = bottom - top
376
+ val box = if (cover) intArrayOf(0, 0, w, h) else G9ProtectedVideoProps.containBox(w, h, videoW, videoH)
377
+ val bw = box[2] - box[0]
378
+ val bh = box[3] - box[1]
379
+ if (surface.measuredWidth != bw || surface.measuredHeight != bh) {
380
+ surface.measure(MeasureSpec.makeMeasureSpec(bw, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(bh, MeasureSpec.EXACTLY))
381
+ }
382
+ surface.layout(box[0], box[1], box[2], box[3])
383
+ }
384
+
385
+ override fun onAttachedToWindow() {
386
+ super.onAttachedToWindow()
387
+ shown = windowVisibility == View.VISIBLE
388
+ }
389
+
390
+ override fun onDetachedFromWindow() {
391
+ shown = false
392
+ super.onDetachedFromWindow()
393
+ }
394
+
395
+ override fun onWindowVisibilityChanged(visibility: Int) {
396
+ super.onWindowVisibilityChanged(visibility)
397
+ shown = visibility == View.VISIBLE && isAttachedToWindow
398
+ }
399
+ }
400
+
401
+ /**
402
+ * The host's side of `<g9-protected-video>`: the network stack it fetches through. Set [dataSourceFactory] once (the
403
+ * Application's onCreate) to the app's pinned client, e.g. `OkHttpDataSource.Factory { request ->
404
+ * pinnedClient.newCall(request) }` (media3-datasource-okhttp in the app); a factory function is read per player, so a
405
+ * pin change takes effect on the next video. Left unset, Media3's default HTTP stack is used (the system's trust only).
406
+ */
407
+ @OptIn(UnstableApi::class)
408
+ object G9ProtectedVideo {
409
+ @JvmStatic var dataSourceFactory: (() -> DataSource.Factory)? = null
410
+
411
+ internal fun dataSource(): DataSource.Factory =
412
+ dataSourceFactory?.invoke() ?: DefaultHttpDataSource.Factory().setAllowCrossProtocolRedirects(false)
413
+ }
414
+
415
+ /**
416
+ * `<g9-protected-video>` for the LynxViewBuilder: `builder.addBehaviors(G9ProtectedVideoBehaviors.create())`. Needs
417
+ * Media3's HLS module in the app (`g9native.hls=true` in gradle.properties, or the host's own
418
+ * `androidx.media3:media3-exoplayer-hls`); without it the list is empty and a log line says why.
419
+ */
420
+ object G9ProtectedVideoBehaviors {
421
+ @JvmStatic
422
+ fun create(): List<Behavior> {
423
+ val hls = runCatching { Class.forName("androidx.media3.exoplayer.hls.HlsMediaSource") }.isSuccess
424
+ if (!hls) {
425
+ Log.e("G9Lynx", "<g9-protected-video> needs androidx.media3:media3-exoplayer-hls (g9native.hls=true): not registered")
426
+ return emptyList()
427
+ }
428
+ return listOf(
429
+ object : Behavior("g9-protected-video", false, false, false) {
430
+ override fun createUI(context: LynxContext): LynxUI<*> = G9ProtectedVideoUI(context)
431
+ },
432
+ )
433
+ }
434
+ }
@@ -0,0 +1,90 @@
1
+ package com.g9lynx.g9native.video.core
2
+
3
+ /**
4
+ * The platform-free decisions of `<g9-protected-video>` (2.8.0, G9Hub Plan-V8 row 145, ported from Hub's
5
+ * `G9ProtectedVideoProps`): attribute parsing, the letterbox box and the reported state. Every attribute arrives as text
6
+ * (`paused="true"`, `seek="12.5"`); the element turns a boolean or a number the page passes into the same text first.
7
+ * Pure Kotlin so the JVM suite runs it.
8
+ */
9
+ object G9ProtectedVideoProps {
10
+ /** `"true"` / `"1"` / an empty (bare) attribute → true; `"false"` / `"0"` → false; anything else → [fallback]. */
11
+ fun flag(value: String?, fallback: Boolean): Boolean {
12
+ val text = value?.trim()?.lowercase() ?: return fallback
13
+ return when (text) {
14
+ "true", "1", "" -> true
15
+ "false", "0" -> false
16
+ else -> fallback
17
+ }
18
+ }
19
+
20
+ /** Seconds of a `seek` value: `"42.5"`, or `"42.5|<nonce>"` to seek to the same second again; null when unusable. */
21
+ fun seekSeconds(value: String?): Double? {
22
+ val number = value?.substringBefore('|')?.trim()?.toDoubleOrNull() ?: return null
23
+ return if (number.isFinite()) number.coerceAtLeast(0.0) else null
24
+ }
25
+
26
+ /** The playback speed: 0.25 – 4, 1 when missing or unusable. */
27
+ fun rate(value: String?): Float {
28
+ val number = value?.trim()?.toFloatOrNull() ?: return 1f
29
+ return if (number.isFinite() && number > 0f) number.coerceIn(0.25f, 4f) else 1f
30
+ }
31
+
32
+ /** `cover` crops; anything else letterboxes (`contain`, the default). */
33
+ fun cover(value: String?): Boolean = value?.trim()?.lowercase() == "cover"
34
+
35
+ /**
36
+ * A source the player may open: `https://`, or `http://` only to a local-network host (loopback, 10/8, 172.16/12,
37
+ * 192.168/16, `*.local`) — a protected stream never crosses the internet in clear text. Null otherwise.
38
+ */
39
+ fun usableSource(value: String?): String? {
40
+ val text = value?.trim()?.takeIf { it.isNotEmpty() } ?: return null
41
+ val lower = text.lowercase()
42
+ if (lower.startsWith("https://")) return text
43
+ if (!lower.startsWith("http://")) return null
44
+ val host = lower.removePrefix("http://").substringBefore('/').substringBefore('?').substringBeforeLast(':').trim('[', ']')
45
+ return if (isLocalHost(host)) text else null
46
+ }
47
+
48
+ /** Loopback, a private IPv4 range, `localhost` or an mDNS `*.local` name. */
49
+ fun isLocalHost(host: String): Boolean {
50
+ if (host == "localhost" || host == "::1" || host.endsWith(".local")) return true
51
+ val parts = host.split('.').map { it.toIntOrNull() ?: return false }
52
+ if (parts.size != 4 || parts.any { it !in 0..255 }) return false
53
+ return parts[0] == 127 || parts[0] == 10 || (parts[0] == 172 && parts[1] in 16..31) || (parts[0] == 192 && parts[1] == 168)
54
+ }
55
+
56
+ /**
57
+ * The box (left, top, right, bottom) that letterboxes a video of [videoW]×[videoH] into [width]×[height], centred;
58
+ * the whole area while the video size is unknown.
59
+ */
60
+ fun containBox(width: Int, height: Int, videoW: Float, videoH: Float): IntArray {
61
+ if (width <= 0 || height <= 0 || videoW <= 0f || videoH <= 0f) return intArrayOf(0, 0, width, height)
62
+ val scale = minOf(width / videoW, height / videoH)
63
+ val w = Math.round(videoW * scale).coerceIn(1, width)
64
+ val h = Math.round(videoH * scale).coerceIn(1, height)
65
+ val left = (width - w) / 2
66
+ val top = (height - h) / 2
67
+ return intArrayOf(left, top, left + w, top + h)
68
+ }
69
+
70
+ /**
71
+ * The state the element reports from the player's facts: `loading` until the first ready, then `ended`, `playing`,
72
+ * `buffering` (only while it should play), `ready` (the first pause after ready, before any play) or `paused`.
73
+ */
74
+ fun state(
75
+ readySeen: Boolean,
76
+ ended: Boolean,
77
+ playing: Boolean,
78
+ buffering: Boolean,
79
+ playWhenReady: Boolean,
80
+ current: String,
81
+ ): String =
82
+ when {
83
+ !readySeen -> "loading"
84
+ ended -> "ended"
85
+ playing -> "playing"
86
+ buffering && playWhenReady -> "buffering"
87
+ current == "ready" && !playWhenReady -> "ready"
88
+ else -> "paused"
89
+ }
90
+ }
@@ -0,0 +1,17 @@
1
+ # G9ProtectedVideo
2
+
3
+ `import { G9ProtectedVideo } from '@g9tm/lynxcontrols-native/media';`
4
+
5
+ A protected HLS video (2.8.0, G9Hub Plan-V8 row 145): `<g9-protected-video>` with typed props.
6
+
7
+ Props:
8
+ - `src`: string
9
+ - `children?`: ReactNode
10
+ - `onProgress?`: (progress: G9ProtectedVideoProgress) => void
11
+ - `onStatus?`: (status: G9ProtectedVideoStatus) => void
12
+ - `fit?`: 'contain' | 'cover'
13
+ - `muted?`: boolean
14
+ - `paused?`: boolean = true
15
+ - `protectWindow?`: boolean
16
+
17
+ Example: `<G9ProtectedVideo src="src" />`