feat: 接入端到端 demo 与签名变体

- Flutter 桌面端通过 dart:ffi 调用 Rust Core cdylib
- 实现 ECDH P-256 密钥协商、HKDF 子密钥派生、AES-256-GCM 控制帧
- Android 被控端用派生密钥做控制帧加密与媒体包 MAC
- 新增 libopus JNI 骨架,默认回退 MediaCodec
- 新增 aosp/zhanxun/neutral 签名变体与系统 sharedUserId
- 本机独立信令服务与设置页开关
- 新增 .gitignore 排除所有编译产物与打包目录
This commit is contained in:
tongtong committed 2026-11-26 18:24:02 +08:00
commit 31b9a52eb4
154 files changed
+13287

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.ttstd.lancast.receiver"
compileSdk = 35
defaultConfig {
applicationId = "com.ttstd.lancast.receiver"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
}
signingConfigs {
create("keypub") {
storeFile = file("D:/TongTongStudio/TTSTD/keypub.jks")
storePassword = "123456"
keyAlias = "publickey"
keyPassword = "123456"
}
create("crosshatch") {
storeFile = file("D:/TongTongStudio/TTSTD/AospCrosshatch.keystore")
storePassword = "Fan1996"
keyAlias = "AospCrosshatch"
keyPassword = "Fan1996"
}
create("zhanxun") {
storeFile = file("D:/TongTongStudio/TTSTD/zhanxun.keystore")
storePassword = "123456"
keyAlias = "zhanxun"
keyPassword = "123456"
}
}
// 按签名划分变体:aosp/zhanxun 为系统签名,neutral 为普通(中性)签名。
flavorDimensions += "signature"
productFlavors {
create("aosp") {
dimension = "signature"
signingConfig = signingConfigs.getByName("crosshatch")
}
create("zhanxun") {
dimension = "signature"
signingConfig = signingConfigs.getByName("zhanxun")
}
create("neutral") {
dimension = "signature"
signingConfig = signingConfigs.getByName("keypub")
}
}
buildTypes {
getByName("debug") {
// 避免 AGP 默认 debug keystore 覆盖 flavor 指定的签名
signingConfig = null
}
getByName("release") {
isMinifyEnabled = false
}
}
lint {
checkReleaseBuilds = false
abortOnError = false
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
externalNativeBuild {
cmake {
path = file("src/main/cpp/CMakeLists.txt")
}
}
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib:2.0.21")
}
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="android.uid.system" />
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="false"
android:label="@string/app_name"
android:theme="@style/Theme.Lancast">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".input.LancastAccessibilityService"
android:exported="false"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibility_service_config" />
</service>
</application>
</manifest>
@@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.22.1)
project(ttstd_opus)
add_library(ttstd_opus SHARED opus_jni.cpp)
find_library(log-lib log)
target_link_libraries(ttstd_opus ${log-lib})
# TODO(libopus): 将 opus 源码加入后,取消下面注释并启用 native 编码:
# add_subdirectory(opus)
# target_link_libraries(ttstd_opus opus)
# 同时把 opus_jni.cpp 中的 OPUS_NATIVE_AVAILABLE 改为 1。
@@ -0,0 +1,31 @@
#include <jni.h>
#include <android/log.h>
// 接入 libopus 源码后改为 1,Kotlin 侧会自动切换到 native 编码器。
#define OPUS_NATIVE_AVAILABLE 0
extern "C" JNIEXPORT jboolean JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_isAvailable(JNIEnv*, jclass) {
return OPUS_NATIVE_AVAILABLE == 1 ? JNI_TRUE : JNI_FALSE;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_createEncoder(
JNIEnv*, jclass, jint, jint, jint) {
if (OPUS_NATIVE_AVAILABLE != 1) return 0;
// TODO(libopus): return reinterpret_cast<jlong>(opus_encoder_create(...));
return 0;
}
extern "C" JNIEXPORT void JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_destroyEncoder(JNIEnv*, jclass, jlong) {
// TODO(libopus): opus_encoder_destroy(reinterpret_cast<OpusEncoder*>(handle));
}
extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_encode(
JNIEnv* env, jclass, jlong, jbyteArray) {
if (OPUS_NATIVE_AVAILABLE != 1) return nullptr;
// TODO(libopus): 调用 opus_encode 生成 OPUS 包并返回 ByteArray 数组。
return env->NewObjectArray(0, env->FindClass("[B"), nullptr);
}
@@ -0,0 +1,98 @@
package com.ttstd.lancast.receiver
import android.app.Activity
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.ttstd.lancast.receiver.session.PairingCode
import com.ttstd.lancast.receiver.session.TlsSession
import java.net.NetworkInterface
class MainActivity : Activity() {
companion object {
private const val REQUEST_CAPTURE = 1001
private const val FINGERPRINT = "sha256:ab12cd34ef567890"
}
private var session: ReceiverSession? = null
private lateinit var status: TextView
private lateinit var hostInput: EditText
private lateinit var signalingInput: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
status = TextView(this).apply { text = "状态:未开始" }
hostInput = EditText(this).apply {
hint = "主控端 IP"
setText("192.168.1.5")
}
signalingInput = EditText(this).apply {
hint = "信令服务器"
setText("http://192.168.1.5:8080")
}
val pairing = TextView(this).apply {
text = "配对码:\n${PairingCode.build(localIp(), 41001, FINGERPRINT)}"
textSize = 13f
}
val start = Button(this).apply { text = "授权并开始投屏" }
val stop = Button(this).apply { text = "停止" }
setContentView(LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(48, 64, 48, 48)
addView(status)
addView(hostInput)
addView(signalingInput)
addView(pairing)
addView(start)
addView(stop)
})
start.setOnClickListener {
val manager = getSystemService(MediaProjectionManager::class.java)
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
}
stop.setOnClickListener {
session?.stop()
session = null
status.text = "状态:已停止"
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQUEST_CAPTURE || resultCode != RESULT_OK || data == null) return
val manager = getSystemService(MediaProjectionManager::class.java)
val projection = manager.getMediaProjection(resultCode, data)
if (projection == null) {
Toast.makeText(this, "MediaProjection 授权失败", Toast.LENGTH_SHORT).show()
return
}
session = ReceiverSession(
context = this,
projection = projection,
host = hostInput.text.toString().trim(),
signalingUrl = signalingInput.text.toString().trim(),
certificatePem = "",
)
session?.start()
status.text = "状态:采集中 · 指纹 ${TlsSession.sha256Hex(FINGERPRINT.toByteArray()).take(16)}"
}
override fun onDestroy() {
session?.stop()
session = null
super.onDestroy()
}
private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
?.hostAddress ?: "192.168.1.10"
}
@@ -0,0 +1,121 @@
package com.ttstd.lancast.receiver
import android.content.Context
import android.media.projection.MediaProjection
import android.os.Build
import android.os.SystemClock
import com.ttstd.lancast.receiver.capture.AudioCapturer
import com.ttstd.lancast.receiver.capture.ScreenCapturer
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
import com.ttstd.lancast.receiver.discovery.AnnouncedDevice
import com.ttstd.lancast.receiver.discovery.NsdAdvertiser
import com.ttstd.lancast.receiver.discovery.ReceiverAnnouncer
import com.ttstd.lancast.receiver.encode.OpusEncoder
import com.ttstd.lancast.receiver.encode.VideoEncoder
import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector
import com.ttstd.lancast.receiver.protocol.ControlEvent
import com.ttstd.lancast.receiver.session.ReceiverTransport
import com.ttstd.lancast.receiver.session.TlsSession
import java.io.File
import java.util.UUID
import java.util.concurrent.Executors
class ReceiverSession(
private val context: Context,
private val projection: MediaProjection,
private val host: String,
private val signalingUrl: String,
private val certificatePem: String,
private val preferH265: Boolean = false,
private val bitrateMbps: Int = 8,
) {
private val executor = Executors.newFixedThreadPool(2)
private val clipboard = ClipboardBridge(context)
private val injector = InputInjector(context)
private val fileService = FileService(File(context.filesDir, "file-inbox"))
private val opusEncoder = OpusEncoder()
private val fingerprint = TlsSession.sha256Hex(certificatePem.toByteArray()).take(16)
private val transport = ReceiverTransport(
host,
41001,
41000,
41002,
fingerprint,
certificatePem,
injector,
clipboard,
fileService,
)
private val encoder = VideoEncoder { buffer, info -> transport.sendVideo(buffer, info) }
private var capturer: ScreenCapturer? = null
private var audio: AudioCapturer? = null
private var announcer: ReceiverAnnouncer? = null
private var nsdAdvertiser: NsdAdvertiser? = null
@Volatile
private var running = false
fun start() {
if (running) return
running = true
val metrics = context.resources.displayMetrics
val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920)
val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080)
encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265)
val surface = encoder.inputSurface ?: return
capturer = ScreenCapturer(projection, surface, metrics.densityDpi).also { it.start(width, height) }
transport.start()
clipboard.start { text -> transport.sendControl(ControlEvent.Clipboard(text)) }
val device = AnnouncedDevice(
id = UUID.randomUUID().toString(),
name = "Android Receiver",
ip = localIp,
mediaPort = 41000,
controlPort = 41001,
fingerprint = this@ReceiverSession.fingerprint,
capabilities = listOf("h264", "opus", "uibc", "clipboard", "file"),
model = Build.MODEL,
resolution = "${width}x$height",
)
announcer = ReceiverAnnouncer(signalingUrl, device).also { it.start() }
nsdAdvertiser = NsdAdvertiser(context, device).also { it.start() }
opusEncoder.start()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
audio = AudioCapturer(projection) { pcm ->
opusEncoder.encode(pcm).forEach { packet ->
transport.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
}
}.also { it.start() }
}
executor.execute {
while (running) {
encoder.drain()
Thread.sleep(4)
}
}
}
fun stop() {
running = false
capturer?.stop()
audio?.stop()
clipboard.stop()
announcer?.stop()
nsdAdvertiser?.stop()
opusEncoder.stop()
transport.close()
encoder.stop()
executor.shutdownNow()
}
private val localIp: String
get() = java.net.NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
?.hostAddress ?: "192.168.1.10"
}
@@ -0,0 +1,57 @@
package com.ttstd.lancast.receiver.capture
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioPlaybackCaptureConfiguration
import android.media.AudioRecord
import android.media.projection.MediaProjection
class AudioCapturer(
private val projection: MediaProjection,
private val onPcm: (ByteArray) -> Unit,
) {
private var recorder: AudioRecord? = null
private var thread: Thread? = null
@Volatile
private var running = false
fun start() {
if (running) return
val sampleRate = 48_000
val channelMask = AudioFormat.CHANNEL_IN_STEREO
val encoding = AudioFormat.ENCODING_PCM_16BIT
val config = AudioPlaybackCaptureConfiguration.Builder(projection)
.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
.addMatchingUsage(AudioAttributes.USAGE_GAME)
.build()
val format = AudioFormat.Builder()
.setSampleRate(sampleRate)
.setChannelMask(channelMask)
.setEncoding(encoding)
.build()
val bufferSize = maxOf(AudioRecord.getMinBufferSize(sampleRate, channelMask, encoding), 4096)
recorder = AudioRecord.Builder()
.setAudioFormat(format)
.setBufferSizeInBytes(bufferSize)
.setAudioPlaybackCaptureConfig(config)
.build()
running = true
recorder?.startRecording()
thread = Thread {
val buffer = ByteArray(bufferSize)
while (running) {
val read = recorder?.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING) ?: 0
if (read > 0) onPcm(buffer.copyOf(read))
}
}.also { it.isDaemon = true; it.start() }
}
fun stop() {
running = false
recorder?.stop()
recorder?.release()
recorder = null
thread = null
}
}
@@ -0,0 +1,36 @@
package com.ttstd.lancast.receiver.capture
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.projection.MediaProjection
import android.view.Surface
class ScreenCapturer(
private val projection: MediaProjection,
private val surface: Surface,
private val density: Int,
) {
private var virtualDisplay: VirtualDisplay? = null
fun start(width: Int, height: Int) {
virtualDisplay = projection.createVirtualDisplay(
"lancast-capture",
width,
height,
density,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
surface,
null,
null,
)
}
fun resize(width: Int, height: Int) {
virtualDisplay?.resize(width, height, density)
}
fun stop() {
virtualDisplay?.release()
virtualDisplay = null
}
}
@@ -0,0 +1,27 @@
package com.ttstd.lancast.receiver.clipboard
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
class ClipboardBridge(context: Context) {
private val manager = context.getSystemService(ClipboardManager::class.java)
private var listener: ClipboardManager.OnPrimaryClipChangedListener? = null
fun start(onText: (String) -> Unit) {
listener = ClipboardManager.OnPrimaryClipChangedListener {
val text = manager?.primaryClip?.getItemAt(0)?.text?.toString()
if (!text.isNullOrEmpty()) onText(text)
}
listener?.let { manager?.addPrimaryClipChangedListener(it) }
}
fun publish(text: String) {
manager?.setPrimaryClip(ClipData.newPlainText("lancast", text))
}
fun stop() {
listener?.let { manager?.removePrimaryClipChangedListener(it) }
listener = null
}
}
@@ -0,0 +1,13 @@
package com.ttstd.lancast.receiver.discovery
data class AnnouncedDevice(
val id: String,
val name: String,
val ip: String,
val mediaPort: Int,
val controlPort: Int,
val fingerprint: String,
val capabilities: List<String>,
val model: String,
val resolution: String,
)
@@ -0,0 +1,68 @@
package com.ttstd.lancast.receiver.discovery
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
class NsdAdvertiser(private val context: Context, private val device: AnnouncedDevice) {
private val manager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
private var registeredService: NsdServiceInfo? = null
@Volatile
private var running = false
private val registrationListener = object : NsdManager.RegistrationListener {
override fun onServiceRegistered(info: NsdServiceInfo?) {
registeredService = info
}
override fun onRegistrationFailed(info: NsdServiceInfo?, errorCode: Int) {
running = false
}
override fun onServiceUnregistered(info: NsdServiceInfo?) {
running = false
}
override fun onUnregistrationFailed(info: NsdServiceInfo?, errorCode: Int) = Unit
}
fun start() {
if (running) return
val info = NsdServiceInfo().apply {
serviceName = device.name
serviceType = SERVICE_TYPE
port = device.controlPort
setAttribute("txtvers", "1")
setAttribute("ver", "1")
setAttribute("dev", "android")
setAttribute("id", device.id)
setAttribute("cap", device.capabilities.joinToString(","))
setAttribute("res", device.resolution)
setAttribute("model", device.model)
setAttribute("fp", device.fingerprint)
setAttribute("cport", device.controlPort.toString())
setAttribute("mport", device.mediaPort.toString())
device.ip.takeIf { it.isNotBlank() }?.let { setAttribute("ip", it) }
}
try {
manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, registrationListener)
running = true
} catch (_: IllegalArgumentException) {
running = false
}
}
fun stop() {
if (!running) return
try {
manager.unregisterService(registrationListener)
} catch (_: IllegalArgumentException) {
}
running = false
registeredService = null
}
companion object {
const val SERVICE_TYPE = "_lancast._tcp."
}
}
@@ -0,0 +1,89 @@
package com.ttstd.lancast.receiver.discovery
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
class NsdDiscovery(
context: Context,
private val onDeviceFound: (AnnouncedDevice) -> Unit,
private val onDeviceLost: (String) -> Unit = {},
) {
private val manager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
@Volatile
private var running = false
private val resolveListener = object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) = Unit
override fun onServiceResolved(serviceInfo: NsdServiceInfo?) {
val info = serviceInfo ?: return
val attributes = info.attributes
val ip = info.host?.hostAddress ?: attributes["ip"]?.decodeToString() ?: return
val fingerprint = attributes["fp"]?.decodeToString() ?: return
val mediaPort = attributes["mport"]?.decodeToString()?.toIntOrNull() ?: info.port + 1
val controlPort = attributes["cport"]?.decodeToString()?.toIntOrNull() ?: info.port
val device = AnnouncedDevice(
id = attributes["id"]?.decodeToString() ?: info.serviceName,
name = info.serviceName,
ip = ip,
mediaPort = mediaPort,
controlPort = controlPort,
fingerprint = fingerprint,
capabilities = attributes["cap"]?.decodeToString()?.split(",") ?: emptyList(),
model = attributes["model"]?.decodeToString() ?: "",
resolution = attributes["res"]?.decodeToString() ?: "1920x1080",
)
onDeviceFound(device)
}
}
private val discoveryListener = object : NsdManager.DiscoveryListener {
override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {
running = false
}
override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) = Unit
override fun onDiscoveryStarted(serviceType: String?) {
running = true
}
override fun onDiscoveryStopped(serviceType: String?) {
running = false
}
override fun onServiceFound(serviceInfo: NsdServiceInfo?) {
val info = serviceInfo ?: return
if (info.serviceType == NsdAdvertiser.SERVICE_TYPE) {
manager.resolveService(info, resolveListener)
}
}
override fun onServiceLost(serviceInfo: NsdServiceInfo?) {
serviceInfo?.serviceName?.let(onDeviceLost)
}
}
fun start() {
if (running) return
try {
manager.discoverServices(
NsdAdvertiser.SERVICE_TYPE,
NsdManager.PROTOCOL_DNS_SD,
discoveryListener,
)
} catch (_: IllegalArgumentException) {
running = false
}
}
fun stop() {
if (!running) return
try {
manager.stopServiceDiscovery(discoveryListener)
} catch (_: IllegalArgumentException) {
}
running = false
}
}
@@ -0,0 +1,65 @@
package com.ttstd.lancast.receiver.discovery
import android.os.Handler
import android.os.Looper
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
class ReceiverAnnouncer(
private val signalingUrl: String,
private val device: AnnouncedDevice,
) {
private val handler = Handler(Looper.getMainLooper())
private var runnable: Runnable? = null
private var registered = false
fun start() {
if (runnable != null) return
runnable = object : Runnable {
override fun run() {
val path = if (registered) "/heartbeat" else "/register"
post(path, body())
registered = true
handler.postDelayed(this, 15_000)
}
}
handler.post(runnable!!)
}
fun stop() {
runnable?.let { handler.removeCallbacks(it) }
runnable = null
registered = false
}
private fun body(): String = JSONObject().apply {
put("deviceId", device.id)
put("name", device.name)
put("ip", device.ip)
put("mediaPort", device.mediaPort)
put("controlPort", device.controlPort)
put("fp", device.fingerprint)
put("cap", JSONArray(device.capabilities))
put("model", device.model)
put("res", device.resolution)
put("ttl", 30)
}.toString()
private fun post(path: String, body: String) {
try {
val connection = URL(signalingUrl.trimEnd('/') + path).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json")
connection.connectTimeout = 3000
connection.readTimeout = 3000
connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
connection.responseCode
connection.disconnect()
} catch (_: Exception) {
// 信令临时不可达不影响 mDNS 同网段直连。
}
}
}
@@ -0,0 +1,99 @@
package com.ttstd.lancast.receiver.encode
import android.media.AudioFormat
import android.media.MediaCodec
import android.media.MediaFormat
import java.io.ByteArrayOutputStream
/** OPUS 编码器:native libopus 就绪时优先使用,否则回退 Android MediaCodec。 */
class OpusEncoder {
private var codec: MediaCodec? = null
private var nativeHandle = 0L
private var presentationTimeUs = 0L
private val pending = ByteArrayOutputStream()
private val info = MediaCodec.BufferInfo()
val usesNative: Boolean get() = nativeHandle != 0L
fun start(sampleRate: Int = 48_000, channels: Int = 2, bitrate: Int = 64_000) {
nativeHandle = OpusNative.createEncoder(sampleRate, channels, bitrate)
if (nativeHandle != 0L) return
try {
val format = MediaFormat.createAudioFormat(MIME_OPUS, sampleRate, channels).apply {
setInteger(MediaFormat.KEY_BIT_RATE, bitrate)
setInteger(MediaFormat.KEY_PCM_ENCODING, AudioFormat.ENCODING_PCM_16BIT)
}
codec = MediaCodec.createEncoderByType(MIME_OPUS).apply {
configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
start()
}
} catch (_: Exception) {
// 设备不支持 OPUS 硬件编码器时静默降级,音频通道将无输出。
codec = null
}
}
fun encode(pcm16: ByteArray): List<ByteArray> {
if (nativeHandle != 0L) {
return OpusNative.encode(nativeHandle, pcm16)?.toList() ?: emptyList()
}
val encoder = codec ?: return emptyList()
val frameBytes = FRAME_SAMPLES * CHANNELS * BYTES_PER_SAMPLE
pending.write(pcm16)
val buffered = pending.toByteArray()
pending.reset()
val packets = mutableListOf<ByteArray>()
var offset = 0
while (offset + frameBytes <= buffered.size) {
val frame = buffered.copyOfRange(offset, offset + frameBytes)
offset += frameBytes
queueFrame(encoder, frame)
drain(encoder, packets)
}
pending.write(buffered, offset, buffered.size - offset)
return packets
}
fun stop() {
if (nativeHandle != 0L) {
OpusNative.destroyEncoder(nativeHandle)
nativeHandle = 0L
}
codec?.stop()
codec?.release()
codec = null
pending.reset()
}
private fun queueFrame(encoder: MediaCodec, frame: ByteArray) {
val index = encoder.dequeueInputBuffer(0)
if (index < 0) return
val buffer = encoder.getInputBuffer(index) ?: return
buffer.clear()
buffer.put(frame)
encoder.queueInputBuffer(index, 0, frame.size, presentationTimeUs, 0)
presentationTimeUs += FRAME_SAMPLES * 1_000_000L / 48_000
}
private fun drain(encoder: MediaCodec, packets: MutableList<ByteArray>) {
var index = encoder.dequeueOutputBuffer(info, 0)
while (index >= 0) {
val buffer = encoder.getOutputBuffer(index)
if (buffer != null && info.size > 0) {
val packet = ByteArray(info.size)
buffer.get(packet)
packets.add(packet)
}
encoder.releaseOutputBuffer(index, false)
index = encoder.dequeueOutputBuffer(info, 0)
}
}
companion object {
private const val MIME_OPUS = "audio/opus"
private const val FRAME_SAMPLES = 960
private const val CHANNELS = 2
private const val BYTES_PER_SAMPLE = 2
}
}
@@ -0,0 +1,32 @@
package com.ttstd.lancast.receiver.encode
/** libopus JNI 通道。native 库未接入源码时 isAvailable 为 false,由 MediaCodec 承接。 */
object OpusNative {
private var loaded = true
init {
try {
System.loadLibrary("ttstd_opus")
} catch (_: UnsatisfiedLinkError) {
loaded = false
}
}
val isAvailable: Boolean
get() = loaded && nativeIsAvailable()
fun createEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long =
if (isAvailable) nativeCreateEncoder(sampleRate, channels, bitrate) else 0L
fun destroyEncoder(handle: Long) {
if (handle != 0L) nativeDestroyEncoder(handle)
}
fun encode(handle: Long, pcm16: ByteArray): Array<ByteArray>? =
if (handle != 0L) nativeEncode(handle, pcm16) else null
private external fun nativeIsAvailable(): Boolean
private external fun nativeCreateEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long
private external fun nativeDestroyEncoder(handle: Long)
private external fun nativeEncode(handle: Long, pcm16: ByteArray): Array<ByteArray>?
}
@@ -0,0 +1,57 @@
package com.ttstd.lancast.receiver.encode
import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.os.Bundle
import android.view.Surface
import java.nio.ByteBuffer
class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) -> Unit) {
private var codec: MediaCodec? = null
var inputSurface: Surface? = null
private set
fun start(width: Int, height: Int, fps: Int, bitrateBps: Int, preferH265: Boolean) {
val mime = if (preferH265) MediaFormat.MIMETYPE_VIDEO_HEVC else MediaFormat.MIMETYPE_VIDEO_AVC
val format = MediaFormat.createVideoFormat(mime, width, height).apply {
setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
setInteger(MediaFormat.KEY_BIT_RATE, bitrateBps)
setInteger(MediaFormat.KEY_FRAME_RATE, fps)
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
}
val encoder = MediaCodec.createEncoderByType(mime)
encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
inputSurface = encoder.createInputSurface()
encoder.start()
codec = encoder
}
fun drain() {
val encoder = codec ?: return
val info = MediaCodec.BufferInfo()
var index = encoder.dequeueOutputBuffer(info, 0)
while (index >= 0) {
val buffer = encoder.getOutputBuffer(index)
if (buffer != null && info.size > 0) {
onPacket(buffer, info)
}
encoder.releaseOutputBuffer(index, false)
index = encoder.dequeueOutputBuffer(info, 0)
}
}
fun requestKeyFrame() {
codec?.setParameters(Bundle().apply {
putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0)
})
}
fun stop() {
codec?.stop()
codec?.release()
codec = null
inputSurface?.release()
inputSurface = null
}
}
@@ -0,0 +1,99 @@
package com.ttstd.lancast.receiver.file
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.RandomAccessFile
import java.security.MessageDigest
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
class FileService(private val root: File) {
private data class Entry(
val id: String,
val name: String,
val size: Long,
val sha256: String,
val token: String,
var offset: Long,
)
private data class Session(val id: String, val files: MutableMap<String, Entry>)
private val sessions = ConcurrentHashMap<String, Session>()
fun prepare(body: String): String {
root.mkdirs()
val request = JSONObject(body)
val files = request.getJSONArray("files")
val sessionId = UUID.randomUUID().toString()
val entries = mutableMapOf<String, Entry>()
val tokens = JSONObject()
val rejected = JSONArray()
for (index in 0 until files.length()) {
val file = files.getJSONObject(index)
val id = file.getString("id")
val name = safeName(file.getString("name"))
val size = file.getLong("size")
val hash = file.optString("sha256", "")
val target = File(root, "$sessionId-$name")
val token = UUID.randomUUID().toString()
val alreadyThere = target.exists() && target.length() == size && sha256(target) == hash
entries[id] = Entry(id, name, size, hash, token, if (alreadyThere) size else 0)
tokens.put(id, token)
}
sessions[sessionId] = Session(sessionId, entries)
return JSONObject().apply {
put("sessionId", sessionId)
put("tokens", tokens)
put("rejected", rejected)
}.toString()
}
fun writeChunk(sessionId: String, fileId: String, token: String, offset: Long, bytes: ByteArray): Int {
val entry = sessions[sessionId]?.files?.get(fileId)
?: throw IllegalArgumentException("未知文件会话")
if (entry.token != token) throw SecurityException("文件令牌不匹配")
val target = File(root, "$sessionId-${entry.name}")
RandomAccessFile(target, "rw").use { file ->
file.seek(offset)
file.write(bytes)
}
entry.offset = maxOf(entry.offset, offset + bytes.size)
return bytes.size
}
fun progress(sessionId: String): String {
val session = sessions[sessionId] ?: return JSONObject().put("files", JSONArray()).toString()
val array = JSONArray()
session.files.values.forEach { entry ->
array.put(JSONObject().apply {
put("fileId", entry.id)
put("received", entry.offset)
put("total", entry.size)
})
}
return JSONObject().put("sessionId", sessionId).put("files", array).toString()
}
fun cancel(sessionId: String) {
sessions.remove(sessionId)
}
private fun safeName(name: String) = name.replace("/", "_").replace("\\", "_").replace("..", "_")
private fun sha256(file: File): String =
MessageDigest.getInstance("SHA-256").let { digest ->
file.inputStream().use { stream ->
val buffer = ByteArray(8192)
while (true) {
val read = stream.read(buffer)
if (read <= 0) break
digest.update(buffer, 0, read)
}
}
digest.digest().joinToString("") { "%02x".format(it) }
}
}
@@ -0,0 +1,75 @@
package com.ttstd.lancast.receiver.input
import android.accessibilityservice.AccessibilityService
import android.content.Context
import com.ttstd.lancast.receiver.protocol.ControlEvent
import com.ttstd.lancast.receiver.protocol.ControlFrame
class InputInjector(private val context: Context) {
private var touchStart: Pair<Int, Int>? = null
fun inject(frame: ControlFrame) {
when (val event = frame.event) {
is ControlEvent.Touch -> injectTouch(event)
is ControlEvent.Mouse -> injectMouse(event)
is ControlEvent.Key -> injectKey(event)
is ControlEvent.Wheel -> injectWheel(event)
is ControlEvent.Clipboard -> injectText(event.text)
is ControlEvent.Ping, is ControlEvent.Pong -> Unit
}
}
private fun injectTouch(event: ControlEvent.Touch) {
when (event.action) {
0 -> {
touchStart = event.x to event.y
accessibility()?.tap(event.x, event.y) ?: shell("input", "tap", "${event.x}", "${event.y}")
}
2 -> {
val start = touchStart
if (start != null) {
accessibility()?.swipe(start.first, start.second, event.x, event.y)
?: shell("input", "swipe", "${start.first}", "${start.second}", "${event.x}", "${event.y}")
}
}
}
}
private fun injectMouse(event: ControlEvent.Mouse) {
if (event.action == 0) {
accessibility()?.tap(event.x, event.y) ?: shell("input", "tap", "${event.x}", "${event.y}")
}
}
private fun injectKey(event: ControlEvent.Key) {
when (event.keycode) {
3 -> accessibility()?.systemAction(AccessibilityService.GLOBAL_ACTION_HOME)
?: shell("input", "keyevent", "KEYCODE_HOME")
4 -> accessibility()?.systemAction(AccessibilityService.GLOBAL_ACTION_BACK)
?: shell("input", "keyevent", "KEYCODE_BACK")
else -> shell("input", "keyevent", event.keycode.toString())
}
}
private fun injectWheel(event: ControlEvent.Wheel) {
// AccessibilityService 不直接支持滚轮;映射为上下滑动。
val service = accessibility()
if (service != null) {
service.swipe(720, 800, 720 + event.deltaX, 800 - event.deltaY * 60)
}
}
private fun injectText(text: String) {
shell("input", "text", text.replace(" ", "%s"))
}
private fun accessibility() = LancastAccessibilityService.instance
private fun shell(vararg command: String) {
try {
Runtime.getRuntime().exec(command)
} catch (_: Exception) {
// 普通应用无 shell 权限时静默降级到无障碍服务。
}
}
}
@@ -0,0 +1,55 @@
package com.ttstd.lancast.receiver.input
import android.accessibilityservice.AccessibilityService
import android.graphics.Path
import android.view.accessibility.AccessibilityEvent
import android.accessibilityservice.GestureDescription
class LancastAccessibilityService : AccessibilityService() {
companion object {
@Volatile
var instance: LancastAccessibilityService? = null
}
override fun onServiceConnected() {
instance = this
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) = Unit
override fun onInterrupt() = Unit
override fun onDestroy() {
instance = null
super.onDestroy()
}
fun tap(x: Int, y: Int) {
val path = Path().apply { moveTo(x.toFloat(), y.toFloat()) }
dispatchGesture(
GestureDescription.Builder()
.addStroke(GestureDescription.StrokeDescription(path, 0, 80))
.build(),
null,
null,
)
}
fun swipe(x1: Int, y1: Int, x2: Int, y2: Int) {
val path = Path().apply {
moveTo(x1.toFloat(), y1.toFloat())
lineTo(x2.toFloat(), y2.toFloat())
}
dispatchGesture(
GestureDescription.Builder()
.addStroke(GestureDescription.StrokeDescription(path, 0, 220))
.build(),
null,
null,
)
}
fun systemAction(action: Int) {
performGlobalAction(action)
}
}
@@ -0,0 +1,136 @@
package com.ttstd.lancast.receiver.protocol
import java.nio.charset.StandardCharsets
sealed class ControlEvent {
data class Touch(val action: Int, val pointerId: Int, val x: Int, val y: Int, val pressure: Int) : ControlEvent()
data class Mouse(val action: Int, val x: Int, val y: Int, val buttons: Int) : ControlEvent()
data class Key(val action: Int, val keycode: Int, val modifiers: Int) : ControlEvent()
data class Wheel(val deltaX: Int, val deltaY: Int, val buttons: Int) : ControlEvent()
data class Clipboard(val text: String) : ControlEvent()
data class Ping(val timestamp: Long) : ControlEvent()
data class Pong(val timestamp: Long) : ControlEvent()
}
data class ControlFrame(val version: Int, val sequence: Int, val event: ControlEvent)
object ControlFrames {
const val VERSION = 1
private const val HEADER = 8
fun decode(bytes: ByteArray): ControlFrame? {
if (bytes.size < HEADER) return null
val version = bytes[0].toInt() and 0xff
if (version != VERSION) return null
val msgType = bytes[1].toInt() and 0xff
val sequence = u16(bytes, 2)
val length = u32(bytes, 4)
if (length < 0 || bytes.size < HEADER + length) return null
val payload = bytes.copyOfRange(HEADER, HEADER + length)
val event = when (msgType) {
0 -> {
if (payload.size != 8) return null
ControlEvent.Touch(
action = payload[0].toInt() and 0xff,
pointerId = payload[1].toInt() and 0xff,
x = i16(payload, 2),
y = i16(payload, 4),
pressure = u16(payload, 6),
)
}
1 -> {
if (payload.size != 6) return null
ControlEvent.Mouse(
action = payload[0].toInt() and 0xff,
x = i16(payload, 1),
y = i16(payload, 3),
buttons = payload[5].toInt() and 0xff,
)
}
2 -> {
if (payload.size != 5) return null
ControlEvent.Key(
action = payload[0].toInt() and 0xff,
keycode = u16(payload, 1),
modifiers = u16(payload, 3),
)
}
3 -> {
if (payload.size != 5) return null
ControlEvent.Wheel(i16(payload, 0), i16(payload, 2), payload[4].toInt() and 0xff)
}
4 -> {
if (payload.size < 4) return null
val lengthText = u32(payload, 0)
if (lengthText != payload.size - 4) return null
ControlEvent.Clipboard(String(payload, 4, lengthText, StandardCharsets.UTF_8))
}
5 -> {
if (payload.size != 8) return null
ControlEvent.Ping(u64(payload, 0))
}
6 -> {
if (payload.size != 8) return null
ControlEvent.Pong(u64(payload, 0))
}
else -> return null
}
return ControlFrame(version, sequence, event)
}
fun encode(event: ControlEvent, sequence: Int): ByteArray {
val payload = when (event) {
is ControlEvent.Touch -> byteArrayOf(
event.action.toByte(), event.pointerId.toByte(),
) + i16Bytes(event.x) + i16Bytes(event.y) + u16Bytes(event.pressure)
is ControlEvent.Mouse -> byteArrayOf(event.action.toByte()) +
i16Bytes(event.x) + i16Bytes(event.y) + byteArrayOf(event.buttons.toByte())
is ControlEvent.Key -> byteArrayOf(event.action.toByte()) +
u16Bytes(event.keycode) + u16Bytes(event.modifiers)
is ControlEvent.Wheel -> i16Bytes(event.deltaX) + i16Bytes(event.deltaY) +
byteArrayOf(event.buttons.toByte())
is ControlEvent.Clipboard -> {
val text = event.text.toByteArray(StandardCharsets.UTF_8)
u32Bytes(text.size) + text
}
is ControlEvent.Ping -> u64Bytes(event.timestamp)
is ControlEvent.Pong -> u64Bytes(event.timestamp)
}
return byteArrayOf(VERSION.toByte(), msgType(event).toByte()) +
u16Bytes(sequence) + u32Bytes(payload.size) + payload
}
private fun msgType(event: ControlEvent) = when (event) {
is ControlEvent.Touch -> 0
is ControlEvent.Mouse -> 1
is ControlEvent.Key -> 2
is ControlEvent.Wheel -> 3
is ControlEvent.Clipboard -> 4
is ControlEvent.Ping -> 5
is ControlEvent.Pong -> 6
}
private fun u16(bytes: ByteArray, offset: Int) =
(bytes[offset].toInt() and 0xff) or ((bytes[offset + 1].toInt() and 0xff) shl 8)
private fun i16(bytes: ByteArray, offset: Int) = u16(bytes, offset).toShort().toInt()
private fun u32(bytes: ByteArray, offset: Int): Int =
(bytes[offset].toInt() and 0xff) or
((bytes[offset + 1].toInt() and 0xff) shl 8) or
((bytes[offset + 2].toInt() and 0xff) shl 16) or
((bytes[offset + 3].toInt() and 0xff) shl 24)
private fun u64(bytes: ByteArray, offset: Int): Long =
(0 until 8).fold(0L) { acc, index -> acc or ((bytes[offset + index].toLong() and 0xff) shl (8 * index)) }
private fun u16Bytes(value: Int) = byteArrayOf(value.toByte(), (value shr 8).toByte())
private fun i16Bytes(value: Int) = u16Bytes(value and 0xffff)
private fun u32Bytes(value: Int) = byteArrayOf(
value.toByte(), (value shr 8).toByte(), (value shr 16).toByte(), (value shr 24).toByte(),
)
private fun u64Bytes(value: Long) = ByteArray(8) { index -> (value shr (8 * index)).toByte() }
}
@@ -0,0 +1,26 @@
package com.ttstd.lancast.receiver.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
object MediaPackets {
const val FLAG_KEYFRAME = 1
const val FLAG_AUDIO = 2
private const val HEADER_SIZE = 13
private const val MAC_SIZE = 4
fun encode(payload: ByteArray, pts: Long, flags: Int, sessionKey: ByteArray): ByteArray {
val header = ByteBuffer.allocate(HEADER_SIZE).order(ByteOrder.LITTLE_ENDIAN).apply {
putLong(pts)
put(flags.toByte())
putInt(payload.size)
}.array()
val signed = header + payload
val mac = Mac.getInstance("HmacSHA256").apply {
init(SecretKeySpec(sessionKey, "HmacSHA256"))
}.doFinal(signed)
return signed + mac.copyOf(MAC_SIZE)
}
}
@@ -0,0 +1,14 @@
package com.ttstd.lancast.receiver.session
import android.net.Uri
object PairingCode {
fun build(ip: String, port: Int, fingerprint: String): String = Uri.Builder()
.scheme("lancast")
.authority("pair")
.appendQueryParameter("ip", ip)
.appendQueryParameter("port", port.toString())
.appendQueryParameter("fp", fingerprint)
.build()
.toString()
}
@@ -0,0 +1,195 @@
package com.ttstd.lancast.receiver.session
import android.media.MediaCodec
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector
import com.ttstd.lancast.receiver.protocol.ControlEvent
import com.ttstd.lancast.receiver.protocol.ControlFrames
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetSocketAddress
import java.net.Socket
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.concurrent.Executors
/**
* demo v1 传输层:
* 1. TCP 反连 host:controlPort,先做 ECDH P-256 握手(互发 65 字节公钥)。
* 2. 派生 control/video/audio 三把会话密钥。
* 3. 控制帧使用 AES-256-GCM(8 字节明头作 AAD);媒体包使用 HMAC-SHA256 截断 MAC。
*
* 握手后控制通道的机密性由控制帧 AES-GCM 保证,demo 阶段不再叠加 TLS。
*/
class ReceiverTransport(
private val host: String,
private val controlPort: Int,
private val mediaPort: Int,
private val audioPort: Int,
private val expectedFingerprint: String,
private val certificatePem: String,
private val injector: InputInjector,
private val clipboard: ClipboardBridge,
private val fileService: FileService,
) {
private val executor = Executors.newFixedThreadPool(2)
private val crypto = SessionCrypto()
private var socket: Socket? = null
private var output: DataOutputStream? = null
private var udp: DatagramSocket? = null
private var keys: SessionCrypto.SessionKeys? = null
@Volatile
private var running = false
@Volatile
private var sequence = 0
val keyEstablished: Boolean get() = keys != null
fun start() {
val raw = Socket().apply {
tcpNoDelay = true
soTimeout = 5000
connect(InetSocketAddress(host, controlPort), 5000)
}
socket = raw
output = DataOutputStream(raw.outputStream)
val input = DataInputStream(raw.inputStream)
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
output?.write(crypto.publicBytes)
output?.flush()
val peerPublic = ByteArray(65)
input.readFully(peerPublic)
keys = crypto.deriveKeys(peerPublic)
udp = DatagramSocket()
running = true
executor.execute { readLoop(input) }
}
fun sendControl(event: ControlEvent) {
val key = keys?.control ?: return
if (!running) return
val frame = ControlFrames.encode(event, sequence++)
writeFrame(crypto.encodeControlFrame(frame, key))
}
fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
val key = keys?.video ?: return
if (!running) return
val duplicate = buffer.duplicate().apply {
position(info.offset)
limit(info.offset + info.size)
}
val payload = ByteArray(info.size)
duplicate.get(payload)
val flags = if (info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0) {
MediaPackets.FLAG_KEYFRAME
} else {
0
}
val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key)
udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, mediaPort)))
}
fun sendAudio(opusPacket: ByteArray, pts: Long) {
val key = keys?.audio ?: return
if (!running) return
val packet = MediaPackets.encode(opusPacket, pts, MediaPackets.FLAG_AUDIO, key)
udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, audioPort)))
}
fun close() {
running = false
try {
socket?.close()
udp?.close()
} catch (_: Exception) {
}
socket = null
udp = null
keys = null
executor.shutdownNow()
}
private fun readLoop(input: DataInputStream) {
val controlKey = keys?.control ?: return
try {
while (running) {
val header = ByteArray(8)
input.readFully(header)
val length = le32(header, 4)
if (length < 0 || length > 16 * 1024 * 1024) break
val rest = ByteArray(12 + length + 16)
input.readFully(rest)
val secureFrame = header + rest
val plaintext = crypto.decodeControlFrame(secureFrame, controlKey) ?: continue
when (plaintext[1].toInt() and 0xff) {
7 -> handleFileFrame(plaintext.copyOfRange(8, plaintext.size))
else -> {
val frame = ControlFrames.decode(plaintext) ?: continue
when (val event = frame.event) {
is ControlEvent.Clipboard -> clipboard.publish(event.text)
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
else -> injector.inject(frame)
}
}
}
}
} catch (_: Exception) {
// 对端断开时结束读取循环。
}
}
private fun handleFileFrame(payload: ByteArray) {
val request = JSONObject(String(payload, StandardCharsets.UTF_8))
when (request.optString("op")) {
"prepare" -> sendRaw(7, fileService.prepare(request.getString("body")))
"chunk" -> {
val received = fileService.writeChunk(
request.getString("sessionId"),
request.getString("fileId"),
request.getString("token"),
request.getLong("offset"),
request.getString("data").toByteArray(StandardCharsets.ISO_8859_1),
)
sendRaw(7, JSONObject().put("op", "chunkAck").put("received", received).toString())
}
"progress" -> sendRaw(7, fileService.progress(request.getString("sessionId")))
"cancel" -> fileService.cancel(request.getString("sessionId"))
}
}
private fun sendRaw(msgType: Int, text: String) {
val controlKey = keys?.control ?: return
val payload = text.toByteArray(StandardCharsets.UTF_8)
val frame = byteArrayOf(ControlFrames.VERSION.toByte(), msgType.toByte()) +
u16(sequence++) + u32(payload.size) + payload
writeFrame(crypto.encodeControlFrame(frame, controlKey))
}
private fun writeFrame(frame: ByteArray) {
try {
output?.write(frame)
output?.flush()
} catch (_: Exception) {
// 控制通道断开后忽略写入失败。
}
}
private fun u16(value: Int) = byteArrayOf(value.toByte(), (value shr 8).toByte())
private fun u32(value: Int) = byteArrayOf(
value.toByte(), (value shr 8).toByte(), (value shr 16).toByte(), (value shr 24).toByte(),
)
private fun le32(bytes: ByteArray, offset: Int): Int =
(bytes[offset].toInt() and 0xff) or
((bytes[offset + 1].toInt() and 0xff) shl 8) or
((bytes[offset + 2].toInt() and 0xff) shl 16) or
((bytes[offset + 3].toInt() and 0xff) shl 24)
}
@@ -0,0 +1,127 @@
package com.ttstd.lancast.receiver.session
import java.math.BigInteger
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.spec.ECGenParameterSpec
import java.security.spec.ECPoint
import java.security.spec.ECPublicKeySpec
import java.util.concurrent.atomic.AtomicLong
import javax.crypto.Cipher
import javax.crypto.KeyAgreement
import javax.crypto.Mac
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.security.interfaces.ECPublicKey
/**
* 与 Rust Core 对齐的会话密码学:
* - ECDH P-256(公钥 65 字节非压缩形式 0x04 || X || Y)
* - HKDF-SHA256(salt="ttstdconnect-v1",info=label,输出 32 字节)
* - AES-256-GCM(12 字节 nonce,8 字节控制帧头作为 AAD,16 字节 tag)
*/
class SessionCrypto {
private val keyPair: KeyPair = KeyPairGenerator.getInstance("EC").apply {
initialize(ECGenParameterSpec("secp256r1"))
}.generateKeyPair()
private val sendCounter = AtomicLong(1)
val publicBytes: ByteArray
get() {
val point = (keyPair.public as ECPublicKey).w
return byteArrayOf(4) + fixed32(point.affineX) + fixed32(point.affineY)
}
fun deriveKeys(peerPublic: ByteArray): SessionKeys {
require(peerPublic.size == 65 && (peerPublic[0].toInt() and 0xff) == 4) {
"对端 ECDH 公钥必须为 65 字节未压缩形式"
}
val x = BigInteger(1, peerPublic.copyOfRange(1, 33))
val y = BigInteger(1, peerPublic.copyOfRange(33, 65))
val params = (keyPair.public as ECPublicKey).params
val peer = KeyFactory.getInstance("EC")
.generatePublic(ECPublicKeySpec(ECPoint(x, y), params))
val agreement = KeyAgreement.getInstance("ECDH").apply {
init(keyPair.private)
doPhase(peer, true)
}
val secret = agreement.generateSecret()
return SessionKeys(
control = hkdf(secret, LABEL_CONTROL),
video = hkdf(secret, LABEL_VIDEO),
audio = hkdf(secret, LABEL_AUDIO),
)
}
/** 加密控制帧:输出 = 8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag。 */
fun encodeControlFrame(frame: ByteArray, key: ByteArray): ByteArray {
require(frame.size >= 8) { "控制帧至少需要 8 字节头" }
val header = frame.copyOfRange(0, 8)
val payload = frame.copyOfRange(8, frame.size)
val nonce = ByteArray(12).also { result ->
byteArrayOf('c'.toByte(), 't'.toByte(), 'l'.toByte(), '-'.toByte()).copyInto(result)
val counter = sendCounter.getAndIncrement()
for (index in 0 until 8) {
result[4 + index] = (counter shr (8 * index)).toByte()
}
}
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
updateAAD(header)
}
val encrypted = cipher.doFinal(payload)
return header + nonce + encrypted
}
/** 解密控制帧,返回完整的 8 字节头 + 明文负载。 */
fun decodeControlFrame(frame: ByteArray, key: ByteArray): ByteArray? {
if (frame.size < 8 + 12 + 16) return null
val header = frame.copyOfRange(0, 8)
val length = le32(header, 4)
if (length < 0 || length > 16 * 1024 * 1024) return null
val total = 8 + 12 + length + 16
if (frame.size < total) return null
val nonce = frame.copyOfRange(8, 20)
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
updateAAD(header)
}
val payload = cipher.doFinal(frame.copyOfRange(20, total))
return header + payload
}
private fun hkdf(secret: ByteArray, label: ByteArray): ByteArray {
val salt = "ttstdconnect-v1".toByteArray(Charsets.UTF_8)
val prk = hmacSha256(salt, secret)
return hmacSha256(prk, label + byteArrayOf(0x01)).copyOf(32)
}
private fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray =
Mac.getInstance("HmacSHA256").apply {
init(SecretKeySpec(key, "HmacSHA256"))
}.doFinal(data)
private fun fixed32(value: BigInteger): ByteArray {
val raw = value.toByteArray()
return when {
raw.size == 32 -> raw
raw.size > 32 -> raw.copyOfRange(raw.size - 32, raw.size)
else -> ByteArray(32 - raw.size) + raw
}
}
private fun le32(bytes: ByteArray, offset: Int): Int =
(bytes[offset].toInt() and 0xff) or
((bytes[offset + 1].toInt() and 0xff) shl 8) or
((bytes[offset + 2].toInt() and 0xff) shl 16) or
((bytes[offset + 3].toInt() and 0xff) shl 24)
data class SessionKeys(val control: ByteArray, val video: ByteArray, val audio: ByteArray)
companion object {
private val LABEL_CONTROL = "lancast/control/v1".toByteArray(Charsets.UTF_8)
private val LABEL_VIDEO = "lancast/video/v1".toByteArray(Charsets.UTF_8)
private val LABEL_AUDIO = "lancast/audio/v1".toByteArray(Charsets.UTF_8)
}
}
@@ -0,0 +1,41 @@
package com.ttstd.lancast.receiver.session
import java.io.ByteArrayInputStream
import java.security.KeyStore
import java.security.MessageDigest
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManagerFactory
object TlsSession {
fun sha256Hex(bytes: ByteArray): String =
MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
fun verifyFingerprint(certificate: X509Certificate, expected: String): Boolean {
val actual = sha256Hex(certificate.encoded)
val prefix = expected.removePrefix("sha256:").replace(":", "").lowercase()
return prefix.length >= 16 && actual.startsWith(prefix)
}
fun socketFactory(expectedFingerprint: String, certificatePem: String?): SSLSocketFactory {
if (certificatePem.isNullOrBlank()) {
return SSLContext.getDefault().socketFactory
}
val certificate = CertificateFactory.getInstance("X.509")
.generateCertificate(ByteArrayInputStream(certificatePem.toByteArray())) as X509Certificate
require(verifyFingerprint(certificate, expectedFingerprint)) { "证书指纹不匹配" }
val keyStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply {
load(null, null)
setCertificateEntry("peer", certificate)
}
val trustManagers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
.apply { init(keyStore) }
.trustManagers
return SSLContext.getInstance("TLSv1.3").apply {
init(null, trustManagers, null)
}.socketFactory
}
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TTSTD Receiver</string>
<string name="accessibility_label">TTSTD 远控注入服务</string>
<string name="accessibility_description">免 root 场景下注入点击、滑动与系统按键。</string>
</resources>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Lancast" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:windowBackground">@android:color/background_dark</item>
<item name="android:textColorPrimary">@android:color/white</item>
</style>
</resources>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault"
android:canPerformGestures="true"
android:description="@string/accessibility_description"
android:notificationTimeout="100"
android:settingsActivity="com.ttstd.lancast.receiver.MainActivity" />
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="android.uid.system" />