merge: 合并远端前台服务与稳定性修复,保留去虚拟数据改动

This commit is contained in:
tongtong committed 2026-11-26 21:40:08 +08:00
commit adaa23f895
15 files changed
+702 -126

No files matched your search

@@ -21,6 +21,12 @@
</intent-filter>
</activity>
<service
android:name=".MediaProjectionService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="mediaProjection" />
<service
android:name=".input.LancastAccessibilityService"
android:exported="false"
@@ -6,6 +6,14 @@ add_library(ttstd_opus SHARED opus_jni.cpp)
find_library(log-lib log)
target_link_libraries(ttstd_opus ${log-lib})
# Android 15+ 的 16 KB 页设备要求 .so 的 LOAD 段按 16 KB 对齐。
# NDK r27 默认仍是 4 KB,NDK r28+ 才默认 16 KB,因此这里显式指定,
# 避免安装时报 "not compatible with 16 KB devices"。
target_link_options(ttstd_opus PRIVATE
-Wl,-z,max-page-size=16384
-Wl,-z,common-page-size=16384
)
# TODO(libopus): 将 opus 源码加入后,取消下面注释并启用 native 编码:
# add_subdirectory(opus)
# target_link_libraries(ttstd_opus opus)
@@ -4,13 +4,16 @@
// 接入 libopus 源码后改为 1,Kotlin 侧会自动切换到 native 编码器。
#define OPUS_NATIVE_AVAILABLE 0
// 注意:JNI 符号必须与 Kotlin 侧 external fun 的名称完全一致。
// OpusNative.kt 声明的是 nativeIsAvailable / nativeCreateEncoder /
// nativeDestroyEncoder / nativeEncode,因此这里不能省略 "native" 前缀。
extern "C" JNIEXPORT jboolean JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_isAvailable(JNIEnv*, jclass) {
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeIsAvailable(JNIEnv*, jclass) {
return OPUS_NATIVE_AVAILABLE == 1 ? JNI_TRUE : JNI_FALSE;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_createEncoder(
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeCreateEncoder(
JNIEnv*, jclass, jint, jint, jint) {
if (OPUS_NATIVE_AVAILABLE != 1) return 0;
// TODO(libopus): return reinterpret_cast<jlong>(opus_encoder_create(...));
@@ -18,12 +21,13 @@ Java_com_ttstd_lancast_receiver_encode_OpusNative_createEncoder(
}
extern "C" JNIEXPORT void JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_destroyEncoder(JNIEnv*, jclass, jlong) {
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeDestroyEncoder(
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(
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeEncode(
JNIEnv* env, jclass, jlong, jbyteArray) {
if (OPUS_NATIVE_AVAILABLE != 1) return nullptr;
// TODO(libopus): 调用 opus_encode 生成 OPUS 包并返回 ByteArray 数组。
@@ -19,7 +19,6 @@ class MainActivity : Activity() {
const val EXTRA_SIGNALING = "com.ttstd.lancast.receiver.SIGNALING"
}
private var session: ReceiverSession? = null
private lateinit var status: TextView
private lateinit var hostInput: EditText
private lateinit var signalingInput: EditText
@@ -27,7 +26,9 @@ class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
status = TextView(this).apply { text = "状态:未开始" }
status = TextView(this).apply {
text = if (MediaProjectionService.isRunning) "状态:采集中" else "状态:未开始"
}
val initialHost = intent?.getStringExtra(EXTRA_HOST)?.takeIf { it.isNotBlank() } ?: ""
val initialSignaling = intent?.getStringExtra(EXTRA_SIGNALING)?.takeIf { it.isNotBlank() } ?: ""
hostInput = EditText(this).apply {
@@ -74,8 +75,7 @@ class MainActivity : Activity() {
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
}
stop.setOnClickListener {
session?.stop()
session = null
MediaProjectionService.stop(this)
status.text = "状态:已停止"
}
}
@@ -83,34 +83,10 @@ class MainActivity : Activity() {
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 = "",
)
val host = hostInput.text.toString().trim()
val signalingUrl = signalingInput.text.toString().trim()
MediaProjectionService.start(this, resultCode, data, host, signalingUrl)
status.text = "状态:连接中..."
Thread {
try {
session?.start()
runOnUiThread { status.text = "状态:采集中" }
} catch (error: Exception) {
runOnUiThread { status.text = "状态:连接失败 - ${error.message}" }
}
}.start()
}
override fun onDestroy() {
session?.stop()
session = null
super.onDestroy()
}
private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList()
@@ -0,0 +1,205 @@
package com.ttstd.lancast.receiver
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.widget.Toast
class MediaProjectionService : Service() {
companion object {
private const val TAG = "MediaProjectionService"
private const val CHANNEL_ID = "media_projection_service_channel"
private const val NOTIFICATION_ID = 1001
const val ACTION_START = "com.ttstd.lancast.receiver.action.START"
const val ACTION_STOP = "com.ttstd.lancast.receiver.action.STOP"
const val EXTRA_RESULT_CODE = "extra_result_code"
const val EXTRA_DATA = "extra_data"
const val EXTRA_HOST = "extra_host"
const val EXTRA_SIGNALING_URL = "extra_signaling_url"
@Volatile
var isRunning = false
private set
fun start(context: Context, resultCode: Int, data: Intent, host: String, signalingUrl: String) {
val intent = Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_START
putExtra(EXTRA_RESULT_CODE, resultCode)
putExtra(EXTRA_DATA, data)
putExtra(EXTRA_HOST, host)
putExtra(EXTRA_SIGNALING_URL, signalingUrl)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
}
fun stop(context: Context) {
val intent = Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_STOP
}
context.startService(intent)
}
}
private var session: ReceiverSession? = null
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_START -> {
val resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0)
val data: Intent? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(EXTRA_DATA, Intent::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra(EXTRA_DATA)
}
val host = intent.getStringExtra(EXTRA_HOST) ?: ""
val signalingUrl = intent.getStringExtra(EXTRA_SIGNALING_URL) ?: ""
if (resultCode != 0 && data != null) {
startForegroundServiceWithNotification()
startProjectionSession(resultCode, data, host, signalingUrl)
} else {
stopSelf()
}
}
ACTION_STOP -> {
stopProjectionSession()
stopSelf()
}
}
return START_NOT_STICKY
}
private fun startForegroundServiceWithNotification() {
val notification = createNotification()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
)
} else {
startForeground(NOTIFICATION_ID, notification)
}
}
private fun startProjectionSession(resultCode: Int, data: Intent, host: String, signalingUrl: String) {
stopProjectionSession()
try {
val manager = getSystemService(MediaProjectionManager::class.java)
val projection = manager.getMediaProjection(resultCode, data)
if (projection == null) {
Toast.makeText(this, "MediaProjection 授权失败", Toast.LENGTH_SHORT).show()
stopSelf()
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
projection.registerCallback(object : MediaProjection.Callback() {
override fun onStop() {
Log.i(TAG, "MediaProjection session stopped by system")
stopProjectionSession()
stopSelf()
}
}, Handler(Looper.getMainLooper()))
}
session = ReceiverSession(
context = this,
projection = projection,
host = host,
signalingUrl = signalingUrl,
certificatePem = "",
)
// 连接建立包含 TCP 握手,必须在后台线程执行,避免服务主线程 ANR。
Thread {
try {
session?.start()
isRunning = true
} catch (e: Exception) {
Log.e(TAG, "Failed to start receiver session", e)
Handler(Looper.getMainLooper()).post {
Toast.makeText(this@MediaProjectionService, "连接失败: ${e.message}", Toast.LENGTH_SHORT).show()
}
stopProjectionSession()
stopSelf()
}
}.start()
} catch (e: Exception) {
Log.e(TAG, "Failed to start MediaProjection session", e)
Toast.makeText(this, "启动屏幕投影失败: ${e.message}", Toast.LENGTH_SHORT).show()
stopSelf()
}
}
private fun stopProjectionSession() {
session?.stop()
session = null
isRunning = false
}
override fun onDestroy() {
stopProjectionSession()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(STOP_FOREGROUND_REMOVE)
} else {
@Suppress("DEPRECATION")
stopForeground(true)
}
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"屏幕投屏服务",
NotificationManager.IMPORTANCE_LOW
).apply {
description = "保持屏幕捕获服务在后台运行"
}
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(channel)
}
}
private fun createNotification(): Notification {
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
@Suppress("DEPRECATION")
Notification.Builder(this)
}
return builder
.setContentTitle("Lancast 投屏服务")
.setContentText("屏幕投屏服务正在运行中")
.setSmallIcon(android.R.drawable.ic_menu_camera)
.setOngoing(true)
.build()
}
}
@@ -1,36 +1,42 @@
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
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
class ReceiverAnnouncer(
private val signalingUrl: String,
private val device: AnnouncedDevice,
) {
private val handler = Handler(Looper.getMainLooper())
private var runnable: Runnable? = null
private var executor: ScheduledExecutorService? = null
private var future: ScheduledFuture<*>? = null
@Volatile
private var registered = false
fun start() {
if (runnable != null) return
runnable = object : Runnable {
override fun run() {
if (future != null) return
val exec = Executors.newSingleThreadScheduledExecutor()
executor = exec
future = exec.scheduleWithFixedDelay({
try {
val path = if (registered) "/heartbeat" else "/register"
post(path, body())
registered = true
handler.postDelayed(this, 15_000)
} catch (_: Exception) {
}
}
handler.post(runnable!!)
}, 0, 15, TimeUnit.SECONDS)
}
fun stop() {
runnable?.let { handler.removeCallbacks(it) }
runnable = null
future?.cancel(true)
future = null
executor?.shutdownNow()
executor = null
registered = false
}
@@ -1,30 +1,66 @@
package com.ttstd.lancast.receiver.encode
import android.util.Log
/** libopus JNI 通道。native 库未接入源码时 isAvailable 为 false,由 MediaCodec 承接。 */
object OpusNative {
private const val TAG = "OpusNative"
@Volatile
private var loaded = true
init {
try {
System.loadLibrary("ttstd_opus")
} catch (error: UnsatisfiedLinkError) {
loaded = false
Log.w(TAG, "libttstd_opus 加载失败,回退 MediaCodec", error)
}
}
val isAvailable: Boolean
get() {
if (!loaded) return false
return try {
nativeIsAvailable()
} catch (error: UnsatisfiedLinkError) {
// 库存在但 JNI 符号缺失时不能让进程崩溃,直接永久回退。
loaded = false
Log.w(TAG, "JNI 符号缺失,回退 MediaCodec", error)
false
}
}
fun createEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long {
if (!isAvailable) return 0L
return try {
nativeCreateEncoder(sampleRate, channels, bitrate)
} catch (error: UnsatisfiedLinkError) {
loaded = false
Log.w(TAG, "nativeCreateEncoder 不可用,回退 MediaCodec", error)
0L
}
}
fun destroyEncoder(handle: Long) {
if (handle == 0L) return
try {
nativeDestroyEncoder(handle)
} 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) return null
return try {
nativeEncode(handle, pcm16)
} catch (_: UnsatisfiedLinkError) {
loaded = false
null
}
}
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)
@@ -1,6 +1,7 @@
package com.ttstd.lancast.receiver.session
import android.media.MediaCodec
import android.util.Log
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector
@@ -50,32 +51,41 @@ class ReceiverTransport(
val keyEstablished: Boolean get() = keys != null
fun start() {
val raw = Socket().apply {
tcpNoDelay = true
soTimeout = 5000
connect(InetSocketAddress(host, controlPort), 5000)
executor.execute {
try {
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
readLoop(input)
} catch (e: Exception) {
Log.e("ReceiverTransport", "Failed to connect or handshake", e)
close()
}
}
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))
executor.execute {
val key = keys?.control ?: return@execute
if (!running) return@execute
val frame = ControlFrames.encode(event, sequence++)
writeFrame(crypto.encodeControlFrame(frame, key))
}
}
fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
@@ -172,6 +182,7 @@ class ReceiverTransport(
writeFrame(crypto.encodeControlFrame(frame, controlKey))
}
@Synchronized
private fun writeFrame(frame: ByteArray) {
try {
output?.write(frame)