Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

feat(x11): render the desktop viewer on its own thread with GPU scaling

ExTvee85f97f0fd0
diff --git a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
index d232374..e6e5623 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
@@ -89,6 +89,7 @@ class SettingsRepository @Inject constructor(
val KEY_X11_ROTATION = stringPreferencesKey("x11_rotation_lock")
val KEY_X11_SHOW_EXTRA_KEYS = booleanPreferencesKey("x11_show_extra_keys")
val KEY_X11_DPI = intPreferencesKey("x11_dpi")
+ val KEY_X11_RENDER_SCALE = intPreferencesKey("x11_render_scale")
val KEY_LANGUAGE = stringPreferencesKey("language")
/**
@@ -254,6 +255,7 @@ class SettingsRepository @Inject constructor(
rotationLock = runCatching { com.excp.podroid.x11.RotationLock.valueOf(p[KEY_X11_ROTATION] ?: "AUTO") }.getOrDefault(com.excp.podroid.x11.RotationLock.AUTO),
showExtraKeys = p[KEY_X11_SHOW_EXTRA_KEYS] ?: true,
dpi = p[KEY_X11_DPI] ?: 96,
+ renderScale = (p[KEY_X11_RENDER_SCALE] ?: 100).let { if (it == 100 || it == 75 || it == 50) it else 100 },
)
}
@@ -269,6 +271,7 @@ class SettingsRepository @Inject constructor(
suspend fun setX11Rotation(v: String) = set(KEY_X11_ROTATION, v)
suspend fun setX11ShowExtraKeys(v: Boolean) = set(KEY_X11_SHOW_EXTRA_KEYS, v)
suspend fun setX11Dpi(v: Int) = set(KEY_X11_DPI, v)
+ suspend fun setX11RenderScale(v: Int) = set(KEY_X11_RENDER_SCALE, v)
suspend fun getX11DpiSnapshot() = (x11Settings.first()).dpi
suspend fun getLanguageSnapshot() = language.first()
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
index 2cb2945..6552859 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
@@ -5,8 +5,6 @@
package com.excp.podroid.ui.screens.x11
import android.content.pm.ActivityInfo
-import android.graphics.Bitmap
-import android.graphics.Rect
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
@@ -106,8 +104,10 @@ import com.excp.podroid.ui.components.PodroidTopBar
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.math.abs
+import com.excp.podroid.x11.RenderGeometry
import com.excp.podroid.x11.TouchMode
import com.excp.podroid.x11.VncClient
+import com.excp.podroid.x11.X11SurfaceRenderer
// X11 keysyms used outside the label table.
private const val XK_BackSpace = 0xFF08
@@ -167,12 +167,19 @@ fun X11Screen(
viewModel: X11ViewModel = hiltViewModel(),
) {
val connection by viewModel.connection.collectAsStateWithLifecycle()
- val frameCount by viewModel.frameCounter.collectAsStateWithLifecycle()
val fb by viewModel.fbSize.collectAsStateWithLifecycle()
- val bitmap = remember(fb) { Bitmap.createBitmap(fb.w, fb.h, Bitmap.Config.ARGB_8888) }
val s by viewModel.x11Settings.collectAsStateWithLifecycle()
LaunchedEffect(Unit) { viewModel.connect() }
+ // Owned by the AndroidView factory below; the ViewModel's onFrame hook
+ // (fired from the RFB read thread) just wakes it up to present on the
+ // next vsync instead of driving Compose recomposition per frame.
+ var renderer by remember { mutableStateOf<X11SurfaceRenderer?>(null) }
+ DisposableEffect(Unit) {
+ viewModel.onFrame = { renderer?.requestFrame() }
+ onDispose { viewModel.onFrame = null }
+ }
+
val activity = LocalActivity.current
// Restore orientation when leaving; without this the lock persists onto
// terminal/home until process restart.
@@ -231,20 +238,17 @@ fun X11Screen(
// beyond this baseline (or a width change) is a real surface resize.
var svGenuineHeight by remember { mutableIntStateOf(0) }
- // Letterbox / pillarbox dst rect, pinned to top so the soft keyboard
- // (and the extra-keys row) live in the empty bottom strip.
- val (dstX, dstY, dstW, dstH) = remember(svWidth, svHeight, fb) {
- val fbW = fb.w.toFloat()
- val fbH = fb.h.toFloat()
- val viewW = svWidth.toFloat().coerceAtLeast(1f)
- val viewH = svHeight.toFloat().coerceAtLeast(1f)
- val scale = minOf(viewW / fbW, viewH / fbH)
- val dW = (fbW * scale).toInt().coerceAtLeast(1)
- val dH = (fbH * scale).toInt().coerceAtLeast(1)
- val dX = ((viewW - dW) / 2f).toInt()
- val dY = 0
- IntArray4(dX, dY, dW, dH)
+ // Letterbox / pillarbox geometry, pinned to top so the soft keyboard (and
+ // the extra-keys row) live in the empty bottom strip. dstX/dstY/dstW/dstH
+ // (view px) drive input mapping below; the buffer-px fields drive
+ // X11SurfaceRenderer's setFixedSize + drawBitmap.
+ val geometry = remember(svWidth, svHeight, fb) {
+ RenderGeometry.compute(svWidth, svHeight, fb.w, fb.h)
}
+ val dstX = geometry.dstX
+ val dstY = geometry.dstY
+ val dstW = geometry.dstW
+ val dstH = geometry.dstH
val focusRequester = remember { FocusRequester() }
val viewerFocus = remember { FocusRequester() }
@@ -619,72 +623,52 @@ fun X11Screen(
},
factory = { ctx ->
SurfaceView(ctx).apply {
+ val r = X11SurfaceRenderer(
+ holder = holder,
+ frameBufferSize = { viewModel.framebuffer.size },
+ withFrame = { block -> viewModel.withFrame(block) },
+ debugRfbStats = { viewModel.debugSnapshotAndReset() },
+ presentHw = { viewModel.debugPresentHw },
+ )
+ renderer = r
holder.addCallback(object : SurfaceHolder.Callback {
- override fun surfaceCreated(h: SurfaceHolder) {}
- override fun surfaceChanged(h: SurfaceHolder, f: Int, w: Int, hh: Int) {
- // Ignore height changes caused by the IME opening/closing;
- // those reflow the layout but don't change the genuine surface
- // size. A width change resets the baseline (rotation/relayout);
- // otherwise only a height BEYOND the largest non-IME height seen
- // counts as a real resize. An IME dismiss grows hh back up to the
- // baseline and is correctly skipped.
- val widthChanged = w != svWidth
- if (widthChanged) svGenuineHeight = 0
- val heightGrew = hh > svGenuineHeight
- svWidth = w
- svHeight = hh
- if (heightGrew) svGenuineHeight = hh
- if (widthChanged || heightGrew) {
- viewModel.requestResolution(w, hh)
- }
- }
+ override fun surfaceCreated(h: SurfaceHolder) { r.onSurfaceCreated() }
+ override fun surfaceChanged(h: SurfaceHolder, f: Int, w: Int, hh: Int) { r.onSurfaceChanged() }
override fun surfaceDestroyed(h: SurfaceHolder) {}
})
- }
- },
- update = { sv ->
- @Suppress("UNUSED_EXPRESSION")
- frameCount
- // Lock the IntArray for the copy into Bitmap pixels so
- // we never observe a half-written frame from the RFB
- // decoder thread (paired with synchronized(fbLock)
- // in X11ViewModel.connect).
- synchronized(viewModel.fbLock) {
- val src = viewModel.framebuffer
- val bw = bitmap.width
- val bh = bitmap.height
- // During a resolution change the framebuffer array is
- // reallocated on the RFB thread while the Bitmap is
- // recreated on a (slightly later) recomposition. Blit
- // only when array and Bitmap agree in size, and clamp
- // against the Bitmap's OWN dimensions — otherwise skip
- // this frame (the next is consistent). Guards the
- // "y + height must be <= bitmap.height()" crash on open.
- if (src.size == bw * bh) {
- val damage = viewModel.lastDamage
- if (damage.isEmpty()) {
- bitmap.setPixels(src, 0, bw, 0, 0, bw, bh)
- } else {
- for (r in damage) {
- val rx = r.x.coerceIn(0, bw)
- val ry = r.y.coerceIn(0, bh)
- val rw = (r.x + r.w).coerceAtMost(bw) - rx
- val rh = (r.y + r.h).coerceAtMost(bh) - ry
- if (rw <= 0 || rh <= 0) continue
- bitmap.setPixels(src, ry * bw + rx, bw, rx, ry, rw, rh)
- }
+ // holder.setFixedSize (below, via the renderer) makes
+ // SurfaceHolder.Callback.surfaceChanged report the BUFFER
+ // size, not the view size, so the viewport used for
+ // requestResolution must come from layout size instead:
+ // otherwise feeding the buffer size back in would create a
+ // resize feedback loop. Same IME baseline rule as before:
+ // ignore height changes from the soft keyboard opening/
+ // closing (a width change resets the baseline; otherwise
+ // only a height BEYOND the largest non-IME height seen
+ // counts as a real resize; an IME dismiss grows height back
+ // up to the baseline and is correctly skipped).
+ addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
+ val w = right - left
+ val hh = bottom - top
+ if (w == oldRight - oldLeft && hh == oldBottom - oldTop) return@addOnLayoutChangeListener
+ val widthChanged = w != svWidth
+ if (widthChanged) svGenuineHeight = 0
+ val heightGrew = hh > svGenuineHeight
+ svWidth = w
+ svHeight = hh
+ if (heightGrew) svGenuineHeight = hh
+ if (widthChanged || heightGrew) {
+ viewModel.requestResolution(w, hh)
}
}
}
- val holder = sv.holder
- val canvas = holder.lockCanvas() ?: return@AndroidView
- try {
- canvas.drawColor(android.graphics.Color.BLACK)
- val dst = Rect(dstX, dstY, dstX + dstW, dstY + dstH)
- canvas.drawBitmap(bitmap, null, dst, null)
- } finally {
- holder.unlockCanvasAndPost(canvas)
- }
+ },
+ update = {
+ renderer?.updateGeometry(fb.w, fb.h, geometry)
+ },
+ onRelease = {
+ renderer?.release()
+ renderer = null
},
)
@@ -889,5 +873,3 @@ private fun forwardImeDiff(old: String, new: String, vm: X11ViewModel) {
i += Character.charCount(cp)
}
}
-
-private data class IntArray4(val a: Int, val b: Int, val c: Int, val d: Int)
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11SettingsSheet.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11SettingsSheet.kt
index 5bdf7e3..336d34a 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11SettingsSheet.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11SettingsSheet.kt
@@ -123,6 +123,30 @@ fun X11SettingsSheet(viewModel: X11ViewModel, onDismiss: () -> Unit) {
)
}
+ if (s.resolutionMode == ResolutionMode.MATCH) {
+ Spacer(Modifier.height(PodroidTokens.Spacing.SM))
+ PodroidSectionLabel(stringResource(R.string.x11_render_scale))
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ listOf(100, 75, 50).forEach { scale ->
+ FilterChip(
+ selected = s.renderScale == scale,
+ onClick = { viewModel.setRenderScale(scale) },
+ label = { Text("$scale%") },
+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),
+ colors = PodroidChipColors(),
+ )
+ }
+ }
+ Text(
+ stringResource(R.string.x11_render_scale_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+
// ── ROTATION ──────────────────────────────────────────────
PodroidSectionLabel(stringResource(R.string.rotation))
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
index fdbf6d7..d782cf1 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
@@ -4,15 +4,20 @@
*/
package com.excp.podroid.ui.screens.x11
+import android.content.Context
+import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.excp.podroid.BuildConfig
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.engine.VmEngine
import com.excp.podroid.engine.VmState
import com.excp.podroid.x11.AudioStreamer
+import com.excp.podroid.x11.DamageTracker
import com.excp.podroid.x11.ResolutionMode
import com.excp.podroid.x11.ResolutionPolicy
import com.excp.podroid.x11.ResolutionPreset
+import com.excp.podroid.x11.RfbDebugSnapshot
import com.excp.podroid.x11.RotationLock
import com.excp.podroid.x11.TouchMode
import com.excp.podroid.x11.VncClient
@@ -22,6 +27,7 @@ import com.excp.podroid.x11.X11Constants
import com.excp.podroid.x11.X11Settings
import com.excp.podroid.x11.ZrleDecoder
import dagger.hilt.android.lifecycle.HiltViewModel
+import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -33,6 +39,9 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
+import java.io.File
+import java.io.FilterInputStream
+import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
import java.net.Socket
@@ -50,6 +59,7 @@ sealed interface X11ConnectionState {
class X11ViewModel @Inject constructor(
val engine: VmEngine,
private val settings: SettingsRepository,
+ @ApplicationContext private val context: Context,
) : ViewModel() {
val vmState: StateFlow<VmState> = engine.state
@@ -73,10 +83,49 @@ class X11ViewModel @Inject constructor(
private val zrle = ZrleDecoder()
@Volatile private var screenId = 0
@Volatile private var desiredW = 0; @Volatile private var desiredH = 0
- @Volatile var lastDamage: List<VncRect> = emptyList(); private set
-
- private val _frameCounter = MutableStateFlow(0)
- val frameCounter: StateFlow<Int> = _frameCounter.asStateFlow()
+ // Guarded by fbLock, like framebuffer itself.
+ private val damageTracker = DamageTracker()
+
+ // Renderer hook: invoked outside fbLock after each recorded update so the
+ // renderer can schedule a redraw without the read loop depending on a
+ // StateFlow (which conflates and can silently drop damage between ticks).
+ @Volatile var onFrame: (() -> Unit)? = null
+
+ /** Takes fbLock and drains pending damage. Prefer [withFrame] when the pixel
+ * data is needed too, so the drain and the pixel copy share one critical
+ * section instead of two separate locks. */
+ fun drainDamage(): List<VncRect> = synchronized(fbLock) { damageTracker.drain() }
+
+ /** Atomically hands the current framebuffer, its dimensions, and the drained
+ * pending damage to [block] under fbLock. */
+ fun <T> withFrame(block: (fb: IntArray, fbW: Int, fbH: Int, damage: List<VncRect>) -> T): T =
+ synchronized(fbLock) { block(framebuffer, fbW, fbH, damageTracker.drain()) }
+
+ // Debug-only (BuildConfig.DEBUG) stats for the once-per-second X11Stats log
+ // assembled in X11SurfaceRenderer: bytes read off the RFB socket, framebuffer
+ // updates applied, time spent copying damaged rows + updating the damage
+ // tracker, and time from a FramebufferUpdate message's first byte to its
+ // full decode (rx = transfer + decode). Written from the single-threaded
+ // read loop in connect(), read and reset from the render thread via
+ // debugSnapshotAndReset(); the lock only guards this snapshot, never fbLock.
+ private val debugStatsLock = Any()
+ private var debugBytes = 0L
+ private var debugUpdates = 0L
+ private var debugCopyNanos = 0L
+ private var debugRxNanos = 0L
+ // Effective encoding for the current session (set once at connect() from
+ // x11-debug.conf, debug builds only); read cross-thread by the renderer.
+ @Volatile private var debugEncodingName = "raw"
+ // Effective present mode for the current session (used by Task F3);
+ // parsed here so the control file's format is settled before that lands.
+ @Volatile var debugPresentHw: Boolean = false; private set
+
+ /** Debug-only: atomically snapshots and resets (bytesRead, updates, copyNanos, rxNanos). */
+ fun debugSnapshotAndReset(): RfbDebugSnapshot = synchronized(debugStatsLock) {
+ val s = RfbDebugSnapshot(debugBytes, debugUpdates, debugCopyNanos, debugRxNanos, debugEncodingName)
+ debugBytes = 0L; debugUpdates = 0L; debugCopyNanos = 0L; debugRxNanos = 0L
+ s
+ }
private val audio = AudioStreamer()
private var sessionJob: Job? = null
@@ -109,7 +158,12 @@ class X11ViewModel @Inject constructor(
try {
rfbSocket = sock
sock.connect(InetSocketAddress("127.0.0.1", X11Constants.VNC_PORT), 2000)
- val inp = sock.getInputStream()
+ val rawInp = sock.getInputStream()
+ // Debug-only (BuildConfig.DEBUG): counts bytes read off the RFB
+ // socket for the X11Stats log; never wrapped in a release build.
+ val inp: InputStream = if (BuildConfig.DEBUG) {
+ CountingInputStream(rawInp) { n -> synchronized(debugStatsLock) { debugBytes += n } }
+ } else rawInp
val out = sock.getOutputStream()
rfbOut = out
// Each RFB session is a fresh zlib stream; reset the ZRLE inflater
@@ -117,22 +171,45 @@ class X11ViewModel @Inject constructor(
// inflater (which yields corrupt output or DataFormatException).
zrle.reset()
+ // Debug-only (BuildConfig.DEBUG): x11-debug.conf lets a developer
+ // flip the advertised encoding list (and, for Task F3, the present
+ // mode) without a rebuild. Release builds never read this file and
+ // always advertise VncClient.DEFAULT_ENCODINGS.
+ val encodings = if (BuildConfig.DEBUG) {
+ val cfg = X11DebugConfig.read(context)
+ debugEncodingName = cfg.encodingName
+ debugPresentHw = cfg.presentHw
+ Log.d("X11Stats", "debug-config encoding=${cfg.encodingName} present=${if (cfg.presentHw) "hw" else "sw"}")
+ cfg.encodings
+ } else {
+ VncClient.DEFAULT_ENCODINGS
+ }
+
VncClient.handshake(inp, out)
- VncClient.negotiatePixelFormat(out)
+ VncClient.negotiatePixelFormat(out, encodings)
if (desiredW > 0) VncClient.requestDesktopSize(out, screenId, desiredW, desiredH)
VncClient.requestFramebufferUpdate(out, w = fbW, h = fbH, incremental = false)
_connection.value = X11ConnectionState.Connected
audio.start(viewModelScope)
+ var rxT0 = 0L
while (isActive) {
- val upd = VncClient.readFramebufferUpdate(inp, scratch, fbW, zrle)
+ val upd = VncClient.readFramebufferUpdate(
+ inp, scratch, fbW, zrle,
+ onMessageStart = if (BuildConfig.DEBUG) { { rxT0 = System.nanoTime() } } else null,
+ )
+ if (BuildConfig.DEBUG) {
+ val rxElapsed = System.nanoTime() - rxT0
+ synchronized(debugStatsLock) { debugRxNanos += rxElapsed }
+ }
val ns = upd.newSize
if (ns != null && (ns.w != fbW || ns.h != fbH)) {
fbW = ns.w; fbH = ns.h
val fresh = IntArray(fbW * fbH)
- // Clear damage in the same critical section that swaps the
- // framebuffer so a recomposition between resize and the next
- // full frame can't blit stale damage rects against the new size.
- synchronized(fbLock) { framebuffer = fresh; lastDamage = emptyList() }
+ // Swap the framebuffer and mark the whole new frame dirty in
+ // the same critical section, so a recomposition between resize
+ // and the next full frame can't blit stale damage rects (or a
+ // stale bounding box) against the new size.
+ synchronized(fbLock) { framebuffer = fresh; damageTracker.invalidateAll(fbW, fbH) }
scratch = IntArray(fbW * fbH)
_fbSize.value = ns
cursor.value = android.graphics.Point(fbW / 2, fbH / 2)
@@ -149,11 +226,24 @@ class X11ViewModel @Inject constructor(
// incremental request.
continue
}
+ val debugT0 = if (BuildConfig.DEBUG) System.nanoTime() else 0L
synchronized(fbLock) {
- System.arraycopy(scratch, 0, framebuffer, 0, framebuffer.size)
- lastDamage = upd.damage
+ // scratch stays the authoritative full image (CopyRect reads
+ // from it), so only the damaged row-ranges need copying into
+ // the framebuffer the renderer reads.
+ for (r in upd.damage) {
+ for (row in 0 until r.h) {
+ val base = (r.y + row) * fbW + r.x
+ System.arraycopy(scratch, base, framebuffer, base, r.w)
+ }
+ }
+ damageTracker.add(upd.damage)
+ }
+ if (BuildConfig.DEBUG) {
+ val elapsed = System.nanoTime() - debugT0
+ synchronized(debugStatsLock) { debugUpdates++; debugCopyNanos += elapsed }
}
- _frameCounter.value = _frameCounter.value + 1
+ onFrame?.invoke()
// Same serialized path as input writes: queued FIFO behind any
// in-flight pointer/key message rather than colliding with it on
// the socket. Cadence is unchanged (one request per frame); the
@@ -272,6 +362,12 @@ class X11ViewModel @Inject constructor(
viewModelScope.launch { settings.setX11Dpi(v) }
}
+ fun setRenderScale(v: Int) {
+ viewModelScope.launch { settings.setX11RenderScale(v) }
+ val explicit = x11Settings.value.copy(renderScale = v)
+ reapplyResolution(explicit)
+ }
+
private fun reapplyResolution(explicit: X11Settings) {
if (lastViewportW <= 0) return
val t = ResolutionPolicy.target(explicit, lastViewportW, lastViewportH)
@@ -315,3 +411,58 @@ class X11ViewModel @Inject constructor(
const val MAX_RESOLUTION = 7680
}
}
+
+/**
+ * Debug-only (BuildConfig.DEBUG) reader for `filesDir/x11-debug.conf`: lets a
+ * developer flip the advertised SetEncodings list, and (Task F3) the present
+ * mode, without a rebuild. Read once per connect(), only when
+ * BuildConfig.DEBUG; release builds never call [read]. Format is `key=value`
+ * lines; a missing/unreadable file or an unrecognized value falls back to the
+ * default for that key.
+ */
+private object X11DebugConfig {
+ class Config(val encodings: IntArray, val encodingName: String, val presentHw: Boolean)
+
+ fun read(context: Context): Config {
+ var encodingName = "raw"
+ var presentName = "sw"
+ runCatching {
+ val f = File(context.filesDir, "x11-debug.conf")
+ if (f.isFile) {
+ f.forEachLine { line ->
+ val parts = line.split("=", limit = 2)
+ if (parts.size == 2) {
+ when (parts[0].trim()) {
+ "encoding" -> encodingName = parts[1].trim()
+ "present" -> presentName = parts[1].trim()
+ }
+ }
+ }
+ }
+ }
+ val zrle = encodingName == "zrle"
+ return Config(
+ encodings = if (zrle) VncClient.ZRLE_ENCODINGS else VncClient.DEFAULT_ENCODINGS,
+ encodingName = if (zrle) "zrle" else "raw",
+ presentHw = presentName == "hw",
+ )
+ }
+}
+
+/**
+ * Debug-only (BuildConfig.DEBUG) counting wrapper around the RFB socket's
+ * InputStream, feeding [X11ViewModel.debugSnapshotAndReset] for the
+ * once-per-second X11Stats log. Never constructed in a release build.
+ */
+private class CountingInputStream(inp: InputStream, private val onBytes: (Int) -> Unit) : FilterInputStream(inp) {
+ override fun read(): Int {
+ val b = super.read()
+ if (b >= 0) onBytes(1)
+ return b
+ }
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
+ val n = super.read(b, off, len)
+ if (n > 0) onBytes(n)
+ return n
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/x11/DamageTracker.kt b/app/src/main/java/com/excp/podroid/x11/DamageTracker.kt
new file mode 100644
index 0000000..2e73124
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/x11/DamageTracker.kt
@@ -0,0 +1,58 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.x11
+
+/**
+ * Accumulates RFB damage rects between renders so a renderer can copy only
+ * what changed instead of the whole framebuffer. Not thread-safe by itself:
+ * callers hold the framebuffer lock (X11ViewModel.fbLock) around every call.
+ */
+class DamageTracker {
+ private val pending = ArrayList<VncRect>()
+
+ /** Appends [rects]; once pending exceeds [CAP] entries, collapses them to one bounding box. */
+ fun add(rects: List<VncRect>) {
+ if (rects.isEmpty()) return
+ pending.addAll(rects)
+ if (pending.size > CAP) {
+ val box = boundingBox(pending)
+ pending.clear()
+ pending.add(box)
+ }
+ }
+
+ /** Marks the whole [w] x [h] frame dirty, replacing any finer-grained pending rects. */
+ fun invalidateAll(w: Int, h: Int) {
+ pending.clear()
+ pending.add(VncRect(0, 0, w, h))
+ }
+
+ /** Returns pending damage and clears it. An empty result means nothing new to draw. */
+ fun drain(): List<VncRect> {
+ if (pending.isEmpty()) return emptyList()
+ val out = ArrayList(pending)
+ pending.clear()
+ return out
+ }
+
+ private fun boundingBox(rects: List<VncRect>): VncRect {
+ var minX = rects[0].x
+ var minY = rects[0].y
+ var maxX = rects[0].x + rects[0].w
+ var maxY = rects[0].y + rects[0].h
+ for (i in 1 until rects.size) {
+ val r = rects[i]
+ if (r.x < minX) minX = r.x
+ if (r.y < minY) minY = r.y
+ if (r.x + r.w > maxX) maxX = r.x + r.w
+ if (r.y + r.h > maxY) maxY = r.y + r.h
+ }
+ return VncRect(minX, minY, maxX - minX, maxY - minY)
+ }
+
+ private companion object {
+ const val CAP = 32
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/x11/RenderGeometry.kt b/app/src/main/java/com/excp/podroid/x11/RenderGeometry.kt
new file mode 100644
index 0000000..8dcab53
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/x11/RenderGeometry.kt
@@ -0,0 +1,89 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.x11
+
+/**
+ * [dstX]/[dstY]/[dstW]/[dstH] is the letterbox rect in VIEW px (top-pinned,
+ * horizontally centered); used for input mapping. It is DERIVED from the
+ * buffer-space rect below (not computed independently), so it agrees with
+ * where the compositor actually draws the buffer within 1px on every edge.
+ *
+ * [bufW]/[bufH] is the SurfaceHolder buffer size ([android.view.SurfaceHolder.setFixedSize]),
+ * and [bufDstX]/[bufDstY]/[bufDstW]/[bufDstH] is the same letterbox rect but in
+ * BUFFER px: the buffer is sized so that rect is exactly the framebuffer's own
+ * size whenever [RenderGeometry.compute]'s `maxBuffer` allows it, so the
+ * renderer can `drawBitmap` at 1:1 (no CPU scaling) and let the compositor do
+ * the final scale-up from buffer px to view px when presenting the surface.
+ */
+data class RenderGeom(
+ val dstX: Int,
+ val dstY: Int,
+ val dstW: Int,
+ val dstH: Int,
+ val bufW: Int,
+ val bufH: Int,
+ val bufDstX: Int,
+ val bufDstY: Int,
+ val bufDstW: Int,
+ val bufDstH: Int,
+)
+
+object RenderGeometry {
+ /** Sane ceiling for a SurfaceHolder buffer / Bitmap dimension. */
+ const val DEFAULT_MAX_BUFFER = 4096
+
+ /**
+ * Pure geometry function: no Android types, safe to unit test directly.
+ * Zero/negative [viewW]/[viewH]/[fbW]/[fbH] are coerced to 1 first, so the
+ * result is always a valid, non-degenerate (>= 1x1 everywhere) geometry.
+ */
+ fun compute(viewW: Int, viewH: Int, fbW: Int, fbH: Int, maxBuffer: Int = DEFAULT_MAX_BUFFER): RenderGeom {
+ val vw = viewW.coerceAtLeast(1)
+ val vh = viewH.coerceAtLeast(1)
+ val fw = fbW.coerceAtLeast(1)
+ val fh = fbH.coerceAtLeast(1)
+ val vwD = vw.toDouble()
+ val vhD = vh.toDouble()
+ val fwD = fw.toDouble()
+ val fhD = fh.toDouble()
+
+ // Buffer space is computed first, in Double with rounding (not
+ // truncation): on the fit axis the raw value is mathematically
+ // exactly fbW or fbH, and Float truncation could shave it down to
+ // fbW-1/fbH-1, clipping the last framebuffer row/column. Clamp
+ // uniformly (preserving aspect) if that would exceed maxBuffer, then
+ // coerce each buffer dimension to be at least its own letterbox
+ // dimension so the letterbox rect always fits inside the buffer.
+ val scaleD = minOf(vwD / fwD, vhD / fhD)
+ val rawBufW = vwD / scaleD
+ val rawBufH = vhD / scaleD
+ val largest = maxOf(rawBufW, rawBufH)
+ val clamp = if (largest > maxBuffer) maxBuffer / largest else 1.0
+
+ val bufDstW = Math.round(fwD * clamp).toInt().coerceIn(1, maxBuffer)
+ val bufDstH = Math.round(fhD * clamp).toInt().coerceIn(1, maxBuffer)
+ val bufW = Math.round(rawBufW * clamp).toInt().coerceIn(bufDstW, maxBuffer)
+ val bufH = Math.round(rawBufH * clamp).toInt().coerceIn(bufDstH, maxBuffer)
+ val bufDstX = ((bufW - bufDstW) / 2).coerceAtLeast(0)
+ val bufDstY = 0
+
+ // View space is DERIVED from the buffer-space rect (single source of
+ // truth) instead of being recomputed independently from the fit
+ // scale: that used to leave the Float-truncated view rect and the
+ // Double-rounded buffer rect disagreeing by a few px once the
+ // compositor scaled the buffer up to the view, which threw off touch
+ // mapping (view rect) versus the drawn edge (buffer rect). Mapping
+ // buffer px back to view px via the buffer's own size keeps both
+ // within 1px of each other on every edge. Top pinning (dY = 0) is
+ // kept explicit; horizontal centering falls out of bufDstX already
+ // being centered in the buffer.
+ val dW = Math.round(bufDstW.toDouble() * vwD / bufW).toInt().coerceIn(1, vw)
+ val dH = Math.round(bufDstH.toDouble() * vhD / bufH).toInt().coerceIn(1, vh)
+ val dX = Math.round(bufDstX.toDouble() * vwD / bufW).toInt().coerceIn(0, vw - dW)
+ val dY = 0
+
+ return RenderGeom(dX, dY, dW, dH, bufW, bufH, bufDstX, bufDstY, bufDstW, bufDstH)
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/x11/VncClient.kt b/app/src/main/java/com/excp/podroid/x11/VncClient.kt
index ad849d8..b10020f 100644
--- a/app/src/main/java/com/excp/podroid/x11/VncClient.kt
+++ b/app/src/main/java/com/excp/podroid/x11/VncClient.kt
@@ -100,12 +100,23 @@ object VncClient {
private const val ENC_ZRLE = 16
private const val ENC_EXTENDED_DESKTOP_SIZE = -308
+ // Default SetEncodings list: CopyRect, Raw, ExtendedDesktopSize(-308). ZRLE
+ // is deliberately not in the default: the historical desync cause is fixed
+ // (ZrleDecoder now feeds the inflater on demand and bounds-checks palette
+ // indices/run lengths instead of dropping >4KB blocks), but re-enabling it
+ // changes what the server streams, so it stays gated until validated
+ // on-device against real Firefox/xfce tiles. Exposed for the debug-only
+ // encoding switch (x11-debug.conf, read only when BuildConfig.DEBUG).
+ val DEFAULT_ENCODINGS: IntArray = intArrayOf(ENC_COPY_RECT, ENC_RAW, ENC_EXTENDED_DESKTOP_SIZE)
+ val ZRLE_ENCODINGS: IntArray = intArrayOf(ENC_ZRLE, ENC_COPY_RECT, ENC_RAW, ENC_EXTENDED_DESKTOP_SIZE)
+
/**
* Sends SetPixelFormat to lock the server to 32-bit BGRA, then SetEncodings
- * to advertise Raw + CopyRect. Call once after handshake before requesting
- * any framebuffer update.
+ * to advertise [encodings] (default: Raw + CopyRect + ExtendedDesktopSize,
+ * byte-identical to the previously hardcoded list). Call once after
+ * handshake before requesting any framebuffer update.
*/
- fun negotiatePixelFormat(out: OutputStream) {
+ fun negotiatePixelFormat(out: OutputStream, encodings: IntArray = DEFAULT_ENCODINGS) {
// SetPixelFormat (msg=0): pad[3] + 16-byte PixelFormat
val pf = byteArrayOf(
0x00, 0x00, 0x00, 0x00, // msg + 3 pad
@@ -116,18 +127,10 @@ object VncClient {
)
out.write(pf)
- // SetEncodings (msg=2): CopyRect, Raw, ExtendedDesktopSize(-308).
- // ZRLE is still NOT advertised, but the historical desync cause is now
- // fixed: ZrleDecoder fed the inflater in chunks without draining, dropping
- // all but the last 4 KB of any block >4096 bytes ("invalid distance code").
- // It now feeds on demand and bounds-checks palette indices and run lengths.
- // Re-enabling ZRLE changes what the server streams, so it stays gated until
- // validated on-device against real Firefox/xfce tiles (a separate change).
- val se = java.nio.ByteBuffer.allocate(4 + 3 * 4)
- se.put(2.toByte()); se.put(0.toByte()); se.putShort(3)
- se.putInt(1) // CopyRect
- se.putInt(0) // Raw
- se.putInt(-308) // ExtendedDesktopSize
+ // SetEncodings (msg=2): header + one int32 per encoding, in order.
+ val se = java.nio.ByteBuffer.allocate(4 + encodings.size * 4)
+ se.put(2.toByte()); se.put(0.toByte()); se.putShort(encodings.size.toShort())
+ for (enc in encodings) se.putInt(enc)
out.write(se.array()); out.flush()
}
@@ -155,13 +158,27 @@ object VncClient {
data class RfbUpdate(val newSize: VncSize?, val damage: List<VncRect>)
- fun readFramebufferUpdate(inp: InputStream, targetArgb: IntArray, stride: Int, zrle: ZrleDecoder): RfbUpdate {
+ /**
+ * [onMessageStart], when non-null, is invoked exactly once, right when the
+ * message-type byte for the FramebufferUpdate itself is read (i.e. once
+ * its first byte is available on the wire), not for any Bell/
+ * SetColourMapEntries/ServerCutText messages skipped beforehand. Callers
+ * use this to time transfer + decode of one update without VncClient
+ * depending on any timing/stats type itself.
+ */
+ fun readFramebufferUpdate(
+ inp: InputStream,
+ targetArgb: IntArray,
+ stride: Int,
+ zrle: ZrleDecoder,
+ onMessageStart: (() -> Unit)? = null,
+ ): RfbUpdate {
val din = DataInputStream(inp)
var msgType: Int
while (true) {
msgType = din.readUnsignedByte()
when (msgType) {
- MSG_FRAMEBUFFER_UPDATE -> break
+ MSG_FRAMEBUFFER_UPDATE -> { onMessageStart?.invoke(); break }
1 -> { skipFully(din, 1); din.readUnsignedShort(); val n = din.readUnsignedShort(); skipFully(din, n * 6) }
2 -> { }
3 -> { skipFully(din, 3); val len = din.readInt(); if (len in 0..(1 shl 20)) skipFully(din, len) else throw java.io.IOException("ServerCutText absurd length=$len") }
@@ -191,14 +208,17 @@ object VncClient {
val rowPixels = rowBuf?.takeIf { it.size >= needed } ?: ByteArray(needed).also { rowBuf = it }
for (row in 0 until h) {
din.readFully(rowPixels, 0, needed)
- var off = 0; val base = (y + row) * stride + x
- for (col in 0 until w) {
- val b = rowPixels[off].toInt() and 0xFF
- val g = rowPixels[off + 1].toInt() and 0xFF
- val r = rowPixels[off + 2].toInt() and 0xFF
- targetArgb[base + col] = (0xFF shl 24) or (r shl 16) or (g shl 8) or b
- off += 4
- }
+ val base = (y + row) * stride + x
+ // Wire pixel is BGRX little-endian, so reading it as one
+ // little-endian int32 gives 0xXXRRGGBB directly (R shift
+ // 16, G shift 8, B shift 0); no per-byte masking needed.
+ // OR-ing 0xFF000000 forces alpha to 0xFF regardless of the
+ // padding byte X, matching the old per-byte loop exactly.
+ java.nio.ByteBuffer.wrap(rowPixels, 0, needed)
+ .order(java.nio.ByteOrder.LITTLE_ENDIAN)
+ .asIntBuffer()
+ .get(targetArgb, base, w)
+ for (col in base until base + w) targetArgb[col] = targetArgb[col] or (0xFF shl 24)
}
damage.add(VncRect(x, y, w, h))
}
diff --git a/app/src/main/java/com/excp/podroid/x11/X11Settings.kt b/app/src/main/java/com/excp/podroid/x11/X11Settings.kt
index e338d83..4ab0007 100644
--- a/app/src/main/java/com/excp/podroid/x11/X11Settings.kt
+++ b/app/src/main/java/com/excp/podroid/x11/X11Settings.kt
@@ -30,6 +30,7 @@ data class X11Settings(
val rotationLock: RotationLock = RotationLock.AUTO,
val showExtraKeys: Boolean = true,
val dpi: Int = 96,
+ val renderScale: Int = 100,
)
object ResolutionPolicy {
@@ -40,7 +41,10 @@ object ResolutionPolicy {
/** Target X-desktop size for the given settings + current viewport (device px). */
fun target(s: X11Settings, viewportW: Int, viewportH: Int): VncSize = when (s.resolutionMode) {
- ResolutionMode.MATCH -> VncSize(norm(viewportW, MIN), norm(viewportH, 240))
+ ResolutionMode.MATCH -> {
+ val scale = s.renderScale / 100f
+ VncSize(norm((viewportW * scale).toInt(), MIN), norm((viewportH * scale).toInt(), 240))
+ }
ResolutionMode.CUSTOM -> VncSize(norm(s.customW, MIN), norm(s.customH, 240))
ResolutionMode.PRESET -> {
val landscape = viewportW >= viewportH
diff --git a/app/src/main/java/com/excp/podroid/x11/X11SurfaceRenderer.kt b/app/src/main/java/com/excp/podroid/x11/X11SurfaceRenderer.kt
new file mode 100644
index 0000000..40123ce
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/x11/X11SurfaceRenderer.kt
@@ -0,0 +1,350 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.x11
+
+import android.graphics.Bitmap
+import android.graphics.Color
+import android.graphics.Rect
+import android.os.Handler
+import android.os.HandlerThread
+import android.os.Looper
+import android.util.Log
+import android.view.Choreographer
+import android.view.SurfaceHolder
+import com.excp.podroid.BuildConfig
+import java.util.concurrent.atomic.AtomicBoolean
+
+/**
+ * Debug-only (BuildConfig.DEBUG) snapshot of RFB-side stats for the
+ * once-per-second X11Stats log: bytes read off the socket, framebuffer
+ * updates applied, damaged-row copy time, time from a FramebufferUpdate
+ * message's first byte to its full decode (transfer + decode, excludes the
+ * idle wait before the message), and the currently advertised encoding.
+ */
+data class RfbDebugSnapshot(
+ val bytes: Long,
+ val updates: Long,
+ val copyNanos: Long,
+ val rxNanos: Long,
+ val encoding: String,
+)
+
+/**
+ * Dedicated render thread for the X11 viewer's SurfaceView. Paces
+ * presentation to vsync via [Choreographer] (at most one present per vsync),
+ * keeps the SurfaceHolder's own buffer sized per [RenderGeometry] so the
+ * compositor does the scale-up to the view's on-screen size instead of a
+ * per-frame CPU-scaled `drawBitmap`, and blits only the RFB-damaged rows each
+ * frame via [SurfaceHolder.lockCanvas] with a dirty rect.
+ *
+ * No Compose imports: X11Screen owns the SurfaceView, its lifecycle, and the
+ * ViewModel, and feeds geometry / frame-ready notifications in through the
+ * plain function references below.
+ */
+class X11SurfaceRenderer(
+ private val holder: SurfaceHolder,
+ // Non-draining peek at the current framebuffer array's length. Checked
+ // BEFORE calling [withFrame] so a frame whose Bitmap hasn't been resized
+ // to match a just-landed server resize yet can skip the copy WITHOUT
+ // draining the pending damage; draining here would discard the very
+ // invalidateAll() the eventually-resized Bitmap needs to fill itself in.
+ private val frameBufferSize: () -> Int,
+ // X11ViewModel.withFrame: atomically drains pending damage and hands back
+ // the framebuffer under the ViewModel's fbLock.
+ private val withFrame: ((fb: IntArray, fbW: Int, fbH: Int, damage: List<VncRect>) -> Unit) -> Unit,
+ // X11ViewModel.debugSnapshotAndReset: only called when BuildConfig.DEBUG,
+ // once per second, to assemble the combined X11Stats log line below.
+ private val debugRfbStats: () -> RfbDebugSnapshot,
+ // X11ViewModel.debugPresentHw: the F2 debug control file's present=hw|sw
+ // setting for this session. Always false (sw) in release builds, which
+ // never read that file. Consulted once per Surface, at its first present.
+ private val presentHw: () -> Boolean,
+) {
+ private val thread = HandlerThread("X11Render").apply { start() }
+ private val handler = Handler(thread.looper)
+ private val mainHandler = Handler(Looper.getMainLooper())
+
+ @Volatile private var choreographer: Choreographer? = null
+ private val framePending = AtomicBoolean(false)
+ @Volatile private var released = false
+
+ // Render-thread-confined state below; only ever touched on `handler`'s looper.
+ private var bitmap: Bitmap? = null
+ private var fbW = 0
+ private var fbH = 0
+ private var geom = RenderGeometry.compute(1, 1, 1, 1)
+ private var lastBufW = -1
+ private var lastBufH = -1
+ private var forceFullRedraw = true
+
+ // Debug-only (BuildConfig.DEBUG) counters for the once-per-second X11Stats
+ // log; render-thread-confined like the other fields above, reset each time
+ // the line is logged. pixMs = setPixels into the bitmap (doFrame); drawMs =
+ // lock + draw + unlockAndPost (present).
+ private var debugPresents = 0L
+ private var debugPixNanos = 0L
+ private var debugDrawNanos = 0L
+ private var debugLastLogNanos = 0L
+
+ // Render-thread-confined present-mode state. A Surface that has had
+ // lockHardwareCanvas() called stays HWUI-backed, so a software lockCanvas
+ // on it throws or returns null: the mode is therefore chosen once per
+ // Surface (null = not chosen yet, reset by onSurfaceCreated) and never
+ // switched from HW to SW on the same Surface. hwUnusable is sticky for the
+ // session once hw drawing has thrown; that Surface then skips frames
+ // (SKIP) and the next Surface picks SW.
+ private var surfaceMode: PresentMode? = null
+ private var hwUnusable = false
+
+ private enum class PresentMode { HW, SW, SKIP }
+
+ init {
+ handler.post { choreographer = Choreographer.getInstance() }
+ }
+
+ /** Called from the ViewModel's onFrame hook after a framebuffer update lands.
+ * Coalesces bursts: a callback already pending absorbs this request. */
+ fun requestFrame() {
+ if (released || !framePending.compareAndSet(false, true)) return
+ handler.post {
+ val c = choreographer
+ if (released) { framePending.set(false); return@post }
+ if (c == null) {
+ // First call can race Choreographer.getInstance() in init;
+ // draw directly rather than dropping the frame.
+ framePending.set(false)
+ doFrame()
+ return@post
+ }
+ c.postFrameCallback {
+ framePending.set(false)
+ if (!released) doFrame()
+ }
+ }
+ }
+
+ /** New view/framebuffer geometry: recreates the Bitmap when the framebuffer
+ * size changed and/or resizes the surface's own buffer when the target
+ * buffer size changed, then forces a full redraw either way. */
+ fun updateGeometry(newFbW: Int, newFbH: Int, newGeom: RenderGeom) {
+ if (released) return
+ handler.post {
+ if (newFbW != fbW || newFbH != fbH) {
+ fbW = newFbW; fbH = newFbH
+ bitmap = if (fbW > 0 && fbH > 0) Bitmap.createBitmap(fbW, fbH, Bitmap.Config.ARGB_8888) else null
+ forceFullRedraw = true
+ }
+ geom = newGeom
+ if (geom.bufW != lastBufW || geom.bufH != lastBufH) {
+ lastBufW = geom.bufW; lastBufH = geom.bufH
+ val w = geom.bufW; val h = geom.bufH
+ // setFixedSize interacts with the Surface's producer side; post
+ // it to the main thread as SurfaceHolder expects.
+ mainHandler.post { runCatching { holder.setFixedSize(w, h) } }
+ forceFullRedraw = true
+ }
+ }
+ requestFrame()
+ }
+
+ /** New Surface instance: re-pick the present mode at its first present
+ * and force a full redraw (buffer contents are undefined). */
+ fun onSurfaceCreated() {
+ if (released) return
+ handler.post { surfaceMode = null; forceFullRedraw = true }
+ requestFrame()
+ }
+
+ /** Surface changed: buffer contents are undefined, so force a full redraw. */
+ fun onSurfaceChanged() {
+ if (released) return
+ handler.post { forceFullRedraw = true }
+ requestFrame()
+ }
+
+ /** Stops the render thread. Does not recycle the Bitmap; a frame may still
+ * be mid-flight when this is called; let GC reclaim it once the thread
+ * (its only other reader) has actually quit. */
+ fun release() {
+ released = true
+ handler.removeCallbacksAndMessages(null)
+ thread.quitSafely()
+ }
+
+ private fun doFrame() {
+ val bmp = bitmap ?: return
+ val bw = bmp.width
+ val bh = bmp.height
+ var dirty: Rect? = null
+ if (frameBufferSize() == bw * bh) {
+ withFrame { fb, fw, _, damage ->
+ if (fb.size != bw * bh) {
+ // A resize landed on the RFB thread since the check above;
+ // our Bitmap hasn't caught up yet (updateGeometry does
+ // that once Compose collects the new fbSize). Skip the
+ // copy and retry on the next frame.
+ forceFullRedraw = true
+ return@withFrame
+ }
+ val debugT0 = if (BuildConfig.DEBUG) System.nanoTime() else 0L
+ for (r in damage) {
+ val rx = r.x.coerceIn(0, bw)
+ val ry = r.y.coerceIn(0, bh)
+ val rw = (r.x + r.w).coerceAtMost(bw) - rx
+ val rh = (r.y + r.h).coerceAtMost(bh) - ry
+ if (rw <= 0 || rh <= 0) continue
+ bmp.setPixels(fb, ry * fw + rx, fw, rx, ry, rw, rh)
+ val rect = Rect(rx, ry, rx + rw, ry + rh)
+ dirty = dirty?.apply { union(rect) } ?: rect
+ }
+ if (BuildConfig.DEBUG) debugPixNanos += System.nanoTime() - debugT0
+ }
+ }
+ val fullRedraw = forceFullRedraw
+ if (dirty == null && !fullRedraw) return
+ forceFullRedraw = false
+ present(bmp, dirty, fullRedraw)
+ }
+
+ private fun present(bmp: Bitmap, bitmapDirty: Rect?, fullRedraw: Boolean) {
+ val g = geom
+ val letterbox = Rect(g.bufDstX, g.bufDstY, g.bufDstX + g.bufDstW, g.bufDstY + g.bufDstH)
+ val mode = surfaceMode ?: (
+ if (presentHw() && !hwUnusable && bmp.byteCount < HW_MAX_BITMAP_BYTES) PresentMode.HW else PresentMode.SW
+ ).also { surfaceMode = it }
+ when (mode) {
+ PresentMode.HW -> presentHardware(bmp, letterbox)
+ PresentMode.SW -> presentSoftware(bmp, letterbox, bitmapDirty, fullRedraw)
+ // hw drawing threw on this Surface: nothing more can be posted to
+ // it; keep the bitmap and redraw it all on the next Surface.
+ PresentMode.SKIP -> forceFullRedraw = true
+ }
+ }
+
+ /** Hardware-canvas present: always a full redraw (hardware canvases don't
+ * preserve prior content or honor a dirty rect), so damage/geometry
+ * semantics are unaffected: only the bitmap-to-screen blit changes.
+ * A null lock (surface not ready, drawing stopped, or a swallowed lock
+ * error) skips this frame only. A RuntimeException from drawing/posting
+ * (e.g. a bitmap too large for a hardware canvas) is caught here so it
+ * never escapes doFrame, and marks hw unusable for the session. */
+ private fun presentHardware(bmp: Bitmap, letterbox: Rect) {
+ val debugT0 = if (BuildConfig.DEBUG) System.nanoTime() else 0L
+ val canvas = try {
+ holder.lockHardwareCanvas()
+ } catch (e: RuntimeException) {
+ null
+ }
+ if (canvas == null) {
+ forceFullRedraw = true
+ return
+ }
+ try {
+ try {
+ canvas.drawColor(Color.BLACK)
+ canvas.drawBitmap(bmp, null, letterbox, null)
+ } finally {
+ holder.unlockCanvasAndPost(canvas)
+ }
+ } catch (e: RuntimeException) {
+ hwUnusable = true
+ surfaceMode = PresentMode.SKIP
+ forceFullRedraw = true
+ Log.w("X11Stats", "hw present failed; skipping frames on this surface, sw from the next one", e)
+ return
+ }
+ if (BuildConfig.DEBUG) {
+ debugPresents++
+ debugDrawNanos += System.nanoTime() - debugT0
+ maybeLogDebugStats(usedHw = true)
+ }
+ }
+
+ private fun presentSoftware(bmp: Bitmap, letterbox: Rect, bitmapDirty: Rect?, fullRedraw: Boolean) {
+ val g = geom
+ val unclamped = g.bufDstW == bmp.width && g.bufDstH == bmp.height
+ val requestDirty = when {
+ fullRedraw || !unclamped -> null
+ bitmapDirty != null -> Rect(
+ bitmapDirty.left + g.bufDstX, bitmapDirty.top + g.bufDstY,
+ bitmapDirty.right + g.bufDstX, bitmapDirty.bottom + g.bufDstY,
+ )
+ else -> null
+ }
+ val debugT0 = if (BuildConfig.DEBUG) System.nanoTime() else 0L
+ val canvas = try {
+ holder.lockCanvas(requestDirty)
+ } catch (e: Exception) {
+ null
+ }
+ if (canvas == null) {
+ // Damage was already drained and copied into the bitmap; redraw
+ // all of it on the next successful present instead of losing it.
+ forceFullRedraw = true
+ return
+ }
+ try {
+ // lockCanvas(dirty) clips the canvas to what it actually agreed to
+ // redraw, which may be larger than requested (e.g. the first
+ // frame after create/resize, or a null/full request): read that
+ // back rather than trusting requestDirty, and redraw everything
+ // the returned clip covers.
+ val actual = Rect()
+ if (!canvas.getClipBounds(actual)) actual.set(0, 0, g.bufW, g.bufH)
+ canvas.drawColor(Color.BLACK)
+ val dst = Rect(actual)
+ if (dst.intersect(letterbox)) {
+ if (unclamped) {
+ val src = Rect(dst.left - g.bufDstX, dst.top - g.bufDstY, dst.right - g.bufDstX, dst.bottom - g.bufDstY)
+ canvas.drawBitmap(bmp, src, dst, null)
+ } else {
+ // Clamped case only: the letterbox rect in buffer px is
+ // smaller than the Bitmap, so this draw scales (rare:
+ // only when the framebuffer itself is huge).
+ canvas.drawBitmap(bmp, null, letterbox, null)
+ }
+ }
+ } finally {
+ holder.unlockCanvasAndPost(canvas)
+ }
+ if (BuildConfig.DEBUG) {
+ debugPresents++
+ debugDrawNanos += System.nanoTime() - debugT0
+ maybeLogDebugStats(usedHw = false)
+ }
+ }
+
+ /** Debug-only: logs one X11Stats line at most once per second, combining
+ * this renderer's presents/pix-time/draw-time with the ViewModel's
+ * RFB-side bytes/updates/copy-time. Called only from [presentHardware] /
+ * [presentSoftware], themselves gated on BuildConfig.DEBUG, so this never
+ * runs in a release build. */
+ private fun maybeLogDebugStats(usedHw: Boolean) {
+ val now = System.nanoTime()
+ if (now - debugLastLogNanos < 1_000_000_000L) return
+ debugLastLogNanos = now
+ val snap = debugRfbStats()
+ val presents = debugPresents
+ val pixNanos = debugPixNanos
+ val drawNanos = debugDrawNanos
+ debugPresents = 0L
+ debugPixNanos = 0L
+ debugDrawNanos = 0L
+ Log.d(
+ "X11Stats",
+ "updates=%d bytesKB=%d copyMs=%.1f rxMs=%.1f presents=%d pixMs=%.1f drawMs=%.1f fb=%dx%d enc=%s present=%s".format(
+ snap.updates, snap.bytes / 1024, snap.copyNanos / 1_000_000.0, snap.rxNanos / 1_000_000.0,
+ presents, pixNanos / 1_000_000.0, drawNanos / 1_000_000.0, fbW, fbH, snap.encoding,
+ if (usedHw) "hw" else "sw",
+ ),
+ )
+ }
+
+ private companion object {
+ // Hardware canvases reject bitmaps above RecordingCanvas.MAX_BITMAP_SIZE
+ // (about 100 MB floor); stay safely below it when picking HW.
+ const val HW_MAX_BITMAP_BYTES = 90 * 1024 * 1024
+ }
+}
diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml
index fbe84b9..88302cf 100644
--- a/app/src/main/res/values-zh/strings.xml
+++ b/app/src/main/res/values-zh/strings.xml
@@ -277,6 +277,8 @@
<string name="res_900p">900p</string>
<string name="res_1080p">1080p</string>
<string name="res_1440p">1440p</string>
+ <string name="x11_render_scale">渲染比例</string>
+ <string name="x11_render_scale_hint">数值越低越流畅,桌面会放大以适应屏幕。</string>
<string name="rotation">旋转</string>
<string name="auto_rotation">自动</string>
<string name="landscape">横屏</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index f2be0a6..752f973 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -277,6 +277,8 @@
<string name="res_900p">900p</string>
<string name="res_1080p">1080p</string>
<string name="res_1440p">1440p</string>
+ <string name="x11_render_scale">Render scale</string>
+ <string name="x11_render_scale_hint">Lower is faster. The desktop is scaled up to fit the screen.</string>
<string name="rotation">Rotation</string>
<string name="auto_rotation">Auto</string>
<string name="landscape">Landscape</string>
diff --git a/app/src/test/java/com/excp/podroid/x11/DamageTrackerTest.kt b/app/src/test/java/com/excp/podroid/x11/DamageTrackerTest.kt
new file mode 100644
index 0000000..07d1a77
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/x11/DamageTrackerTest.kt
@@ -0,0 +1,102 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.x11
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class DamageTrackerTest {
+
+ @Test fun `drain on a fresh tracker returns empty`() {
+ assertTrue(DamageTracker().drain().isEmpty())
+ }
+
+ @Test fun `add then drain returns exactly the added rects`() {
+ val t = DamageTracker()
+ t.add(listOf(VncRect(0, 0, 10, 10), VncRect(20, 20, 5, 5)))
+
+ val drained = t.drain()
+
+ assertEquals(listOf(VncRect(0, 0, 10, 10), VncRect(20, 20, 5, 5)), drained)
+ }
+
+ @Test fun `drain clears pending so a second drain is empty`() {
+ val t = DamageTracker()
+ t.add(listOf(VncRect(0, 0, 10, 10)))
+ t.drain()
+
+ assertTrue(t.drain().isEmpty())
+ }
+
+ @Test fun `add with an empty list is a no-op`() {
+ val t = DamageTracker()
+ t.add(emptyList())
+
+ assertTrue(t.drain().isEmpty())
+ }
+
+ @Test fun `rects accumulate across multiple add calls before a drain`() {
+ val t = DamageTracker()
+ t.add(listOf(VncRect(0, 0, 1, 1)))
+ t.add(listOf(VncRect(5, 5, 1, 1)))
+
+ assertEquals(listOf(VncRect(0, 0, 1, 1), VncRect(5, 5, 1, 1)), t.drain())
+ }
+
+ @Test fun `exceeding the cap collapses pending rects to one bounding box`() {
+ val t = DamageTracker()
+ // 33 disjoint 1x1 rects on a diagonal exceeds the 32-entry cap, so they
+ // collapse to a single rect spanning the full diagonal.
+ repeat(33) { i -> t.add(listOf(VncRect(i, i, 1, 1))) }
+
+ val drained = t.drain()
+
+ assertEquals(1, drained.size)
+ assertEquals(VncRect(0, 0, 33, 33), drained[0])
+ }
+
+ @Test fun `at exactly the cap rects are not collapsed`() {
+ val t = DamageTracker()
+ repeat(32) { i -> t.add(listOf(VncRect(i, i, 1, 1))) }
+
+ assertEquals(32, t.drain().size)
+ }
+
+ @Test fun `invalidateAll replaces pending rects with one full-frame rect`() {
+ val t = DamageTracker()
+ t.add(listOf(VncRect(0, 0, 1, 1), VncRect(50, 50, 1, 1)))
+
+ t.invalidateAll(1280, 720)
+
+ assertEquals(listOf(VncRect(0, 0, 1280, 720)), t.drain())
+ }
+
+ @Test fun `invalidateAll on an empty tracker still yields a full-frame rect`() {
+ val t = DamageTracker()
+
+ t.invalidateAll(640, 480)
+
+ assertEquals(listOf(VncRect(0, 0, 640, 480)), t.drain())
+ }
+
+ @Test fun `bounding box collapse covers rects on both axes`() {
+ val t = DamageTracker()
+ // 34 rects added in one call exceeds the 32-entry cap, forcing an
+ // immediate collapse; the box must span both the x-run and the
+ // vertically offset outlier.
+ val rects = (0 until 33).map { i -> VncRect(i, 0, 1, 1) } + VncRect(0, 50, 1, 1)
+ t.add(rects)
+
+ val drained = t.drain()
+
+ assertEquals(1, drained.size)
+ val box = drained[0]
+ assertEquals(0, box.x)
+ assertEquals(0, box.y)
+ assertEquals(33, box.x + box.w)
+ assertEquals(51, box.y + box.h)
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/x11/RenderGeometryTest.kt b/app/src/test/java/com/excp/podroid/x11/RenderGeometryTest.kt
new file mode 100644
index 0000000..a58f1af
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/x11/RenderGeometryTest.kt
@@ -0,0 +1,256 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.x11
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class RenderGeometryTest {
+
+ @Test fun `exact fit uses the whole view and buffer equals framebuffer size`() {
+ val g = RenderGeometry.compute(viewW = 1280, viewH = 720, fbW = 1280, fbH = 720)
+
+ assertEquals(0, g.dstX); assertEquals(0, g.dstY)
+ assertEquals(1280, g.dstW); assertEquals(720, g.dstH)
+ assertEquals(1280, g.bufW); assertEquals(720, g.bufH)
+ assertEquals(0, g.bufDstX); assertEquals(0, g.bufDstY)
+ assertEquals(1280, g.bufDstW); assertEquals(720, g.bufDstH)
+ }
+
+ @Test fun `landscape framebuffer in a portrait view is top-pinned and centered`() {
+ val g = RenderGeometry.compute(viewW = 1080, viewH = 1920, fbW = 1280, fbH = 720)
+
+ // View-space letterbox: full width used, pinned to the top, extra
+ // space (if any) left at the bottom.
+ assertEquals(0, g.dstY)
+ assertEquals(0, g.dstX)
+ assertEquals(1080, g.dstW)
+ assertTrue(g.dstH in 1..1920)
+ // Buffer-space letterbox mirrors the same top-pinned/centered layout
+ // and, unclamped, is exactly the framebuffer's own size.
+ assertEquals(0, g.bufDstY)
+ assertEquals(1280, g.bufDstW)
+ assertEquals(720, g.bufDstH)
+ assertEquals(0, g.bufDstX)
+ }
+
+ @Test fun `framebuffer larger than the view still fits and centers`() {
+ val g = RenderGeometry.compute(viewW = 400, viewH = 800, fbW = 1920, fbH = 1080)
+
+ assertEquals(0, g.dstY)
+ assertTrue(g.dstW <= 400)
+ assertTrue(g.dstH <= 800)
+ assertEquals(1920, g.bufDstW)
+ assertEquals(1080, g.bufDstH)
+ }
+
+ @Test fun `clamping at maxBuffer keeps the buffer letterbox aspect close to the framebuffer's`() {
+ // A huge framebuffer relative to maxBuffer forces the clamp path.
+ val g = RenderGeometry.compute(viewW = 1080, viewH = 1920, fbW = 7680, fbH = 4320, maxBuffer = 2048)
+
+ assertTrue(g.bufW <= 2048)
+ assertTrue(g.bufH <= 2048)
+ // Clamped, so the buffer-space letterbox is smaller than the real
+ // framebuffer, but its aspect ratio must still match fbW:fbH.
+ assertTrue(g.bufDstW < 7680)
+ val fbAspect = 7680.0 / 4320.0
+ val bufDstAspect = g.bufDstW.toDouble() / g.bufDstH.toDouble()
+ assertTrue(Math.abs(fbAspect - bufDstAspect) < 0.02)
+ }
+
+ @Test fun `degenerate zero and negative inputs never crash and stay at least 1x1`() {
+ val cases = listOf(
+ RenderGeometry.compute(0, 0, 0, 0),
+ RenderGeometry.compute(-5, -5, -5, -5),
+ RenderGeometry.compute(100, 100, 0, 0),
+ RenderGeometry.compute(0, 0, 100, 100),
+ )
+ for (g in cases) {
+ assertTrue(g.dstW >= 1); assertTrue(g.dstH >= 1)
+ assertTrue(g.bufW >= 1); assertTrue(g.bufH >= 1)
+ assertTrue(g.bufDstW >= 1); assertTrue(g.bufDstH >= 1)
+ }
+ }
+
+ @Test fun `unclamped buffer letterbox always equals the framebuffer size exactly`() {
+ val cases = listOf(
+ RenderGeometry.compute(1920, 1080, 1280, 720),
+ RenderGeometry.compute(600, 1200, 1920, 1080),
+ RenderGeometry.compute(2000, 1000, 640, 480),
+ )
+ for (g in cases) {
+ assertTrue(g.bufW <= RenderGeometry.DEFAULT_MAX_BUFFER)
+ assertTrue(g.bufH <= RenderGeometry.DEFAULT_MAX_BUFFER)
+ }
+ val g0 = cases[0]
+ assertEquals(1280, g0.bufDstW); assertEquals(720, g0.bufDstH)
+ val g1 = cases[1]
+ assertEquals(1920, g1.bufDstW); assertEquals(1080, g1.bufDstH)
+ val g2 = cases[2]
+ assertEquals(640, g2.bufDstW); assertEquals(480, g2.bufDstH)
+ }
+
+ @Test fun `307x313 view with 306x312 framebuffer does not clip the last row`() {
+ // Regression case: Float truncation on the fit axis (height) used to
+ // land bufH on fbH-1 (311) while bufDstH stayed fbH (312), so the
+ // letterbox rect overflowed the buffer by one pixel.
+ val g = RenderGeometry.compute(viewW = 307, viewH = 313, fbW = 306, fbH = 312)
+
+ assertEquals(306, g.bufDstW); assertEquals(312, g.bufDstH)
+ assertTrue(g.bufW >= g.bufDstW)
+ assertTrue(g.bufH >= g.bufDstH)
+ assertTrue(g.bufDstX + g.bufDstW <= g.bufW)
+ assertTrue(g.bufDstY + g.bufDstH <= g.bufH)
+ }
+
+ @Test fun `brute-force sweep never lets the buffer letterbox overflow the buffer`() {
+ val fbSizes = listOf(
+ 1920 to 1080,
+ 1280 to 720,
+ 306 to 312,
+ Math.round(2400 * 0.75).toInt() to Math.round(1080 * 0.75 / 2).toInt() * 2,
+ )
+ val maxBuffer = RenderGeometry.DEFAULT_MAX_BUFFER
+
+ for ((fbW, fbH) in fbSizes) {
+ var viewW = 200
+ while (viewW <= 400) {
+ var viewH = 200
+ while (viewH <= 400) {
+ val g = RenderGeometry.compute(viewW, viewH, fbW, fbH, maxBuffer)
+
+ // Fit-inside property: the buffer-space letterbox rect
+ // never overflows the buffer, clamped or not.
+ assertTrue(
+ "overflow x for view=${viewW}x$viewH fb=${fbW}x$fbH: $g",
+ g.bufDstX + g.bufDstW <= g.bufW,
+ )
+ assertTrue(
+ "overflow y for view=${viewW}x$viewH fb=${fbW}x$fbH: $g",
+ g.bufDstY + g.bufDstH <= g.bufH,
+ )
+ assertTrue(g.bufW <= maxBuffer)
+ assertTrue(g.bufH <= maxBuffer)
+
+ // Mirror compute()'s own pre-clamp math to know whether
+ // this case is expected to hit the maxBuffer clamp.
+ val scale = minOf(viewW.toDouble() / fbW, viewH.toDouble() / fbH)
+ val rawBufW = viewW / scale
+ val rawBufH = viewH / scale
+ val clamped = maxOf(rawBufW, rawBufH) > maxBuffer
+ if (!clamped) {
+ assertEquals(
+ "bufDstW for view=${viewW}x$viewH fb=${fbW}x$fbH: $g",
+ fbW,
+ g.bufDstW,
+ )
+ assertEquals(
+ "bufDstH for view=${viewW}x$viewH fb=${fbW}x$fbH: $g",
+ fbH,
+ g.bufDstH,
+ )
+ }
+
+ viewH += 7
+ }
+ viewW += 7
+ }
+ }
+ }
+
+ @Test fun `view rect stays within 1px of the buffer rect mapped back to view space`() {
+ val fbSizes = listOf(
+ 1920 to 1080,
+ 1080 to 1920,
+ 1280 to 720,
+ 2560 to 1440,
+ 306 to 312,
+ 1800 to 810,
+ 810 to 1800,
+ )
+
+ for ((fbW, fbH) in fbSizes) {
+ var viewW = 100
+ while (viewW <= 3200) {
+ var viewH = 100
+ while (viewH <= 3200) {
+ val g = RenderGeometry.compute(viewW, viewH, fbW, fbH)
+ val label = "view=${viewW}x$viewH fb=${fbW}x$fbH: $g"
+
+ // Fit-inside in buffer space.
+ assertTrue("buffer overflow x for $label", g.bufDstX + g.bufDstW <= g.bufW)
+ assertTrue("buffer overflow y for $label", g.bufDstY + g.bufDstH <= g.bufH)
+
+ // View rect stays within the viewport.
+ assertTrue("view dstX for $label", g.dstX >= 0)
+ assertTrue("view dstY for $label", g.dstY >= 0)
+ assertTrue("view overflow x for $label", g.dstX + g.dstW <= viewW)
+ assertTrue("view overflow y for $label", g.dstY + g.dstH <= viewH)
+
+ // The buffer rect, mapped back to view space, must land
+ // within 1px of the view rect on every edge - this is
+ // the property touch mapping (view rect) relies on to
+ // agree with the drawn edge (buffer rect, scaled up by
+ // the compositor).
+ val mappedLeft = g.bufDstX.toDouble() * viewW / g.bufW
+ val mappedRight = (g.bufDstX + g.bufDstW).toDouble() * viewW / g.bufW
+ val mappedTop = g.bufDstY.toDouble() * viewH / g.bufH
+ val mappedBottom = (g.bufDstY + g.bufDstH).toDouble() * viewH / g.bufH
+
+ assertTrue("left edge for $label", Math.abs(mappedLeft - g.dstX) <= 1.0)
+ assertTrue(
+ "right edge for $label",
+ Math.abs(mappedRight - (g.dstX + g.dstW)) <= 1.0,
+ )
+ assertTrue("top edge for $label", Math.abs(mappedTop - g.dstY) <= 1.0)
+ assertTrue(
+ "bottom edge for $label",
+ Math.abs(mappedBottom - (g.dstY + g.dstH)) <= 1.0,
+ )
+
+ viewH += 13
+ }
+ viewW += 13
+ }
+ }
+ }
+
+ @Test fun `height-constrained cases center horizontally within 1px in both view and buffer space`() {
+ // Each case is narrower (fbW / fbH) than the view, so the height
+ // axis is the fit constraint and horizontal bars appear on both
+ // sides - the scenario the suite previously never exercised (dstX
+ // and bufDstX both non-zero).
+ data class Case(val viewW: Int, val viewH: Int, val fbW: Int, val fbH: Int)
+ val cases = listOf(
+ Case(1920, 1080, 810, 1800),
+ Case(1921, 1081, 809, 1799),
+ Case(2000, 1000, 1900, 1800),
+ Case(1600, 900, 1000, 1500),
+ Case(3200, 800, 1080, 1920),
+ )
+
+ var exercised = 0
+ for (c in cases) {
+ val g = RenderGeometry.compute(c.viewW, c.viewH, c.fbW, c.fbH)
+ val label = "view=${c.viewW}x${c.viewH} fb=${c.fbW}x${c.fbH}: $g"
+ assertTrue("expected dstX > 0 for $label", g.dstX > 0)
+ assertTrue("expected bufDstX > 0 for $label", g.bufDstX > 0)
+ exercised++
+
+ val viewRightBar = c.viewW - g.dstX - g.dstW
+ assertTrue(
+ "view left/right bars differ for $label",
+ Math.abs(g.dstX - viewRightBar) <= 1,
+ )
+ val bufRightBar = g.bufW - g.bufDstX - g.bufDstW
+ assertTrue(
+ "buffer left/right bars differ for $label",
+ Math.abs(g.bufDstX - bufRightBar) <= 1,
+ )
+ }
+ assertTrue("no case exercised dX > 0 && bufDstX > 0", exercised > 0)
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/x11/ResolutionPolicyTest.kt b/app/src/test/java/com/excp/podroid/x11/ResolutionPolicyTest.kt
index ad55bee..6c3df48 100644
--- a/app/src/test/java/com/excp/podroid/x11/ResolutionPolicyTest.kt
+++ b/app/src/test/java/com/excp/podroid/x11/ResolutionPolicyTest.kt
@@ -24,4 +24,24 @@ class ResolutionPolicyTest {
assertEquals(VncSize(320, 240), ResolutionPolicy.target(
X11Settings(resolutionMode = ResolutionMode.MATCH), viewportW = 10, viewportH = 8))
}
+ @Test fun `match at 75 percent scales viewport before rounding`() {
+ assertEquals(VncSize(810, 1752), ResolutionPolicy.target(
+ X11Settings(resolutionMode = ResolutionMode.MATCH, renderScale = 75), viewportW = 1080, viewportH = 2337))
+ }
+ @Test fun `match at 50 percent scales viewport before rounding`() {
+ assertEquals(VncSize(540, 1168), ResolutionPolicy.target(
+ X11Settings(resolutionMode = ResolutionMode.MATCH, renderScale = 50), viewportW = 1080, viewportH = 2337))
+ }
+ @Test fun `match at 50 percent still clamps to sane minimum`() {
+ assertEquals(VncSize(320, 240), ResolutionPolicy.target(
+ X11Settings(resolutionMode = ResolutionMode.MATCH, renderScale = 50), viewportW = 100, viewportH = 80))
+ }
+ @Test fun `preset ignores render scale`() {
+ val s = X11Settings(resolutionMode = ResolutionMode.PRESET, preset = ResolutionPreset.R1440P, renderScale = 50)
+ assertEquals(VncSize(2560, 1440), ResolutionPolicy.target(s, viewportW = 2337, viewportH = 1080))
+ }
+ @Test fun `custom ignores render scale`() {
+ val s = X11Settings(resolutionMode = ResolutionMode.CUSTOM, customW = 1600, customH = 900, renderScale = 50)
+ assertEquals(VncSize(1600, 900), ResolutionPolicy.target(s, viewportW = 1080, viewportH = 2337))
+ }
}
diff --git a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt b/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
index 29eced2..4d5c3b5 100644
--- a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
+++ b/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
@@ -80,6 +80,42 @@ class VncClientTest {
assertEquals(0xFF00FF00.toInt(), target[1]) // green
}
+ @Test
+ fun `Raw decode matches per-byte reference and ignores the padding byte`() {
+ // Multi-row rect (2x2) with a non-zero, varying padding byte on every
+ // pixel: the fast IntBuffer decode must produce byte-identical ARGB to
+ // an independent per-byte reference implementation, and the padding
+ // byte must never leak into the alpha channel (always 0xFF).
+ fun refDecode(bgrx: ByteArray): Int {
+ val b = bgrx[0].toInt() and 0xFF
+ val g = bgrx[1].toInt() and 0xFF
+ val r = bgrx[2].toInt() and 0xFF
+ return (0xFF shl 24) or (r shl 16) or (g shl 8) or b
+ }
+ val pixel00 = byteArrayOf(0x11, 0x22, 0x33, 0x00) // padding 0x00
+ val pixel01 = byteArrayOf(0x44, 0x55, 0x66, 0x7F) // padding non-zero
+ val pixel10 = byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte(), 0xFF.toByte())
+ val pixel11 = byteArrayOf(0x00, 0x00, 0x00, 0x01) // padding non-zero, black pixel
+
+ val bos = java.io.ByteArrayOutputStream()
+ val d = java.io.DataOutputStream(bos)
+ d.writeByte(0); d.writeByte(0); d.writeShort(1) // msg, pad, numRects
+ d.writeShort(0); d.writeShort(0); d.writeShort(2); d.writeShort(2) // x=0,y=0,w=2,h=2
+ d.writeInt(0) // encoding = Raw
+ d.write(pixel00); d.write(pixel01) // row 0
+ d.write(pixel10); d.write(pixel11) // row 1
+
+ val target = IntArray(4)
+ VncClient.readFramebufferUpdate(java.io.ByteArrayInputStream(bos.toByteArray()), target, 2, ZrleDecoder())
+
+ assertEquals(refDecode(pixel00), target[0])
+ assertEquals(refDecode(pixel01), target[1])
+ assertEquals(refDecode(pixel10), target[2])
+ assertEquals(refDecode(pixel11), target[3])
+ // Explicit alpha check: every pixel's top byte is 0xFF regardless of padding.
+ for (px in target) assertEquals(0xFF, (px ushr 24) and 0xFF)
+ }
+
@Test fun `requestDesktopSize serializes type 251 single-screen layout`() {
val out = java.io.ByteArrayOutputStream()
VncClient.requestDesktopSize(out, screenId = 7, width = 1920, height = 1080)
@@ -184,6 +220,93 @@ class VncClientTest {
VncClient.readFramebufferUpdate(java.io.ByteArrayInputStream(bos.toByteArray()), target, 1280, ZrleDecoder())
}
+ @Test fun `negotiatePixelFormat with default encodings is byte-identical to the old hardcoded SetEncodings`() {
+ val out = java.io.ByteArrayOutputStream()
+ VncClient.negotiatePixelFormat(out)
+ val sent = out.toByteArray()
+ // SetPixelFormat is fixed-size (20 bytes); SetEncodings follows it.
+ val setEncodings = sent.copyOfRange(20, sent.size)
+ val expected = byteArrayOf(
+ 0x02, 0x00, 0x00, 0x03, // msg=2, pad, count=3
+ 0x00, 0x00, 0x00, 0x01, // CopyRect
+ 0x00, 0x00, 0x00, 0x00, // Raw
+ 0xFF.toByte(), 0xFF.toByte(), 0xFE.toByte(), 0xCC.toByte(), // ExtendedDesktopSize (-308)
+ )
+ assertArrayEquals(expected, setEncodings)
+ // Passing DEFAULT_ENCODINGS explicitly must produce the exact same bytes.
+ val out2 = java.io.ByteArrayOutputStream()
+ VncClient.negotiatePixelFormat(out2, VncClient.DEFAULT_ENCODINGS)
+ assertArrayEquals(sent, out2.toByteArray())
+ }
+
+ @Test fun `negotiatePixelFormat with ZRLE_ENCODINGS advertises ZRLE first`() {
+ val out = java.io.ByteArrayOutputStream()
+ VncClient.negotiatePixelFormat(out, VncClient.ZRLE_ENCODINGS)
+ val setEncodings = out.toByteArray().copyOfRange(20, out.size())
+ val expected = byteArrayOf(
+ 0x02, 0x00, 0x00, 0x04, // msg=2, pad, count=4
+ 0x00, 0x00, 0x00, 0x10, // ZRLE (16)
+ 0x00, 0x00, 0x00, 0x01, // CopyRect
+ 0x00, 0x00, 0x00, 0x00, // Raw
+ 0xFF.toByte(), 0xFF.toByte(), 0xFE.toByte(), 0xCC.toByte(), // ExtendedDesktopSize (-308)
+ )
+ assertArrayEquals(expected, setEncodings)
+ }
+
+ @Test fun `onMessageStart fires once when the FramebufferUpdate message-type byte is read`() {
+ val msg = byteArrayOf(
+ 0x00, 0x00, // msg-type, padding
+ 0x00, 0x01, // num rects
+ 0x00, 0x00, 0x00, 0x00, // x=0, y=0
+ 0x00, 0x01, 0x00, 0x01, // w=1, h=1
+ 0x00, 0x00, 0x00, 0x00, // encoding = 0 (Raw)
+ 0, 0, 0, 0, // 1 BGRA pixel
+ )
+ var calls = 0
+ VncClient.readFramebufferUpdate(
+ inp = java.io.ByteArrayInputStream(msg),
+ targetArgb = IntArray(1),
+ stride = 1,
+ zrle = ZrleDecoder(),
+ onMessageStart = { calls++ },
+ )
+ assertEquals(1, calls)
+ }
+
+ @Test fun `ZRLE-encoded rectangle round-trips through readFramebufferUpdate`() {
+ // Solid-color 4x4 ZRLE tile (subencoding 1), zlib-compressed per RFB 6.4 -
+ // same vector shape as ZrleDecoderTest's solid-tile case, but wrapped in a
+ // full FramebufferUpdate message so it exercises the ENC_ZRLE dispatch too.
+ fun cpixel(argb: Int) = byteArrayOf(
+ (argb and 0xFF).toByte(),
+ ((argb shr 8) and 0xFF).toByte(),
+ ((argb shr 16) and 0xFF).toByte(),
+ )
+ val red = 0xFFFF0000.toInt()
+ val plain = byteArrayOf(1) + cpixel(red) // subencoding 1 = solid
+ val deflater = java.util.zip.Deflater(java.util.zip.Deflater.DEFAULT_COMPRESSION, false)
+ deflater.setInput(plain); deflater.finish()
+ val zbuf = ByteArray(4096)
+ val zout = java.io.ByteArrayOutputStream()
+ while (!deflater.finished()) { val n = deflater.deflate(zbuf); zout.write(zbuf, 0, n) }
+ val compressed = zout.toByteArray()
+
+ val bos = java.io.ByteArrayOutputStream()
+ val d = java.io.DataOutputStream(bos)
+ d.writeByte(0); d.writeByte(0); d.writeShort(1) // msg, pad, numRects
+ d.writeShort(0); d.writeShort(0); d.writeShort(4); d.writeShort(4) // x=0,y=0,w=4,h=4
+ d.writeInt(16) // encoding = ZRLE
+ d.writeInt(compressed.size)
+ d.write(compressed)
+
+ val target = IntArray(4 * 4)
+ val r = VncClient.readFramebufferUpdate(java.io.ByteArrayInputStream(bos.toByteArray()), target, 4, ZrleDecoder())
+
+ assertEquals(red, target[0])
+ assertEquals(red, target[15])
+ assertEquals(listOf(VncRect(0, 0, 4, 4)), r.damage)
+ }
+
@Test fun `ExtendedDesktopSize rect reports new size and writes no pixels`() {
// FramebufferUpdate: type=0, pad, numRects=1; rect x=0 y=0 w=800 h=600 enc=-308;
// body: screens=1 pad[3]; screen{id=1,x=0,y=0,w=800,h=600,flags=0}