generated from ali/HarmonyTemplate
提交 Haven Android 仓库源码 v5.87.79
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "sh.haven.core.rdp"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
|
||||
// Include native libraries built from Rust source by rdp-kotlin:buildRdpNative
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
jniLibs.srcDirs("${rootProject.projectDir}/rdp-kotlin/jniLibs")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure Rust native library is built before this module compiles
|
||||
tasks.configureEach {
|
||||
if (name == "preBuild") {
|
||||
dependsOn(gradle.includedBuild("rdp-kotlin").task(":buildRdpNative"))
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api("sh.haven:rdp-transport:0.1.0")
|
||||
implementation(project(":core:data"))
|
||||
implementation(libs.jna) { artifact { type = "aar" } }
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest />
|
||||
@@ -0,0 +1,380 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import android.media.MediaCodec
|
||||
import android.media.MediaCodecInfo
|
||||
import android.media.MediaFormat
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import sh.haven.rdp.Avc420Decoder
|
||||
import java.io.Closeable
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
private const val TAG = "Avc420Decoder"
|
||||
|
||||
/**
|
||||
* MediaCodec-backed H.264/AVC420 decoder for EGFX tiles (#425, KRDP).
|
||||
*
|
||||
* The Rust session thread owns the framebuffer and decodes every other codec
|
||||
* inline, so [decode] is a **blocking** call: one Annex-B access unit in, one
|
||||
* `width*height*4` RGBA frame out (empty on failure → the caller drops the
|
||||
* tile). A single [MediaCodec] instance persists across calls so its reference
|
||||
* picture survives — KRDP sends SPS+PPS+IDR only in the first frame and
|
||||
* P-slices thereafter. KRDP's stream is Baseline profile (no B-frames, no
|
||||
* reordering), so the 1-in/1-out poll below is valid.
|
||||
*
|
||||
* ponytail: YUV→RGBA is a straight integer BT.601 loop on the session thread —
|
||||
* the known hotspot. Correct first; move to Rust/GL if device profiling shows
|
||||
* it caps the framerate. See #425.
|
||||
*/
|
||||
class Avc420MediaCodecDecoder : Avc420Decoder, Closeable {
|
||||
|
||||
/**
|
||||
* #466: where the per-frame decode time actually goes.
|
||||
*
|
||||
* A reporter's 1080p KRDP session reports `decode` at 120-243 ms per frame
|
||||
* while `publish` is under 3 ms, so decode is ~98% of the frame — but
|
||||
* `decode` spans MediaCodec *and* the CPU YUV->RGBA conversion, and
|
||||
* attributing it by eye is how the last three rounds of this issue went
|
||||
* wrong. A desktop-JVM benchmark puts the conversion alone at 7 ms for
|
||||
* 1080p, which extrapolates to tens of ms on a phone and does **not**
|
||||
* account for the rest. So measure the split rather than argue about it.
|
||||
*
|
||||
* Set by [RdpSession] so the line reaches the in-app verbose log (#477)
|
||||
* rather than needing adb.
|
||||
*/
|
||||
var perfSink: ((String) -> Unit)? = null
|
||||
|
||||
private var pFrames = 0L
|
||||
private var pCodecNs = 0L
|
||||
private var pConvertNs = 0L
|
||||
private var pPolls = 0L
|
||||
private var codec: MediaCodec? = null
|
||||
private var lastConvertNs = 0L
|
||||
private var configuredWidth = 0
|
||||
private var configuredHeight = 0
|
||||
private var ptsUs = 0L
|
||||
@Volatile private var failed = false
|
||||
private val bufferInfo = MediaCodec.BufferInfo()
|
||||
// Reused I420 scratch, grown as needed to avoid a per-frame allocation.
|
||||
private var i420 = ByteArray(0)
|
||||
|
||||
/**
|
||||
* Decode one access unit straight into the caller's buffer (#466).
|
||||
*
|
||||
* This used to return the frame as a `ByteArray` for UniFFI to marshal
|
||||
* back. That crossing cost 47 ms per 1080p frame with a decoder that did
|
||||
* no decoding at all — linear in payload at about 62 MB/s, against 45 GB/s
|
||||
* for the same copy inside Rust — and was the ~80 ms per frame neither
|
||||
* side could account for. Writing into the caller's buffer measured
|
||||
* 0.24 ms for the same 3037 KB.
|
||||
*
|
||||
* The packing itself is unchanged: [yuvImageToI420] still fills the reused
|
||||
* scratch, and one bulk copy hands it over. Keeping that split means
|
||||
* [packPlane] and its tests carry on covering the pixel work, and only the
|
||||
* handoff is new.
|
||||
*
|
||||
* SAFETY: [dstAddr] is valid for [dstLen] bytes only for the duration of
|
||||
* this call. Never retain it, and never write past [dstLen].
|
||||
*/
|
||||
override fun decodeInto(
|
||||
annexB: ByteArray,
|
||||
width: UShort,
|
||||
height: UShort,
|
||||
dstAddr: ULong,
|
||||
dstLen: ULong,
|
||||
): UInt {
|
||||
val w = width.toInt()
|
||||
val h = height.toInt()
|
||||
if (failed || w <= 0 || h <= 0 || annexB.isEmpty()) return 0u
|
||||
val mc = try {
|
||||
ensureCodec(annexB, w, h)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "MediaCodec init failed (${w}x${h}): ${e.message}")
|
||||
failed = true
|
||||
releaseCodec()
|
||||
return 0u
|
||||
} ?: return 0u
|
||||
|
||||
return try {
|
||||
val t0 = System.nanoTime()
|
||||
queueInput(mc, annexB)
|
||||
val out = drainToI420(mc, w, h) ?: ByteArray(0)
|
||||
val written = if (out.isEmpty()) {
|
||||
0
|
||||
} else {
|
||||
val n = minOf(out.size.toLong(), dstLen.toLong()).toInt()
|
||||
// One bulk copy into the caller's memory. `getByteBuffer` hands
|
||||
// back a direct buffer over that address, so this is a memcpy
|
||||
// rather than the marshalling it replaces.
|
||||
com.sun.jna.Pointer(dstAddr.toLong())
|
||||
.getByteBuffer(0, n.toLong())
|
||||
.put(out, 0, n)
|
||||
n
|
||||
}
|
||||
pFrames++
|
||||
pCodecNs += System.nanoTime() - t0 - lastConvertNs
|
||||
pConvertNs += lastConvertNs
|
||||
lastConvertNs = 0L
|
||||
if (pFrames >= PERF_REPORT_FRAMES) {
|
||||
val line = "AVC420 decode split over $pFrames frames — mediacodec ${pCodecNs / pFrames / 1000}us, " +
|
||||
"i420 pack ${pConvertNs / pFrames / 1000}us, polls/frame ${"%.1f".format(pPolls.toDouble() / pFrames)}"
|
||||
Log.i(TAG, line)
|
||||
perfSink?.invoke(line)
|
||||
pFrames = 0; pCodecNs = 0; pConvertNs = 0; pPolls = 0
|
||||
}
|
||||
written.toUInt()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "AVC420 decode failed: ${e.message}")
|
||||
failed = true
|
||||
releaseCodec()
|
||||
0u
|
||||
}
|
||||
}
|
||||
|
||||
/** Configure the decoder on the first frame using its in-band SPS/PPS. */
|
||||
private fun ensureCodec(annexB: ByteArray, w: Int, h: Int): MediaCodec? {
|
||||
codec?.let { return it }
|
||||
val sps = findNal(annexB, 7)
|
||||
val pps = findNal(annexB, 8)
|
||||
if (sps == null || pps == null) {
|
||||
// First AU must carry the parameter sets; a P-slice can't configure.
|
||||
Log.e(TAG, "first AVC420 AU lacks SPS/PPS — cannot configure")
|
||||
failed = true
|
||||
return null
|
||||
}
|
||||
val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, w, h).apply {
|
||||
setByteBuffer("csd-0", ByteBuffer.wrap(sps))
|
||||
setByteBuffer("csd-1", ByteBuffer.wrap(pps))
|
||||
// Ask for a byte-buffer output format we can read as planar YUV.
|
||||
setInteger(
|
||||
MediaFormat.KEY_COLOR_FORMAT,
|
||||
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible,
|
||||
)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
setInteger(MediaFormat.KEY_LOW_LATENCY, 1)
|
||||
}
|
||||
// #477: the standard low-latency key is a request many decoders
|
||||
// ignore; the vendor extensions below are what actually collapse
|
||||
// the output pipeline on Qualcomm/MediaTek/Exynos parts. Unknown
|
||||
// keys are silently dropped by codecs that don't recognise them,
|
||||
// so setting all of them is safe everywhere. PRIORITY 0 marks the
|
||||
// session realtime, which affects codec scheduling on big.LITTLE.
|
||||
setInteger(MediaFormat.KEY_PRIORITY, 0)
|
||||
setInteger("vendor.qti-ext-dec-low-latency.enable", 1)
|
||||
setInteger("vendor.rtc-ext-dec-low-latency.enable", 1)
|
||||
setInteger("vendor.low-latency.enable", 1)
|
||||
}
|
||||
val mc = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
|
||||
mc.configure(format, /* surface = */ null, /* crypto = */ null, /* flags = */ 0)
|
||||
mc.start()
|
||||
codec = mc
|
||||
configuredWidth = w
|
||||
configuredHeight = h
|
||||
Log.d(TAG, "AVC420 MediaCodec configured ${w}x${h} (${mc.codecInfo.name})")
|
||||
return mc
|
||||
}
|
||||
|
||||
private fun queueInput(mc: MediaCodec, annexB: ByteArray) {
|
||||
// Bounded wait for an input buffer; the decoder should always have one
|
||||
// for a low-latency Baseline stream.
|
||||
val inIx = mc.dequeueInputBuffer(INPUT_TIMEOUT_US)
|
||||
if (inIx < 0) throw IllegalStateException("no input buffer available")
|
||||
val inBuf = mc.getInputBuffer(inIx) ?: throw IllegalStateException("null input buffer")
|
||||
inBuf.clear()
|
||||
inBuf.put(annexB)
|
||||
mc.queueInputBuffer(inIx, 0, annexB.size, ptsUs, 0)
|
||||
ptsUs += FRAME_INTERVAL_US
|
||||
}
|
||||
|
||||
/** Poll for the single output frame for the AU just queued. */
|
||||
private fun drainToI420(mc: MediaCodec, w: Int, h: Int): ByteArray? {
|
||||
var polls = 0
|
||||
while (polls++ < MAX_OUTPUT_POLLS) {
|
||||
pPolls++
|
||||
val outIx = mc.dequeueOutputBuffer(bufferInfo, OUTPUT_TIMEOUT_US)
|
||||
when {
|
||||
outIx >= 0 -> {
|
||||
val out = try {
|
||||
val image = mc.getOutputImage(outIx)
|
||||
if (image != null) {
|
||||
val c0 = System.nanoTime()
|
||||
val r = yuvImageToI420(image, w, h)
|
||||
lastConvertNs += System.nanoTime() - c0
|
||||
r
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} finally {
|
||||
mc.releaseOutputBuffer(outIx, /* render = */ false)
|
||||
}
|
||||
if (out != null) return out
|
||||
// No image (config-only) — keep polling.
|
||||
}
|
||||
outIx == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {
|
||||
Log.d(TAG, "AVC420 output format: ${mc.outputFormat}")
|
||||
}
|
||||
outIx == MediaCodec.INFO_TRY_AGAIN_LATER -> {
|
||||
// Decoder still working on this AU; retry within budget.
|
||||
}
|
||||
else -> { /* INFO_OUTPUT_BUFFERS_CHANGED (deprecated) — ignore */ }
|
||||
}
|
||||
}
|
||||
Log.w(TAG, "AVC420 decode produced no frame within poll budget")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Repack a YUV_420_888 [android.media.Image] into tightly-packed I420 at
|
||||
* [w]x[h], edge-replicating where the requested size exceeds the decoded
|
||||
* one. Handles planar (I420) and semi-planar (NV12/NV21) chroma via each
|
||||
* plane's row and pixel stride.
|
||||
*
|
||||
* This replaces a full BT.601 conversion to RGBA, which cost 27-109 ms per
|
||||
* frame on a reporter's 1080p session against 9-25 ms for the hardware
|
||||
* decode itself (#466). Colour conversion now happens in Rust; what leaves
|
||||
* here is 1.5 bytes per pixel instead of 4, which also cuts what the
|
||||
* Kotlin/Rust boundary has to allocate and copy — separately measured at
|
||||
* 87-112 ms per frame.
|
||||
*
|
||||
* The work left is byte movement with no arithmetic, and the common case
|
||||
* (a plane whose rowStride equals its width) is a bulk copy rather than a
|
||||
* loop.
|
||||
*/
|
||||
private fun yuvImageToI420(image: android.media.Image, w: Int, h: Int): ByteArray {
|
||||
val cw = (w + 1) / 2
|
||||
val ch = (h + 1) / 2
|
||||
val need = w * h + 2 * cw * ch
|
||||
if (i420.size < need) i420 = ByteArray(need)
|
||||
val out = i420
|
||||
|
||||
val srcW = minOf(w, image.width)
|
||||
val srcH = minOf(h, image.height)
|
||||
val yP = image.planes[0]
|
||||
val uP = image.planes[1]
|
||||
val vP = image.planes[2]
|
||||
|
||||
packPlane(out, 0, yP.buffer, yP.rowStride, 1, w, h, srcW, srcH)
|
||||
// Chroma is half resolution in both axes; the source's own chroma
|
||||
// extent follows from its luma extent the same way.
|
||||
val sCw = (srcW + 1) / 2
|
||||
val sCh = (srcH + 1) / 2
|
||||
packPlane(out, w * h, uP.buffer, uP.rowStride, uP.pixelStride, cw, ch, sCw, sCh)
|
||||
packPlane(out, w * h + cw * ch, vP.buffer, vP.rowStride, vP.pixelStride, cw, ch, sCw, sCh)
|
||||
|
||||
return exactly(out, need)
|
||||
}
|
||||
|
||||
/**
|
||||
* Exactly [need] bytes, without copying when the scratch buffer is already
|
||||
* that size (#477).
|
||||
*
|
||||
* Handing back the scratch buffer itself is safe because the caller copies
|
||||
* it into the Rust-owned frame buffer synchronously, before control
|
||||
* returns to the loop that would overwrite it, and nothing retains it
|
||||
* afterwards.
|
||||
*
|
||||
* ★ That rests on the copy being synchronous. If decoding ever becomes
|
||||
* asynchronous, or something starts holding this array across frames,
|
||||
* restore a defensive copy.
|
||||
*/
|
||||
internal fun exactly(out: ByteArray, need: Int): ByteArray =
|
||||
if (out.size == need) out else out.copyOf(need)
|
||||
|
||||
/**
|
||||
* Copy one plane into [out] at [offset] as [dstW]x[dstH] tightly packed,
|
||||
* reading [srcW]x[srcH] from [buf] and replicating the last row/column
|
||||
* beyond it.
|
||||
*
|
||||
* Pure over its arguments so it can be tested off-device (see
|
||||
* Avc420I420PackTest).
|
||||
*/
|
||||
internal fun packPlane(
|
||||
out: ByteArray,
|
||||
offset: Int,
|
||||
buf: java.nio.ByteBuffer,
|
||||
rowStride: Int,
|
||||
pixelStride: Int,
|
||||
dstW: Int,
|
||||
dstH: Int,
|
||||
srcW: Int,
|
||||
srcH: Int,
|
||||
) {
|
||||
var o = offset
|
||||
for (y in 0 until dstH) {
|
||||
val sy = if (y < srcH) y else srcH - 1
|
||||
val row = sy * rowStride
|
||||
if (pixelStride == 1 && dstW <= srcW) {
|
||||
// Planar and no replication needed — one bulk copy per row.
|
||||
val dup = buf.duplicate()
|
||||
dup.position(row)
|
||||
dup.get(out, o, dstW)
|
||||
o += dstW
|
||||
} else {
|
||||
var x = 0
|
||||
while (x < dstW) {
|
||||
val sx = if (x < srcW) x else srcW - 1
|
||||
out[o] = buf.get(row + sx * pixelStride)
|
||||
o++
|
||||
x++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseCodec() {
|
||||
try {
|
||||
codec?.stop()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
try {
|
||||
codec?.release()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
codec = null
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
releaseCodec()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val INPUT_TIMEOUT_US = 20_000L
|
||||
const val OUTPUT_TIMEOUT_US = 10_000L
|
||||
const val MAX_OUTPUT_POLLS = 8
|
||||
const val PERF_REPORT_FRAMES = 30L
|
||||
|
||||
// Nominal 60 fps spacing; PTS ordering only, value is otherwise unused
|
||||
// for a no-reorder Baseline stream.
|
||||
const val FRAME_INTERVAL_US = 16_666L
|
||||
|
||||
/**
|
||||
* Return the first Annex-B NAL (including its start code) whose
|
||||
* nal_unit_type == [type], or null. Scans for 3- and 4-byte start codes.
|
||||
*/
|
||||
fun findNal(data: ByteArray, type: Int): ByteArray? {
|
||||
val starts = ArrayList<Int>()
|
||||
var i = 0
|
||||
while (i + 3 < data.size) {
|
||||
if (data[i] == 0.toByte() && data[i + 1] == 0.toByte()) {
|
||||
if (data[i + 2] == 1.toByte()) {
|
||||
starts.add(i); i += 3; continue
|
||||
}
|
||||
if (data[i + 2] == 0.toByte() && data[i + 3] == 1.toByte()) {
|
||||
starts.add(i); i += 4; continue
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
for ((k, s) in starts.withIndex()) {
|
||||
// NAL header byte follows the start code (00 00 01 or 00 00 00 01).
|
||||
val hdr = if (s + 3 < data.size && data[s + 2] == 1.toByte()) s + 3 else s + 4
|
||||
if (hdr >= data.size) continue
|
||||
if ((data[hdr].toInt() and 0x1F) == type) {
|
||||
val end = if (k + 1 < starts.size) starts[k + 1] else data.size
|
||||
return data.copyOfRange(s, end)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* #504: map the device locale to the Windows keyboard-layout identifier
|
||||
* (KLID) announced in the RDP connect. Servers that build the session's
|
||||
* input layout from the announcement — Windows, xrdp, KRDP — otherwise
|
||||
* hand every non-US user a US layout; the reporter's guest composed
|
||||
* Polish on the console (raw scancodes, guest keymap) but not in
|
||||
* layout-honouring contexts. VirtualBox-style servers ignore this.
|
||||
*
|
||||
* The table covers layouts where the language's dominant physical
|
||||
* keyboard differs meaningfully from US. Anything unlisted announces
|
||||
* US English (0x0409) — the pre-#504 behaviour for everyone.
|
||||
*/
|
||||
fun keyboardLayoutKlid(locale: Locale = Locale.getDefault()): UInt {
|
||||
val lang = locale.language.lowercase(Locale.ROOT)
|
||||
val country = locale.country.uppercase(Locale.ROOT)
|
||||
return when (lang) {
|
||||
"en" -> if (country == "GB") 0x0809u else 0x0409u
|
||||
"pl" -> 0x0415u
|
||||
"de" -> if (country == "CH") 0x0807u else 0x0407u
|
||||
"fr" -> when (country) {
|
||||
"CH" -> 0x100Cu
|
||||
"BE" -> 0x080Cu
|
||||
"CA" -> 0x0C0Cu
|
||||
else -> 0x040Cu
|
||||
}
|
||||
"es" -> 0x040Au
|
||||
"it" -> 0x0410u
|
||||
"pt" -> if (country == "BR") 0x0416u else 0x0816u
|
||||
"ru" -> 0x0419u
|
||||
"cs" -> 0x0405u
|
||||
"sk" -> 0x041Bu
|
||||
"sv" -> 0x041Du
|
||||
"nb", "nn", "no" -> 0x0414u
|
||||
"da" -> 0x0406u
|
||||
"fi" -> 0x040Bu
|
||||
"nl" -> if (country == "BE") 0x0813u else 0x0413u
|
||||
"tr" -> 0x041Fu
|
||||
"hu" -> 0x040Eu
|
||||
"uk" -> 0x0422u
|
||||
"el" -> 0x0408u
|
||||
"he" -> 0x040Du
|
||||
"ar" -> 0x0401u
|
||||
"ja" -> 0x0411u
|
||||
"ko" -> 0x0412u
|
||||
"zh" -> 0x0804u
|
||||
else -> 0x0409u
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Copies a decoded frame region straight from the native framebuffer into a
|
||||
* locked Android bitmap, skipping the byte-array round trip (#466).
|
||||
*
|
||||
* The normal publish path hands every frame across the FFI: native builds a
|
||||
* `Vec`, UniFFI marshals it into a `ByteArray`, and Kotlin copies that into the
|
||||
* bitmap. Three copies of the region — 8.3 MB each at 1080p, every frame.
|
||||
* Measured at ~57 ms per frame against a ~138 ms budget.
|
||||
*
|
||||
* This is a hand-written JNI entry point rather than a UniFFI method because
|
||||
* `AndroidBitmap_lockPixels` needs the JNIEnv and the jobject, neither of which
|
||||
* UniFFI can pass. The [bridgeId] is how the native side finds the session
|
||||
* again: a raw JNI function cannot reach a UniFFI object, whose handle is
|
||||
* opaque, so the client registers its state and hands out this key.
|
||||
*
|
||||
* [blitRegion] returns false for anything the caller can recover from — an
|
||||
* unknown id, a bitmap of the wrong format or size, a refused lock — and the
|
||||
* caller falls back to the byte-array path. A refusal costs a frame's latency,
|
||||
* never correctness.
|
||||
*/
|
||||
internal object RdpBitmapBridge {
|
||||
|
||||
/** Whether the native symbol is present; false on a build without it. */
|
||||
val available: Boolean = try {
|
||||
System.loadLibrary("rdp_transport")
|
||||
true
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
// UniFFI normally loads this already, so reaching here means something
|
||||
// is badly wrong — but the caller has a working fallback, so degrade
|
||||
// rather than take the session down.
|
||||
Log.w(TAG, "rdp_transport not loadable; bitmap bridge disabled", e)
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy `w`x`h` pixels at (`x`,`y`) from the session's framebuffer into
|
||||
* [bitmap], which must be ARGB_8888 and the same size as the framebuffer.
|
||||
*
|
||||
* @return true if the pixels were written; false to use the fallback.
|
||||
*/
|
||||
@JvmStatic
|
||||
external fun blitRegion(
|
||||
bitmap: Bitmap,
|
||||
bridgeId: Long,
|
||||
x: Int,
|
||||
y: Int,
|
||||
w: Int,
|
||||
h: Int,
|
||||
): Boolean
|
||||
|
||||
private const val TAG = "RdpBitmapBridge"
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
/**
|
||||
* Process-global debug toggles for the RDP path.
|
||||
*
|
||||
* [RdpSession] is constructed by hand at several call sites (desktop VM,
|
||||
* feature/rdp VM, session manager) and isn't in the DI graph, so a debug flag
|
||||
* that has to reach [RdpConfig] is simplest as a process-global read there.
|
||||
* The value is bridged in from a persisted preference by `HavenApp` (which
|
||||
* observes the pref and pushes it here, seeding on startup and updating live).
|
||||
*
|
||||
* #418: temporary while the RemoteFX-Progressive WBT_TILE_UPGRADE decode is
|
||||
* verified against real Windows captures. Remove this once the upgrade path is
|
||||
* verified and enabled unconditionally.
|
||||
*/
|
||||
object RdpDebugToggles {
|
||||
/** Enable WBT_TILE_UPGRADE refinement decoding in the native decoder. */
|
||||
@Volatile
|
||||
@JvmField
|
||||
var progressiveUpgrade: Boolean = true
|
||||
|
||||
/**
|
||||
* #425: advertise EGFX H.264/AVC420. On by default (device-verified against
|
||||
* KRDP, which speaks only H.264). Advertising it switches the EGFX caps from
|
||||
* V10/AVC-disabled to V8.1/AVC420 for every server; Windows/xrdp still render
|
||||
* (AVC420 + ClearCodec/Planar/Progressive, all decoded) but Windows drops
|
||||
* from AVC444 to AVC420. Users can turn it off in Settings → Diagnostics.
|
||||
*/
|
||||
@Volatile
|
||||
@JvmField
|
||||
var avcEnabled: Boolean = true
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.util.Log
|
||||
import sh.haven.rdp.FrameCallback
|
||||
import sh.haven.rdp.FrameData
|
||||
import sh.haven.rdp.MouseButton
|
||||
import sh.haven.rdp.PointerCallback
|
||||
import sh.haven.rdp.RdpClient
|
||||
import sh.haven.rdp.RdpConfig
|
||||
import sh.haven.rdp.RdpException
|
||||
import sh.haven.rdp.RdpRect
|
||||
import sh.haven.rdp.SessionCallback
|
||||
import sh.haven.rdp.SocksProxyConfig
|
||||
import java.io.Closeable
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
private const val TAG = "RdpSession"
|
||||
|
||||
/**
|
||||
* Wraps an [RdpClient] (IronRDP via UniFFI) with Android-specific
|
||||
* bitmap management and lifecycle.
|
||||
*
|
||||
* Similar pattern to VncClient but adapted for RDP:
|
||||
* - RDP uses scancodes, not X11 KeySyms
|
||||
* - Frame delivery via polling getFramebuffer() + callback for dirty rects
|
||||
* - No mid-session resize (RDP requires reconnect)
|
||||
*/
|
||||
class RdpSession(
|
||||
val sessionId: String,
|
||||
private val host: String,
|
||||
private val port: Int,
|
||||
private val username: String,
|
||||
private val password: String,
|
||||
private val domain: String = "",
|
||||
private val width: Int = 1920,
|
||||
private val height: Int = 1080,
|
||||
private val useNla: Boolean = true,
|
||||
private val colorDepth: Int = 16,
|
||||
onDisconnected: (() -> Unit)? = null,
|
||||
private val verboseBuffer: ConcurrentLinkedQueue<String>? = null,
|
||||
/**
|
||||
* Optional SOCKS5 endpoint for routing IronRDP's TCP through a
|
||||
* userspace tunnel — typically the WireGuard / Tailscale tunnel's
|
||||
* 127.0.0.1 listener (#149). Null = direct kernel dial.
|
||||
*/
|
||||
private val socksProxy: SocksProxyConfig? = null,
|
||||
/**
|
||||
* TOFU verifier for the server's TLS certificate (security-review #2). The
|
||||
* pinned fingerprint is looked up before connect and a changed cert is
|
||||
* rejected inside the native handshake before credentials are sent; the
|
||||
* observed cert is pinned on first use. Null disables pinning.
|
||||
*/
|
||||
private val tlsCertVerifier: sh.haven.core.data.agent.TlsCertVerifier? = null,
|
||||
/**
|
||||
* Stable server identity for the cert pin, independent of the socket
|
||||
* target. For an SSH-tunnelled session [host] is 127.0.0.1, so the caller
|
||||
* passes the real remote here; defaults to [host]:[port] for direct dials.
|
||||
*/
|
||||
private val certHost: String = host,
|
||||
private val certPort: Int = port,
|
||||
) : Closeable {
|
||||
|
||||
@Volatile
|
||||
private var closed = false
|
||||
private var client: RdpClient? = null
|
||||
private var currentBitmap: Bitmap? = null
|
||||
|
||||
/**
|
||||
* Framebuffer size as last announced by the server, so the dirty-rect path
|
||||
* can tell whether [currentBitmap] is still the right size WITHOUT fetching
|
||||
* the whole framebuffer to ask (#422). Updated from onConnected/onResize,
|
||||
* which are the only things that change it.
|
||||
*/
|
||||
@Volatile
|
||||
private var fbWidth: Int = 0
|
||||
|
||||
@Volatile
|
||||
private var fbHeight: Int = 0
|
||||
// #425: MediaCodec H.264 decoder, created only when AVC is enabled.
|
||||
private var avcDecoder: Avc420MediaCodecDecoder? = null
|
||||
private val startTime = System.currentTimeMillis()
|
||||
|
||||
private fun log(level: String, msg: String) {
|
||||
if (level == "E") Log.e(TAG, msg) else Log.d(TAG, msg)
|
||||
verboseBuffer?.add("+${System.currentTimeMillis() - startTime}ms [$TAG] $level: $msg")
|
||||
}
|
||||
|
||||
/**
|
||||
* Called on frame updates. Set by the ViewModel.
|
||||
*
|
||||
* ★The bitmap is now the SAME instance for the life of a framebuffer size —
|
||||
* it is mutated in place (#422). Anything keyed on its identity (a
|
||||
* `StateFlow`, `remember(bitmap)`) will therefore not see a change; observe
|
||||
* [frameSeq] to know when to redraw.
|
||||
*/
|
||||
var onFrameUpdate: ((Bitmap) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Bumped once per framebuffer change, so a viewer holding the stable bitmap
|
||||
* from [onFrameUpdate] knows to repaint.
|
||||
*
|
||||
* #422: previously every update allocated a fresh full-screen bitmap purely
|
||||
* so the `StateFlow<Bitmap?>` carrying it would emit — it conflates on
|
||||
* equality, and re-publishing one instance emits nothing. On a 1920x1080
|
||||
* session that meant an 8.29 MB allocation plus two full-frame copies for
|
||||
* updates whose median size was 127x82 (about 41 KB), roughly 400x more
|
||||
* work than the update contained, at 14-21 updates/sec. That is what made a
|
||||
* VirtualBox UEFI menu take seconds to repaint and eventually wedge.
|
||||
*/
|
||||
val frameSeq: StateFlow<Long> get() = _frameSeq
|
||||
private val _frameSeq = MutableStateFlow(0L)
|
||||
|
||||
/**
|
||||
* Called when the server pushes a new cursor shape / visibility (#212).
|
||||
* Args mirror VncConfig.onCursorUpdate: (cursor bitmap or null to hide,
|
||||
* hotspot x, hotspot y). The app layer wraps this into a CursorOverlay.
|
||||
*/
|
||||
var onCursorUpdate: ((Bitmap?, Int, Int) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Called when the server moves the pointer (DIRECT mode). Touchpad mode
|
||||
* drives the cursor position client-side, so this is advisory.
|
||||
*/
|
||||
var onCursorPosition: ((Int, Int) -> Unit)? = null
|
||||
|
||||
/** Last non-null cursor shape, re-emitted on PointerDefault. */
|
||||
private var lastCursor: Triple<Bitmap, Int, Int>? = null
|
||||
|
||||
/** Called when an error occurs. */
|
||||
var onError: ((Exception) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Called when the native session loop ends without a surfaced error — a
|
||||
* server-side logoff/close, or a socket death the loop treats as a clean
|
||||
* exit. Settable post-construction (like [onError]) so the desktop tab
|
||||
* can mark itself dead instead of staying "connected" forever (#437).
|
||||
*/
|
||||
var onDisconnected: (() -> Unit)? = onDisconnected
|
||||
|
||||
/**
|
||||
* Called once the RDP handshake + capability exchange completes. Prior to
|
||||
* this the session is still in the "Connecting" phase even though
|
||||
* [start] has returned — the Rust connect() only spawns the worker
|
||||
* thread. The UI uses this to flip from "Connecting…" to the rendered
|
||||
* framebuffer.
|
||||
*/
|
||||
var onConnected: ((Int, Int) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Start the RDP session. Call from `Dispatchers.IO`.
|
||||
*
|
||||
* Returns once the TCP connection is established and the worker thread
|
||||
* is spawned — this is NOT equivalent to a usable RDP session. The
|
||||
* handshake, TLS upgrade and capability exchange happen asynchronously
|
||||
* on the worker thread; [onConnected] fires when it completes, [onError]
|
||||
* fires if it fails.
|
||||
*/
|
||||
fun start() {
|
||||
if (closed) return
|
||||
log("D", "Starting RDP session $sessionId: ${redactHost(host, port)} user=${redactUsername(username)}")
|
||||
|
||||
try {
|
||||
// Trust-on-first-use pin: the fingerprint remembered from a prior
|
||||
// connection, or null on first use. A short blocking DB read.
|
||||
val pinnedCert = tlsCertVerifier?.let { v ->
|
||||
kotlinx.coroutines.runBlocking { v.pinnedFingerprint(certHost, certPort) }
|
||||
}
|
||||
// #461: a `MicrosoftAccount\you@example.com` or `CORP\alice` typed
|
||||
// into the username box has to reach the Client Info PDU as two
|
||||
// fields, or Windows authenticates the transport and then shows the
|
||||
// lock screen. Splitting only — a bare UPN is left alone.
|
||||
val logon = qualifyRdpLogon(username, domain)
|
||||
val config = RdpConfig(
|
||||
username = logon.username,
|
||||
password = password,
|
||||
domain = logon.domain,
|
||||
width = width.toUShort(),
|
||||
height = height.toUShort(),
|
||||
// Per-profile colour depth (#109). Default 16 is xrdp-
|
||||
// safe; user can switch to 32 for Windows servers to get
|
||||
// RemoteFX-driven smooth updates. Picker lives in the
|
||||
// RDP block of ConnectionEditDialog.
|
||||
colorDepth = colorDepth.toUByte(),
|
||||
enableCredssp = useNla,
|
||||
pinnedCertSha256 = pinnedCert,
|
||||
// #418 debug opt-in: WBT_TILE_UPGRADE refinement decoding.
|
||||
// Bridged from Settings → Diagnostics via RdpDebugToggles.
|
||||
progressiveUpgrade = RdpDebugToggles.progressiveUpgrade,
|
||||
// #425: advertise H.264/AVC420 (KRDP). Only meaningful with a
|
||||
// decoder registered below, so keep the two in lock-step.
|
||||
avcEnabled = RdpDebugToggles.avcEnabled,
|
||||
// #504: announce the device locale's keyboard layout instead
|
||||
// of hardcoded US, for servers that honour the announcement.
|
||||
keyboardLayout = keyboardLayoutKlid(),
|
||||
)
|
||||
|
||||
// #477: record which settings this session actually ran with. Two
|
||||
// reporter logs labelled "AVC420 enabled" negotiated different
|
||||
// pipelines, and nothing in either log said which toggle was live —
|
||||
// so whether the setting had failed to apply or the label was wrong
|
||||
// could not be told apart without asking.
|
||||
log(
|
||||
"D",
|
||||
"RDP settings: avc420=${config.avcEnabled} progressiveUpgrade=" +
|
||||
"${config.progressiveUpgrade} colorDepth=$colorDepth nla=$useNla",
|
||||
)
|
||||
|
||||
val c = RdpClient(config)
|
||||
client = c
|
||||
|
||||
// #425: register the MediaCodec AVC420 decoder before connect so
|
||||
// negotiated H.264 tiles have somewhere to decode. The native side
|
||||
// calls it (blocking) on the session thread per frame.
|
||||
if (RdpDebugToggles.avcEnabled) {
|
||||
val dec = Avc420MediaCodecDecoder()
|
||||
// #466: route the decode split into the verbose log, so the
|
||||
// number that settles this reaches a reporter without adb.
|
||||
dec.perfSink = { line -> log("D", line) }
|
||||
avcDecoder = dec
|
||||
c.setAvcDecoder(dec)
|
||||
}
|
||||
|
||||
c.setFrameCallback(object : FrameCallback {
|
||||
override fun onFrameUpdate(x: UShort, y: UShort, w: UShort, h: UShort) {
|
||||
if (closed) return
|
||||
try {
|
||||
refreshBitmap(RdpRect(x, y, w, h))
|
||||
} catch (e: Exception) {
|
||||
log("E", "Frame update failed (${x},${y} ${w}x${h}): ${e.message}")
|
||||
onError?.invoke(e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResize(width: UShort, height: UShort) {
|
||||
if (closed) return
|
||||
log("D", "Desktop resized: ${width}x${height}")
|
||||
fbWidth = width.toInt()
|
||||
fbHeight = height.toInt()
|
||||
try {
|
||||
synchronized(this@RdpSession) {
|
||||
// #425: don't recycle() — this bitmap may still be
|
||||
// referenced by the Compose viewer (asImageBitmap);
|
||||
// recycling under an in-flight draw crashes with
|
||||
// "trying to use a recycled bitmap". refreshBitmap
|
||||
// already leaks superseded frames to GC, so just drop
|
||||
// the ref. Continuous H.264 streaming (KRDP) makes the
|
||||
// draw-vs-recycle race fire where sporadic RDP didn't.
|
||||
currentBitmap = null
|
||||
}
|
||||
refreshBitmap()
|
||||
} catch (e: Exception) {
|
||||
log("E", "Resize failed (${width}x${height}): ${e.message}")
|
||||
onError?.invoke(e)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
c.setSessionCallback(object : SessionCallback {
|
||||
override fun onConnected(width: UShort, height: UShort) {
|
||||
if (closed) return
|
||||
log("D", "RDP handshake complete: ${width}x${height}")
|
||||
fbWidth = width.toInt()
|
||||
fbHeight = height.toInt()
|
||||
onConnected?.invoke(width.toInt(), height.toInt())
|
||||
}
|
||||
|
||||
override fun onError(message: String) {
|
||||
if (closed) return
|
||||
log("E", "RDP session error: $message")
|
||||
this@RdpSession.onError?.invoke(RuntimeException(message))
|
||||
}
|
||||
|
||||
override fun onDisconnected() {
|
||||
if (closed) return
|
||||
log("D", "RDP session ended cleanly")
|
||||
onDisconnected?.invoke()
|
||||
}
|
||||
|
||||
override fun onServerCert(sha256: String) {
|
||||
// First-use TOFU pin (a changed cert was already rejected
|
||||
// in the native handshake, so this only fires on match or
|
||||
// first connect). Idempotent for an already-pinned cert.
|
||||
val v = tlsCertVerifier ?: return
|
||||
try {
|
||||
kotlinx.coroutines.runBlocking { v.accept(certHost, certPort, sha256) }
|
||||
log("D", "Pinned RDP TLS cert for $certHost:$certPort: ${sha256.take(16)}…")
|
||||
} catch (e: Exception) {
|
||||
log("E", "Failed to pin RDP TLS cert: ${e.message}")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
c.setPointerCallback(object : PointerCallback {
|
||||
override fun onPointerBitmap(
|
||||
width: UShort,
|
||||
height: UShort,
|
||||
hotspotX: UShort,
|
||||
hotspotY: UShort,
|
||||
rgba: ByteArray,
|
||||
) {
|
||||
if (closed) return
|
||||
val w = width.toInt()
|
||||
val h = height.toInt()
|
||||
if (w <= 0 || h <= 0 || rgba.size < w * h * 4) {
|
||||
log("E", "Bad pointer bitmap ${w}x$h, ${rgba.size} bytes")
|
||||
return
|
||||
}
|
||||
try {
|
||||
val bmp = pointerToBitmap(rgba, w, h)
|
||||
lastCursor = Triple(bmp, hotspotX.toInt(), hotspotY.toInt())
|
||||
onCursorUpdate?.invoke(bmp, hotspotX.toInt(), hotspotY.toInt())
|
||||
} catch (e: Exception) {
|
||||
log("E", "pointerToBitmap failed (${w}x$h): ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPointerHidden() {
|
||||
if (closed) return
|
||||
// Temporary hide (video/games) — drop the overlay but keep
|
||||
// lastCursor so a subsequent PointerDefault can restore it.
|
||||
onCursorUpdate?.invoke(null, 0, 0)
|
||||
}
|
||||
|
||||
override fun onPointerDefault() {
|
||||
if (closed) return
|
||||
lastCursor?.let { (bmp, hx, hy) -> onCursorUpdate?.invoke(bmp, hx, hy) }
|
||||
}
|
||||
|
||||
override fun onPointerPosition(x: UShort, y: UShort) {
|
||||
if (closed) return
|
||||
onCursorPosition?.invoke(x.toInt(), y.toInt())
|
||||
}
|
||||
})
|
||||
|
||||
log("D", "Connecting to ${redactHost(host, port)} (worker thread will handle handshake, socks=${socksProxy != null})")
|
||||
c.connect(host, port.toUShort(), socksProxy)
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
val msg = "RDP native library failed to load: ${e.message}"
|
||||
log("E", msg)
|
||||
val wrapped = RuntimeException(msg, e)
|
||||
onError?.invoke(wrapped)
|
||||
onDisconnected?.invoke()
|
||||
throw wrapped
|
||||
} catch (e: Exception) {
|
||||
log("E", "RDP connect dispatch failed: ${e.message}")
|
||||
onError?.invoke(e)
|
||||
onDisconnected?.invoke()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the on-screen bitmap up to date. [dirty] is the region the server
|
||||
* actually changed; only that region is written, and only into a bitmap
|
||||
* that already exists at the right size (#422).
|
||||
*/
|
||||
private fun refreshBitmap(dirty: RdpRect? = null) {
|
||||
val c = client ?: return
|
||||
val bitmap = try {
|
||||
val existing = synchronized(this) { currentBitmap }
|
||||
val reusable = existing != null &&
|
||||
!existing.isRecycled &&
|
||||
existing.width == fbWidth &&
|
||||
existing.height == fbHeight
|
||||
// The common path: fetch ONLY the changed region and paint it into
|
||||
// the bitmap the viewer already holds. Fetching the whole
|
||||
// framebuffer here was the last full-frame copy per update (#422).
|
||||
// Fastest path: let native write straight into the bitmap we
|
||||
// already hold, skipping the Vec, the FFI marshalling and the
|
||||
// Kotlin-side copy entirely (#466). Returns false for anything
|
||||
// recoverable — wrong size, wrong format, session gone — and we
|
||||
// fall through to the byte-array path below.
|
||||
val blitted = reusable && dirty != null && RdpBitmapBridge.available &&
|
||||
runCatching {
|
||||
RdpBitmapBridge.blitRegion(
|
||||
existing!!,
|
||||
c.bitmapBridgeId(),
|
||||
dirty.x.toInt(),
|
||||
dirty.y.toInt(),
|
||||
dirty.width.toInt(),
|
||||
dirty.height.toInt(),
|
||||
)
|
||||
}.getOrDefault(false)
|
||||
|
||||
val region = if (!blitted && reusable && dirty != null) {
|
||||
c.getFramebufferRegion(dirty.x, dirty.y, dirty.width, dirty.height)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (blitted) {
|
||||
existing!!
|
||||
} else if (region != null) {
|
||||
existing!!.also {
|
||||
// A region covering the whole bitmap is the common case, not
|
||||
// the exception: progressive and AVC both hand us a
|
||||
// full-screen dirty bbox every frame. drawTile would
|
||||
// allocate a second full-size bitmap, copy into it, then
|
||||
// blit that over the destination — two 8.3MB copies and an
|
||||
// 8.3MB allocation per frame, to land the pixels exactly
|
||||
// where copyPixelsFromBuffer puts them in one. Measured at
|
||||
// 1080p the whole publish step was ~72ms/frame (#466).
|
||||
if (dirty!!.x.toInt() == 0 && dirty.y.toInt() == 0 &&
|
||||
region.width.toInt() == it.width && region.height.toInt() == it.height
|
||||
) {
|
||||
it.copyPixelsFromBuffer(ByteBuffer.wrap(region.pixels))
|
||||
} else {
|
||||
drawTile(it, region, dirty.x.toInt(), dirty.y.toInt())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// First frame, a resize, or a rect the native side rejected:
|
||||
// fall back to a full repaint.
|
||||
val frame = c.getFramebuffer() ?: return
|
||||
if (reusable && existing!!.width == frame.width.toInt() &&
|
||||
existing.height == frame.height.toInt()
|
||||
) {
|
||||
existing.also { it.copyPixelsFromBuffer(ByteBuffer.wrap(frame.pixels)) }
|
||||
} else {
|
||||
frameToBitmap(frame)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
log("E", "frame paint failed (dirty=${dirty?.width}x${dirty?.height}): ${e.message}")
|
||||
onError?.invoke(e)
|
||||
return
|
||||
}
|
||||
synchronized(this) {
|
||||
currentBitmap = bitmap
|
||||
}
|
||||
// Identity may be unchanged, so the counter is what tells the viewer to
|
||||
// repaint. Bumped before the callback so an observer that reads it
|
||||
// synchronously sees this frame, not the previous one.
|
||||
_frameSeq.value = _frameSeq.value + 1
|
||||
onFrameUpdate?.invoke(bitmap)
|
||||
}
|
||||
|
||||
/**
|
||||
* Paint an already tightly-packed RGBA [region] into [dst] at ([x], [y]).
|
||||
*
|
||||
* Goes via a tile bitmap and [Canvas] rather than `setPixels`, because
|
||||
* `copyPixelsFromBuffer` keeps the same RGBA byte order the full-frame path
|
||||
* has always used — `setPixels` takes packed ARGB ints and would reintroduce
|
||||
* the red/blue swap of #212.
|
||||
*/
|
||||
private fun drawTile(dst: Bitmap, region: FrameData, x: Int, y: Int) {
|
||||
val w = region.width.toInt()
|
||||
val h = region.height.toInt()
|
||||
if (w <= 0 || h <= 0) return
|
||||
val tile = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
|
||||
try {
|
||||
tile.copyPixelsFromBuffer(ByteBuffer.wrap(region.pixels))
|
||||
Canvas(dst).drawBitmap(tile, x.toFloat(), y.toFloat(), null)
|
||||
} finally {
|
||||
tile.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert FrameData (ARGB_8888 byte array) to Android Bitmap.
|
||||
*/
|
||||
private fun frameToBitmap(frame: FrameData): Bitmap {
|
||||
val w = frame.width.toInt()
|
||||
val h = frame.height.toInt()
|
||||
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
|
||||
bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(frame.pixels))
|
||||
return bitmap
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an IronRDP DecodedPointer bitmap (RGBA bytes, non-premultiplied
|
||||
* alpha — `pointer_software_rendering` is off) to an Android Bitmap. Packs
|
||||
* each RGBA pixel into an ARGB colour int; `createBitmap(IntArray, …)`
|
||||
* treats the input as non-premultiplied and stores it premultiplied, so the
|
||||
* Compose overlay alpha-blends correctly. Mirrors the VNC cursor path
|
||||
* (Framebuffer.renderCursor).
|
||||
*/
|
||||
private fun pointerToBitmap(rgba: ByteArray, w: Int, h: Int): Bitmap {
|
||||
val argb = IntArray(w * h)
|
||||
for (i in 0 until w * h) {
|
||||
val o = i * 4
|
||||
val r = rgba[o].toInt() and 0xFF
|
||||
val g = rgba[o + 1].toInt() and 0xFF
|
||||
val b = rgba[o + 2].toInt() and 0xFF
|
||||
val a = rgba[o + 3].toInt() and 0xFF
|
||||
argb[i] = (a shl 24) or (r shl 16) or (g shl 8) or b
|
||||
}
|
||||
return Bitmap.createBitmap(argb, w, h, Bitmap.Config.ARGB_8888)
|
||||
}
|
||||
|
||||
/** Get the current frame as a Bitmap. */
|
||||
fun getFrame(): Bitmap? = synchronized(this) { currentBitmap }
|
||||
|
||||
// --- Input forwarding ---
|
||||
|
||||
fun sendKey(scancode: Int, pressed: Boolean) {
|
||||
if (closed) return
|
||||
client?.sendKey(scancode.toUShort(), pressed)
|
||||
}
|
||||
|
||||
fun sendUnicodeKey(codepoint: Int, pressed: Boolean) {
|
||||
if (closed) return
|
||||
client?.sendUnicodeKey(codepoint.toUInt(), pressed)
|
||||
}
|
||||
|
||||
fun sendMouseMove(x: Int, y: Int) {
|
||||
if (closed) return
|
||||
client?.sendMouseMove(x.toUShort(), y.toUShort())
|
||||
}
|
||||
|
||||
fun sendMouseButton(button: MouseButton, pressed: Boolean) {
|
||||
if (closed) return
|
||||
client?.sendMouseButton(button, pressed)
|
||||
}
|
||||
|
||||
fun sendMouseClick(x: Int, y: Int, button: MouseButton = MouseButton.LEFT) {
|
||||
if (closed) return
|
||||
client?.sendMouseMove(x.toUShort(), y.toUShort())
|
||||
client?.sendMouseButton(button, true)
|
||||
client?.sendMouseButton(button, false)
|
||||
}
|
||||
|
||||
fun sendMouseWheel(vertical: Boolean, delta: Int) {
|
||||
if (closed) return
|
||||
client?.sendMouseWheel(vertical, delta.toShort())
|
||||
}
|
||||
|
||||
fun sendClipboardText(text: String) {
|
||||
if (closed) return
|
||||
client?.sendClipboardText(text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the native EGFX frame timings into the verbose buffer (#477).
|
||||
*
|
||||
* These say whether decode is actually the bottleneck, and they used to go
|
||||
* only to the Android log — needing adb to read, so the one measurement
|
||||
* that settles a lag report was invisible to the people filing them.
|
||||
*
|
||||
* Best-effort: a diagnostic that breaks the log it is being written into
|
||||
* would be worse than no diagnostic.
|
||||
*/
|
||||
private fun drainNativePerfLog() {
|
||||
val lines = try {
|
||||
client?.takePerfLog().orEmpty()
|
||||
} catch (e: Exception) {
|
||||
log("E", "Could not read native perf log: ${e.message}")
|
||||
return
|
||||
}
|
||||
lines.forEach { log("D", it) }
|
||||
}
|
||||
|
||||
/** Drain captured verbose logs. Returns null if verbose logging was not enabled. */
|
||||
fun drainVerboseLog(): String? {
|
||||
val buf = verboseBuffer ?: return null
|
||||
// Before the empty check, not after: a session whose only entries are
|
||||
// perf lines would otherwise report having nothing to say.
|
||||
drainNativePerfLog()
|
||||
if (buf.isEmpty()) return null
|
||||
val sb = StringBuilder()
|
||||
while (true) {
|
||||
val line = buf.poll() ?: break
|
||||
sb.appendLine(line)
|
||||
}
|
||||
return sb.toString().trimEnd()
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
log("D", "Closing RDP session $sessionId")
|
||||
try {
|
||||
client?.disconnect()
|
||||
} catch (e: Exception) {
|
||||
log("E", "Error disconnecting RDP: ${e.message}")
|
||||
}
|
||||
client = null
|
||||
try {
|
||||
avcDecoder?.close()
|
||||
} catch (e: Exception) {
|
||||
log("E", "Error releasing AVC decoder: ${e.message}")
|
||||
}
|
||||
avcDecoder = null
|
||||
synchronized(this) {
|
||||
// #425: never recycle a bitmap the Compose viewer may still be
|
||||
// drawing (see onResize) — drop the ref and let GC reclaim it.
|
||||
currentBitmap = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import java.io.Closeable
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.Executors
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private const val TAG = "RdpSessionManager"
|
||||
|
||||
/**
|
||||
* Manages active RDP sessions across the app.
|
||||
* Same pattern as EtSessionManager / MoshSessionManager.
|
||||
*/
|
||||
@Singleton
|
||||
class RdpSessionManager @Inject constructor(
|
||||
@ApplicationContext private val context: android.content.Context,
|
||||
private val tlsCertVerifier: sh.haven.core.data.agent.TlsCertVerifier,
|
||||
) {
|
||||
|
||||
data class SessionState(
|
||||
val sessionId: String,
|
||||
val profileId: String,
|
||||
val label: String,
|
||||
val status: Status,
|
||||
val host: String = "",
|
||||
val port: Int = 3389,
|
||||
/** Stable server identity for the TLS cert pin (real remote for a
|
||||
* tunnelled session, where [host] is 127.0.0.1). */
|
||||
val certHost: String = "",
|
||||
val certPort: Int = 0,
|
||||
val username: String = "",
|
||||
val password: String = "",
|
||||
val domain: String = "",
|
||||
val rdpSession: RdpSession? = null,
|
||||
/** SSH client kept alive for tunneled connections (opaque Closeable). */
|
||||
val sshClient: Closeable? = null,
|
||||
/** Local port for SSH tunnel, if tunneled. */
|
||||
val tunnelPort: Int? = null,
|
||||
) {
|
||||
enum class Status { CONNECTING, CONNECTED, DISCONNECTED, ERROR }
|
||||
}
|
||||
|
||||
private val _sessions = MutableStateFlow<Map<String, SessionState>>(emptyMap())
|
||||
val sessions: StateFlow<Map<String, SessionState>> = _sessions.asStateFlow()
|
||||
|
||||
private val ioExecutor = Executors.newSingleThreadExecutor { r ->
|
||||
Thread(r, "rdp-session-io").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
val activeSessions: List<SessionState>
|
||||
get() = _sessions.value.values.filter {
|
||||
it.status == SessionState.Status.CONNECTED ||
|
||||
it.status == SessionState.Status.CONNECTING
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new session. Returns the generated sessionId.
|
||||
*/
|
||||
fun registerSession(profileId: String, label: String): String {
|
||||
val sessionId = UUID.randomUUID().toString()
|
||||
_sessions.update { map ->
|
||||
map + (sessionId to SessionState(
|
||||
sessionId = sessionId,
|
||||
profileId = profileId,
|
||||
label = label,
|
||||
status = SessionState.Status.CONNECTING,
|
||||
))
|
||||
}
|
||||
return sessionId
|
||||
}
|
||||
|
||||
/**
|
||||
* Store connection parameters for a registered session.
|
||||
*/
|
||||
fun connectSession(
|
||||
sessionId: String,
|
||||
host: String,
|
||||
port: Int,
|
||||
username: String,
|
||||
password: String,
|
||||
domain: String = "",
|
||||
sshClient: Closeable? = null,
|
||||
tunnelPort: Int? = null,
|
||||
// Real remote for the TLS cert pin; defaults to the socket target. For
|
||||
// an SSH-tunnelled session the caller passes the real remote so the pin
|
||||
// survives across sessions (the local tunnel port changes each time).
|
||||
certHost: String = host,
|
||||
certPort: Int = port,
|
||||
) {
|
||||
_sessions.value[sessionId]
|
||||
?: throw IllegalStateException("Session $sessionId not found")
|
||||
|
||||
Log.d(TAG, "Connecting RDP session: ${redactHost(host, port)} user=${redactUsername(username)} (ssh tunnel: ${sshClient != null})")
|
||||
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(
|
||||
status = SessionState.Status.CONNECTED,
|
||||
host = host,
|
||||
port = port,
|
||||
certHost = certHost,
|
||||
certPort = certPort,
|
||||
username = username,
|
||||
password = password,
|
||||
domain = domain,
|
||||
sshClient = sshClient,
|
||||
tunnelPort = tunnelPort,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an [RdpSession] for a connected session.
|
||||
* Returns the session instance ready to start.
|
||||
*/
|
||||
fun createRdpSession(sessionId: String): RdpSession? {
|
||||
val session = _sessions.value[sessionId] ?: return null
|
||||
if (session.status != SessionState.Status.CONNECTED) return null
|
||||
if (session.rdpSession != null) return null
|
||||
|
||||
val rdpSession = RdpSession(
|
||||
sessionId = sessionId,
|
||||
host = session.host,
|
||||
port = session.port,
|
||||
username = session.username,
|
||||
password = session.password,
|
||||
domain = session.domain,
|
||||
onDisconnected = {
|
||||
Log.d(TAG, "Session $sessionId disconnected")
|
||||
updateStatus(sessionId, SessionState.Status.DISCONNECTED)
|
||||
},
|
||||
tlsCertVerifier = tlsCertVerifier,
|
||||
certHost = session.certHost.ifEmpty { session.host },
|
||||
certPort = if (session.certPort != 0) session.certPort else session.port,
|
||||
)
|
||||
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(rdpSession = rdpSession))
|
||||
}
|
||||
|
||||
return rdpSession
|
||||
}
|
||||
|
||||
fun updateStatus(sessionId: String, status: SessionState.Status) {
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
// Clear password from memory when session is no longer active
|
||||
val clearPwd = status == SessionState.Status.DISCONNECTED ||
|
||||
status == SessionState.Status.ERROR
|
||||
map + (sessionId to existing.copy(
|
||||
status = status,
|
||||
password = if (clearPwd) "" else existing.password,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fun removeSession(sessionId: String) {
|
||||
val session = _sessions.value[sessionId] ?: return
|
||||
_sessions.update { it - sessionId }
|
||||
ioExecutor.execute {
|
||||
try {
|
||||
session.rdpSession?.close()
|
||||
session.sshClient?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "tearDown failed for $sessionId", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun removeAllSessionsForProfile(profileId: String) {
|
||||
val toRemove = _sessions.value.values.filter { it.profileId == profileId }
|
||||
_sessions.update { map -> map.filterValues { it.profileId != profileId } }
|
||||
ioExecutor.execute {
|
||||
toRemove.forEach { session ->
|
||||
try {
|
||||
session.rdpSession?.close()
|
||||
session.sshClient?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "tearDown failed for ${session.sessionId}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun disconnectSession(sessionId: String) {
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(
|
||||
status = SessionState.Status.DISCONNECTED,
|
||||
password = "",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fun disconnectAll() {
|
||||
val snapshot = _sessions.value.values.toList()
|
||||
_sessions.update { emptyMap() }
|
||||
ioExecutor.execute {
|
||||
snapshot.forEach { session ->
|
||||
try {
|
||||
session.rdpSession?.close()
|
||||
session.sshClient?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "tearDown failed for ${session.sessionId}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getSessionsForProfile(profileId: String): List<SessionState> =
|
||||
_sessions.value.values.filter { it.profileId == profileId }
|
||||
|
||||
fun isProfileConnected(profileId: String): Boolean =
|
||||
_sessions.value.values.any {
|
||||
it.profileId == profileId && it.status == SessionState.Status.CONNECTED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
/** An RDP logon identity split into the two fields the Client Info PDU carries. */
|
||||
data class RdpLogonName(val username: String, val domain: String)
|
||||
|
||||
/**
|
||||
* Split a qualified RDP username into the username and domain fields (#461).
|
||||
*
|
||||
* Windows will not auto-logon a Microsoft account unless the name is qualified
|
||||
* as `MicrosoftAccount\you@example.com`; a local account on a domain-joined box
|
||||
* often needs `.\you`. Users type those into Haven's username box because that
|
||||
* is what every guide tells them to, and Haven passed the whole string through
|
||||
* as the username with an empty domain — so Windows accepted the credentials at
|
||||
* the transport and then showed the lock screen anyway.
|
||||
*
|
||||
* The rule is deliberately narrow: **split what the user already qualified, and
|
||||
* never invent a qualification.** A bare `user@example.com` is left alone,
|
||||
* because it is indistinguishable from an Active Directory UPN — prefixing
|
||||
* `MicrosoftAccount\` on sight would log AD users out of their own domain to fix
|
||||
* a Microsoft-account case we cannot detect from the string. When someone means
|
||||
* a Microsoft account they can say so, and this makes saying so work.
|
||||
*
|
||||
* An explicit domain field always wins: if the profile already carries one, the
|
||||
* username is passed through untouched, so this can never override a choice the
|
||||
* user made deliberately.
|
||||
*/
|
||||
fun qualifyRdpLogon(rawUsername: String, rawDomain: String): RdpLogonName {
|
||||
val username = rawUsername.trim()
|
||||
val domain = rawDomain.trim()
|
||||
|
||||
// The user filled in the domain field — respect it, whatever the username
|
||||
// looks like. Splitting here would silently discard what they typed.
|
||||
if (domain.isNotEmpty()) return RdpLogonName(username, domain)
|
||||
|
||||
// Split on the FIRST backslash only, matching FreeRDP's
|
||||
// freerdp_parse_username_ptr (client/common/cmdline.c), whose comment
|
||||
// states the same rule about '@': "Do not break up the name for '@'; both
|
||||
// credSSP and the ClientInfo PDU expect 'user@corp.net' to be transmitted
|
||||
// as username 'user@corp.net', domain empty".
|
||||
val sep = username.indexOf('\\')
|
||||
if (sep < 0) {
|
||||
// Bare `user` and UPN `user@example.com` — both already correct.
|
||||
return RdpLogonName(username, "")
|
||||
}
|
||||
|
||||
val prefix = username.substring(0, sep)
|
||||
val account = username.substring(sep + 1)
|
||||
// `DOMAIN\` with nothing after it is a half-typed entry, not a
|
||||
// qualification. FreeRDP would yield an empty username here; keeping the
|
||||
// raw text at least fails with something the user can recognise.
|
||||
if (account.isEmpty()) return RdpLogonName(username, "")
|
||||
|
||||
// A leading `\user` leaves an empty domain, which is what FreeRDP produces
|
||||
// and what Windows accepts — dropping the stray separator is the point.
|
||||
return RdpLogonName(account, prefix)
|
||||
}
|
||||
|
||||
/**
|
||||
* A username's *shape* for logs, never the username itself.
|
||||
*
|
||||
* Haven's logs are meant to be attached to bug reports, and a reporter on #477
|
||||
* deleted three of them after noticing his Windows account name was in every
|
||||
* one. Anything written here can end up in a public issue, so it has to be
|
||||
* useful to whoever reads it and worthless to anyone else.
|
||||
*
|
||||
* The shape is kept because it has already mattered: #461 was sspi truncating
|
||||
* `me@example.com` at the `@` under NLA, and "does this name contain an @"
|
||||
* was the question that identified it. Length and qualification style answer
|
||||
* that without naming anybody.
|
||||
*/
|
||||
fun redactUsername(username: String): String = when {
|
||||
username.isEmpty() -> "<none>"
|
||||
username.contains('@') -> "<${username.length} chars, upn>"
|
||||
username.contains('\\') -> "<${username.length} chars, domain\\user>"
|
||||
else -> "<${username.length} chars>"
|
||||
}
|
||||
|
||||
/** The RDP port every client and server assumes, so naming it identifies nobody. */
|
||||
private const val DEFAULT_RDP_PORT = 3389
|
||||
|
||||
/**
|
||||
* A target's *shape* for logs, never the address itself (#477).
|
||||
*
|
||||
* The same reporter who found his account name in the logs found his server's
|
||||
* address and port there too. An internal address is still his network's
|
||||
* topology, and a public one names the machine outright.
|
||||
*
|
||||
* What is kept is what has actually been used to read these logs: whether the
|
||||
* profile holds a name that had to resolve or an address that did not, and
|
||||
* whether the port is the one everything defaults to. `<ipv4>` versus
|
||||
* `<hostname>` is the difference between a DNS failure and a routing one.
|
||||
*/
|
||||
fun redactHost(host: String, port: Int): String {
|
||||
val kind = when {
|
||||
host.isEmpty() -> "<no host>"
|
||||
// Bracketed or bare, a colon in a host is IPv6 — no hostname has one.
|
||||
host.contains(':') -> "<ipv6>"
|
||||
host.all { it.isDigit() || it == '.' } -> "<ipv4>"
|
||||
else -> "<hostname>"
|
||||
}
|
||||
return if (port == DEFAULT_RDP_PORT) kind else "$kind:<non-default port>"
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Test
|
||||
import java.nio.ByteBuffer
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* The plane repack that replaced the in-Kotlin BT.601 conversion (#466).
|
||||
*
|
||||
* The conversion itself moved to Rust and is checked there against a golden
|
||||
* digest generated from the Kotlin it replaced, so the *colours* are covered.
|
||||
* What did **not** move is the awkward part: real decoders hand back planes
|
||||
* with row strides wider than the image, chroma that may be planar or
|
||||
* interleaved, and an output smaller than the size Haven asked for. That logic
|
||||
* lives here now, and these are the cases the old conversion test covered.
|
||||
*
|
||||
* Each case is compared against a naive reference written independently of the
|
||||
* bulk-copy fast path, so "the fast path and the slow path agree" is the
|
||||
* assertion rather than "it did something".
|
||||
*/
|
||||
class Avc420I420PackTest {
|
||||
|
||||
/** Straightforward per-sample transcription of the intended behaviour. */
|
||||
private fun reference(
|
||||
out: ByteArray,
|
||||
offset: Int,
|
||||
buf: ByteBuffer,
|
||||
rowStride: Int,
|
||||
pixelStride: Int,
|
||||
dstW: Int,
|
||||
dstH: Int,
|
||||
srcW: Int,
|
||||
srcH: Int,
|
||||
) {
|
||||
var o = offset
|
||||
for (y in 0 until dstH) {
|
||||
val sy = if (y < srcH) y else srcH - 1
|
||||
for (x in 0 until dstW) {
|
||||
val sx = if (x < srcW) x else srcW - 1
|
||||
out[o++] = buf.get(sy * rowStride + sx * pixelStride)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun check(dstW: Int, dstH: Int, srcW: Int, srcH: Int, pixelStride: Int, seed: Int) {
|
||||
val rnd = Random(seed)
|
||||
// Row stride deliberately wider than the plane, as real decoders emit.
|
||||
val rowStride = srcW * pixelStride + 7
|
||||
val buf = ByteBuffer.wrap(ByteArray(rowStride * (srcH + 2)).also { rnd.nextBytes(it) })
|
||||
|
||||
val expected = ByteArray(dstW * dstH)
|
||||
reference(expected, 0, buf, rowStride, pixelStride, dstW, dstH, srcW, srcH)
|
||||
|
||||
val actual = ByteArray(dstW * dstH)
|
||||
Avc420MediaCodecDecoder().packPlane(
|
||||
actual, 0, buf, rowStride, pixelStride, dstW, dstH, srcW, srcH,
|
||||
)
|
||||
assertArrayEquals(
|
||||
"dst=${dstW}x$dstH src=${srcW}x$srcH pixelStride=$pixelStride",
|
||||
expected,
|
||||
actual,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `planar plane, exact fit`() = check(64, 32, 64, 32, pixelStride = 1, seed = 1)
|
||||
|
||||
@Test fun `semi-planar chroma, exact fit`() = check(32, 16, 32, 16, pixelStride = 2, seed = 2)
|
||||
|
||||
@Test fun `odd width`() = check(33, 16, 33, 16, pixelStride = 2, seed = 3)
|
||||
|
||||
@Test fun `requested wider than decoded replicates the edge column`() =
|
||||
check(64, 32, 60, 32, pixelStride = 1, seed = 4)
|
||||
|
||||
@Test fun `requested taller than decoded replicates the edge row`() =
|
||||
check(64, 32, 64, 28, pixelStride = 1, seed = 5)
|
||||
|
||||
@Test fun `odd decoded width with edge replication`() =
|
||||
check(64, 32, 31, 32, pixelStride = 2, seed = 6)
|
||||
|
||||
@Test fun `single decoded column`() = check(16, 8, 1, 8, pixelStride = 2, seed = 7)
|
||||
|
||||
/**
|
||||
* The bulk-copy path only applies when nothing needs replicating, so it
|
||||
* must agree with the per-sample path on the case it does take.
|
||||
*/
|
||||
@Test
|
||||
fun `the bulk-copy path agrees with the per-sample path`() {
|
||||
val rnd = Random(99)
|
||||
val w = 40
|
||||
val h = 12
|
||||
val rowStride = w + 9
|
||||
val buf = ByteBuffer.wrap(ByteArray(rowStride * h).also { rnd.nextBytes(it) })
|
||||
|
||||
val bulk = ByteArray(w * h)
|
||||
Avc420MediaCodecDecoder().packPlane(bulk, 0, buf, rowStride, 1, w, h, w, h)
|
||||
|
||||
// Force the per-sample branch by asking for one fewer source column.
|
||||
val perSample = ByteArray(w * h)
|
||||
reference(perSample, 0, buf, rowStride, 1, w, h, w, h)
|
||||
|
||||
assertArrayEquals(perSample, bulk)
|
||||
}
|
||||
|
||||
/** Writing at an offset must not disturb what is already in the buffer. */
|
||||
@Test
|
||||
fun `packing at an offset leaves earlier bytes alone`() {
|
||||
val buf = ByteBuffer.wrap(ByteArray(64) { (it + 1).toByte() })
|
||||
val out = ByteArray(40) { 0x7F }
|
||||
Avc420MediaCodecDecoder().packPlane(out, 8, buf, 8, 1, 4, 4, 4, 4)
|
||||
assertArrayEquals(ByteArray(8) { 0x7F }, out.copyOfRange(0, 8))
|
||||
assertArrayEquals(ByteArray(16) { 0x7F }, out.copyOfRange(24, 40))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import java.util.Locale
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* #504: the KLID announced at connect must follow the device locale. The
|
||||
* reporter's session announced US English on a Polish phone — harmless
|
||||
* against VirtualBox (raw scancodes), wrong against every server that
|
||||
* builds the session layout from the announcement.
|
||||
*/
|
||||
class KeyboardLayoutKlidTest {
|
||||
|
||||
@Test
|
||||
fun `polish maps to the polish programmers layout`() {
|
||||
assertEquals(0x0415u, keyboardLayoutKlid(Locale.forLanguageTag("pl-PL")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `english defaults to US but GB gets the UK layout`() {
|
||||
assertEquals(0x0409u, keyboardLayoutKlid(Locale.forLanguageTag("en-US")))
|
||||
assertEquals(0x0809u, keyboardLayoutKlid(Locale.forLanguageTag("en-GB")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `country variants pick their own layouts`() {
|
||||
assertEquals(0x0416u, keyboardLayoutKlid(Locale.forLanguageTag("pt-BR")))
|
||||
assertEquals(0x0816u, keyboardLayoutKlid(Locale.forLanguageTag("pt-PT")))
|
||||
assertEquals(0x0807u, keyboardLayoutKlid(Locale.forLanguageTag("de-CH")))
|
||||
assertEquals(0x0C0Cu, keyboardLayoutKlid(Locale.forLanguageTag("fr-CA")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown languages fall back to US — the pre-504 behaviour`() {
|
||||
assertEquals(0x0409u, keyboardLayoutKlid(Locale.forLanguageTag("sw-KE")))
|
||||
assertEquals(0x0409u, keyboardLayoutKlid(Locale.ROOT))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* #461: Windows 11 accepted the credentials and then showed the lock screen,
|
||||
* because a `MicrosoftAccount\you@example.com` typed into the username box was
|
||||
* sent whole as the username with an empty domain. Splitting it is the fix; the
|
||||
* tests that matter most here are the ones pinning what must NOT be split.
|
||||
*/
|
||||
class RdpUsernameTest {
|
||||
|
||||
@Test
|
||||
fun `a Microsoft account qualification is split into domain and user`() {
|
||||
assertEquals(
|
||||
RdpLogonName("you@example.com", "MicrosoftAccount"),
|
||||
qualifyRdpLogon("MicrosoftAccount\\you@example.com", ""),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a domain-qualified name is split`() {
|
||||
assertEquals(RdpLogonName("alice", "CORP"), qualifyRdpLogon("CORP\\alice", ""))
|
||||
}
|
||||
|
||||
/** `.\user` means "the local machine" and is a domain like any other here. */
|
||||
@Test
|
||||
fun `the local-machine prefix is split`() {
|
||||
assertEquals(RdpLogonName("alice", "."), qualifyRdpLogon(".\\alice", ""))
|
||||
}
|
||||
|
||||
/**
|
||||
* The one that stops this fix causing a worse bug: a bare UPN is a valid
|
||||
* Active Directory logon and must be passed through. Guessing
|
||||
* `MicrosoftAccount` here would break every AD user to help a Microsoft
|
||||
* account we cannot identify from the string.
|
||||
*/
|
||||
@Test
|
||||
fun `a bare UPN is never qualified`() {
|
||||
assertEquals(RdpLogonName("alice@corp.example.com", ""), qualifyRdpLogon("alice@corp.example.com", ""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a plain username is left alone`() {
|
||||
assertEquals(RdpLogonName("alice", ""), qualifyRdpLogon("alice", ""))
|
||||
}
|
||||
|
||||
/** An explicit domain is a deliberate choice; never override or discard it. */
|
||||
@Test
|
||||
fun `an explicit domain field wins over a qualified username`() {
|
||||
assertEquals(
|
||||
RdpLogonName("CORP\\alice", "OTHER"),
|
||||
qualifyRdpLogon("CORP\\alice", "OTHER"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an explicit domain is kept for an unqualified username`() {
|
||||
assertEquals(RdpLogonName("alice", "CORP"), qualifyRdpLogon("alice", "CORP"))
|
||||
}
|
||||
|
||||
/** Half-typed entries must not turn into an empty username. */
|
||||
@Test
|
||||
fun `a trailing separator is not a qualification`() {
|
||||
assertEquals(RdpLogonName("CORP\\", ""), qualifyRdpLogon("CORP\\", ""))
|
||||
}
|
||||
|
||||
/**
|
||||
* FreeRDP drops a leading separator and leaves the domain empty, which
|
||||
* Windows accepts; passing `\alice` through as the username would not work.
|
||||
*/
|
||||
@Test
|
||||
fun `a leading separator is dropped, leaving an empty domain`() {
|
||||
assertEquals(RdpLogonName("alice", ""), qualifyRdpLogon("\\alice", ""))
|
||||
}
|
||||
|
||||
/** Only the first separator splits — a password-manager paste may add more. */
|
||||
@Test
|
||||
fun `only the first separator splits`() {
|
||||
assertEquals(RdpLogonName("weird\\name", "CORP"), qualifyRdpLogon("CORP\\weird\\name", ""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `surrounding whitespace is trimmed`() {
|
||||
assertEquals(
|
||||
RdpLogonName("you@example.com", "MicrosoftAccount"),
|
||||
qualifyRdpLogon(" MicrosoftAccount\\you@example.com ", " "),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an empty username stays empty`() {
|
||||
assertEquals(RdpLogonName("", ""), qualifyRdpLogon("", ""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package sh.haven.core.rdp
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* #477: a reporter deleted three log attachments after noticing his Windows
|
||||
* account name was in every one, which stopped a diagnosis dead.
|
||||
*
|
||||
* The rule these pin is simple and easy to erode: whatever we print, none of
|
||||
* the name's characters may appear in it. The shape is kept deliberately —
|
||||
* #461 was sspi truncating `me@example.com` at the `@` under NLA, and "does
|
||||
* this name contain an @" was the question that found it.
|
||||
*/
|
||||
class RedactUsernameTest {
|
||||
|
||||
/**
|
||||
* The property that matters: the output tells you nothing about the
|
||||
* *content*. Two different names of the same length and qualification
|
||||
* style must redact to the same string.
|
||||
*
|
||||
* My first attempt asserted "no character of the name appears in the
|
||||
* output", which is a different and wrong property — the word "chars"
|
||||
* contains c, h, a, r and s, so any username using those letters failed a
|
||||
* correct implementation. Worth leaving noted: the test was the thing
|
||||
* that was broken.
|
||||
*/
|
||||
@Test
|
||||
fun `names of the same shape are indistinguishable after redaction`() {
|
||||
assertEquals(redactUsername("alice"), redactUsername("bobby"))
|
||||
assertEquals(redactUsername("Quickemu"), redactUsername("zzzzzzzz"))
|
||||
assertEquals(redactUsername("me@aa.com"), redactUsername("yo@bb.org"))
|
||||
assertEquals(redactUsername("CORP\\bob"), redactUsername("ACME\\joe"))
|
||||
}
|
||||
|
||||
/** And the name itself never appears. */
|
||||
@Test
|
||||
fun `the username is never quoted back`() {
|
||||
listOf(
|
||||
"Quickemu",
|
||||
"alice",
|
||||
"CORP\\bob",
|
||||
"me@example.com",
|
||||
"MicrosoftAccount\\someone@outlook.com",
|
||||
"Ian Williams",
|
||||
).forEach { name ->
|
||||
assertFalse(
|
||||
"redaction of '$name' quoted it back",
|
||||
redactUsername(name).contains(name),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the qualification style is kept, because it is what found 461`() {
|
||||
assertEquals("<14 chars, upn>", redactUsername("me@example.com"))
|
||||
assertEquals("<8 chars, domain\\user>", redactUsername("CORP\\bob"))
|
||||
assertEquals("<5 chars>", redactUsername("alice"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an empty username says so rather than printing nothing`() {
|
||||
assertEquals("<none>", redactUsername(""))
|
||||
}
|
||||
|
||||
/**
|
||||
* Length is a weak identifier on its own but a strong one combined with a
|
||||
* guess, so it is worth being deliberate that this is the trade: the
|
||||
* length is kept because "the server rejected an 18-character UPN" is a
|
||||
* usable report and "the server rejected a username" is not.
|
||||
*/
|
||||
@Test
|
||||
fun `length is reported`() {
|
||||
assertEquals("<3 chars>", redactUsername("abc"))
|
||||
assertEquals("<30 chars>", redactUsername("a".repeat(30)))
|
||||
}
|
||||
|
||||
/**
|
||||
* The follow-up on the same issue: the address and port went out in the
|
||||
* clear next to the (redacted) name. Same rule, same reason.
|
||||
*/
|
||||
@Test
|
||||
fun `the host is never quoted back`() {
|
||||
listOf(
|
||||
"192.168.1.100" to 3389,
|
||||
"10.0.0.7" to 13389,
|
||||
"desktop.lan" to 3389,
|
||||
"rdp.example.com" to 3391,
|
||||
"fe80::1" to 3389,
|
||||
).forEach { (host, port) ->
|
||||
val out = redactHost(host, port)
|
||||
assertFalse("redaction of '$host' quoted it back", out.contains(host))
|
||||
assertFalse("redaction of '$host:$port' quoted the port back", out.contains("$port"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the host kind is kept, because DNS and routing fail differently`() {
|
||||
assertEquals("<ipv4>", redactHost("192.168.1.100", 3389))
|
||||
assertEquals("<hostname>", redactHost("desktop.lan", 3389))
|
||||
assertEquals("<ipv6>", redactHost("fe80::1", 3389))
|
||||
assertEquals("<no host>", redactHost("", 3389))
|
||||
}
|
||||
|
||||
/** A non-default port is a real clue; the number itself is not needed. */
|
||||
@Test
|
||||
fun `only the fact of a non-default port survives`() {
|
||||
assertEquals("<ipv4>", redactHost("10.0.0.7", 3389))
|
||||
assertEquals("<ipv4>:<non-default port>", redactHost("10.0.0.7", 13389))
|
||||
assertEquals(redactHost("10.0.0.7", 3390), redactHost("10.0.0.7", 33890))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user