Compare commits

...
1 Commits
Author SHA1 Message Date
robinandCursor 982702cde1 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>
2026-08-01 09:11:03 +02:00
14 changed files with 441 additions and 57 deletions

No files matched your search

+6
View File
@@ -34,3 +34,9 @@ Encoder-Surfaces (MediaCodec / MediaRecorder) schon — wie bei scrcpy und Scree
- Problem: Codec-Pump alle 1 ms + Capture 960×540 @ 4 Mbit → Gerät eingefroren, App/Settings nicht nutzbar - Problem: Codec-Pump alle 1 ms + Capture 960×540 @ 4 Mbit → Gerät eingefroren, App/Settings nicht nutzbar
- Fix: Capture zurück auf **640×360**, Bitrate ~1.5 Mbit, Pump an Ziel-FPS, Letterbox-Crop sofort locken - Fix: Capture zurück auf **640×360**, Bitrate ~1.5 Mbit, Pump an Ziel-FPS, Letterbox-Crop sofort locken
- Preferences: null-sicheres Caching + robustes `getInt` (leere Strings) - Preferences: null-sicheres Caching + robustes `getInt` (leere Strings)
## Follow-up (Reconnect / Status / WakeLock)
- Reconnect: echte Retry-Schleife auch vor erstem Connect; Socket-Close nach Write-Fehler; `isConnected` prüft `!isClosed`
- WakeLock ohne 1h-Timeout (Dauerbetrieb TV)
- `DEBUG=false` in Encoder/Service
- Übersicht: Live-Status (Server, Port, Status, Sende-FPS, Capture→Output, Frames, Priorität)
@@ -0,0 +1,65 @@
package com.hyperion.grabber;
import android.content.Context;
import android.content.Intent;
import android.widget.TextView;
import com.hyperion.grabber.common.HyperionScreenService;
import com.hyperion.grabber.common.R;
import com.hyperion.grabber.common.util.Preferences;
/**
* Formats and applies grabber status text on the main overview screen.
*/
public final class GrabberStatusHelper {
private GrabberStatusHelper() {}
public static void applyBroadcast(TextView target, Intent intent) {
if (target == null || intent == null) return;
String text = intent.getStringExtra(HyperionScreenService.BROADCAST_STATUS_TEXT);
if (text != null && !text.isEmpty()) {
target.setText(text);
target.setVisibility(TextView.VISIBLE);
}
}
public static void applyFromPreferences(TextView target, Context context) {
if (target == null || context == null) return;
target.setText(formatFromPreferences(context));
target.setVisibility(TextView.VISIBLE);
}
public static String formatFromPreferences(Context context) {
Preferences prefs = new Preferences(context);
boolean wled = prefs.getBoolean(R.string.pref_key_wled_enabled);
String host = prefs.getString(R.string.pref_key_host, null);
int port = prefs.getInt(R.string.pref_key_port, -1);
int fps = prefs.getInt(R.string.pref_key_framerate);
int ledX = prefs.getInt(R.string.pref_key_x_led);
int ledY = prefs.getInt(R.string.pref_key_y_led);
String priority = prefs.getString(R.string.pref_key_priority, "100");
boolean avg = prefs.getBoolean(R.string.pref_key_use_avg_color);
String wledIp = prefs.getString(R.string.pref_key_wled_ip, null);
StringBuilder sb = new StringBuilder();
if (wled) {
sb.append("WLED ").append(wledIp != null && !wledIp.isEmpty() ? wledIp : "—").append(":4048\n");
} else if (host != null && !host.isEmpty() && port > 0) {
sb.append(context.getString(R.string.status_server))
.append(" ").append(host).append(':').append(port).append('\n');
} else {
sb.append(context.getString(R.string.status_not_configured)).append('\n');
}
sb.append(context.getString(R.string.status_state))
.append(" ").append(context.getString(R.string.status_state_off)).append('\n');
sb.append(context.getString(R.string.status_target_fps)).append(" ").append(fps).append('\n');
sb.append(context.getString(R.string.status_leds)).append(" ")
.append(ledX).append('×').append(ledY).append('\n');
sb.append(context.getString(R.string.status_priority)).append(" ").append(priority);
if (avg) {
sb.append(" · ").append(context.getString(R.string.status_avg_color));
}
sb.append('\n').append(context.getString(R.string.credit_modified_by));
return sb.toString();
}
}
@@ -43,6 +43,7 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
private Intent mPendingProjectionData = null; private Intent mPendingProjectionData = null;
private int mPendingResultCode = 0; private int mPendingResultCode = 0;
private int mPermissionDeniedCount = 0; private int mPermissionDeniedCount = 0;
private String mLastToastError = null;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override @Override
@@ -51,12 +52,16 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
mRecorderRunning = checked; mRecorderRunning = checked;
String error = intent.getStringExtra(HyperionScreenService.BROADCAST_ERROR); String error = intent.getStringExtra(HyperionScreenService.BROADCAST_ERROR);
if (error != null && if (error != null && !error.equals(mLastToastError) &&
(Build.VERSION.SDK_INT < Build.VERSION_CODES.N || (Build.VERSION.SDK_INT < Build.VERSION_CODES.N ||
!HyperionGrabberTileService.isListening())) { !HyperionGrabberTileService.isListening())) {
mLastToastError = error;
Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show(); Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show();
} else if (error == null) {
mLastToastError = null;
} }
setImageViews(checked, checked); setImageViews(checked, checked);
GrabberStatusHelper.applyBroadcast(findViewById(R.id.statusInfoText), intent);
} }
}; };
@@ -85,6 +90,7 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
} }
setImageViews(mRecorderRunning, false); setImageViews(mRecorderRunning, false);
GrabberStatusHelper.applyFromPreferences(findViewById(R.id.statusInfoText), this);
LocalBroadcastManager.getInstance(this).registerReceiver( LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(HyperionScreenService.BROADCAST_FILTER)); mMessageReceiver, new IntentFilter(HyperionScreenService.BROADCAST_FILTER));
@@ -99,6 +105,10 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
if (!mRecorderRunning) {
GrabberStatusHelper.applyFromPreferences(findViewById(R.id.statusInfoText), this);
}
checkForInstance();
} }
private void requestNotificationPermission() { private void requestNotificationPermission() {
@@ -31,6 +31,7 @@ import com.hyperion.grabber.common.BootActivity;
import com.hyperion.grabber.common.HyperionScreenService; import com.hyperion.grabber.common.HyperionScreenService;
import com.hyperion.grabber.common.util.MediaProjectionHelper; import com.hyperion.grabber.common.util.MediaProjectionHelper;
import com.hyperion.grabber.common.util.Preferences; import com.hyperion.grabber.common.util.Preferences;
import com.hyperion.grabber.GrabberStatusHelper;
import com.hyperion.grabber.R; import com.hyperion.grabber.R;
public class MainActivity extends LeanbackActivity implements ImageView.OnClickListener, public class MainActivity extends LeanbackActivity implements ImageView.OnClickListener,
@@ -45,6 +46,7 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
private boolean mRecorderRunning = false; private boolean mRecorderRunning = false;
private static MediaProjectionManager mMediaProjectionManager; private static MediaProjectionManager mMediaProjectionManager;
private int mPermissionDeniedCount = 0; private int mPermissionDeniedCount = 0;
private String mLastToastError = null;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override @Override
@@ -53,10 +55,14 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
mRecorderRunning = checked; mRecorderRunning = checked;
String error = intent.getStringExtra(BROADCAST_ERROR); String error = intent.getStringExtra(BROADCAST_ERROR);
if (error != null) { if (error != null && !error.equals(mLastToastError)) {
mLastToastError = error;
Toast.makeText(getBaseContext(), error, Toast.LENGTH_SHORT).show(); Toast.makeText(getBaseContext(), error, Toast.LENGTH_SHORT).show();
} else if (error == null) {
mLastToastError = null;
} }
setImageViews(checked, true); setImageViews(checked, true);
GrabberStatusHelper.applyBroadcast(findViewById(R.id.statusInfoText), intent);
} }
}; };
@@ -138,6 +144,7 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
ib.setFocusable(true); ib.setFocusable(true);
setImageViews(mRecorderRunning, false); setImageViews(mRecorderRunning, false);
GrabberStatusHelper.applyFromPreferences(findViewById(R.id.statusInfoText), this);
LocalBroadcastManager.getInstance(this).registerReceiver( LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(BROADCAST_FILTER)); mMessageReceiver, new IntentFilter(BROADCAST_FILTER));
@@ -146,6 +153,15 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
checkForInstance(); checkForInstance();
} }
@Override
protected void onResume() {
super.onResume();
if (!mRecorderRunning) {
GrabberStatusHelper.applyFromPreferences(findViewById(R.id.statusInfoText), this);
}
checkForInstance();
}
@Override @Override
public void onClick(View view) { public void onClick(View view) {
int id = view.getId(); int id = view.getId();
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="16dp" />
<solid android:color="#CC1A1A1A" />
</shape>
+24 -1
View File
@@ -11,6 +11,30 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" /> android:layout_height="match_parent" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/statusInfoText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginTop="36dp"
android:layout_marginEnd="48dp"
android:background="@drawable/status_card_background"
android:fontFamily="monospace"
android:includeFontPadding="false"
android:lineSpacingExtra="3dp"
android:maxWidth="520dp"
android:paddingStart="20dp"
android:paddingTop="14dp"
android:paddingEnd="20dp"
android:paddingBottom="14dp"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:visibility="visible"
app:layout_constrainedWidth="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Server: 10.0.50.2:19400\nStatus: Sendet\nSende-FPS: 28.4 / 30" />
<androidx.appcompat.widget.AppCompatTextView <androidx.appcompat.widget.AppCompatTextView
android:id="@+id/grabberStartedText" android:id="@+id/grabberStartedText"
android:layout_width="wrap_content" android:layout_width="wrap_content"
@@ -82,4 +106,3 @@
app:srcCompat="@drawable/ic_settings_black_72dp" /> app:srcCompat="@drawable/ic_settings_black_72dp" />
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>
@@ -37,7 +37,7 @@ import java.nio.ByteBuffer;
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @TargetApi(Build.VERSION_CODES.LOLLIPOP)
public final class HyperionScreenEncoder extends HyperionScreenEncoderBase { public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
private static final String TAG = "HyperionScreenEncoder"; 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 String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC;
private static final int MAX_CAPTURE_WIDTH = 640; private static final int MAX_CAPTURE_WIDTH = 640;
@@ -88,6 +88,7 @@ public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
private int mFpsWindowCount; private int mFpsWindowCount;
private int mFramesSent; private int mFramesSent;
private int mBlackFrameCount; private int mBlackFrameCount;
private volatile float mLastSendFps;
private AnimationSyncController mAnimationSync; private AnimationSyncController mAnimationSync;
private Preferences mPreferences; private Preferences mPreferences;
@@ -475,16 +476,55 @@ public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
long elapsed = now - mFpsWindowStartMs; long elapsed = now - mFpsWindowStartMs;
if (elapsed >= FPS_LOG_INTERVAL_MS) { if (elapsed >= FPS_LOG_INTERVAL_MS) {
float fps = mFpsWindowCount * 1000f / elapsed; float fps = mFpsWindowCount * 1000f / elapsed;
mLastSendFps = fps;
if (DEBUG) {
Log.i(TAG, "Send-FPS=" + String.format("%.1f", fps) Log.i(TAG, "Send-FPS=" + String.format("%.1f", fps)
+ " framesSent=" + mFramesSent + " framesSent=" + mFramesSent
+ " blackFrames=" + mBlackFrameCount + " blackFrames=" + mBlackFrameCount
+ " capture=" + mCaptureWidth + "x" + mCaptureHeight + " capture=" + mCaptureWidth + "x" + mCaptureHeight
+ " output=" + mOutputWidth + "x" + mOutputHeight); + " output=" + mOutputWidth + "x" + mOutputHeight);
}
mFpsWindowStartMs = now; mFpsWindowStartMs = now;
mFpsWindowCount = 0; 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) { private void yuvToRgbDownscale(Image image, byte[] rgb, int outW, int outH) {
final Image.Plane[] planes = image.getPlanes(); final Image.Plane[] planes = image.getPlanes();
if (planes.length < 3) { if (planes.length < 3) {
@@ -1,5 +1,6 @@
package com.hyperion.grabber.common; package com.hyperion.grabber.common;
import android.annotation.SuppressLint;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.app.ForegroundServiceStartNotAllowedException; import android.app.ForegroundServiceStartNotAllowedException;
import android.app.Notification; 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_ERROR = "SERVICE_ERROR";
public static final String BROADCAST_TAG = "SERVICE_STATUS"; public static final String BROADCAST_TAG = "SERVICE_STATUS";
public static final String BROADCAST_FILTER = "SERVICE_FILTER"; 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 String TAG = "HyperionScreenService";
private static final long STATUS_TICK_MS = 1000L;
private boolean mForegroundFailed = false; private boolean mForegroundFailed = false;
private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mWakeLock;
@@ -62,26 +69,48 @@ public class HyperionScreenService extends Service {
private boolean mSendAverageColor; private boolean mSendAverageColor;
private boolean mWledEnabled; private boolean mWledEnabled;
private String mWledIp; private String mWledIp;
private String mHost;
private int mPort = -1;
private int mPriority = 100;
private HyperionScreenEncoder mHyperionEncoder; private HyperionScreenEncoder mHyperionEncoder;
private NotificationManager mNotificationManager; private NotificationManager mNotificationManager;
private String mStartError = null; 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() { private final HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
@Override @Override
public void onConnected() { public void onConnected() {
if (DEBUG) Log.d(TAG, "Connected to Hyperion server"); Log.i(TAG, "Connected to Hyperion server");
mHasConnected = true; mHasConnected = true;
mStartError = null;
notifyActivity(); notifyActivity();
startStatusTicker();
} }
@Override @Override
public void onConnectionError(int errorID, String error) { public void onConnectionError(int errorID, String error) {
Log.e(TAG, "Connection error: " + (error != null ? error : "unknown")); Log.e(TAG, "Connection error: " + (error != null ? error : "unknown"));
if (!mHasConnected) { if (!mHasConnected) {
// Still connecting / reconnecting from cold start — keep trying if enabled.
if (!mReconnectEnabled) {
mStartError = getResources().getString(R.string.error_server_unreachable); mStartError = getResources().getString(R.string.error_server_unreachable);
haltStartup(); haltStartup();
} else {
mStartError = getResources().getString(R.string.error_server_unreachable);
notifyActivity();
}
} else if (mReconnectEnabled) { } else if (mReconnectEnabled) {
Log.i(TAG, "Attempting automatic reconnect..."); Log.i(TAG, "Attempting automatic reconnect...");
notifyActivity();
} else { } else {
mStartError = getResources().getString(R.string.error_connection_lost); mStartError = getResources().getString(R.string.error_connection_lost);
stopSelf(); stopSelf();
@@ -135,8 +164,8 @@ public class HyperionScreenService extends Service {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private boolean prepared() { private boolean prepared() {
Preferences prefs = new Preferences(getBaseContext()); Preferences prefs = new Preferences(getBaseContext());
String host = prefs.getString(R.string.pref_key_host, null); mHost = prefs.getString(R.string.pref_key_host, null);
int port = prefs.getInt(R.string.pref_key_port, -1); mPort = prefs.getInt(R.string.pref_key_port, -1);
String priority = prefs.getString(R.string.pref_key_priority, "100"); String priority = prefs.getString(R.string.pref_key_priority, "100");
mFrameRate = prefs.getInt(R.string.pref_key_framerate); mFrameRate = prefs.getInt(R.string.pref_key_framerate);
mHorizontalLEDCount = prefs.getInt(R.string.pref_key_x_led); 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); int delay = prefs.getInt(R.string.pref_key_reconnect_delay);
if (!mWledEnabled) { 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); mStartError = getResources().getString(R.string.error_empty_host);
return false; return false;
} }
if (port == -1) { if (mPort == -1) {
mStartError = getResources().getString(R.string.error_empty_port); mStartError = getResources().getString(R.string.error_empty_port);
return false; return false;
} }
@@ -161,6 +190,8 @@ public class HyperionScreenService extends Service {
mStartError = "WLED IP should not be empty"; mStartError = "WLED IP should not be empty";
return false; return false;
} }
mHost = mWledIp;
mPort = 4048;
} }
if (mHorizontalLEDCount <= 0 || mVerticalLEDCount <= 0) { if (mHorizontalLEDCount <= 0 || mVerticalLEDCount <= 0) {
@@ -168,8 +199,12 @@ public class HyperionScreenService extends Service {
return false; return false;
} }
mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
int priorityValue = Integer.parseInt(priority); try {
mHyperionThread = new HyperionThread(mReceiver, host, port, priorityValue, mReconnectEnabled, delay, mWledEnabled, mWledIp); mPriority = Integer.parseInt(priority);
} catch (NumberFormatException e) {
mPriority = 100;
}
mHyperionThread = new HyperionThread(mReceiver, mHost, mPort, mPriority, mReconnectEnabled, delay, mWledEnabled, mWledIp);
mHyperionThread.start(); mHyperionThread.start();
mStartError = null; mStartError = null;
return true; return true;
@@ -248,6 +283,8 @@ public class HyperionScreenService extends Service {
public void onDestroy() { public void onDestroy() {
if (DEBUG) Log.v(TAG, "Ending service"); if (DEBUG) Log.v(TAG, "Ending service");
stopStatusTicker();
try { try {
unregisterReceiver(mEventReceiver); unregisterReceiver(mEventReceiver);
} catch (Exception e) { } catch (Exception e) {
@@ -302,6 +339,7 @@ public class HyperionScreenService extends Service {
} }
} }
@SuppressLint("WakelockTimeout")
private void acquireWakeLock() { private void acquireWakeLock() {
if (mWakeLock == null) { if (mWakeLock == null) {
try { try {
@@ -309,7 +347,10 @@ public class HyperionScreenService extends Service {
if (pm != null) { if (pm != null) {
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"HyperionGrabber::ScreenCapture"); "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) { } catch (Exception e) {
Log.e(TAG, "Failed to acquire wake lock", e); Log.e(TAG, "Failed to acquire wake lock", e);
@@ -423,11 +464,13 @@ public class HyperionScreenService extends Service {
options, options,
this); this);
mHyperionEncoder.sendStatus(); mHyperionEncoder.sendStatus();
startStatusTicker();
} }
private void stopScreenRecord() { private void stopScreenRecord() {
if (DEBUG) Log.v(TAG, "Stopping screen recorder"); if (DEBUG) Log.v(TAG, "Stopping screen recorder");
mReconnectEnabled = false; mReconnectEnabled = false;
stopStatusTicker();
mNotificationManager.cancel(NOTIFICATION_ID); mNotificationManager.cancel(NOTIFICATION_ID);
if (mHyperionEncoder != null) { if (mHyperionEncoder != null) {
@@ -439,9 +482,15 @@ public class HyperionScreenService extends Service {
releaseResource(); releaseResource();
if (mHyperionThread != null) { if (mHyperionThread != null) {
try {
mHyperionThread.getReceiver().disconnect();
} catch (Exception e) {
Log.w(TAG, "Error disconnecting Hyperion thread: " + e.getMessage());
}
mHyperionThread.interrupt(); mHyperionThread.interrupt();
mHyperionThread = null; mHyperionThread = null;
} }
mHasConnected = false;
} }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @TargetApi(Build.VERSION_CODES.LOLLIPOP)
@@ -460,10 +509,28 @@ public class HyperionScreenService extends Service {
return isCapturing() && mHasConnected; 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() { private void notifyActivity() {
Intent intent = new Intent(BROADCAST_FILTER); Intent intent = new Intent(BROADCAST_FILTER);
intent.putExtra(BROADCAST_TAG, isCommunicating()); intent.putExtra(BROADCAST_TAG, isCommunicating());
intent.putExtra(BROADCAST_ERROR, mStartError); 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) { if (DEBUG) {
Log.v(TAG, "Broadcasting status: communicating=" + isCommunicating() + Log.v(TAG, "Broadcasting status: communicating=" + isCommunicating() +
(mStartError != null ? ", error=" + mStartError : "")); (mStartError != null ? ", error=" + mStartError : ""));
@@ -471,8 +538,78 @@ public class HyperionScreenService extends Service {
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent); 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 { public interface HyperionThreadBroadcaster {
// void onResponse(String response);
void onConnected(); void onConnected();
void onConnectionError(int errorHash, String errorString); void onConnectionError(int errorHash, String errorString);
void onReceiveStatus(boolean isCapturing); void onReceiveStatus(boolean isCapturing);
@@ -35,14 +35,21 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
} }
override fun isConnected(): Boolean { override fun isConnected(): Boolean {
return mSocket.isConnected return try {
!mSocket.isClosed && mSocket.isConnected
} catch (_: Exception) {
false
}
} }
@Throws(IOException::class) @Throws(IOException::class)
override fun disconnect() { override fun disconnect() {
if (isConnected()) { try {
if (!mSocket.isClosed) {
mSocket.close() mSocket.close()
} }
} catch (_: IOException) {
}
} }
@Throws(IOException::class) @Throws(IOException::class)
@@ -91,7 +98,10 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
@Throws(IOException::class) @Throws(IOException::class)
private fun sendRequest(bb: ByteBuffer) { private fun sendRequest(bb: ByteBuffer) {
if (isConnected()) { if (!isConnected()) {
throw IOException("Socket not connected")
}
try {
val size = bb.remaining() val size = bb.remaining()
val header = ByteArray(4) val header = ByteArray(4)
header[0] = ((size shr 24) and 0xFF).toByte() header[0] = ((size shr 24) and 0xFF).toByte()
@@ -108,7 +118,12 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
output.flush() output.flush()
// Don't wait for reply - fire and forget for minimal latency // 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() { private fun receiveReply() {
// Non-blocking reply consumption to keep socket clean // Non-blocking reply consumption to keep socket clean
// This is called separately and doesn't block frame sending
try { try {
while (mSocket.getInputStream().available() >= 4) { while (mSocket.getInputStream().available() >= 4) {
val header = ByteArray(4) val header = ByteArray(4)
@@ -132,13 +146,13 @@ class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : Hyperion
val data = ByteArray(size) val data = ByteArray(size)
mSocket.getInputStream().read(data, 0, size) mSocket.getInputStream().read(data, 0, size)
} else { } else {
break // Not enough data yet, will consume later break
} }
} else { } else {
break break
} }
} }
} catch (e: IOException) { } catch (_: IOException) {
// Ignore - non-blocking read // Ignore - non-blocking read
} }
} }
@@ -1,11 +1,11 @@
package com.hyperion.grabber.common.network package com.hyperion.grabber.common.network
import android.util.Log
import com.hyperion.grabber.common.HyperionScreenService.HyperionThreadBroadcaster import com.hyperion.grabber.common.HyperionScreenService.HyperionThreadBroadcaster
import java.io.IOException import java.io.IOException
import java.net.InetAddress import java.net.InetAddress
import java.util.concurrent.ExecutorService import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicReference
@@ -21,9 +21,10 @@ class HyperionThread(
private val wledIp: String? private val wledIp: String?
) : Thread(TAG) { ) : Thread(TAG) {
private val reconnectDelayMs = (delaySeconds * 1000).toLong() private val reconnectDelayMs = (delaySeconds.coerceAtLeast(1) * 1000).toLong()
private val reconnectEnabled = AtomicBoolean(reconnect) private val reconnectEnabled = AtomicBoolean(reconnect)
private val connected = AtomicBoolean(false) private val connected = AtomicBoolean(false)
private val shuttingDown = AtomicBoolean(false)
private val clientRef = AtomicReference<HyperionClient>() private val clientRef = AtomicReference<HyperionClient>()
private val networkExecutor: ExecutorService = Executors.newSingleThreadExecutor() private val networkExecutor: ExecutorService = Executors.newSingleThreadExecutor()
@@ -71,12 +72,14 @@ class HyperionThread(
try { try {
client.clear(priority) client.clear(priority)
} catch (e: IOException) { } catch (e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error") handleError(e)
} }
} }
} }
override fun disconnect() { override fun disconnect() {
shuttingDown.set(true)
reconnectEnabled.set(false)
latestFrame.set(null) latestFrame.set(null)
lastFrameNumber = 0 lastFrameNumber = 0
sendTaskScheduled.set(false) sendTaskScheduled.set(false)
@@ -90,14 +93,7 @@ class HyperionThread(
} }
} }
val client = clientRef.getAndSet(null) closeClient()
if (client != null) {
try {
client.disconnect()
} catch (ignored: IOException) {
}
}
connected.set(false) connected.set(false)
} }
@@ -110,32 +106,20 @@ class HyperionThread(
connect() connect()
} }
fun isNetworkConnected(): Boolean = connected.get() && clientRef.get()?.isConnected() == true
fun pauseConnection() { fun pauseConnection() {
latestFrame.set(null) latestFrame.set(null)
lastFrameNumber = 0 lastFrameNumber = 0
sendTaskScheduled.set(false) sendTaskScheduled.set(false)
val client = clientRef.getAndSet(null) closeClient()
if (client != null) {
try { client.disconnect() } catch (ignored: IOException) {}
}
connected.set(false) connected.set(false)
} }
fun resumeConnection() { fun resumeConnection() {
if (networkExecutor.isShutdown) return if (shuttingDown.get() || networkExecutor.isShutdown) return
networkExecutor.submit { networkExecutor.submit {
try { tryReconnect(notifyErrors = true)
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")
}
} }
} }
@@ -147,38 +131,83 @@ 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() { private fun connect() {
do { while (!shuttingDown.get() && !isInterrupted) {
try { try {
val client = createClient() val client = createClient()
if (client.isConnected()) { if (client.isConnected()) {
clientRef.set(client) clientRef.set(client)
connected.set(true) connected.set(true)
Log.i(TAG, "Connected to Hyperion")
callback.onConnected() callback.onConnected()
return return
} }
client.disconnect()
} catch (e: IOException) { } catch (e: IOException) {
Log.w(TAG, "Connect failed: ${e.message}")
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error") callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
if (reconnectEnabled.get() && connected.get()) { }
if (!reconnectEnabled.get() || shuttingDown.get()) {
return
}
sleepSafe(reconnectDelayMs) sleepSafe(reconnectDelayMs)
} }
} }
} while (reconnectEnabled.get() && connected.get())
}
private fun handleError(e: IOException) { 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") 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) sleepSafe(reconnectDelayMs)
if (tryReconnect(notifyErrors = false)) {
return
}
}
}
private fun tryReconnect(notifyErrors: Boolean): Boolean {
if (shuttingDown.get() || !reconnectEnabled.get()) return false
try { try {
closeClient()
val newClient = createClient() val newClient = createClient()
if (newClient.isConnected()) { if (newClient.isConnected()) {
clientRef.set(newClient) clientRef.set(newClient)
connected.set(true)
Log.i(TAG, "Reconnected to Hyperion")
callback.onConnected()
return true
} }
} catch (ignored: IOException) { 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) { private fun sleepSafe(ms: Long) {
@@ -11,15 +11,17 @@ class WledDdpClient(
private val port: Int = 4048 private val port: Int = 4048
) : HyperionClient { ) : HyperionClient {
private var socket: DatagramSocket? = null private var socket: DatagramSocket? = DatagramSocket()
private var sequenceNumber = 1 private var sequenceNumber = 1
private var active = true
override fun isConnected(): Boolean { override fun isConnected(): Boolean {
return socket?.isClosed == false return active && socket?.isClosed == false
} }
@Throws(IOException::class) @Throws(IOException::class)
override fun disconnect() { override fun disconnect() {
active = false
socket?.close() socket?.close()
socket = null socket = null
} }
+18
View File
@@ -60,6 +60,24 @@
<string name="error_connection_lost">Die Verbindung zum Hyperion Server wurde getrennt. Die Bilderfassung wir angehalten.</string> <string name="error_connection_lost">Die Verbindung zum Hyperion Server wurde getrennt. Die Bilderfassung wir angehalten.</string>
<string name="toast_must_give_permission">Bitte erlaube die Bilderfassung.</string> <string name="toast_must_give_permission">Bitte erlaube die Bilderfassung.</string>
<string name="message_service_started">Du kannst Hyperion Grabber mit der Zurück-Taste verlassen. Der Bildschirminhalt wird im Hintergrund an deinen Hyperion Server gesendet.</string> <string name="message_service_started">Du kannst Hyperion Grabber mit der Zurück-Taste verlassen. Der Bildschirminhalt wird im Hintergrund an deinen Hyperion Server gesendet.</string>
<string name="status_server">Server</string>
<string name="status_state">Status</string>
<string name="status_state_off">Aus</string>
<string name="status_state_connecting">Verbinde…</string>
<string name="status_state_reconnecting">Wiederverbindung…</string>
<string name="status_state_connected">Verbunden</string>
<string name="status_state_capturing">Capture aktiv (kein Server)</string>
<string name="status_state_active">Sendet</string>
<string name="status_fps">Sende-FPS</string>
<string name="status_target_fps">Ziel-FPS</string>
<string name="status_capture">Capture</string>
<string name="status_frames">Frames</string>
<string name="status_black">schwarz</string>
<string name="status_leds">LEDs</string>
<string name="status_priority">Priorität</string>
<string name="status_avg_color">Nur Durchschnittsfarbe</string>
<string name="status_not_configured">Server nicht konfiguriert</string>
<string name="credit_modified_by">modified by Robin Hartung</string>
<string name="error_no_host_name_extra">Eigentlich sollte hier eine IP Adresse eingegeben werden</string> <string name="error_no_host_name_extra">Eigentlich sollte hier eine IP Adresse eingegeben werden</string>
<string name="notification_channel_label">Hyperion Grabber Benachrichtigungen</string> <string name="notification_channel_label">Hyperion Grabber Benachrichtigungen</string>
<string name="notification_description">Bildschirminhalt wird übertragen</string> <string name="notification_description">Bildschirminhalt wird übertragen</string>
+18
View File
@@ -67,6 +67,24 @@
<string name="error_media_projection_denied">Screen recording permission was denied. Please grant permission when prompted</string> <string name="error_media_projection_denied">Screen recording permission was denied. Please grant permission when prompted</string>
<string name="toast_must_give_permission">Permission must be granted to record screen data.</string> <string name="toast_must_give_permission">Permission must be granted to record screen data.</string>
<string name="message_service_started">Press Back to close the app. Your screen content will continue to be sent to Hyperion</string> <string name="message_service_started">Press Back to close the app. Your screen content will continue to be sent to Hyperion</string>
<string name="status_server">Server</string>
<string name="status_state">Status</string>
<string name="status_state_off">Off</string>
<string name="status_state_connecting">Connecting…</string>
<string name="status_state_reconnecting">Reconnecting…</string>
<string name="status_state_connected">Connected</string>
<string name="status_state_capturing">Capturing (no server)</string>
<string name="status_state_active">Sending</string>
<string name="status_fps">Send FPS</string>
<string name="status_target_fps">Target FPS</string>
<string name="status_capture">Capture</string>
<string name="status_frames">Frames</string>
<string name="status_black">black</string>
<string name="status_leds">LEDs</string>
<string name="status_priority">Priority</string>
<string name="status_avg_color">Average color mode</string>
<string name="status_not_configured">Server not configured</string>
<string name="credit_modified_by">modified by Robin Hartung</string>
<string name="error_no_host_name_extra">That\'s weird, expected a hostname here</string> <string name="error_no_host_name_extra">That\'s weird, expected a hostname here</string>
<string name="notification_channel_label">Hyperion Grabber Notifications</string> <string name="notification_channel_label">Hyperion Grabber Notifications</string>
<string name="notification_description">Currently grabbing screen content</string> <string name="notification_description">Currently grabbing screen content</string>
Binary file not shown.