契约 websocket-keypoints 0.1.0 -> 0.2.0(向后兼容,子协议名与帧 version 不变;
先在 opendance-web 修改并提升版本,再同步三端快照)。
T-AND-011:连接状态异常、频繁重连(查实 3 个根因)
1. 保活用错了层:Windows 端有 5s 静默超时(只看应用层收到的帧),而本端只有
OkHttp 的协议层 ping —— 它由底层库自动应答、**不暴露给应用层**,根本不能续命。
画面里没人时 5s 必被踢、再重连,循环往复。
- 契约新增 §1.1(welcome/config 声明 silentTimeoutMs 与 heartbeatIntervalMs,
且心跳必须 < 静默超时的一半)与 §3.6(应用层 ping/pong);
- Windows 端超时 5s -> 15s、期望心跳 5s,并在 welcome/config 中下发;
- 本端按声明发 ping,连续 3 个周期无 pong 才判定链路已死并主动重连。
2. 不该重连时也重连:契约新增 §7 关闭码策略,1000/1001/1002 与主动停止一律不重连。
3. frame_id 恒为 0:PoseDetector.detect() 算了 safeTimestamp 却忘了写回
lastTimestampMs,接收端的丢包检测因此完全失效。已修。
其他对齐:
- 契约新增 §8 连接状态机 idle -> resolving -> connecting -> handshaking ->
streaming -> degraded -> reconnecting -> stopped,两端同名便于对照日志;
resolving 只对主机名生效,局域网直连 IP 直接进 connecting;
- 退避与抖动按 §7.1 冻结:0.5s -> 1 -> 2 -> 4 -> 8 -> 15s 封顶 + ±20% 抖动;
- 契约新增 §5 设备去重:hello 携带稳定 deviceId(ANDROID_ID 的 SHA-256 前 16 位,
不含硬件序列号),Windows 端据此去重、旧连接以 1000 关闭;
- 新增 util/ConnectionLog(环形缓冲,最近 500 条:状态迁移 / close code /
子协议协商 / 首帧时间 / 保活参数),运行页可一键导出(FileProvider)。
T-AND-012:MediaPipe 初始化崩溃(ExceptionInInitializerError: null)
- 诊断:新增 pose/PoseDiagnostics 展开 cause 链取真因(通常 UnsatisfiedLinkError)、
区分 native 加载失败、比对设备 ABI 与 APK 内 ABI 并给出可执行结论;
- native 解压:packaging { jniLibs { useLegacyPackaging = true } }(AGP 8 release
默认 extractNativeLibs=false,MediaPipe JNI 对它不兼容);
- R8:补 -keepclasseswithmembernames 的 native 方法保留规则,并 -printseeds 输出
seeds 供发布前核对(实测保留 20169 条 MediaPipe 条目);
- 构建期新增 verifyReleaseAbi:release ABI 必须恰为 arm64-v8a/armeabi-v7a、
每个 ABI 下必须有 MediaPipe native 库、模型资源必须存在;
- 未换库:诊断指向集成配置而非 MediaPipe 本身,保留 33 点契约零成本。
T-AND-010:版本号展示与单一来源
- 版本唯一来源 versionName(= project.yaml 的 version);versionCode 按
10000*主+100*次+修订 递增(0.2.0 -> 200);
- 契约版本改为构建期解析 contracts/VERSION 后注入 BuildConfig(六项各自独立
递增,原先的单个 CONTRACT_VERSION 常量已失真);界面不再手写任何版本号;
- 新增 checkReleaseConsistency 并挂到 preBuild,三者不一致直接 BUILD FAILED。
README/DSH/THIRD_PARTY/tasks 同步更新(含「导出连接日志」「保活参数」
「最近断开原因」等新增可观察项与排查表)。
测试:56 项全部通过(新增 ReconnectPolicyTest 11 项、PoseDiagnosticsTest 12 项);
build/verify.sh 全通过(单元测试 -> 构建 -> 签名/ABI/native/seeds/dex 校验)
328 lines
14 KiB
Kotlin
328 lines
14 KiB
Kotlin
import java.util.Properties
|
||
import java.util.zip.ZipFile
|
||
|
||
// OpenDance Studio —— Android 辅助 App(应用模块)
|
||
//
|
||
// 契约:contracts/websocket-keypoints.md v0.2.0(本端为**发送方**)
|
||
// contracts/skeleton-topology.md v0.2.0(MediaPipe 33 点)
|
||
//
|
||
// 版本号与契约版本的**单一来源**(文档 §11.2 第 1 条):
|
||
// - 应用版本 -> app/build.gradle.kts 的 versionName(= 本次要发布的版本)
|
||
// - 契约版本 -> contracts/VERSION(构建期解析后注入 BuildConfig)
|
||
// 两者都不允许在 Kotlin 界面代码里再手写一份;文件末尾的
|
||
// `checkReleaseConsistency` 任务会在打包前校验与 project.yaml 一致。
|
||
|
||
plugins {
|
||
id("com.android.application")
|
||
id("org.jetbrains.kotlin.android")
|
||
id("org.jetbrains.kotlin.plugin.compose")
|
||
}
|
||
|
||
android {
|
||
namespace = "com.opendance.studio"
|
||
compileSdk = 34
|
||
|
||
defaultConfig {
|
||
applicationId = "com.opendance.studio"
|
||
minSdk = 29 // Android 10(文档 T-AND-009 验收要求 Android 10+)
|
||
targetSdk = 34
|
||
// 文档 §11.1:versionCode 用整数按 10000*主 + 100*次 + 修订 递增,
|
||
// versionName 用 X.Y.Z,两者同一次发布一起更新。
|
||
versionCode = 200
|
||
versionName = "0.2.0"
|
||
|
||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||
buildConfigField("String", "WS_SUBPROTOCOL", "\"opendance.pose.v1\"")
|
||
|
||
// ---- 契约版本:从 contracts/VERSION 解析,作为唯一来源注入 BuildConfig ----
|
||
// 六项契约各自独立递增(rest-api 0.5.0 时 skeleton-topology 可能还是 0.2.0),
|
||
// 因此注入每一项 + 一个用于展示的汇总串,界面不再手写任何版本号。
|
||
val contractVersions = linkedMapOf<String, String>()
|
||
val versionFile = rootProject.file("contracts/VERSION")
|
||
versionFile.readLines()
|
||
.map { it.trim() }
|
||
.filter { it.isNotEmpty() && !it.startsWith("#") && it.contains(":") }
|
||
.forEach { line ->
|
||
val key = line.substringBefore(":").trim()
|
||
val value = line.substringAfter(":").trim()
|
||
if (key.isNotEmpty() && value.isNotEmpty()) contractVersions[key] = value
|
||
}
|
||
check(contractVersions.isNotEmpty()) {
|
||
"无法从 ${versionFile.path} 解析契约版本:请确认该文件存在且格式为 `key: value`"
|
||
}
|
||
contractVersions.forEach { (key, value) ->
|
||
val field = "CONTRACT_" + key.uppercase().replace('-', '_')
|
||
buildConfigField("String", field, "\"$value\"")
|
||
}
|
||
buildConfigField(
|
||
"String",
|
||
"CONTRACT_VERSION",
|
||
"\"" + contractVersions["websocket-keypoints"] + "\"",
|
||
)
|
||
buildConfigField(
|
||
"String[]",
|
||
"CONTRACT_VERSION_KEYS",
|
||
contractVersions.keys.joinToString(", ") { "\"$it\"" }.let { "new String[]{$it}" },
|
||
)
|
||
buildConfigField(
|
||
"String[]",
|
||
"CONTRACT_VERSION_VALUES",
|
||
contractVersions.values.joinToString(", ") { "\"$it\"" }.let { "new String[]{$it}" },
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 签名配置:优先读取 keystore.properties(已被 .gitignore 忽略),
|
||
* 否则读取环境变量;两者都没有时回退到 debug 签名。
|
||
*
|
||
* 这样 `./gradlew assembleRelease` 在没有任何私密文件的情况下也能产出**已签名**的
|
||
* APK(用 debug key),便于 CI 与验收;正式发布必须提供自己的 keystore
|
||
* (见 build/gen-keystore.sh 与 README.txt)。
|
||
*/
|
||
val keystorePropertiesFile = rootProject.file("keystore.properties")
|
||
val keystoreProperties = Properties()
|
||
if (keystorePropertiesFile.exists()) {
|
||
keystorePropertiesFile.inputStream().use { keystoreProperties.load(it) }
|
||
}
|
||
|
||
fun signingValue(key: String, env: String): String? =
|
||
keystoreProperties.getProperty(key) ?: System.getenv(env)
|
||
|
||
val releaseStoreFile = signingValue("storeFile", "KEYSTORE_PATH")
|
||
val hasReleaseKeystore = releaseStoreFile != null && file(releaseStoreFile).exists()
|
||
|
||
signingConfigs {
|
||
if (hasReleaseKeystore) {
|
||
create("release") {
|
||
storeFile = file(releaseStoreFile!!)
|
||
storePassword = signingValue("storePassword", "KEYSTORE_PASSWORD")
|
||
keyAlias = signingValue("keyAlias", "KEY_ALIAS")
|
||
keyPassword = signingValue("keyPassword", "KEY_PASSWORD")
|
||
}
|
||
}
|
||
}
|
||
|
||
buildTypes {
|
||
debug {
|
||
applicationIdSuffix = ".debug"
|
||
isMinifyEnabled = false
|
||
// debug 保留全部 ABI,方便在模拟器(x86_64)上调试
|
||
ndk {
|
||
abiFilters.clear()
|
||
abiFilters.addAll(listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64"))
|
||
}
|
||
}
|
||
release {
|
||
// 发布包只打包真实手机用得到的 ABI。
|
||
// x86/x86_64 仅供模拟器使用,却占掉约 27 MB(几乎是发布包的一半),
|
||
// 对真机用户纯属浪费。
|
||
ndk {
|
||
abiFilters.clear()
|
||
abiFilters.addAll(listOf("arm64-v8a", "armeabi-v7a"))
|
||
}
|
||
isMinifyEnabled = true
|
||
isShrinkResources = true
|
||
proguardFiles(
|
||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||
"proguard-rules.pro",
|
||
)
|
||
signingConfig = if (hasReleaseKeystore) {
|
||
signingConfigs.getByName("release")
|
||
} else {
|
||
// 回退:用 debug 签名,保证 CI 上 assembleRelease 也能产出已签名 APK
|
||
signingConfigs.getByName("debug")
|
||
}
|
||
}
|
||
}
|
||
|
||
compileOptions {
|
||
sourceCompatibility = JavaVersion.VERSION_17
|
||
targetCompatibility = JavaVersion.VERSION_17
|
||
}
|
||
|
||
kotlinOptions {
|
||
jvmTarget = "17"
|
||
}
|
||
|
||
buildFeatures {
|
||
compose = true
|
||
buildConfig = true
|
||
}
|
||
|
||
packaging {
|
||
resources {
|
||
excludes += setOf(
|
||
"/META-INF/{AL2.0,LGPL2.1}",
|
||
"/META-INF/DEPENDENCIES",
|
||
"/META-INF/LICENSE*",
|
||
"/META-INF/NOTICE*",
|
||
)
|
||
}
|
||
// MediaPipe 的 .task 模型必须保持不压缩,否则运行时按文件路径读取会失败
|
||
androidResources {
|
||
noCompress += "task"
|
||
}
|
||
|
||
// T-AND-012:release 默认 extractNativeLibs=false(native 库直接从 APK mmap),
|
||
// MediaPipe 的 JNI 加载对这一点有历史兼容问题,会表现为
|
||
// ExceptionInInitializerError / UnsatisfiedLinkError。
|
||
// 显式使用传统打包(等价 android:extractNativeLibs="true")。
|
||
jniLibs {
|
||
useLegacyPackaging = true
|
||
}
|
||
}
|
||
|
||
testOptions {
|
||
unitTests {
|
||
isReturnDefaultValues = true
|
||
// Robolectric 需要真实资源与 Manifest 才能组合 Compose 界面
|
||
isIncludeAndroidResources = true
|
||
}
|
||
}
|
||
|
||
lint {
|
||
abortOnError = false
|
||
}
|
||
}
|
||
|
||
dependencies {
|
||
// ---- Android 基础 ----
|
||
implementation("androidx.core:core-ktx:1.13.1")
|
||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6")
|
||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.6")
|
||
implementation("androidx.activity:activity-compose:1.9.2")
|
||
|
||
// ---- Compose ----
|
||
val composeBom = platform("androidx.compose:compose-bom:2024.10.01")
|
||
implementation(composeBom)
|
||
androidTestImplementation(composeBom)
|
||
implementation("androidx.compose.ui:ui")
|
||
implementation("androidx.compose.ui:ui-graphics")
|
||
implementation("androidx.compose.ui:ui-tooling-preview")
|
||
implementation("androidx.compose.material3:material3")
|
||
implementation("androidx.compose.material:material-icons-extended")
|
||
debugImplementation("androidx.compose.ui:ui-tooling")
|
||
|
||
// ---- CameraX(T-AND-002)----
|
||
val cameraX = "1.4.0"
|
||
implementation("androidx.camera:camera-core:$cameraX")
|
||
implementation("androidx.camera:camera-camera2:$cameraX")
|
||
implementation("androidx.camera:camera-lifecycle:$cameraX")
|
||
implementation("androidx.camera:camera-view:$cameraX")
|
||
|
||
// ---- MediaPipe Pose 端侧推理(T-AND-003)----
|
||
implementation("com.google.mediapipe:tasks-vision:0.10.35")
|
||
|
||
// ---- WebSocket 推流(T-AND-005)----
|
||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||
|
||
// 权限:使用平台 Activity Result API(androidx.activity)。
|
||
// 原先用 accompanist-permissions 0.34.0,它发布于 2024-02,会传递引入
|
||
// compose animation-core 1.6.0,与 Compose BOM 存在版本偏斜风险;
|
||
// 该库已进入维护状态,官方也建议改用 Activity Result API。
|
||
|
||
// ---- 单元测试(T-AND-004 等纯逻辑,跑在 JVM 上,无需设备)----
|
||
testImplementation("junit:junit:4.13.2")
|
||
testImplementation("org.jetbrains.kotlin:kotlin-test:2.0.21")
|
||
|
||
// Robolectric:在 JVM 上跑 Android 框架 + Compose,用于验证
|
||
// 「进入运行页即崩溃」这类只在真机/运行时才暴露的缺陷
|
||
testImplementation("org.robolectric:robolectric:4.13")
|
||
testImplementation("androidx.test:core-ktx:1.6.1")
|
||
testImplementation("androidx.test.ext:junit:1.2.1")
|
||
testImplementation("androidx.compose.ui:ui-test-junit4")
|
||
// 必须用 debugImplementation:它往 debug 变体的合并 Manifest 里注册
|
||
// androidx.activity.ComponentActivity,Compose 测试规则要靠它启动宿主 Activity。
|
||
// 放 testImplementation 不会参与 Manifest 合并,运行时报
|
||
// "Unable to resolve activity for Intent ... ComponentActivity"。
|
||
debugImplementation("androidx.compose.ui:ui-test-manifest")
|
||
|
||
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
|
||
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
|
||
}
|
||
|
||
// ============================================================================
|
||
// T-AND-010 / T-AND-012:发布前自检
|
||
//
|
||
// 1) 版本号与 project.yaml 一致(文档 §11.2:产物名 / tag / README / 界面必须同源);
|
||
// 2) release APK 的 ABI 必须与 abiFilters 一致,且每个 ABI 目录下都要有
|
||
// MediaPipe 的 native 库 —— 这正是 "debug 好用、release 崩" 的典型根因
|
||
// (在 x86_64 模拟器上装 release 包必然缺库)。
|
||
// ============================================================================
|
||
|
||
/** 从 project.yaml 取 `version:` */
|
||
fun projectYamlVersion(): String {
|
||
val file = rootProject.file("project.yaml")
|
||
if (!file.exists()) return ""
|
||
return file.readLines()
|
||
.firstOrNull { it.trimStart().startsWith("version:") }
|
||
?.substringAfter(":")
|
||
?.trim()
|
||
?: ""
|
||
}
|
||
|
||
// 每次构建都先做版本/契约一致性校验,避免版本漂移进入产物
|
||
tasks.matching { it.name == "preBuild" }.configureEach { dependsOn("checkReleaseConsistency") }
|
||
|
||
tasks.register("checkReleaseConsistency") {
|
||
group = "verification"
|
||
description = "校验 versionName 与 project.yaml / 契约快照一致(文档 §11.2)"
|
||
doLast {
|
||
val yamlVersion = projectYamlVersion()
|
||
val name = android.defaultConfig.versionName
|
||
if (yamlVersion.isNotEmpty() && yamlVersion != name) {
|
||
throw GradleException("versionName=$name 与 project.yaml 的 version=$yamlVersion 不一致")
|
||
}
|
||
val wsVersion = android.defaultConfig.buildConfigFields["CONTRACT_WEBSOCKET_KEYPOINTS"]?.value?.trim('"')
|
||
if (wsVersion != "0.2.0") {
|
||
throw GradleException("contracts/VERSION 的 websocket-keypoints=$wsVersion,期望 0.2.0")
|
||
}
|
||
val code = android.defaultConfig.versionCode
|
||
val expected = name!!.split(".").let {
|
||
it[0].toInt() * 10000 + it[1].toInt() * 100 + it[2].toInt()
|
||
}
|
||
logger.lifecycle("[consistency] versionName=$name versionCode=$code 契约(websocket-keypoints)=$wsVersion")
|
||
if (code != expected) {
|
||
throw GradleException("versionCode=$code 与 versionName=$name 不匹配(应为 $expected)")
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验 release APK 里的 native 库:
|
||
* - ABI 目录集合必须等于 abiFilters(多一个或少一个都算失败);
|
||
* - 每个 ABI 目录下必须存在 MediaPipe 的 native 库;
|
||
* - assets 里的 MediaPipe 模型存在。
|
||
*/
|
||
tasks.register("verifyReleaseAbi") {
|
||
group = "verification"
|
||
description = "校验 release APK 的 ABI 与 MediaPipe native 库(T-AND-012)"
|
||
dependsOn("assembleRelease")
|
||
doLast {
|
||
val apk = file("build/outputs/apk/release/app-release.apk")
|
||
if (!apk.exists()) throw GradleException("未生成 ${apk.path}")
|
||
val expected = setOf("arm64-v8a", "armeabi-v7a")
|
||
// 注意:脚本里 `java` 被 JavaPluginExtension 遮蔽,必须用顶部 import 的 ZipFile
|
||
val entries: List<String> = ZipFile(apk).use { zip ->
|
||
zip.entries().asSequence().map { entry -> entry.name }.toList()
|
||
}
|
||
val abis: Set<String> = entries.filter { name -> name.startsWith("lib/") }
|
||
.map { name -> name.removePrefix("lib/").substringBefore("/") }
|
||
.toSet()
|
||
logger.lifecycle("[abi] release APK 包含 ABI:$abis")
|
||
if (abis != expected) {
|
||
throw GradleException("release APK 的 ABI=$abis,期望 $expected")
|
||
}
|
||
abis.forEach { abi: String ->
|
||
val hasJni = entries.any { name -> name.startsWith("lib/$abi/") && name.contains("mediapipe") }
|
||
if (!hasJni) throw GradleException("lib/$abi/ 下缺少 MediaPipe native 库")
|
||
logger.lifecycle("[abi] $abi 下 MediaPipe native 库存在")
|
||
}
|
||
val model = entries.count { name -> name == "assets/pose_landmarker_lite.task" }
|
||
if (model != 1) throw GradleException("assets/pose_landmarker_lite.task 数量为 $model(期望 1)")
|
||
logger.lifecycle("[abi] MediaPipe 模型资源存在")
|
||
}
|
||
}
|
||
|