Harden reconnect and WakeLock, add live status UI on the overview.
Android CI / build (push) Canceled after 0s

Fixes flaky Hyperion reconnects and 1h WakeLock cutoffs, disables verbose DEBUG logging, and shows server/FPS/capture stats plus credit in the main status card.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
robinandCursor committed 2026-08-01 09:11:03 +02:00
1 parent 063a068620
commit 982702cde1
14 files changed
+460 -76

No files matched your search

@@ -37,7 +37,7 @@ import java.nio.ByteBuffer;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
private static final String TAG = "HyperionScreenEncoder";
private static final boolean DEBUG = true;
private static final boolean DEBUG = false;
private static final String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC;
private static final int MAX_CAPTURE_WIDTH = 640;
@@ -88,6 +88,7 @@ public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
private int mFpsWindowCount;
private int mFramesSent;
private int mBlackFrameCount;
private volatile float mLastSendFps;
private AnimationSyncController mAnimationSync;
private Preferences mPreferences;
@@ -475,16 +476,55 @@ public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
long elapsed = now - mFpsWindowStartMs;
if (elapsed >= FPS_LOG_INTERVAL_MS) {
float fps = mFpsWindowCount * 1000f / elapsed;
Log.i(TAG, "Send-FPS=" + String.format("%.1f", fps)
+ " framesSent=" + mFramesSent
+ " blackFrames=" + mBlackFrameCount
+ " capture=" + mCaptureWidth + "x" + mCaptureHeight
+ " output=" + mOutputWidth + "x" + mOutputHeight);
mLastSendFps = fps;
if (DEBUG) {
Log.i(TAG, "Send-FPS=" + String.format("%.1f", fps)
+ " framesSent=" + mFramesSent
+ " blackFrames=" + mBlackFrameCount
+ " capture=" + mCaptureWidth + "x" + mCaptureHeight
+ " output=" + mOutputWidth + "x" + mOutputHeight);
}
mFpsWindowStartMs = now;
mFpsWindowCount = 0;
}
}
public float getSendFps() {
long elapsed = SystemClock.elapsedRealtime() - mFpsWindowStartMs;
if (elapsed >= 500L && mFpsWindowCount > 0) {
return mFpsWindowCount * 1000f / elapsed;
}
return mLastSendFps;
}
public int getFramesSent() {
return mFramesSent;
}
public int getBlackFrameCount() {
return mBlackFrameCount;
}
public int getCaptureWidth() {
return mCaptureWidth;
}
public int getCaptureHeight() {
return mCaptureHeight;
}
public int getOutputWidth() {
return mOutputWidth;
}
public int getOutputHeight() {
return mOutputHeight;
}
public int getTargetFrameRate() {
return mFrameRate;
}
private void yuvToRgbDownscale(Image image, byte[] rgb, int outW, int outH) {
final Image.Plane[] planes = image.getPlanes();
if (planes.length < 3) {
@@ -1,5 +1,6 @@
package com.hyperion.grabber.common;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ForegroundServiceStartNotAllowedException;
import android.app.Notification;
@@ -35,8 +36,14 @@ public class HyperionScreenService extends Service {
public static final String BROADCAST_ERROR = "SERVICE_ERROR";
public static final String BROADCAST_TAG = "SERVICE_STATUS";
public static final String BROADCAST_FILTER = "SERVICE_FILTER";
private static final boolean DEBUG = true;
public static final String BROADCAST_STATUS_TEXT = "SERVICE_STATUS_TEXT";
public static final String BROADCAST_SEND_FPS = "SERVICE_SEND_FPS";
public static final String BROADCAST_TARGET_FPS = "SERVICE_TARGET_FPS";
public static final String BROADCAST_HOST = "SERVICE_HOST";
public static final String BROADCAST_PORT = "SERVICE_PORT";
private static final boolean DEBUG = false;
private static final String TAG = "HyperionScreenService";
private static final long STATUS_TICK_MS = 1000L;
private boolean mForegroundFailed = false;
private PowerManager.WakeLock mWakeLock;
@@ -62,26 +69,48 @@ public class HyperionScreenService extends Service {
private boolean mSendAverageColor;
private boolean mWledEnabled;
private String mWledIp;
private String mHost;
private int mPort = -1;
private int mPriority = 100;
private HyperionScreenEncoder mHyperionEncoder;
private NotificationManager mNotificationManager;
private String mStartError = null;
private final Runnable mStatusTicker = new Runnable() {
@Override
public void run() {
notifyActivity();
if (mHyperionEncoder != null && isCapturing() && mHandler != null) {
mHandler.postDelayed(this, STATUS_TICK_MS);
}
}
};
private final HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
@Override
public void onConnected() {
if (DEBUG) Log.d(TAG, "Connected to Hyperion server");
Log.i(TAG, "Connected to Hyperion server");
mHasConnected = true;
mStartError = null;
notifyActivity();
startStatusTicker();
}
@Override
public void onConnectionError(int errorID, String error) {
Log.e(TAG, "Connection error: " + (error != null ? error : "unknown"));
if (!mHasConnected) {
mStartError = getResources().getString(R.string.error_server_unreachable);
haltStartup();
// Still connecting / reconnecting from cold start — keep trying if enabled.
if (!mReconnectEnabled) {
mStartError = getResources().getString(R.string.error_server_unreachable);
haltStartup();
} else {
mStartError = getResources().getString(R.string.error_server_unreachable);
notifyActivity();
}
} else if (mReconnectEnabled) {
Log.i(TAG, "Attempting automatic reconnect...");
notifyActivity();
} else {
mStartError = getResources().getString(R.string.error_connection_lost);
stopSelf();
@@ -135,8 +164,8 @@ public class HyperionScreenService extends Service {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private boolean prepared() {
Preferences prefs = new Preferences(getBaseContext());
String host = prefs.getString(R.string.pref_key_host, null);
int port = prefs.getInt(R.string.pref_key_port, -1);
mHost = prefs.getString(R.string.pref_key_host, null);
mPort = prefs.getInt(R.string.pref_key_port, -1);
String priority = prefs.getString(R.string.pref_key_priority, "100");
mFrameRate = prefs.getInt(R.string.pref_key_framerate);
mHorizontalLEDCount = prefs.getInt(R.string.pref_key_x_led);
@@ -148,11 +177,11 @@ public class HyperionScreenService extends Service {
int delay = prefs.getInt(R.string.pref_key_reconnect_delay);
if (!mWledEnabled) {
if (host == null || Objects.equals(host, "0.0.0.0") || Objects.equals(host, "")) {
if (mHost == null || Objects.equals(mHost, "0.0.0.0") || Objects.equals(mHost, "")) {
mStartError = getResources().getString(R.string.error_empty_host);
return false;
}
if (port == -1) {
if (mPort == -1) {
mStartError = getResources().getString(R.string.error_empty_port);
return false;
}
@@ -161,6 +190,8 @@ public class HyperionScreenService extends Service {
mStartError = "WLED IP should not be empty";
return false;
}
mHost = mWledIp;
mPort = 4048;
}
if (mHorizontalLEDCount <= 0 || mVerticalLEDCount <= 0) {
@@ -168,8 +199,12 @@ public class HyperionScreenService extends Service {
return false;
}
mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
int priorityValue = Integer.parseInt(priority);
mHyperionThread = new HyperionThread(mReceiver, host, port, priorityValue, mReconnectEnabled, delay, mWledEnabled, mWledIp);
try {
mPriority = Integer.parseInt(priority);
} catch (NumberFormatException e) {
mPriority = 100;
}
mHyperionThread = new HyperionThread(mReceiver, mHost, mPort, mPriority, mReconnectEnabled, delay, mWledEnabled, mWledIp);
mHyperionThread.start();
mStartError = null;
return true;
@@ -248,6 +283,8 @@ public class HyperionScreenService extends Service {
public void onDestroy() {
if (DEBUG) Log.v(TAG, "Ending service");
stopStatusTicker();
try {
unregisterReceiver(mEventReceiver);
} catch (Exception e) {
@@ -302,14 +339,18 @@ public class HyperionScreenService extends Service {
}
}
@SuppressLint("WakelockTimeout")
private void acquireWakeLock() {
if (mWakeLock == null) {
try {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm != null) {
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"HyperionGrabber::ScreenCapture");
mWakeLock.acquire(60 * 60 * 1000L);
mWakeLock.setReferenceCounted(false);
// No timeout — TV ambilight sessions routinely exceed 1 hour.
mWakeLock.acquire();
Log.i(TAG, "Wake lock acquired (no timeout)");
}
} catch (Exception e) {
Log.e(TAG, "Failed to acquire wake lock", e);
@@ -423,11 +464,13 @@ public class HyperionScreenService extends Service {
options,
this);
mHyperionEncoder.sendStatus();
startStatusTicker();
}
private void stopScreenRecord() {
if (DEBUG) Log.v(TAG, "Stopping screen recorder");
mReconnectEnabled = false;
stopStatusTicker();
mNotificationManager.cancel(NOTIFICATION_ID);
if (mHyperionEncoder != null) {
@@ -439,9 +482,15 @@ public class HyperionScreenService extends Service {
releaseResource();
if (mHyperionThread != null) {
try {
mHyperionThread.getReceiver().disconnect();
} catch (Exception e) {
Log.w(TAG, "Error disconnecting Hyperion thread: " + e.getMessage());
}
mHyperionThread.interrupt();
mHyperionThread = null;
}
mHasConnected = false;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@@ -460,10 +509,28 @@ public class HyperionScreenService extends Service {
return isCapturing() && mHasConnected;
}
private void startStatusTicker() {
if (mHandler == null) return;
mHandler.removeCallbacks(mStatusTicker);
mHandler.post(mStatusTicker);
}
private void stopStatusTicker() {
if (mHandler != null) {
mHandler.removeCallbacks(mStatusTicker);
}
}
private void notifyActivity() {
Intent intent = new Intent(BROADCAST_FILTER);
intent.putExtra(BROADCAST_TAG, isCommunicating());
intent.putExtra(BROADCAST_ERROR, mStartError);
intent.putExtra(BROADCAST_STATUS_TEXT, buildStatusText());
intent.putExtra(BROADCAST_HOST, mHost);
intent.putExtra(BROADCAST_PORT, mPort);
intent.putExtra(BROADCAST_TARGET_FPS, mFrameRate);
float sendFps = mHyperionEncoder != null ? mHyperionEncoder.getSendFps() : 0f;
intent.putExtra(BROADCAST_SEND_FPS, sendFps);
if (DEBUG) {
Log.v(TAG, "Broadcasting status: communicating=" + isCommunicating() +
(mStartError != null ? ", error=" + mStartError : ""));
@@ -471,8 +538,78 @@ public class HyperionScreenService extends Service {
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
private String buildStatusText() {
StringBuilder sb = new StringBuilder();
if (mWledEnabled) {
sb.append("WLED ").append(mWledIp != null ? mWledIp : "—").append(":4048\n");
} else {
sb.append(getString(R.string.status_server))
.append(" ")
.append(mHost != null ? mHost : "—")
.append(':')
.append(mPort > 0 ? mPort : "—")
.append('\n');
}
boolean capturing = isCapturing();
boolean connected = mHasConnected
|| (mHyperionThread != null && mHyperionThread.isNetworkConnected());
String state;
if (capturing && connected) {
state = getString(R.string.status_state_active);
} else if (capturing) {
state = getString(R.string.status_state_capturing);
} else if (connected) {
state = getString(R.string.status_state_connected);
} else if (mHyperionThread != null && mReconnectEnabled) {
state = getString(R.string.status_state_reconnecting);
} else if (mHyperionThread != null) {
state = getString(R.string.status_state_connecting);
} else {
state = getString(R.string.status_state_off);
}
sb.append(getString(R.string.status_state)).append(" ").append(state).append('\n');
if (mHyperionEncoder != null) {
float sendFps = mHyperionEncoder.getSendFps();
sb.append(getString(R.string.status_fps)).append(" ")
.append(String.format(java.util.Locale.US, "%.1f", sendFps))
.append(" / ").append(mFrameRate).append('\n');
sb.append(getString(R.string.status_leds)).append(" ")
.append(mHorizontalLEDCount).append('×').append(mVerticalLEDCount)
.append(" · ")
.append(mHyperionEncoder.getCaptureWidth()).append('×')
.append(mHyperionEncoder.getCaptureHeight())
.append(" → ")
.append(mHyperionEncoder.getOutputWidth()).append('×')
.append(mHyperionEncoder.getOutputHeight())
.append('\n');
sb.append(getString(R.string.status_frames)).append(" ")
.append(mHyperionEncoder.getFramesSent());
int black = mHyperionEncoder.getBlackFrameCount();
if (black > 0) {
sb.append(" · ").append(getString(R.string.status_black)).append(' ')
.append(black);
}
sb.append('\n');
} else {
sb.append(getString(R.string.status_target_fps)).append(" ").append(mFrameRate).append('\n');
sb.append(getString(R.string.status_leds)).append(" ")
.append(mHorizontalLEDCount).append('×').append(mVerticalLEDCount).append('\n');
}
sb.append(getString(R.string.status_priority)).append(" ").append(mPriority);
if (mSendAverageColor) {
sb.append(" · ").append(getString(R.string.status_avg_color));
}
if (mStartError != null && !(mReconnectEnabled && mHyperionThread != null)) {
sb.append('\n').append(mStartError);
}
sb.append('\n').append(getString(R.string.credit_modified_by));
return sb.toString();
}
public interface HyperionThreadBroadcaster {
// void onResponse(String response);
void onConnected();
void onConnectionError(int errorHash, String errorString);
void onReceiveStatus(boolean isCapturing);
@@ -35,13 +35,20 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
}
override fun isConnected(): Boolean {
return mSocket.isConnected
return try {
!mSocket.isClosed && mSocket.isConnected
} catch (_: Exception) {
false
}
}
@Throws(IOException::class)
override fun disconnect() {
if (isConnected()) {
mSocket.close()
try {
if (!mSocket.isClosed) {
mSocket.close()
}
} catch (_: IOException) {
}
}
@@ -91,7 +98,10 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
@Throws(IOException::class)
private fun sendRequest(bb: ByteBuffer) {
if (isConnected()) {
if (!isConnected()) {
throw IOException("Socket not connected")
}
try {
val size = bb.remaining()
val header = ByteArray(4)
header[0] = ((size shr 24) and 0xFF).toByte()
@@ -106,9 +116,14 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
bb[data]
output.write(data)
output.flush()
// Don't wait for reply - fire and forget for minimal latency
// Replies will be handled asynchronously if needed
} catch (e: IOException) {
try {
mSocket.close()
} catch (_: Exception) {
}
throw e
}
}
@@ -118,7 +133,6 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
private fun receiveReply() {
// Non-blocking reply consumption to keep socket clean
// This is called separately and doesn't block frame sending
try {
while (mSocket.getInputStream().available() >= 4) {
val header = ByteArray(4)
@@ -132,14 +146,14 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
val data = ByteArray(size)
mSocket.getInputStream().read(data, 0, size)
} else {
break // Not enough data yet, will consume later
break
}
} else {
break
}
}
} catch (e: IOException) {
} catch (_: IOException) {
// Ignore - non-blocking read
}
}
}
}
@@ -1,11 +1,11 @@
package com.hyperion.grabber.common.network
import android.util.Log
import com.hyperion.grabber.common.HyperionScreenService.HyperionThreadBroadcaster
import java.io.IOException
import java.net.InetAddress
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
@@ -21,12 +21,13 @@ class HyperionThread(
private val wledIp: String?
) : Thread(TAG) {
private val reconnectDelayMs = (delaySeconds * 1000).toLong()
private val reconnectDelayMs = (delaySeconds.coerceAtLeast(1) * 1000).toLong()
private val reconnectEnabled = AtomicBoolean(reconnect)
private val connected = AtomicBoolean(false)
private val shuttingDown = AtomicBoolean(false)
private val clientRef = AtomicReference<HyperionClient>()
private val networkExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private val latestFrame = AtomicReference<FrameData>()
private var lastFrameNumber = 0L
private var sendTaskScheduled = AtomicBoolean(false)
@@ -40,7 +41,7 @@ class HyperionThread(
val copy = data.copyOf()
++lastFrameNumber
latestFrame.set(FrameData(copy, width, height, lastFrameNumber))
if (sendTaskScheduled.compareAndSet(false, true)) {
networkExecutor.submit { sendLatestFrame() }
}
@@ -71,12 +72,14 @@ class HyperionThread(
try {
client.clear(priority)
} catch (e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
handleError(e)
}
}
}
override fun disconnect() {
shuttingDown.set(true)
reconnectEnabled.set(false)
latestFrame.set(null)
lastFrameNumber = 0
sendTaskScheduled.set(false)
@@ -90,14 +93,7 @@ class HyperionThread(
}
}
val client = clientRef.getAndSet(null)
if (client != null) {
try {
client.disconnect()
} catch (ignored: IOException) {
}
}
closeClient()
connected.set(false)
}
@@ -110,32 +106,20 @@ class HyperionThread(
connect()
}
fun isNetworkConnected(): Boolean = connected.get() && clientRef.get()?.isConnected() == true
fun pauseConnection() {
latestFrame.set(null)
lastFrameNumber = 0
sendTaskScheduled.set(false)
val client = clientRef.getAndSet(null)
if (client != null) {
try { client.disconnect() } catch (ignored: IOException) {}
}
closeClient()
connected.set(false)
}
fun resumeConnection() {
if (networkExecutor.isShutdown) return
if (shuttingDown.get() || networkExecutor.isShutdown) return
networkExecutor.submit {
try {
val client = createClient()
if (client.isConnected()) {
clientRef.set(client)
connected.set(true)
callback.onConnected()
} else {
callback.onConnectionError(0, "Failed to reconnect")
}
} catch (e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
}
tryReconnect(notifyErrors = true)
}
}
@@ -147,40 +131,85 @@ class HyperionThread(
}
}
private fun closeClient() {
val client = clientRef.getAndSet(null)
if (client != null) {
try {
client.disconnect()
} catch (_: IOException) {
}
}
}
/**
* Initial connect: with reconnect enabled, keep retrying until success or shutdown.
* Without reconnect, try once and exit.
*/
private fun connect() {
do {
while (!shuttingDown.get() && !isInterrupted) {
try {
val client = createClient()
if (client.isConnected()) {
clientRef.set(client)
connected.set(true)
Log.i(TAG, "Connected to Hyperion")
callback.onConnected()
return
}
client.disconnect()
} catch (e: IOException) {
Log.w(TAG, "Connect failed: ${e.message}")
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
if (reconnectEnabled.get() && connected.get()) {
sleepSafe(reconnectDelayMs)
}
}
} while (reconnectEnabled.get() && connected.get())
if (!reconnectEnabled.get() || shuttingDown.get()) {
return
}
sleepSafe(reconnectDelayMs)
}
}
private fun handleError(e: IOException) {
Log.w(TAG, "Send/connection error: ${e.message}")
connected.set(false)
closeClient()
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
if (reconnectEnabled.get() && connected.get()) {
if (!reconnectEnabled.get() || shuttingDown.get()) {
return
}
// Keep retrying on the network executor thread until success or stop.
while (reconnectEnabled.get() && !shuttingDown.get()) {
sleepSafe(reconnectDelayMs)
try {
val newClient = createClient()
if (newClient.isConnected()) {
clientRef.set(newClient)
}
} catch (ignored: IOException) {
if (tryReconnect(notifyErrors = false)) {
return
}
}
}
private fun tryReconnect(notifyErrors: Boolean): Boolean {
if (shuttingDown.get() || !reconnectEnabled.get()) return false
try {
closeClient()
val newClient = createClient()
if (newClient.isConnected()) {
clientRef.set(newClient)
connected.set(true)
Log.i(TAG, "Reconnected to Hyperion")
callback.onConnected()
return true
}
newClient.disconnect()
} catch (e: IOException) {
if (notifyErrors) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
}
Log.w(TAG, "Reconnect attempt failed: ${e.message}")
}
return false
}
private fun sleepSafe(ms: Long) {
try {
sleep(ms)
@@ -11,15 +11,17 @@ class WledDdpClient(
private val port: Int = 4048
) : HyperionClient {
private var socket: DatagramSocket? = null
private var socket: DatagramSocket? = DatagramSocket()
private var sequenceNumber = 1
private var active = true
override fun isConnected(): Boolean {
return socket?.isClosed == false
return active && socket?.isClosed == false
}
@Throws(IOException::class)
override fun disconnect() {
active = false
socket?.close()
socket = null
}