@g9tm/app-diagnostic-tauri 0.0.0-stage → 0.6.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.
- package/Cargo.toml +18 -0
- package/README.md +23 -3
- package/android/build.gradle.kts +29 -0
- package/android/proguard-rules.pro +2 -0
- package/android/settings.gradle +2 -0
- package/android/src/main/AndroidManifest.xml +5 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/G9AppDiagnosticHost.kt +131 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/RemoteTouch.kt +67 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/ScreenRecorder.kt +250 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/TouchWatcher.kt +129 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/VoiceRecorder.kt +82 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/WindowCapture.kt +92 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/core/TouchCore.kt +270 -0
- package/android/src/main/java/com/g9tm/appdiagnostic/tauri/G9DiagnosticPlugin.kt +180 -0
- package/build.rs +13 -0
- package/ios/Package.swift +20 -0
- package/ios/Sources/G9AppDiagnosticCore/G9AppDiagnosticHost.m +72 -0
- package/ios/Sources/G9AppDiagnosticCore/G9DiagnosticRecorders.m +514 -0
- package/ios/Sources/G9AppDiagnosticCore/include/G9AppDiagnosticHost.h +32 -0
- package/ios/Sources/G9AppDiagnosticCore/include/G9DiagnosticRecorders.h +36 -0
- package/ios/Sources/G9DiagnosticPlugin/G9DiagnosticPlugin.swift +135 -0
- package/package.json +43 -6
- package/permissions/autogenerated/commands/capabilities.toml +13 -0
- package/permissions/autogenerated/commands/read_chunk.toml +13 -0
- package/permissions/autogenerated/commands/registerListener.toml +13 -0
- package/permissions/autogenerated/commands/remove.toml +13 -0
- package/permissions/autogenerated/commands/remove_listener.toml +13 -0
- package/permissions/autogenerated/commands/screenshot.toml +13 -0
- package/permissions/autogenerated/commands/start_screen.toml +13 -0
- package/permissions/autogenerated/commands/start_voice.toml +13 -0
- package/permissions/autogenerated/commands/state.toml +13 -0
- package/permissions/autogenerated/commands/stop_screen.toml +13 -0
- package/permissions/autogenerated/commands/stop_voice.toml +13 -0
- package/permissions/autogenerated/commands/touch.toml +13 -0
- package/permissions/autogenerated/commands/watch_touches.toml +13 -0
- package/permissions/autogenerated/reference.md +367 -0
- package/permissions/default.toml +9 -0
- package/permissions/schemas/schema.json +462 -0
- package/src/index.ts +97 -0
- package/src/lib.rs +119 -0
package/Cargo.toml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "tauri-plugin-g9-diagnostic"
|
|
3
|
+
version = "0.6.0"
|
|
4
|
+
description = "The tester mode of a Tauri v2 app: the native recorders, the window screenshot, the tester gesture and the remote touch of G9AppDiagnostic on Android and iOS; the web layer (@g9tm/app-diagnostic-web) everywhere."
|
|
5
|
+
edition = "2021"
|
|
6
|
+
rust-version = "1.77.2"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
links = "tauri-plugin-g9-diagnostic"
|
|
9
|
+
exclude = ["/node_modules", "/test", "/scripts"]
|
|
10
|
+
|
|
11
|
+
[dependencies]
|
|
12
|
+
tauri = { version = "2" }
|
|
13
|
+
serde = { version = "1", features = ["derive"] }
|
|
14
|
+
serde_json = "1"
|
|
15
|
+
thiserror = "2"
|
|
16
|
+
|
|
17
|
+
[build-dependencies]
|
|
18
|
+
tauri-plugin = { version = "2", features = ["build"] }
|
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @g9tm/app-diagnostic-tauri
|
|
2
|
+
|
|
3
|
+
> 0.6.0: the web element underneath carries both reports with the shared G9 design — the testers' pill and the users' problem report (`tester.openProblemReport()`); every option of `startTester` (`access`, `problemReport`, `features`, `theme`, `strings`) passes through. Guide: `@g9tm/app-diagnostic-web`'s AGENTS.md.
|
|
4
|
+
|
|
5
|
+
The tester mode of a Tauri v2 app: the JS side of the crate `tauri-plugin-g9-diagnostic` (this folder) — the native
|
|
6
|
+
screen, voice, screenshot, gesture and remote touch on Android and iOS — under [`@g9tm/app-diagnostic-web`](https://www.npmjs.com/package/@g9tm/app-diagnostic-web)'s
|
|
7
|
+
`<g9-tester>`. On a desktop the plugin answers that it has no native half and the web recorders work.
|
|
8
|
+
|
|
9
|
+
```rust
|
|
10
|
+
tauri::Builder::default().plugin(tauri_plugin_g9_diagnostic::init())
|
|
11
|
+
```
|
|
12
|
+
Capability file: `"permissions": ["g9-diagnostic:default"]` (it includes the event channel, `registerListener`).
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { startTauriTester } from '@g9tm/app-diagnostic-tauri';
|
|
16
|
+
const tester = await startTauriTester({ gateway: 'https://diagnostic.example.com', appId: 'shop', productName: 'Shop',
|
|
17
|
+
appVersion: '1.4.0', environment: 'production' });
|
|
18
|
+
tester.engine.setEnabled(true);
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The crate ships inside this npm package (no crates.io needed): in `src-tauri/Cargo.toml`,
|
|
22
|
+
`tauri-plugin-g9-diagnostic = { path = "../node_modules/@g9tm/app-diagnostic-tauri" }`. The WebView's origin (`http://tauri.localhost`, `tauri://localhost`) goes into the gateway's
|
|
23
|
+
`WebDiagnostic:Apps[].Origins`. A sample app: `diagnostic/samples/tauri`. MIT.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// tauri-plugin-g9-diagnostic for Android. The recorders, the window capture and the gesture under
|
|
2
|
+
// src/main/java/com/g9tm/appdiagnostic/ are @g9tm/app-diagnostic-lynx's own files (scripts/sync-native.mjs); the plugin is
|
|
3
|
+
// src/main/java/com/g9tm/appdiagnostic/tauri/.
|
|
4
|
+
plugins {
|
|
5
|
+
id("com.android.library")
|
|
6
|
+
id("org.jetbrains.kotlin.android")
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
android {
|
|
10
|
+
namespace = "com.g9tm.appdiagnostic"
|
|
11
|
+
compileSdk = 36
|
|
12
|
+
defaultConfig {
|
|
13
|
+
minSdk = 24
|
|
14
|
+
consumerProguardFiles("proguard-rules.pro")
|
|
15
|
+
}
|
|
16
|
+
compileOptions {
|
|
17
|
+
sourceCompatibility = JavaVersion.VERSION_17
|
|
18
|
+
targetCompatibility = JavaVersion.VERSION_17
|
|
19
|
+
}
|
|
20
|
+
kotlinOptions { jvmTarget = "17" }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
dependencies {
|
|
24
|
+
implementation("androidx.core:core-ktx:1.13.1")
|
|
25
|
+
implementation("androidx.activity:activity:1.10.1")
|
|
26
|
+
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
|
27
|
+
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
|
28
|
+
implementation(project(":tauri-android"))
|
|
29
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
package com.g9tm.appdiagnostic
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.app.Application
|
|
5
|
+
import android.content.Context
|
|
6
|
+
import android.content.ContextWrapper
|
|
7
|
+
import android.os.Bundle
|
|
8
|
+
import android.view.View
|
|
9
|
+
import java.io.File
|
|
10
|
+
import java.lang.ref.WeakReference
|
|
11
|
+
import java.util.concurrent.CopyOnWriteArrayList
|
|
12
|
+
import kotlinx.coroutines.Dispatchers
|
|
13
|
+
import kotlinx.coroutines.delay
|
|
14
|
+
import kotlinx.coroutines.withContext
|
|
15
|
+
import okhttp3.OkHttpClient
|
|
16
|
+
|
|
17
|
+
/** A failure with a code from the module's contract (types/g9-app-diagnostic-module.d.ts). */
|
|
18
|
+
class G9DiagnosticException(val code: String, message: String, cause: Throwable? = null) : Exception(message, cause)
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* What the package needs from the app that hosts it, and the few hooks a host may set — before the first call, typically in
|
|
22
|
+
* `Application.onCreate`. Nothing here names a product: every default is neutral.
|
|
23
|
+
*
|
|
24
|
+
* - [httpClient]: the client a range request goes out on. The host's own, so its trust (a development certificate) and its
|
|
25
|
+
* proxy rules are the ones every other request has. Default: a plain client.
|
|
26
|
+
* - [allowedRoots]: the folders a recording, a screenshot or a sent file may be in. Default: the app's files and cache.
|
|
27
|
+
* - [isExcludedView]: a surface the gesture leaves native in the «except the map» mode (the host's map view). Default: none.
|
|
28
|
+
*
|
|
29
|
+
* The current activity is tracked here (the recorders draw it, the gesture watches its window); the module's events go to
|
|
30
|
+
* every sink a bridge added — Lynx's contexts (LynxBridge.kt), a Capacitor plugin's listeners (0.5.0). This file and the
|
|
31
|
+
* recorders it serves know no bridge: @g9tm/app-diagnostic-capacitor compiles them as they are.
|
|
32
|
+
*/
|
|
33
|
+
object G9AppDiagnosticHost {
|
|
34
|
+
@Volatile var httpClient: () -> OkHttpClient = { defaultClient }
|
|
35
|
+
|
|
36
|
+
@Volatile var allowedRoots: (Context) -> List<File> = { listOf(it.filesDir, it.cacheDir) }
|
|
37
|
+
|
|
38
|
+
@Volatile var isExcludedView: (View) -> Boolean = { false }
|
|
39
|
+
|
|
40
|
+
private val defaultClient by lazy { OkHttpClient() }
|
|
41
|
+
|
|
42
|
+
@Volatile private var application: Application? = null
|
|
43
|
+
@Volatile private var current: WeakReference<Activity>? = null
|
|
44
|
+
private val sinks = CopyOnWriteArrayList<(String, String) -> Unit>()
|
|
45
|
+
|
|
46
|
+
/** Where the events go (a bridge's own way to the JS side). Returns how to take it away again. */
|
|
47
|
+
fun addSink(sink: (name: String, json: String) -> Unit): () -> Unit {
|
|
48
|
+
sinks += sink
|
|
49
|
+
return { sinks -= sink }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Called by every bridge's module: the application and the activity it lives in. Idempotent. */
|
|
53
|
+
fun attach(app: Application, activity: Activity?) {
|
|
54
|
+
activity?.let { if (!it.isFinishing) current = WeakReference(it) }
|
|
55
|
+
if (application != null) return
|
|
56
|
+
synchronized(this) {
|
|
57
|
+
if (application != null) return
|
|
58
|
+
application = app
|
|
59
|
+
app.registerActivityLifecycleCallbacks(
|
|
60
|
+
object : Application.ActivityLifecycleCallbacks {
|
|
61
|
+
override fun onActivityResumed(activity: Activity) {
|
|
62
|
+
current = WeakReference(activity)
|
|
63
|
+
TouchWatcher.attach(activity)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
override fun onActivityDestroyed(activity: Activity) {
|
|
67
|
+
if (current?.get() === activity) current = null
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
|
|
71
|
+
|
|
72
|
+
override fun onActivityStarted(activity: Activity) {}
|
|
73
|
+
|
|
74
|
+
override fun onActivityPaused(activity: Activity) {}
|
|
75
|
+
|
|
76
|
+
override fun onActivityStopped(activity: Activity) {}
|
|
77
|
+
|
|
78
|
+
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
internal val app: Application
|
|
85
|
+
get() = application ?: throw G9DiagnosticException("unavailable", "The module is not attached to an application")
|
|
86
|
+
|
|
87
|
+
internal fun activityNow(): Activity? = current?.get()?.takeIf { !it.isFinishing && !it.isDestroyed }
|
|
88
|
+
|
|
89
|
+
/** The activity on screen, waiting a few seconds for one (an app coming back to the foreground). */
|
|
90
|
+
internal suspend fun awaitActivity(): Activity {
|
|
91
|
+
repeat(50) {
|
|
92
|
+
activityNow()?.let { return it }
|
|
93
|
+
delay(100)
|
|
94
|
+
}
|
|
95
|
+
throw G9DiagnosticException("unavailable", "No activity on screen")
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** A folder or file the caller named, if it is inside the folders the host allows. */
|
|
99
|
+
internal fun inside(path: String): File {
|
|
100
|
+
val file = File(path).canonicalFile
|
|
101
|
+
val roots = allowedRoots(app).map { it.canonicalPath.trimEnd('/') }
|
|
102
|
+
if (roots.none { file.path.startsWith("$it/") }) throw G9DiagnosticException("invalid", "Outside the app folders: $path")
|
|
103
|
+
return file
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** An event to every sink (JSON text): a sink's own failure never stops the next. */
|
|
107
|
+
internal fun emit(name: String, json: String) {
|
|
108
|
+
for (sink in sinks) {
|
|
109
|
+
try {
|
|
110
|
+
sink(name, json)
|
|
111
|
+
} catch (_: Throwable) {
|
|
112
|
+
// A bridge being torn down: the next one still gets it.
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
internal suspend fun <T> onMain(work: () -> T): T = withContext(Dispatchers.Main) { work() }
|
|
118
|
+
|
|
119
|
+
/** The activity a context wraps (a LynxContext, a themed wrapper), or null. */
|
|
120
|
+
fun activityOf(context: Context?): Activity? {
|
|
121
|
+
var c = context
|
|
122
|
+
repeat(10) {
|
|
123
|
+
when (c) {
|
|
124
|
+
is Activity -> return c as Activity
|
|
125
|
+
is ContextWrapper -> c = (c as ContextWrapper).baseContext
|
|
126
|
+
else -> return null
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return null
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
package com.g9tm.appdiagnostic
|
|
2
|
+
|
|
3
|
+
import android.os.SystemClock
|
|
4
|
+
import android.view.InputDevice
|
|
5
|
+
import android.view.MotionEvent
|
|
6
|
+
import android.view.View
|
|
7
|
+
import kotlinx.coroutines.Dispatchers
|
|
8
|
+
import kotlinx.coroutines.delay
|
|
9
|
+
import kotlinx.coroutines.withContext
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The operator's remote control as REAL touches (E-13): `MotionEvent`s with a finger's tool type and the touchscreen
|
|
13
|
+
* source, dispatched into the window's decor view — the input system's own entry point — with real time between DOWN,
|
|
14
|
+
* MOVEs and UP. Whatever is on top (a sheet, the map's own touch handling, a native view) gets it as it gets a finger, in
|
|
15
|
+
* every build; a logical tap (finding a JS handler by position) misses native views and gestures. The decor view hands the
|
|
16
|
+
* events to the window's callback first, so the tester gesture's watcher sees them too.
|
|
17
|
+
*
|
|
18
|
+
* Points are dp from the window's top-left. A separate window on top (a system permission dialog) is not in this tree and
|
|
19
|
+
* is not reached. The caller (the live channel) admits a remote command only with the user's consent.
|
|
20
|
+
*/
|
|
21
|
+
internal object RemoteTouch {
|
|
22
|
+
private const val FRAME_MS = 16L
|
|
23
|
+
|
|
24
|
+
suspend fun perform(kind: String, xDp: Double, yDp: Double, toXDp: Double, toYDp: Double, durationMs: Long): Boolean {
|
|
25
|
+
if (kind !in setOf("tap", "longPress", "drag")) throw G9DiagnosticException("invalid", "touch: kind is tap, longPress or drag (got '$kind')")
|
|
26
|
+
val activity = G9AppDiagnosticHost.awaitActivity()
|
|
27
|
+
return withContext(Dispatchers.Main) {
|
|
28
|
+
val root = activity.window.decorView
|
|
29
|
+
val density = activity.resources.displayMetrics.density
|
|
30
|
+
val x = (xDp * density).toFloat()
|
|
31
|
+
val y = (yDp * density).toFloat()
|
|
32
|
+
if (x < 0 || y < 0 || x >= root.width || y >= root.height) throw G9DiagnosticException("invalid", "touch: ($xDp, $yDp) dp is outside the window")
|
|
33
|
+
val hold = durationMs.coerceIn(1L, 10_000L)
|
|
34
|
+
val downTime = SystemClock.uptimeMillis()
|
|
35
|
+
val handled = dispatch(root, downTime, MotionEvent.ACTION_DOWN, x, y)
|
|
36
|
+
var upX = x
|
|
37
|
+
var upY = y
|
|
38
|
+
if (kind == "drag") {
|
|
39
|
+
val tx = (toXDp * density).toFloat()
|
|
40
|
+
val ty = (toYDp * density).toFloat()
|
|
41
|
+
val steps = (hold / FRAME_MS).coerceAtLeast(1)
|
|
42
|
+
for (i in 1..steps) {
|
|
43
|
+
delay(FRAME_MS)
|
|
44
|
+
val f = i.toFloat() / steps
|
|
45
|
+
dispatch(root, downTime, MotionEvent.ACTION_MOVE, x + (tx - x) * f, y + (ty - y) * f)
|
|
46
|
+
}
|
|
47
|
+
upX = tx
|
|
48
|
+
upY = ty
|
|
49
|
+
} else {
|
|
50
|
+
delay(hold)
|
|
51
|
+
}
|
|
52
|
+
dispatch(root, downTime, MotionEvent.ACTION_UP, upX, upY)
|
|
53
|
+
handled
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private fun dispatch(root: View, downTime: Long, action: Int, x: Float, y: Float): Boolean {
|
|
58
|
+
val props = arrayOf(MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_FINGER })
|
|
59
|
+
val coords = arrayOf(MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f; size = 1f })
|
|
60
|
+
val event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action, 1, props, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
|
|
61
|
+
return try {
|
|
62
|
+
root.dispatchTouchEvent(event)
|
|
63
|
+
} finally {
|
|
64
|
+
event.recycle()
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
package com.g9tm.appdiagnostic
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.graphics.Color
|
|
5
|
+
import android.media.MediaCodec
|
|
6
|
+
import android.media.MediaCodecInfo
|
|
7
|
+
import android.media.MediaCodecList
|
|
8
|
+
import android.media.MediaFormat
|
|
9
|
+
import android.media.MediaMuxer
|
|
10
|
+
import android.os.SystemClock
|
|
11
|
+
import android.util.Log
|
|
12
|
+
import android.view.Surface
|
|
13
|
+
import java.io.File
|
|
14
|
+
import kotlinx.coroutines.CoroutineScope
|
|
15
|
+
import kotlinx.coroutines.Dispatchers
|
|
16
|
+
import kotlinx.coroutines.Job
|
|
17
|
+
import kotlinx.coroutines.SupervisorJob
|
|
18
|
+
import kotlinx.coroutines.delay
|
|
19
|
+
import kotlinx.coroutines.isActive
|
|
20
|
+
import kotlinx.coroutines.launch
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The tester's screen recording (G9AppDiagnostic.Maui TesterScreenRecorder + AndroidTesterVideoEncoder): the app's OWN window — the
|
|
24
|
+
* same composited capture as the screenshot (device/WindowCapture, map included) — into an H.264 MP4.
|
|
25
|
+
* No MediaProjection: no system consent dialog, nothing of other apps in the video, no foreground service.
|
|
26
|
+
*
|
|
27
|
+
* - The rate is ADAPTIVE and bounded (MAUI 6.2.12): it starts at the caller's ceiling (the fleet's
|
|
28
|
+
* `tester_capture_max_fps`, default 10, at most 20) and lowers itself — never below 4 — the moment a frame costs
|
|
29
|
+
* most of its slot, climbing back one step after a run of cheap frames: an app slowed by its own recorder records a
|
|
30
|
+
* slowness that is not the defect. Frames carry their own timestamps (the Surface's), so a lower rate is a slower
|
|
31
|
+
* video, never a faster one. Long edge ≤ 960 px, 2 Mbit/s, a key frame every second (a reviewer scrubs).
|
|
32
|
+
* - The loop SKIPS a slot that a slow capture overran instead of queueing (a slow device makes a shorter video, not a
|
|
33
|
+
* backlog and an OOM).
|
|
34
|
+
* - Geometry is locked at the first frame (H.264 cannot change size mid-stream): a rotation letterboxes.
|
|
35
|
+
* - 10 minutes at most: the recording finalises itself and waits for [stop] to hand it over.
|
|
36
|
+
* - Frames reach the encoder through its input Surface with `lockHardwareCanvas` — a bitmap drawn on a canvas, so no
|
|
37
|
+
* YUV conversion and no EGL context (MAUI's ByteBuffer path needed both colour-format negotiation and a converter).
|
|
38
|
+
*
|
|
39
|
+
* TWIN: ios/src/G9AppDiagnosticMedia.m (AVAssetWriter fed from drawViewHierarchyInRect at the same cadence and caps).
|
|
40
|
+
*/
|
|
41
|
+
internal object ScreenRecorder {
|
|
42
|
+
private const val TAG = "G9AppDiagnostic"
|
|
43
|
+
private const val MIN_FPS = 4
|
|
44
|
+
private const val MAX_FPS = 20
|
|
45
|
+
/** The encoder's nominal rate for [supported] (any value works: the probe asks for an encoder, not a rate). */
|
|
46
|
+
private const val PROBE_FPS = 10
|
|
47
|
+
private const val MAX_EDGE = 960
|
|
48
|
+
private const val BIT_RATE = 2_000_000
|
|
49
|
+
private const val MAX_DURATION_MS = 10 * 60_000L
|
|
50
|
+
private const val MIME = MediaFormat.MIMETYPE_VIDEO_AVC
|
|
51
|
+
|
|
52
|
+
class Result(val path: String, val bytes: Long, val durationMs: Long, val width: Int, val height: Int, val capped: Boolean)
|
|
53
|
+
|
|
54
|
+
private class Session(
|
|
55
|
+
val file: File,
|
|
56
|
+
val codec: MediaCodec,
|
|
57
|
+
val surface: Surface,
|
|
58
|
+
val muxer: MediaMuxer,
|
|
59
|
+
val width: Int,
|
|
60
|
+
val height: Int,
|
|
61
|
+
val startedAt: Long,
|
|
62
|
+
) {
|
|
63
|
+
var track = -1
|
|
64
|
+
var muxing = false
|
|
65
|
+
var frames = 0
|
|
66
|
+
var loop: Job? = null
|
|
67
|
+
var ceiling = MIN_FPS
|
|
68
|
+
var fps = MIN_FPS
|
|
69
|
+
@Volatile var capped = false
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
|
73
|
+
private val lock = Any()
|
|
74
|
+
private var session: Session? = null
|
|
75
|
+
|
|
76
|
+
/** A recording the 10-minute cap finished, waiting for [stop]. */
|
|
77
|
+
private var finished: Result? = null
|
|
78
|
+
|
|
79
|
+
val isRecording: Boolean
|
|
80
|
+
get() = synchronized(lock) { session != null }
|
|
81
|
+
|
|
82
|
+
/** An AVC encoder that takes Surface input exists (every device in practice; the button hides otherwise). */
|
|
83
|
+
fun supported(): Boolean =
|
|
84
|
+
try {
|
|
85
|
+
val format = MediaFormat.createVideoFormat(MIME, 960, 544).apply {
|
|
86
|
+
setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
|
|
87
|
+
setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE)
|
|
88
|
+
setInteger(MediaFormat.KEY_FRAME_RATE, PROBE_FPS)
|
|
89
|
+
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)
|
|
90
|
+
}
|
|
91
|
+
MediaCodecList(MediaCodecList.REGULAR_CODECS).findEncoderForFormat(format) != null
|
|
92
|
+
} catch (_: Throwable) {
|
|
93
|
+
false
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Output size: the window scaled to a ≤ 960 px long edge, both sides even (H.264). */
|
|
97
|
+
internal fun outputSize(width: Int, height: Int): Pair<Int, Int> {
|
|
98
|
+
val scale = minOf(1.0, MAX_EDGE.toDouble() / maxOf(width, height))
|
|
99
|
+
val w = ((width * scale).toInt() / 2 * 2).coerceAtLeast(2)
|
|
100
|
+
val h = ((height * scale).toInt() / 2 * 2).coerceAtLeast(2)
|
|
101
|
+
return w to h
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
suspend fun start(dir: File, maxFps: Int) {
|
|
105
|
+
val ceiling = maxFps.coerceIn(MIN_FPS, MAX_FPS)
|
|
106
|
+
synchronized(lock) {
|
|
107
|
+
if (session != null) throw G9DiagnosticException("busy", "A screen recording is already running")
|
|
108
|
+
finished = null
|
|
109
|
+
}
|
|
110
|
+
val activity = G9AppDiagnosticHost.awaitActivity()
|
|
111
|
+
val (ww, wh) = WindowCapture.windowSize(activity)
|
|
112
|
+
if (ww <= 0 || wh <= 0) throw G9DiagnosticException("unavailable", "The window is not laid out")
|
|
113
|
+
val (width, height) = outputSize(ww, wh)
|
|
114
|
+
dir.mkdirs()
|
|
115
|
+
val file = File(dir, "screen-${System.currentTimeMillis()}.mp4")
|
|
116
|
+
val format = MediaFormat.createVideoFormat(MIME, width, height).apply {
|
|
117
|
+
setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
|
|
118
|
+
setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE)
|
|
119
|
+
// The encoder is told the CEILING (its bitrate / key-frame budget); the actual rate may be lower.
|
|
120
|
+
setInteger(MediaFormat.KEY_FRAME_RATE, ceiling)
|
|
121
|
+
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)
|
|
122
|
+
}
|
|
123
|
+
val codec = MediaCodec.createEncoderByType(MIME)
|
|
124
|
+
try {
|
|
125
|
+
codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
|
126
|
+
} catch (e: Exception) {
|
|
127
|
+
codec.release()
|
|
128
|
+
throw G9DiagnosticException("unavailable", "No encoder for ${width}x$height: ${e.message}", e)
|
|
129
|
+
}
|
|
130
|
+
val surface = codec.createInputSurface()
|
|
131
|
+
codec.start()
|
|
132
|
+
val s = Session(file, codec, surface, MediaMuxer(file.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4), width, height, SystemClock.elapsedRealtime())
|
|
133
|
+
s.ceiling = ceiling
|
|
134
|
+
s.fps = ceiling
|
|
135
|
+
synchronized(lock) { session = s }
|
|
136
|
+
s.loop = scope.launch { captureLoop(activity, s) }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private suspend fun captureLoop(activity: Activity, s: Session) {
|
|
140
|
+
var slotMs = 1000L / s.fps
|
|
141
|
+
var next = SystemClock.elapsedRealtime()
|
|
142
|
+
var costMs = 0.0 // exponential moving average of one frame's cost
|
|
143
|
+
var cheapStreak = 0
|
|
144
|
+
while (scope.isActive && synchronized(lock) { session === s }) {
|
|
145
|
+
if (SystemClock.elapsedRealtime() - s.startedAt >= MAX_DURATION_MS) {
|
|
146
|
+
s.capped = true
|
|
147
|
+
synchronized(lock) { if (session === s) session = null }
|
|
148
|
+
finished = finish(s)
|
|
149
|
+
return
|
|
150
|
+
}
|
|
151
|
+
val frameStarted = SystemClock.elapsedRealtime()
|
|
152
|
+
try {
|
|
153
|
+
val frame = WindowCapture.capture(activity, s.width, s.height)
|
|
154
|
+
val canvas = s.surface.lockHardwareCanvas()
|
|
155
|
+
try {
|
|
156
|
+
canvas.drawColor(Color.BLACK)
|
|
157
|
+
canvas.drawBitmap(frame, 0f, 0f, null)
|
|
158
|
+
} finally {
|
|
159
|
+
s.surface.unlockCanvasAndPost(canvas)
|
|
160
|
+
}
|
|
161
|
+
frame.recycle()
|
|
162
|
+
s.frames++
|
|
163
|
+
drain(s, endOfStream = false)
|
|
164
|
+
} catch (e: Exception) {
|
|
165
|
+
Log.w(TAG, "screen frame skipped: ${e.message}")
|
|
166
|
+
}
|
|
167
|
+
// Adapt: down at once when a frame eats most of its slot, up one step after a run of cheap ones.
|
|
168
|
+
val elapsed = (SystemClock.elapsedRealtime() - frameStarted).toDouble()
|
|
169
|
+
costMs = if (costMs <= 0.0) elapsed else costMs * 0.7 + elapsed * 0.3
|
|
170
|
+
val slot = 1000.0 / s.fps
|
|
171
|
+
if (costMs > slot * 0.85 && s.fps > MIN_FPS) {
|
|
172
|
+
s.fps = maxOf(MIN_FPS, Math.floor(1000.0 / (costMs * 1.25)).toInt())
|
|
173
|
+
slotMs = 1000L / s.fps
|
|
174
|
+
cheapStreak = 0
|
|
175
|
+
} else if (costMs < slot * 0.5 && s.fps < s.ceiling && ++cheapStreak >= s.fps * 3) {
|
|
176
|
+
s.fps++
|
|
177
|
+
slotMs = 1000L / s.fps
|
|
178
|
+
cheapStreak = 0
|
|
179
|
+
}
|
|
180
|
+
next += slotMs
|
|
181
|
+
val now = SystemClock.elapsedRealtime()
|
|
182
|
+
if (next < now) next = now + slotMs - ((now - next) % slotMs) // overran: skip the missed slots
|
|
183
|
+
delay(next - now)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Writes whatever the encoder produced; with [endOfStream], until the end-of-stream buffer. */
|
|
188
|
+
private fun drain(s: Session, endOfStream: Boolean) {
|
|
189
|
+
val info = MediaCodec.BufferInfo()
|
|
190
|
+
while (true) {
|
|
191
|
+
val index = s.codec.dequeueOutputBuffer(info, if (endOfStream) 10_000 else 0)
|
|
192
|
+
when {
|
|
193
|
+
index == MediaCodec.INFO_TRY_AGAIN_LATER -> if (!endOfStream) return
|
|
194
|
+
index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {
|
|
195
|
+
if (!s.muxing) {
|
|
196
|
+
s.track = s.muxer.addTrack(s.codec.outputFormat)
|
|
197
|
+
s.muxer.start()
|
|
198
|
+
s.muxing = true
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
index >= 0 -> {
|
|
202
|
+
val buffer = s.codec.getOutputBuffer(index)
|
|
203
|
+
if ((info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) info.size = 0
|
|
204
|
+
if (buffer != null && info.size > 0 && s.muxing) {
|
|
205
|
+
buffer.position(info.offset)
|
|
206
|
+
buffer.limit(info.offset + info.size)
|
|
207
|
+
s.muxer.writeSampleData(s.track, buffer, info)
|
|
208
|
+
}
|
|
209
|
+
s.codec.releaseOutputBuffer(index, false)
|
|
210
|
+
if ((info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) return
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private fun finish(s: Session): Result? {
|
|
217
|
+
val durationMs = SystemClock.elapsedRealtime() - s.startedAt
|
|
218
|
+
// What the adaptive rate settled on — the way to judge `tester_capture_max_fps` on a real device.
|
|
219
|
+
Log.i(TAG, "screen recording: ${s.frames} frames in ${durationMs / 1000.0} s, last rate ${s.fps} fps, ceiling ${s.ceiling}")
|
|
220
|
+
var ok = s.frames > 0
|
|
221
|
+
try {
|
|
222
|
+
s.codec.signalEndOfInputStream()
|
|
223
|
+
drain(s, endOfStream = true)
|
|
224
|
+
} catch (e: Exception) {
|
|
225
|
+
Log.w(TAG, "screen recording end: ${e.message}")
|
|
226
|
+
ok = false
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
if (s.muxing) s.muxer.stop() else ok = false
|
|
230
|
+
} catch (e: Exception) {
|
|
231
|
+
ok = false
|
|
232
|
+
}
|
|
233
|
+
runCatching { s.muxer.release() }
|
|
234
|
+
runCatching { s.codec.stop() }
|
|
235
|
+
runCatching { s.codec.release() }
|
|
236
|
+
runCatching { s.surface.release() }
|
|
237
|
+
if (!ok || !s.file.isFile || s.file.length() == 0L) {
|
|
238
|
+
s.file.delete()
|
|
239
|
+
return null
|
|
240
|
+
}
|
|
241
|
+
return Result(s.file.path, s.file.length(), durationMs, s.width, s.height, s.capped)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Stops and hands over the MP4 (null when nothing usable was recorded). */
|
|
245
|
+
suspend fun stop(): Result? {
|
|
246
|
+
val s = synchronized(lock) { session.also { session = null } } ?: return finished.also { finished = null }
|
|
247
|
+
s.loop?.join() // the loop sees `session !== s` after its current frame
|
|
248
|
+
return finish(s)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
package com.g9tm.appdiagnostic
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.view.MotionEvent
|
|
5
|
+
import android.view.View
|
|
6
|
+
import android.view.ViewConfiguration
|
|
7
|
+
import android.view.ViewGroup
|
|
8
|
+
import android.view.Window
|
|
9
|
+
import com.g9tm.appdiagnostic.core.TouchCore
|
|
10
|
+
import org.json.JSONObject
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The tester gesture on Android: every touch of the activity's window, seen BEFORE any view through a wrapper around the
|
|
14
|
+
* window's callback — so a host needs no edit in its activity (MAUI needed `MainActivity.DispatchTouchEvent` to forward).
|
|
15
|
+
* The decisions are [TouchCore]'s; this class only converts events and carries the verdicts out: a CANCEL to the views
|
|
16
|
+
* when a hold begins, a replayed DOWN + POINTER_DOWNs when a held touch turns out to be a pinch or a pan.
|
|
17
|
+
*
|
|
18
|
+
* Off (nothing watched) the wrapper returns at its first line: Tester Mode off costs one field read per touch.
|
|
19
|
+
*
|
|
20
|
+
* TWIN: ios/src/G9AppDiagnosticTouches.m (a recogniser on the key window that cancels the views' touches).
|
|
21
|
+
*/
|
|
22
|
+
internal object TouchWatcher {
|
|
23
|
+
const val EVENT = "g9:diagnostic-touch"
|
|
24
|
+
|
|
25
|
+
@Volatile private var core: TouchCore? = null
|
|
26
|
+
|
|
27
|
+
private fun coreFor(activity: Activity): TouchCore =
|
|
28
|
+
core ?: synchronized(this) {
|
|
29
|
+
core ?: TouchCore(maxOf(16, ViewConfiguration.get(activity).scaledTouchSlop * 2).toFloat()) { android.os.SystemClock.uptimeMillis() }.also { core = it }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Sets what is watched; the window of the activity on screen is wrapped (once per window). */
|
|
33
|
+
fun configure(activity: Activity?, taps: Boolean, touches: Boolean, consume: Boolean, excludeSurfaces: Boolean) {
|
|
34
|
+
val c = core ?: activity?.let { coreFor(it) } ?: return
|
|
35
|
+
c.taps = taps
|
|
36
|
+
c.touches = touches
|
|
37
|
+
c.consume = consume
|
|
38
|
+
c.excludeSurfaces = excludeSurfaces
|
|
39
|
+
activity?.let { attach(it) }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Wraps [activity]'s window callback (an activity recreated by a rotation gets wrapped again). Main thread. */
|
|
43
|
+
fun attach(activity: Activity) {
|
|
44
|
+
val window = activity.window ?: return
|
|
45
|
+
val callback = window.callback ?: return
|
|
46
|
+
if (callback is Watching) return
|
|
47
|
+
val c = coreFor(activity)
|
|
48
|
+
c.isExcluded = { x, y -> isOverExcluded(activity, x, y) }
|
|
49
|
+
window.callback = Watching(callback, activity)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
private class Watching(private val inner: Window.Callback, private val activity: Activity) : Window.Callback by inner {
|
|
53
|
+
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
|
54
|
+
val c = core
|
|
55
|
+
if (c == null || !c.watching) return inner.dispatchTouchEvent(event)
|
|
56
|
+
val result =
|
|
57
|
+
try {
|
|
58
|
+
c.onEvent(sample(event))
|
|
59
|
+
} catch (_: Throwable) {
|
|
60
|
+
return inner.dispatchTouchEvent(event) // a watcher never breaks a touch
|
|
61
|
+
}
|
|
62
|
+
for (e in result.emits) emit(e)
|
|
63
|
+
return when (result.verdict) {
|
|
64
|
+
TouchCore.Verdict.PASS -> inner.dispatchTouchEvent(event)
|
|
65
|
+
TouchCore.Verdict.CONSUME -> true
|
|
66
|
+
TouchCore.Verdict.CANCEL_THEN_CONSUME -> {
|
|
67
|
+
val cancel = MotionEvent.obtain(event)
|
|
68
|
+
cancel.action = MotionEvent.ACTION_CANCEL
|
|
69
|
+
inner.dispatchTouchEvent(cancel)
|
|
70
|
+
cancel.recycle()
|
|
71
|
+
true
|
|
72
|
+
}
|
|
73
|
+
TouchCore.Verdict.REPLAY -> {
|
|
74
|
+
replay(event)
|
|
75
|
+
true
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A held gesture back to the views: a DOWN for the first finger, a POINTER_DOWN per further one, where they are NOW. */
|
|
81
|
+
private fun replay(event: MotionEvent) {
|
|
82
|
+
val count = event.pointerCount
|
|
83
|
+
val properties = Array(count) { MotionEvent.PointerProperties().also { p -> event.getPointerProperties(it, p) } }
|
|
84
|
+
val coords = Array(count) { MotionEvent.PointerCoords().also { p -> event.getPointerCoords(it, p) } }
|
|
85
|
+
for (fingers in 1..count) {
|
|
86
|
+
val action = if (fingers == 1) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_POINTER_DOWN or ((fingers - 1) shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
|
87
|
+
val synthetic =
|
|
88
|
+
MotionEvent.obtain(
|
|
89
|
+
event.downTime, event.eventTime, action, fingers, properties.copyOf(fingers).requireNoNulls(), coords.copyOf(fingers).requireNoNulls(),
|
|
90
|
+
event.metaState, event.buttonState, event.xPrecision, event.yPrecision, event.deviceId, event.edgeFlags, event.source, event.flags,
|
|
91
|
+
)
|
|
92
|
+
inner.dispatchTouchEvent(synthetic)
|
|
93
|
+
synthetic.recycle()
|
|
94
|
+
}
|
|
95
|
+
inner.dispatchTouchEvent(event)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private fun emit(e: TouchCore.Emit) {
|
|
99
|
+
val root = activity.window?.decorView ?: return
|
|
100
|
+
val w = root.width.toFloat()
|
|
101
|
+
val h = root.height.toFloat()
|
|
102
|
+
if (w <= 0f || h <= 0f) return
|
|
103
|
+
val json =
|
|
104
|
+
JSONObject().put("type", e.type).put("fingers", e.fingers).put("x", (e.x / w).toDouble()).put("y", (e.y / h).toDouble())
|
|
105
|
+
.put("cx", (e.cx / w).toDouble()).put("cy", (e.cy / h).toDouble()).put("excluded", e.excluded)
|
|
106
|
+
e.info?.let { json.put("info", JSONObject(it)) }
|
|
107
|
+
G9AppDiagnosticHost.emit(EVENT, json.toString())
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private fun sample(event: MotionEvent): TouchCore.Sample =
|
|
112
|
+
TouchCore.Sample(event.actionMasked, List(event.pointerCount) { TouchCore.Pointer(event.getPointerId(it), event.getX(it), event.getY(it)) })
|
|
113
|
+
|
|
114
|
+
/** A visible excluded view under the window point. A first finger is rare enough to walk the tree. */
|
|
115
|
+
private fun isOverExcluded(activity: Activity, x: Float, y: Float): Boolean {
|
|
116
|
+
val root = activity.window?.decorView ?: return false
|
|
117
|
+
fun walk(view: View): Boolean {
|
|
118
|
+
if (!view.isShown) return false
|
|
119
|
+
if (G9AppDiagnosticHost.isExcludedView(view)) {
|
|
120
|
+
val at = IntArray(2)
|
|
121
|
+
view.getLocationInWindow(at)
|
|
122
|
+
return x >= at[0] && x <= at[0] + view.width && y >= at[1] && y <= at[1] + view.height
|
|
123
|
+
}
|
|
124
|
+
if (view is ViewGroup) for (i in 0 until view.childCount) if (walk(view.getChildAt(i))) return true
|
|
125
|
+
return false
|
|
126
|
+
}
|
|
127
|
+
return walk(root)
|
|
128
|
+
}
|
|
129
|
+
}
|