feat(android): add isolated lvbu persona build and pinned asset selection

This commit is contained in:
zenord
2026-10-14 16:41:36 +08:00
parent 3371997252
commit 5a7be557d0
23 changed files with 1507 additions and 31 deletions
+41 -15
View File
@@ -4,6 +4,14 @@ plugins {
id 'org.jetbrains.kotlin.plugin.compose'
}
def characterProfileId = providers.gradleProperty('characterProfile').orNull ?: 'main'
def characterCatalogFile = rootProject.file('manifests/character-build-profiles.json')
def characterCatalog = new groovy.json.JsonSlurper().parse(characterCatalogFile)
def characterProfile = characterCatalog.profiles[characterProfileId]
if (!characterProfile || !(characterProfileId in ['main', 'lvbu-test'])) throw new GradleException('Unknown trusted character profile')
if (characterProfileId != 'main') layout.buildDirectory.set(file('build/characters/' + characterProfileId))
if (characterProfileId == 'lvbu-test' && gradle.startParameter.taskNames.any { it.toLowerCase().contains('release') }) throw new GradleException('Lvbu profile is debug-only')
// Populated once by scripts/prepare-expression.sh from stable Maven versions, then pinned.
def expressionVersions = new Properties()
def expressionVersionFile = rootProject.file('gradle/expression-versions.properties')
@@ -32,6 +40,7 @@ def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnosti
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
if (characterProfileId == 'lvbu-test' && (!avatarUserAssetCandidate || !avatarUserNetworkActions || actionVersionCode < 34)) throw new GradleException('Lvbu test requires existing exact black media/network flags and fresh code >=34')
if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) {
throw new GradleException('Action stage requires the existing mouth runtime and a fresh code >=16')
}
@@ -43,6 +52,7 @@ if (avatarUiCandidate && !avatarNatural) {
}
def naturalManifestSha = providers.gradleProperty('naturalManifestSha').orNull ?: ''
def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?: ''
def characterMedia = characterCatalog.mediaBundles[avatarUserAssetCandidate ? 'black-correct03' : 'white-full04']
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
@@ -86,31 +96,42 @@ def generateNetworkSecurityConfig = tasks.register('generateNetworkSecurityConfi
}
}
// AndroidSourceDirectorySet excludes do not reliably filter mergeAssets. A Sync
// staging directory applies actual file exclusions without touching archived imports.
// Explicit common assets, runtime references, bootstrap and code29 fallback retention.
// Unlisted source directories cannot enter mergeAssets.
def packagedAssets = layout.buildDirectory.dir('generated/packagedAssets')
def stagePackagedAssets = tasks.register('stagePackagedAssets', Sync) {
from('src/main/assets')
exclude 'avatar/a01-v1/**', 'avatar/a01-standing-v2/**'
if (!avatarMouthCandidate) exclude 'avatar/a01-neutral-graph-v1/runtime-04/**'
if (!avatarStartupFix || avatarUserAssetCandidate) exclude 'avatar/startup-white-01/**'
if (!avatarUserAssetCandidate) exclude 'avatar/startup-black-tulle-correct03/**', 'avatar/a01-black-tulle-roomy720-correct03/**'
if (avatarUserAssetCandidate) exclude 'avatar/a01-expression-action-v1/**'
if (!emotionManifestSha) exclude 'avatar/a01-expression-action-v1/**'
into(packagedAssets)
def stagePackagedAssets = tasks.register('stagePackagedAssets', Exec) {
workingDir rootProject.projectDir
inputs.files(characterCatalogFile, rootProject.file('manifests/retained-avatar-files.json'), rootProject.file('scripts/select-character-assets.py'))
inputs.dir(file('src/main/assets'))
inputs.dir(file('src/main/res/drawable-nodpi'))
inputs.property('selection', [characterProfileId, emotionManifestSha, avatarUserAssetCandidate, avatarMouthCandidate, avatarStartupFix].toString())
outputs.dir(packagedAssets)
outputs.file(layout.buildDirectory.file('generated/character-selection.json'))
commandLine 'python3', rootProject.file('scripts/select-character-assets.py'), '--profile', characterProfileId,
'--assets', file('src/main/assets'), '--emotion-sha', emotionManifestSha,
'--user-assets', avatarUserAssetCandidate.toString(), '--mouth', avatarMouthCandidate.toString(),
'--startup', avatarStartupFix.toString(), '--output', packagedAssets.get().asFile,
'--report', layout.buildDirectory.file('generated/character-selection.json').get().asFile
}
android {
namespace 'com.gorios.lanvoice'
compileSdk 34
defaultConfig {
applicationId 'com.gorios.lanvoice'
applicationId characterProfile.applicationId
manifestPlaceholders = [characterAllowBackup: characterProfile.allowBackup.toString()]
resValue 'string', 'character_app_name', characterProfile.appName
buildConfigField 'String', 'CHARACTER_PROFILE', groovy.json.JsonOutput.toJson(characterProfileId)
buildConfigField 'String', 'DIALOGUE_PERSONA', groovy.json.JsonOutput.toJson(characterProfile.persona)
buildConfigField 'String', 'CHARACTER_NOTE', groovy.json.JsonOutput.toJson(characterProfile.settingsNote)
buildConfigField 'boolean', 'PERMISSION_CONNECTION_RETENTION', characterProfile.permissionConnectionRetention.toString()
minSdk 26
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = avatarUserNetworkActions ? '0.7.14' : avatarUserAssetCandidate ? '0.7.12' : cameraProbeDiagnostic ? '0.7.11' : cameraPreviewStream ? '0.7.9' : cameraDirectYuv ? '0.7.8' : cameraCompatibilityFix ? '0.7.7' : faceDiagnosticsFix ? '0.7.6' : presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
ndk { abiFilters 'arm64-v8a' }
versionName += characterProfile.versionSuffix
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
kotlinOptions { jvmTarget = '17' }
@@ -126,9 +147,9 @@ android {
else if (avatarEngineering) versionNameSuffix '-dev'
buildConfigField 'boolean', 'AVATAR_NETWORK_ACTIONS_ALLOWED', (!avatarUserAssetCandidate || avatarUserNetworkActions) ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_USER_ASSET_CANDIDATE', avatarUserAssetCandidate ? 'true' : 'false'
buildConfigField 'String', 'EMOTION_ASSET_ROOT', '"' + (avatarUserAssetCandidate ? 'avatar/a01-black-tulle-roomy720-correct03/' : 'avatar/a01-expression-action-v1/') + '"'
buildConfigField 'String', 'STARTUP_ASSET_ROOT', '"' + (avatarUserAssetCandidate ? 'avatar/startup-black-tulle-correct03/' : 'avatar/startup-white-01/') + '"'
buildConfigField 'String', 'STARTUP_MANIFEST_SHA', '"' + (avatarUserAssetCandidate ? '29669529887db78e0d64d2e7afd89cb8866aefc84e2523195d4bb936ec2ae382' : '461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2') + '"'
buildConfigField 'String', 'EMOTION_ASSET_ROOT', groovy.json.JsonOutput.toJson(characterMedia.assetRoot)
buildConfigField 'String', 'STARTUP_ASSET_ROOT', groovy.json.JsonOutput.toJson(characterMedia.bootstrapRoot)
buildConfigField 'String', 'STARTUP_MANIFEST_SHA', groovy.json.JsonOutput.toJson(characterMedia.bootstrapSha256)
buildConfigField 'boolean', 'CAMERA_PROBE_DIAGNOSTIC', cameraProbeDiagnostic ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_STARTUP_FIX', avatarStartupFix ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_ENGINEERING', (avatarEngineering || avatarNatural) ? 'true' : 'false'
@@ -159,6 +180,11 @@ android {
sourceSets.main.assets.setSrcDirs([packagedAssets])
}
tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig, stagePackagedAssets) }
androidComponents {
beforeVariants(selector().withBuildType('release')) { variant ->
if (characterProfileId == 'lvbu-test') variant.enable = false
}
}
dependencies {
implementation platform('androidx.compose:compose-bom:2024.09.03')
implementation 'androidx.compose.ui:ui'
@@ -22,7 +22,7 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
val result=Bundle()
var success=false
try {
val activity=startActivitySync(Intent().setClassName(targetContext.packageName,"${targetContext.packageName}.MainActivity")
val activity=startActivitySync(Intent().setClassName(targetContext.packageName,"com.gorios.lanvoice.MainActivity")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("avatar_offline_preview",true))
screen=activity; waitForIdleSync()
fun field(instance: Any,name: String): Any? = instance.javaClass.getDeclaredField(name).apply { isAccessible=true }.get(instance)
+4 -3
View File
@@ -7,15 +7,16 @@
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<application
android:label="@string/app_name"
android:label="@string/character_app_name"
android:allowBackup="${characterAllowBackup}"
android:theme="@android:style/Theme.Material.NoActionBar"
android:supportsRtl="true"
android:usesCleartextTraffic="false"
android:networkSecurityConfig="@xml/network_security_config">
<activity android:name=".CameraDiagnosticsActivity" android:exported="false"
<activity android:name="com.gorios.lanvoice.CameraDiagnosticsActivity" android:exported="false"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" />
<activity
android:name=".MainActivity"
android:name="com.gorios.lanvoice.MainActivity"
android:exported="true"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>
@@ -237,6 +237,8 @@ class MainActivity : ComponentActivity() {
pendingActionPackSha = { if(BuildConfig.AVATAR_STARTUP_FIX && BuildConfig.AVATAR_NETWORK_ACTIONS_ALLOWED) BuildConfig.EMOTION_MANIFEST_SHA else null },
actionPlayer = avatarMedia,
onPrepareExpression = avatarMedia::prepare,
persona = BuildConfig.DIALOGUE_PERSONA,
keepPermissionConnection = BuildConfig.PERMISSION_CONNECTION_RETENTION,
)
expressions = ExpressionController(this, this,
onState = {
@@ -404,10 +406,14 @@ class MainActivity : ComponentActivity() {
entry.leave()
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
if (offlineAvatarPreview) { super.onPause(); return }
// Independent persona APK gives up its session before camera unbind, which
// can be slow on vendor HALs. Default APK retains its established ordering.
val releaseSessionFirst = !BuildConfig.PERMISSION_CONNECTION_RETENTION
if(releaseSessionFirst && ::session.isInitialized) session.background()
closeCamera()
// Permission windows can pause/stop the Activity. No sensors survive this pause;
// retain only the fenced connection continuation, bounded by VoiceSession's timeout.
if(::session.isInitialized) session.background(keepConnectionForPermission = true)
if(!releaseSessionFirst && ::session.isInitialized) session.background(keepConnectionForPermission = true)
super.onPause()
}
override fun onStop() {
@@ -57,6 +57,8 @@ class VoiceSession(
private val onPrepareExpression: (ReplyEmotion?) -> Unit = {},
private val emotionObserver: ReplyEmotionObserver = ReplyEmotionObserver {},
private val pendingActionPackSha: ()->String? = { null },
persona: String = "default",
private val keepPermissionConnection: Boolean = true,
) {
private val main = Handler(Looper.getMainLooper())
private var state = VoiceUiState()
@@ -168,6 +170,7 @@ class VoiceSession(
onStatusReason = ::onConnection,
actionPackSha = { actions.capability?.manifestSha },
pendingActionPackSha = pendingActionPackSha,
persona = persona,
onEvent = ::onEvent,
onFrame = ::onFrame,
onProtocolError = { Log.w(TAG, it) },
@@ -198,7 +201,7 @@ class VoiceSession(
backgroundTimeout?.let { main.removeCallbacks(it) }
backgroundTimeout = null
DebugLogUpload.log("connect", "session background permission=$keepConnectionForPermission")
if (keepConnectionForPermission && !released) {
if (keepConnectionForPermission && keepPermissionConnection && !released) {
// A permission Activity can stop this Activity on some ROMs. Stop audio,
// but reuse the authorized WS when it returns. Bound retention if the user leaves.
backgroundTimeout = Runnable {
@@ -135,6 +135,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize(),mediaBinding,
startupBase,onStartupVisible,onStartupFailed,startupStage) { video=it }
},settings={
if(BuildConfig.CHARACTER_NOTE.isNotEmpty()) Text(BuildConfig.CHARACTER_NOTE,fontSize=12.sp)
val status=when(entry) {
EntryPhase.CONNECTING -> "正在连接"
EntryPhase.AWAITING_PERMISSION -> "等待麦克风授权"
@@ -46,6 +46,7 @@ class DialogueClient(
private val actionPackSha: () -> String? = { null },
private val pendingActionPackSha: () -> String? = { null },
private val onStatusReason: (ConnectionStatus, String) -> Unit = { _, _ -> },
private val persona: String = "default",
) {
private val main = Handler(Looper.getMainLooper())
private val endpoint = HttpUrl.Builder()
@@ -314,7 +315,7 @@ class DialogueClient(
connectionLog("auth ok", "auth")
val offeredPack=actionPackSha()
pendingOffered=if(offeredPack==null) pendingActionPackSha() else null
if (webSocket.send(DialogueProtocol.hello(offeredPack,pendingOffered))) {
if (webSocket.send(DialogueProtocol.hello(offeredPack,pendingOffered,persona))) {
helloSent = true
connectionLog("hello sent action_offer=${offeredPack?.takeIf { it.matches(Regex("[0-9a-f]{64}")) }?.take(12) ?: "none"} generation=$attempt", "auth")
} else {
@@ -26,12 +26,14 @@ object DialogueProtocol {
const val UPLINK_PCM_BYTES = 640
const val DOWNLINK_PCM_BYTES = 1_920
fun hello(actionPackSha: String? = null,pendingPackSha: String?=null): String = JSONObject()
fun hello(actionPackSha: String? = null,pendingPackSha: String?=null,persona: String="default"): String {
require(persona in setOf("default","lvbu"))
return JSONObject()
.put("type", "hello")
.put("codec", "pcm16")
.put("sample_rate", 16_000)
.put("frame_duration", 20)
.put("persona", "default")
.put("persona", persona)
.put("presence_greeting_version",1)
.put("voice_mode", "continuous_voice")
.apply { if (actionPackSha?.matches(Regex("[0-9a-f]{64}")) == true) {
@@ -42,6 +44,7 @@ object DialogueProtocol {
put("action_kinds",org.json.JSONArray())
} }
.toString()
}
fun capabilitiesReady(pin: String): String {
require(pin.matches(Regex("[0-9a-f]{64}")))