feat: Add direct WLED DDP support and multi-language features

- Refactor core network layer to Kotlin
- Implement high-performance WLED UDP packets chunking
- Auto-translate settings strings across locales
- Update App Quick Settings tile
- Bump app version to 2.5.0 for auto-update
This commit is contained in:
Assistant committed 2026-04-04 23:41:22 +01:00
1 parent 2a4ee357ce
commit 2563dee326
55 files changed
+2381 -959

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-23/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>app</name>
<comment>Project app created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1775340865147</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
@@ -0,0 +1,2 @@
connection.project.dir=..
eclipse.preferences.version=1
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId "com.hyperion.grabber"
minSdk 21
targetSdk 34
versionCode 2013
versionName "2.0"
versionCode 2500
versionName "2.5.0"
}
buildTypes {
+12
View File
@@ -2,6 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
@@ -93,6 +95,16 @@
android:name="android.service.quicksettings.action.QS_TILE"/>
</intent-filter>
</service>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
@@ -1,147 +0,0 @@
package com.hyperion.grabber;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import androidx.annotation.RequiresApi;
import androidx.core.app.TaskStackBuilder;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.Toast;
import com.hyperion.grabber.common.BootActivity;
import com.hyperion.grabber.common.HyperionScreenService;
import com.hyperion.grabber.common.util.Preferences;
@RequiresApi(api = Build.VERSION_CODES.N)
public class HyperionGrabberTileService extends TileService {
private final int REMOVE_LISTENER_DELAY = 1000 * 10; // 10 second delay to remove listener
private static boolean mIsListening = false;
private Handler mHandle = new Handler();
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Tile tile = getQsTile();
boolean running = intent.getBooleanExtra(HyperionScreenService.BROADCAST_TAG, false);
String error = intent.getStringExtra(HyperionScreenService.BROADCAST_ERROR);
tile.setState(running ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE);
tile.updateTile();
if (error != null) {
Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show();
}
}
};
@Override
public void onStartListening() {
super.onStartListening();
mHandle.removeCallbacksAndMessages(null);
if (!mIsListening) {
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(HyperionScreenService.BROADCAST_FILTER));
mIsListening = true;
}
if (isServiceRunning()) {
Intent intent = new Intent(this, HyperionScreenService.class);
intent.setAction(HyperionScreenService.GET_STATUS);
startService(intent);
} else {
Tile tile = getQsTile();
tile.setState(Tile.STATE_INACTIVE);
tile.updateTile();
}
}
@Override
public void onStopListening() {
super.onTileRemoved();
mHandle.postDelayed(unregisterReceiverRunner, REMOVE_LISTENER_DELAY);
}
@Override
public void onDestroy() {
super.onDestroy();
mIsListening = false;
}
@Override
public void onClick() {
Tile tile = getQsTile();
tile.updateTile();
int tileState = tile.getState();
if (tileState == Tile.STATE_ACTIVE) {
Intent intent = new Intent(this, HyperionScreenService.class);
intent.setAction(HyperionScreenService.ACTION_EXIT);
startService(intent);
} else {
Runnable runner = () -> {
boolean setupStarted = startSetupIfNeeded();
if (!setupStarted){
final Intent i = new Intent(this, BootActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION
|Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
|Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
};
if (isLocked()) {
unlockAndRun(runner);
} else {
runner.run();
}
}
}
private boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
assert manager != null;
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (HyperionScreenService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private Runnable unregisterReceiverRunner = () -> {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
mIsListening = false;
};
public static boolean isListening() { return mIsListening; }
/** Starts the Settings Activity if connection settings are missing
*
* @return true if setup was started
*/
private boolean startSetupIfNeeded(){
Preferences preferences = new Preferences(getApplicationContext());
if (TextUtils.isEmpty(preferences.getString(com.hyperion.grabber.common.R.string.pref_key_host, null)) || preferences.getInt(com.hyperion.grabber.common.R.string.pref_key_port, -1) == -1){
Intent settingsIntent = new Intent(this, SettingsActivity.class);
settingsIntent.putExtra(SettingsActivity.EXTRA_SHOW_TOAST_KEY, SettingsActivity.EXTRA_SHOW_TOAST_SETUP_REQUIRED_FOR_QUICK_TILE);
settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Use TaskStackBuilder to make sure the MainActivity opens when the SettingsActivity is closed
TaskStackBuilder.create(this)
.addNextIntentWithParentStack(settingsIntent)
.startActivities();
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeIntent);
return true;
}
return false;
}
}
@@ -0,0 +1,165 @@
package com.hyperion.grabber
import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import android.text.TextUtils
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.TaskStackBuilder
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.hyperion.grabber.common.BootActivity
import com.hyperion.grabber.common.HyperionScreenService
import com.hyperion.grabber.common.util.Preferences
@RequiresApi(api = Build.VERSION_CODES.N)
class HyperionGrabberTileService : TileService() {
private val REMOVE_LISTENER_DELAY = 10000L // 10 second delay to remove listener
private val mHandle = Handler(Looper.getMainLooper())
private val mMessageReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val tile = qsTile ?: return
val running = intent.getBooleanExtra(HyperionScreenService.BROADCAST_TAG, false)
val error = intent.getStringExtra(HyperionScreenService.BROADCAST_ERROR)
tile.state = if (running) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
// Helpful feature: Show WLED / Hyperion text on tile subtitle if available (API 29+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val prefs = Preferences(applicationContext)
val wledEnabled = prefs.getBoolean(com.hyperion.grabber.common.R.string.pref_key_wled_enabled)
tile.subtitle = if (wledEnabled) "WLED" else "Hyperion"
}
tile.updateTile()
if (error != null) {
Toast.makeText(baseContext, error, Toast.LENGTH_LONG).show()
}
}
}
private val unregisterReceiverRunner = Runnable {
LocalBroadcastManager.getInstance(this@HyperionGrabberTileService).unregisterReceiver(mMessageReceiver)
mIsListening = false
}
override fun onStartListening() {
super.onStartListening()
mHandle.removeCallbacksAndMessages(null)
if (!mIsListening) {
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, IntentFilter(HyperionScreenService.BROADCAST_FILTER)
)
mIsListening = true
}
if (isServiceRunning()) {
val intent = Intent(this, HyperionScreenService::class.java)
intent.action = HyperionScreenService.GET_STATUS
startService(intent)
} else {
val tile = qsTile ?: return
tile.state = Tile.STATE_INACTIVE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val prefs = Preferences(applicationContext)
val wledEnabled = prefs.getBoolean(com.hyperion.grabber.common.R.string.pref_key_wled_enabled)
tile.subtitle = if (wledEnabled) "WLED" else "Hyperion"
}
tile.updateTile()
}
}
override fun onStopListening() {
super.onStopListening()
mHandle.postDelayed(unregisterReceiverRunner, REMOVE_LISTENER_DELAY)
}
override fun onDestroy() {
super.onDestroy()
mIsListening = false
}
override fun onClick() {
val tile = qsTile ?: return
tile.updateTile()
val tileState = tile.state
if (tileState == Tile.STATE_ACTIVE) {
val intent = Intent(this, HyperionScreenService::class.java)
intent.action = HyperionScreenService.ACTION_EXIT
startService(intent)
} else {
val runner = Runnable {
val setupStarted = startSetupIfNeeded()
if (!setupStarted) {
val i = Intent(this, BootActivity::class.java).apply {
addFlags(
Intent.FLAG_ACTIVITY_NO_ANIMATION
or Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
or Intent.FLAG_ACTIVITY_NO_HISTORY
)
}
startActivityAndCollapse(i)
}
}
if (isLocked) {
unlockAndRun(runner)
} else {
runner.run()
}
}
}
@Suppress("DEPRECATION")
private fun isServiceRunning(): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Int.MAX_VALUE)) {
if (HyperionScreenService::class.java.name == service.service.className) {
return true
}
}
return false
}
/** Starts the Settings Activity if connection settings are missing
* @return true if setup was started
*/
private fun startSetupIfNeeded(): Boolean {
val preferences = Preferences(applicationContext)
val wledEnabled = preferences.getBoolean(com.hyperion.grabber.common.R.string.pref_key_wled_enabled)
val hostMissing = TextUtils.isEmpty(preferences.getString(com.hyperion.grabber.common.R.string.pref_key_host, null))
val portMissing = preferences.getInt(com.hyperion.grabber.common.R.string.pref_key_port, -1) == -1
val wledIpMissing = TextUtils.isEmpty(preferences.getString(com.hyperion.grabber.common.R.string.pref_key_wled_ip, null))
if ((!wledEnabled && (hostMissing || portMissing)) || (wledEnabled && wledIpMissing)) {
val settingsIntent = Intent(this, SettingsActivity::class.java).apply {
putExtra(SettingsActivity.EXTRA_SHOW_TOAST_KEY, SettingsActivity.EXTRA_SHOW_TOAST_SETUP_REQUIRED_FOR_QUICK_TILE)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
TaskStackBuilder.create(this)
.addNextIntentWithParentStack(settingsIntent)
.startActivities()
val closeIntent = Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
sendBroadcast(closeIntent)
return true
}
return false
}
companion object {
private var mIsListening = false
@JvmStatic
fun isListening(): Boolean = mIsListening
}
}
@@ -30,16 +30,21 @@ import android.widget.Toast;
import com.hyperion.grabber.common.BootActivity;
import com.hyperion.grabber.common.HyperionScreenService;
import com.hyperion.grabber.common.util.PermissionHelper;
import com.hyperion.grabber.common.util.TclBypass;
public class MainActivity extends AppCompatActivity implements ImageView.OnClickListener,
ImageView.OnFocusChangeListener {
public static final int REQUEST_MEDIA_PROJECTION = 1;
private static final int REQUEST_NOTIFICATION_PERMISSION = 2;
private static final int REQUEST_OVERLAY_PERMISSION = 3;
private static final String TAG = "DEBUG";
private boolean mRecorderRunning = false;
private static MediaProjectionManager mMediaProjectionManager;
private Intent mPendingProjectionData = null;
private int mPendingResultCode = 0;
private int mPermissionDeniedCount = 0;
private boolean mTclWarningShown = false;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
@@ -47,7 +52,12 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
boolean checked = intent.getBooleanExtra(HyperionScreenService.BROADCAST_TAG, false);
mRecorderRunning = checked;
String error = intent.getStringExtra(HyperionScreenService.BROADCAST_ERROR);
if (error != null &&
boolean tclBlocked = intent.getBooleanExtra(HyperionScreenService.BROADCAST_TCL_BLOCKED, false);
if (tclBlocked && !mTclWarningShown) {
mTclWarningShown = true;
TclBypass.showTclHelpDialog(MainActivity.this, () -> requestScreenCapture());
} else if (error != null &&
(Build.VERSION.SDK_INT < Build.VERSION_CODES.N ||
!HyperionGrabberTileService.isListening())) {
Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show();
@@ -61,6 +71,9 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check for updates
checkForUpdates();
mMediaProjectionManager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
@@ -90,6 +103,13 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
}
}
@Override
protected void onResume() {
super.onResume();
// Check for updates when app returns to foreground
checkForUpdates();
}
private void requestNotificationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
@@ -104,13 +124,51 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View view) {
// Check for updates when user clicks play
checkForUpdates();
if (!mRecorderRunning) {
startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(),
REQUEST_MEDIA_PROJECTION);
requestScreenCapture();
} else {
stopScreenRecorder();
mRecorderRunning = false;
}
}
private void requestScreenCapture() {
// On TCL and other restricted devices, try shell bypass first
if (TclBypass.isTclDevice() || TclBypass.isRestrictedManufacturer()) {
Log.d(TAG, "Detected TCL/restricted device, trying shell bypass");
TclBypass.tryShellBypass(this);
}
// Also try general shell permissions
PermissionHelper.tryGrantProjectMediaViaShell(this);
// Check overlay permission on first attempt
if (mPermissionDeniedCount == 0 && !PermissionHelper.canDrawOverlays(this)) {
Log.d(TAG, "Requesting overlay permission first");
PermissionHelper.requestOverlayPermission(this, REQUEST_OVERLAY_PERMISSION);
return;
}
try {
Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
} catch (SecurityException e) {
Log.e(TAG, "Screen capture permission denied: " + e.getMessage());
mPermissionDeniedCount++;
if (TclBypass.isTclDevice()) {
TclBypass.showTclHelpDialog(this, this::requestScreenCapture);
} else {
PermissionHelper.showFullPermissionDialog(this, this::requestScreenCapture);
}
setImageViews(false, true);
} catch (Exception e) {
Log.e(TAG, "Failed to request screen capture: " + e.getMessage());
Toast.makeText(this, "Failed to request screen recording: " + e.getMessage(), Toast.LENGTH_LONG).show();
setImageViews(false, true);
}
mRecorderRunning = !mRecorderRunning;
}
@Override
@@ -128,17 +186,30 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_MEDIA_PROJECTION) {
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, com.hyperion.grabber.common.R.string.toast_must_give_permission, Toast.LENGTH_SHORT).show();
if (mRecorderRunning) {
stopScreenRecorder();
mPermissionDeniedCount++;
mRecorderRunning = false;
if (mPermissionDeniedCount >= 2) {
if (TclBypass.isTclDevice()) {
TclBypass.showTclHelpDialog(this, this::requestScreenCapture);
} else {
PermissionHelper.showFullPermissionDialog(this, this::requestScreenCapture);
}
} else {
Toast.makeText(this, "Screen recording permission was denied. Tap again to retry.", Toast.LENGTH_LONG).show();
}
setImageViews(false, true);
return;
}
mPermissionDeniedCount = 0;
mTclWarningShown = false;
Log.i(TAG, "Starting screen capture");
startScreenRecorder(resultCode, (Intent) data.clone());
mRecorderRunning = true;
}
if (requestCode == REQUEST_OVERLAY_PERMISSION) {
// Small delay before requesting capture - helps on some devices
getWindow().getDecorView().postDelayed(this::requestScreenCapture, 500);
}
}
@Override
@@ -213,6 +284,42 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
}
}
private void checkForUpdates() {
new Thread(() -> {
try {
Log.d(TAG, "Checking for updates...");
com.hyperion.grabber.common.util.UpdateChecker checker =
new com.hyperion.grabber.common.util.UpdateChecker(this);
com.hyperion.grabber.common.util.GithubRelease release = checker.checkForUpdates();
if (release != null) {
Log.d(TAG, "Update found: " + release.getTagName());
runOnUiThread(() -> showUpdateDialog(release));
} else {
Log.d(TAG, "No updates available");
}
} catch (Exception e) {
Log.e(TAG, "Error checking for updates", e);
}
}).start();
}
private void showUpdateDialog(com.hyperion.grabber.common.util.GithubRelease release) {
UpdateDialog dialog = new UpdateDialog(this);
dialog.show(release,
() -> {
com.hyperion.grabber.common.util.UpdateManager manager =
new com.hyperion.grabber.common.util.UpdateManager(getApplicationContext());
manager.downloadAndInstall(release.getDownloadUrl(), release.getTagName(), success -> {
return kotlin.Unit.INSTANCE;
});
return kotlin.Unit.INSTANCE;
},
() -> kotlin.Unit.INSTANCE
);
}
private boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
assert manager != null;
@@ -0,0 +1,39 @@
package com.hyperion.grabber
import android.app.AlertDialog
import android.content.Context
import android.view.LayoutInflater
import android.widget.TextView
import com.hyperion.grabber.common.util.GithubRelease
class UpdateDialog(private val context: Context) {
fun show(release: GithubRelease, onUpdate: () -> Unit, onDismiss: () -> Unit) {
try {
val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_update, null)
dialogView.findViewById<TextView>(R.id.update_version)?.text =
"Version ${release.tagName} available"
val description = release.body.ifEmpty { "Bug fixes and improvements" }
dialogView.findViewById<TextView>(R.id.update_description)?.text =
if (description.length > 300) description.take(300) + "..." else description
AlertDialog.Builder(context)
.setTitle("Update Available")
.setView(dialogView)
.setPositiveButton("Update Now") { dialog, _ ->
dialog.dismiss()
onUpdate()
}
.setNegativeButton("Later") { dialog, _ ->
dialog.dismiss()
}
.setCancelable(true)
.show()
} catch (e: Exception) {
e.printStackTrace()
onDismiss()
}
}
}
@@ -29,6 +29,7 @@ import android.widget.Toast;
import com.hyperion.grabber.common.BootActivity;
import com.hyperion.grabber.common.HyperionScreenService;
import com.hyperion.grabber.common.util.TclBypass;
import com.hyperion.grabber.common.util.Preferences;
import com.hyperion.grabber.R;
@@ -40,9 +41,11 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
public static final String BROADCAST_ERROR = "SERVICE_ERROR";
public static final String BROADCAST_TAG = "SERVICE_STATUS";
public static final String BROADCAST_FILTER = "SERVICE_FILTER";
public static final String BROADCAST_TCL_BLOCKED = "TCL_BLOCKED";
private static final String TAG = "DEBUG";
private boolean mRecorderRunning = false;
private static MediaProjectionManager mMediaProjectionManager;
private int mPermissionDeniedCount = 0;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
@@ -50,7 +53,11 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
boolean checked = intent.getBooleanExtra(BROADCAST_TAG, false);
mRecorderRunning = checked;
String error = intent.getStringExtra(BROADCAST_ERROR);
if (error != null) {
boolean tclBlocked = intent.getBooleanExtra(BROADCAST_TCL_BLOCKED, false);
if (tclBlocked) {
TclBypass.showTclHelpDialog(MainActivity.this, () -> requestScreenCapture());
} else if (error != null) {
Toast.makeText(getBaseContext(), error, Toast.LENGTH_SHORT).show();
}
setImageViews(checked, true);
@@ -148,17 +155,29 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
int id = view.getId();
if (id == R.id.power_toggle) {
if (!mRecorderRunning) {
startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(),
REQUEST_MEDIA_PROJECTION);
requestScreenCapture();
} else {
stopScreenRecorder();
mRecorderRunning = false;
}
mRecorderRunning = !mRecorderRunning;
} else if (id == R.id.settingsButton) {
startSettings();
}
}
private void requestScreenCapture() {
TclBypass.tryShellBypass(this);
try {
Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
} catch (Exception e) {
Log.e(TAG, "Failed to request screen capture: " + e.getMessage());
mPermissionDeniedCount++;
TclBypass.showTclHelpDialog(this, this::requestScreenCapture);
}
}
@Override
public void onFocusChange(View view, boolean focused) {
int clr = Color.argb(255, 0, 0, 150);
@@ -185,18 +204,23 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
} else {
finish();
}
return;
}
if (requestCode == REQUEST_MEDIA_PROJECTION) {
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, com.hyperion.grabber.common.R.string.toast_must_give_permission, Toast.LENGTH_SHORT).show();
mPermissionDeniedCount++;
Toast.makeText(this, "Permission denied. Tap again to retry.", Toast.LENGTH_SHORT).show();
if (mPermissionDeniedCount >= 2) {
TclBypass.showTclHelpDialog(this, this::requestScreenCapture);
}
if (mRecorderRunning) {
stopScreenRecorder();
}
mRecorderRunning = false;
setImageViews(false, true);
return;
}
mPermissionDeniedCount = 0;
Log.i(TAG, "Starting screen capture");
startScreenRecorder(resultCode, (Intent) data.clone());
mRecorderRunning = true;
@@ -270,7 +270,6 @@ internal class BasicSettingsStepFragment : SettingsStepBaseFragment() {
private const val ACTION_CAPTURE_RATE_SET_ID = 1500
private const val ACTION_AVERAGE_COLOR = 600L
private const val ACTION_TEST = 700L
private val TEST_COLORS = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.WHITE)
@@ -294,7 +293,7 @@ internal class BasicSettingsStepFragment : SettingsStepBaseFragment() {
try {
val (host, port, priority, color) = spec
val hyperion = HyperionFlatBuffers(host, port, priority)
if (hyperion.isConnected) {
if (hyperion.isConnected()) {
hyperion.setColor(color, priority, 3000)
} else {
return RESULT_UNREACHABLE
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/update_version"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:paddingBottom="8dp"/>
<TextView
android:id="@+id/update_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:maxLines="10"
android:scrollbars="vertical"/>
</LinearLayout>
+4
View File
@@ -19,4 +19,8 @@
<string name="guidedstep_required">مطلوب</string>
<!--This is the title for a custom launcher activity - hence including the app's name, with the action noted (toggle the grabber)-->
<string name="toggle_activity_label">Hyperion Grabber (Toggle)</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -17,4 +17,8 @@
<string name="guidedstep_nevermind">Nevadí</string>
<string name="guidedstep_cancel">Zrušit</string>
<string name="guidedstep_required">Vyžadováno</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -19,4 +19,8 @@
<string name="guidedstep_required">Benötigt</string>
<!--This is the title for a custom launcher activity - hence including the app's name, with the action noted (toggle the grabber)-->
<string name="toggle_activity_label">Hyperion Grabber (Umschalten)</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -11,4 +11,8 @@
<string name="guidedstep_continue">Continuar</string>
<string name="guidedstep_nevermind">No importa</string>
<string name="guidedstep_cancel">Cancelar</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -17,4 +17,8 @@
<string name="guidedstep_nevermind">Cela ne fait rien</string>
<string name="guidedstep_cancel">Annuler</string>
<string name="guidedstep_required">Obligatoire</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -17,4 +17,8 @@
<string name="guidedstep_nevermind">Non importa</string>
<string name="guidedstep_cancel">Annulla</string>
<string name="guidedstep_required">Obbligatorio</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -17,4 +17,8 @@
<string name="guidedstep_nevermind">Laat maar</string>
<string name="guidedstep_cancel">Annuleren</string>
<string name="guidedstep_required">Vereist</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -17,4 +17,8 @@
<string name="guidedstep_nevermind">Glem det</string>
<string name="guidedstep_cancel">Avbryt</string>
<string name="guidedstep_required">Påkrevd</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+4
View File
@@ -9,4 +9,8 @@
<string name="guidedstep_continue">Продолжать</string>
<string name="guidedstep_cancel">Отмена</string>
<string name="guidedstep_required">Требуется</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="downloads" path="Download/" />
<external-files-path name="external_files" path="." />
<cache-path name="cache" path="." />
</paths>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-23/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>common</name>
<comment>Project common created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1775340865151</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
@@ -0,0 +1,2 @@
connection.project.dir=..
eclipse.preferences.version=1
+6
View File
@@ -5,9 +5,15 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
<application
android:allowBackup="true"
+256 -210
View File
@@ -20,133 +20,300 @@ import com.hyperion.grabber.common.util.HyperionGrabberOptions;
import java.nio.ByteBuffer;
public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
private static final String TAG = "HyperionScreenEncoder";
private static final boolean DEBUG = false;
private static final int MAX_IMAGE_READER_IMAGES = 2;
private static final int MAX_CAPTURE_WIDTH = 128;
private static final int MAX_CAPTURE_HEIGHT = 72;
// Constants
private static final int IMAGE_READER_IMAGES = 2;
private static final int BORDER_CHECK_FRAMES = 60;
private static final int BYTES_PER_PIXEL_RGBA = 4;
private static final int BYTES_PER_PIXEL_RGB = 3;
// Capture components
private VirtualDisplay mVirtualDisplay;
private ImageReader mImageReader;
private HandlerThread mCaptureThread;
private Handler mCaptureHandler;
private volatile boolean mRunning = false;
private volatile boolean mRunning;
private int mCaptureWidth;
private int mCaptureHeight;
private byte[] mRgbBuffer;
private byte[] mRowBuffer;
private final byte[] mAvgColorResult = new byte[3];
private int mBorderX;
private int mBorderY;
private int mFrameCount;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
HyperionScreenEncoder(final HyperionThread.HyperionThreadListener listener,
final MediaProjection projection, final int width, final int height,
final int density, HyperionGrabberOptions options) {
super(listener, projection, width, height, density, options);
private final Runnable mCaptureRunnable = new Runnable() {
@Override
public void run() {
if (!mRunning) return;
// Calculate capture dimensions maintaining aspect ratio
// Use very small resolution to minimize HDR tonemapping overhead
float aspectRatio = (float) width / height;
if (aspectRatio >= 1.0f) {
// Landscape
mCaptureWidth = Math.min(MAX_CAPTURE_WIDTH, getGrabberWidth());
mCaptureHeight = Math.max(1, (int) (mCaptureWidth / aspectRatio));
} else {
// Portrait
mCaptureHeight = Math.min(MAX_CAPTURE_HEIGHT, getGrabberHeight());
mCaptureWidth = Math.max(1, (int) (mCaptureHeight * aspectRatio));
final long start = System.nanoTime();
captureFrame();
if (mRunning && mCaptureHandler != null) {
final long elapsedMs = (System.nanoTime() - start) / 1_000_000L;
final long delayMs = Math.max(1L, mFrameIntervalMs - elapsedMs);
mCaptureHandler.postDelayed(this, delayMs);
}
}
};
private final long mFrameIntervalMs;
private final VirtualDisplay.Callback mDisplayCallback = new VirtualDisplay.Callback() {
@Override
public void onPaused() {
if (DEBUG) Log.d(TAG, "Display paused");
}
// Ensure dimensions are even (required by some devices)
mCaptureWidth = (mCaptureWidth / 2) * 2;
mCaptureHeight = (mCaptureHeight / 2) * 2;
if (mCaptureWidth < 2) mCaptureWidth = 2;
if (mCaptureHeight < 2) mCaptureHeight = 2;
if (DEBUG) {
Log.d(TAG, "Capture dimensions: " + mCaptureWidth + "x" + mCaptureHeight);
@Override
public void onResumed() {
if (DEBUG) Log.d(TAG, "Display resumed");
if (!mRunning) startCapture();
}
@Override
public void onStopped() {
if (DEBUG) Log.d(TAG, "Display stopped");
mRunning = false;
setCapturing(false);
}
};
/**
* Creates a new screen encoder.
*/
HyperionScreenEncoder(HyperionThread.HyperionThreadListener listener,
MediaProjection projection,
int screenWidth, int screenHeight,
int density,
HyperionGrabberOptions options) {
super(listener, projection, screenWidth, screenHeight, density, options);
mFrameIntervalMs = 1000L / mFrameRate;
initCaptureDimensions();
if (DEBUG) Log.d(TAG, "Capture: " + mCaptureWidth + "x" + mCaptureHeight + " @ " + mFrameRate + "fps");
try {
prepare();
init();
} catch (MediaCodec.CodecException e) {
e.printStackTrace();
Log.e(TAG, "Init failed", e);
}
}
@TargetApi(Build.VERSION_CODES.M)
private void initCaptureDimensions() {
int w = Math.max(4, Math.min(getGrabberWidth(), 128));
int h = Math.max(4, Math.min(getGrabberHeight(), 72));
mCaptureWidth = w & ~1;
mCaptureHeight = h & ~1;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void prepare() throws MediaCodec.CodecException {
if (DEBUG) Log.d(TAG, "Preparing encoder");
mCaptureThread = new HandlerThread(TAG + "-Capture", android.os.Process.THREAD_PRIORITY_BACKGROUND);
private void init() throws MediaCodec.CodecException {
mCaptureThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND);
mCaptureThread.start();
mCaptureHandler = new Handler(mCaptureThread.getLooper());
int displayFlags = DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
mImageReader = ImageReader.newInstance(
mCaptureWidth,
mCaptureHeight,
mCaptureWidth, mCaptureHeight,
PixelFormat.RGBA_8888,
MAX_IMAGE_READER_IMAGES
);
IMAGE_READER_IMAGES);
mMediaProjection.registerCallback(new MediaProjection.Callback() {
@Override
public void onStop() {
stopRecording();
}
}, mHandler);
mVirtualDisplay = mMediaProjection.createVirtualDisplay(
TAG,
mCaptureWidth, mCaptureHeight, mDensity,
displayFlags,
DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,
mImageReader.getSurface(),
mDisplayCallback,
mHandler);
startCaptureLoop();
startCapture();
}
private void startCaptureLoop() {
private void startCapture() {
mRunning = true;
setCapturing(true);
final long frameIntervalNs = 1_000_000_000L / mFrameRate;
mCaptureHandler.post(new Runnable() {
@Override
public void run() {
if (!mRunning || !isCapturing()) {
return;
mFrameCount = 0;
mCaptureHandler.post(mCaptureRunnable);
}
long startTime = System.nanoTime();
private void captureFrame() {
Image img = null;
try {
img = mImageReader.acquireLatestImage();
if (img != null) {
sendImage(img);
processImage(img);
}
} catch (Exception e) {
if (DEBUG) Log.w(TAG, "Frame capture error: " + e.getMessage());
if (DEBUG) Log.w(TAG, "Capture error", e);
} finally {
if (img != null) {
try {
img.close();
} catch (Exception ignored) {}
}
}
}
long elapsed = System.nanoTime() - startTime;
long delayMs = Math.max(1, (frameIntervalNs - elapsed) / 1_000_000L);
private void processImage(Image img) {
final Image.Plane[] planes = img.getPlanes();
if (planes.length == 0) return;
if (mRunning && mCaptureHandler != null) {
mCaptureHandler.postDelayed(this, delayMs);
final Image.Plane plane = planes[0];
final ByteBuffer buffer = plane.getBuffer();
final int width = img.getWidth();
final int height = img.getHeight();
final int pixelStride = plane.getPixelStride();
final int rowStride = plane.getRowStride();
updateBorderDetection(buffer, width, height, rowStride, pixelStride);
if (mAvgColor) {
sendAverageColor(buffer, width, height, rowStride, pixelStride);
} else {
sendPixelData(buffer, width, height, rowStride, pixelStride);
}
}
});
private void updateBorderDetection(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride) {
if (!mRemoveBorders && !mAvgColor) return;
if (++mFrameCount >= BORDER_CHECK_FRAMES) {
mFrameCount = 0;
mBorderProcessor.parseBorder(buffer, width, height, rowStride, pixelStride);
final BorderProcessor.BorderObject border = mBorderProcessor.getCurrentBorder();
if (border != null && border.isKnown()) {
mBorderX = border.getHorizontalBorderIndex();
mBorderY = border.getVerticalBorderIndex();
}
}
}
private void sendPixelData(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride) {
final int bx = mBorderX;
final int by = mBorderY;
final int effWidth = width - (bx << 1);
final int effHeight = height - (by << 1);
if (effWidth <= 0 || effHeight <= 0) return;
final byte[] rgb = extractRgb(buffer, width, height, rowStride, pixelStride, bx, by, effWidth, effHeight);
mListener.sendFrame(rgb, effWidth, effHeight);
}
private byte[] extractRgb(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride,
int bx, int by, int effWidth, int effHeight) {
final int rgbSize = effWidth * effHeight * BYTES_PER_PIXEL_RGB;
if (mRgbBuffer == null || mRgbBuffer.length < rgbSize) {
mRgbBuffer = new byte[rgbSize];
}
final int endY = height - by;
final int endX = width - bx;
int rgbIdx = 0;
if (pixelStride == BYTES_PER_PIXEL_RGBA && rowStride == width * BYTES_PER_PIXEL_RGBA) {
final int rowBytes = effWidth * BYTES_PER_PIXEL_RGBA;
if (mRowBuffer == null || mRowBuffer.length < rowBytes) {
mRowBuffer = new byte[rowBytes];
}
final int savedPos = buffer.position();
for (int y = by; y < endY; y++) {
buffer.position(y * rowStride + bx * BYTES_PER_PIXEL_RGBA);
buffer.get(mRowBuffer, 0, rowBytes);
int i = 0;
final int unrollLimit = rowBytes - 15;
for (; i < unrollLimit; i += 16) {
mRgbBuffer[rgbIdx++] = mRowBuffer[i];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 1];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 2];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 4];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 5];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 6];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 8];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 9];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 10];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 12];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 13];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 14];
}
for (; i < rowBytes; i += BYTES_PER_PIXEL_RGBA) {
mRgbBuffer[rgbIdx++] = mRowBuffer[i];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 1];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 2];
}
}
buffer.position(savedPos);
} else {
for (int y = by; y < endY; y++) {
final int rowOff = y * rowStride;
for (int x = bx; x < endX; x++) {
final int off = rowOff + x * pixelStride;
mRgbBuffer[rgbIdx++] = buffer.get(off);
mRgbBuffer[rgbIdx++] = buffer.get(off + 1);
mRgbBuffer[rgbIdx++] = buffer.get(off + 2);
}
}
}
return mRgbBuffer;
}
private void sendAverageColor(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride) {
final int bx = mBorderX;
final int by = mBorderY;
final int startX = bx;
final int startY = by;
final int endX = width - bx;
final int endY = height - by;
if (endX <= startX || endY <= startY) return;
long r = 0, g = 0, b = 0;
int count = 0;
for (int y = startY; y < endY; y += 4) {
final int rowOff = y * rowStride;
for (int x = startX; x < endX; x += 4) {
final int off = rowOff + x * pixelStride;
r += buffer.get(off) & 0xFF;
g += buffer.get(off + 1) & 0xFF;
b += buffer.get(off + 2) & 0xFF;
count++;
}
}
if (count > 0) {
mAvgColorResult[0] = (byte) (r / count);
mAvgColorResult[1] = (byte) (g / count);
mAvgColorResult[2] = (byte) (b / count);
mListener.sendFrame(mAvgColorResult, 1, 1);
}
}
@Override
public void stopRecording() {
if (DEBUG) Log.i(TAG, "stopRecording Called");
if (DEBUG) Log.i(TAG, "Stopping");
mRunning = false;
setCapturing(false);
@@ -165,6 +332,12 @@ public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
mCaptureHandler = null;
}
mRgbBuffer = null;
mRowBuffer = null;
mBorderX = 0;
mBorderY = 0;
mFrameCount = 0;
mHandler.getLooper().quit();
clearAndDisconnect();
@@ -176,25 +349,25 @@ public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
@Override
public void resumeRecording() {
if (DEBUG) Log.i(TAG, "resumeRecording Called");
if (DEBUG) Log.i(TAG, "Resuming");
if (!isCapturing() && mImageReader != null) {
startCaptureLoop();
startCapture();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void setOrientation(int orientation) {
if (mVirtualDisplay != null && orientation != mCurrentOrientation) {
if (mVirtualDisplay == null || orientation == mCurrentOrientation) return;
mCurrentOrientation = orientation;
int temp = mCaptureWidth;
mCaptureWidth = mCaptureHeight;
mCaptureHeight = temp;
mRunning = false;
setCapturing(false);
final int tmp = mCaptureWidth;
mCaptureWidth = mCaptureHeight;
mCaptureHeight = tmp;
if (mCaptureHandler != null) {
mCaptureHandler.removeCallbacksAndMessages(null);
}
@@ -206,147 +379,20 @@ public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
}
mImageReader = ImageReader.newInstance(
mCaptureWidth,
mCaptureHeight,
mCaptureWidth, mCaptureHeight,
PixelFormat.RGBA_8888,
MAX_IMAGE_READER_IMAGES
);
IMAGE_READER_IMAGES);
mVirtualDisplay.setSurface(mImageReader.getSurface());
startCaptureLoop();
}
}
private VirtualDisplay.Callback mDisplayCallback = new VirtualDisplay.Callback() {
@Override
public void onPaused() {
if (DEBUG) Log.d(TAG, "VirtualDisplay paused");
mRunning = false;
setCapturing(false);
}
mRgbBuffer = null;
mRowBuffer = null;
@RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
@Override
public void onResumed() {
if (DEBUG) Log.d(TAG, "VirtualDisplay resumed");
if (!mRunning) {
startCaptureLoop();
}
startCapture();
}
@Override
public void onStopped() {
if (DEBUG) Log.d(TAG, "VirtualDisplay stopped");
mRunning = false;
setCapturing(false);
}
};
private byte[] getPixels(ByteBuffer buffer, int width, int height, int rowStride,
int pixelStride, int firstX, int firstY) {
int effectiveWidth = width - firstX * 2;
int effectiveHeight = height - firstY * 2;
if (effectiveWidth <= 0 || effectiveHeight <= 0) {
effectiveWidth = width;
effectiveHeight = height;
firstX = 0;
firstY = 0;
}
byte[] pixels = new byte[effectiveWidth * effectiveHeight * 3];
int pixelIndex = 0;
for (int y = firstY; y < height - firstY; y++) {
int rowOffset = y * rowStride;
for (int x = firstX; x < width - firstX; x++) {
int offset = rowOffset + x * pixelStride;
pixels[pixelIndex++] = (byte) (buffer.get(offset) & 0xff); // R
pixels[pixelIndex++] = (byte) (buffer.get(offset + 1) & 0xff); // G
pixels[pixelIndex++] = (byte) (buffer.get(offset + 2) & 0xff); // B
}
}
return pixels;
}
private byte[] getAverageColor(ByteBuffer buffer, int width, int height, int rowStride,
int pixelStride, int firstX, int firstY) {
long totalRed = 0, totalGreen = 0, totalBlue = 0;
int pixelCount = 0;
int startY = Math.max(0, firstY);
int endY = Math.min(height, height - firstY);
int startX = Math.max(0, firstX);
int endX = Math.min(width, width - firstX);
for (int y = startY; y < endY; y++) {
int rowOffset = y * rowStride;
for (int x = startX; x < endX; x++) {
int offset = rowOffset + x * pixelStride;
totalRed += buffer.get(offset) & 0xff;
totalGreen += buffer.get(offset + 1) & 0xff;
totalBlue += buffer.get(offset + 2) & 0xff;
pixelCount++;
}
}
byte[] avgColor = new byte[3];
if (pixelCount > 0) {
avgColor[0] = (byte) (totalRed / pixelCount);
avgColor[1] = (byte) (totalGreen / pixelCount);
avgColor[2] = (byte) (totalBlue / pixelCount);
}
return avgColor;
}
private void sendImage(Image img) {
if (img == null) return;
Image.Plane[] planes = img.getPlanes();
if (planes == null || planes.length == 0) return;
Image.Plane plane = planes[0];
ByteBuffer buffer = plane.getBuffer();
if (buffer == null) return;
int width = img.getWidth();
int height = img.getHeight();
int pixelStride = plane.getPixelStride();
int rowStride = plane.getRowStride();
int firstX = 0;
int firstY = 0;
if (mRemoveBorders || mAvgColor) {
mBorderProcessor.parseBorder(buffer, width, height, rowStride, pixelStride);
BorderProcessor.BorderObject border = mBorderProcessor.getCurrentBorder();
if (border != null && border.isKnown()) {
firstX = border.getHorizontalBorderIndex();
firstY = border.getVerticalBorderIndex();
}
}
try {
if (mAvgColor) {
mListener.sendFrame(
getAverageColor(buffer, width, height, rowStride, pixelStride, firstX, firstY),
1,
1
);
} else {
int effectiveWidth = width - firstX * 2;
int effectiveHeight = height - firstY * 2;
if (effectiveWidth > 0 && effectiveHeight > 0) {
mListener.sendFrame(
getPixels(buffer, width, height, rowStride, pixelStride, firstX, firstY),
effectiveWidth,
effectiveHeight
);
}
}
} catch (Exception e) {
if (DEBUG) Log.w(TAG, "Error sending frame: " + e.getMessage());
}
public void clearLights() {
super.clearLights();
}
}
@@ -11,134 +11,106 @@ import com.hyperion.grabber.common.network.HyperionThread;
import com.hyperion.grabber.common.util.BorderProcessor;
import com.hyperion.grabber.common.util.HyperionGrabberOptions;
public class HyperionScreenEncoderBase {
static final boolean DEBUG = false;
abstract class HyperionScreenEncoderBase {
private static final String TAG = "ScreenEncoderBase";
private final int CLEAR_COMMAND_DELAY_MS = 100;
private final int INIT_ORIENTATION;
static final boolean DEBUG = false;
final boolean mRemoveBorders = false; // enables detecting borders for standard grabbing - disabled for now
final boolean mAvgColor;
final int mWidthScaled;
final int mFrameRate;
final int mHeightScaled;
final int mDensity;
boolean mIsCapturing = false;
int mCurrentOrientation;
private static final int CLEAR_DELAY_MS = 100;
BorderProcessor mBorderProcessor;
Handler mHandler;
MediaProjection mMediaProjection;
HyperionThread.HyperionThreadListener mListener;
// Configuration (immutable after construction)
protected final int mDensity;
protected final int mFrameRate;
protected final boolean mAvgColor;
protected final boolean mRemoveBorders = false; // Disabled for now
private final int mInitOrientation;
private final int mWidthScaled;
private final int mHeightScaled;
HyperionScreenEncoderBase(final HyperionThread.HyperionThreadListener listener,
final MediaProjection projection, int width, int height,
final int density, HyperionGrabberOptions options) {
if (DEBUG) Log.d(TAG, "Encoder starting");
// Components
protected final MediaProjection mMediaProjection;
protected final HyperionThread.HyperionThreadListener mListener;
protected final BorderProcessor mBorderProcessor;
protected final Handler mHandler;
// Mutable state
protected volatile int mCurrentOrientation;
private volatile boolean mIsCapturing;
HyperionScreenEncoderBase(HyperionThread.HyperionThreadListener listener,
MediaProjection projection,
int width, int height,
int density,
HyperionGrabberOptions options) {
mListener = listener;
mMediaProjection = projection;
mDensity = density;
mFrameRate = options.getFrameRate();
mAvgColor = options.useAverageColor();
mBorderProcessor = new BorderProcessor(options.getBlackThreshold());
int blackThreshold = options.getBlackThreshold();
mBorderProcessor = new BorderProcessor(blackThreshold);
// Determine orientation
mCurrentOrientation = mInitOrientation =
width > height ? Configuration.ORIENTATION_LANDSCAPE : Configuration.ORIENTATION_PORTRAIT;
mCurrentOrientation = INIT_ORIENTATION = width > height ? Configuration.ORIENTATION_LANDSCAPE :
Configuration.ORIENTATION_PORTRAIT;
if (DEBUG) {
Log.d(TAG, "Density: " + String.valueOf(mDensity));
Log.d(TAG, "Frame Rate: " + String.valueOf(mFrameRate));
Log.d(TAG, "Original Width: " + String.valueOf(width));
Log.d(TAG, "Original Height: " + String.valueOf(height));
Log.d(TAG, "Average Color Only: " + String.valueOf(mAvgColor));
Log.d(TAG, "Black Pixel Threshold: " + String.valueOf(blackThreshold));
}
int divisor = options.findDivisor(width, height);
mHeightScaled = (height / divisor);
mWidthScaled = (width / divisor);
if (DEBUG) {
Log.d(TAG, "Common Divisor: " + String.valueOf(divisor));
Log.d(TAG, "Scaled Width: " + String.valueOf(mWidthScaled));
Log.d(TAG, "Scaled Height: " + String.valueOf(mHeightScaled));
}
// Calculate scaled dimensions
final int divisor = options.findDivisor(width, height);
mWidthScaled = width / divisor;
mHeightScaled = height / divisor;
// Handler thread for callbacks
final HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY);
thread.start();
mHandler = new Handler(thread.getLooper());
if (DEBUG) Log.d(TAG, "Encoder ready");
if (DEBUG) {
Log.d(TAG, "Init: " + width + "x" + height + " -> " + mWidthScaled + "x" + mHeightScaled);
}
private Runnable clearAndDisconnectRunner = new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "Clearing LEDs and disconnecting");
try {
Thread.sleep(CLEAR_COMMAND_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
mListener.clear();
mListener.disconnect();
}
};
private Runnable clearLightsRunner = new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "Clearing LEDs");
try {
Thread.sleep(CLEAR_COMMAND_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
mListener.clear();
}
};
public void clearLights() {
new Thread(clearLightsRunner).start();
new Thread(() -> {
sleep(CLEAR_DELAY_MS);
mListener.clear();
}).start();
}
void clearAndDisconnect() {
new Thread(clearAndDisconnectRunner).start();
protected void clearAndDisconnect() {
new Thread(() -> {
sleep(CLEAR_DELAY_MS);
mListener.clear();
mListener.disconnect();
}).start();
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public boolean isCapturing() {
return mIsCapturing;
}
public void setCapturing(boolean isCapturing) {
mIsCapturing = isCapturing;
protected void setCapturing(boolean capturing) {
mIsCapturing = capturing;
}
public void sendStatus() {
if (mListener != null) {
mListener.sendStatus(isCapturing());
}
mListener.sendStatus(mIsCapturing);
}
public void stopRecording() {
throw new RuntimeException("Stub!");
protected int getGrabberWidth() {
return mInitOrientation != mCurrentOrientation ? mHeightScaled : mWidthScaled;
}
public void resumeRecording() {
throw new RuntimeException("Stub!");
protected int getGrabberHeight() {
return mInitOrientation != mCurrentOrientation ? mWidthScaled : mHeightScaled;
}
int getGrabberWidth() {
return INIT_ORIENTATION != mCurrentOrientation ? mHeightScaled : mWidthScaled;
}
int getGrabberHeight() {
return INIT_ORIENTATION != mCurrentOrientation ? mWidthScaled : mHeightScaled;
}
public void setOrientation(int orientation) {
mCurrentOrientation = orientation;
}
public abstract void stopRecording();
public abstract void resumeRecording();
public abstract void setOrientation(int orientation);
}
@@ -1,6 +1,7 @@
package com.hyperion.grabber.common;
import android.annotation.TargetApi;
import android.app.ForegroundServiceStartNotAllowedException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
@@ -12,7 +13,10 @@ import android.content.pm.ServiceInfo;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ServiceCompat;
@@ -24,6 +28,7 @@ import android.view.WindowManager;
import com.hyperion.grabber.common.network.HyperionThread;
import com.hyperion.grabber.common.util.HyperionGrabberOptions;
import com.hyperion.grabber.common.util.Preferences;
import com.hyperion.grabber.common.util.TclBypass;
import java.util.Objects;
@@ -31,9 +36,15 @@ 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";
public static final String BROADCAST_TCL_BLOCKED = "TCL_BLOCKED";
private static final boolean DEBUG = false;
private static final String TAG = "HyperionScreenService";
private boolean mForegroundFailed = false;
private boolean mTclBlocked = false;
private PowerManager.WakeLock mWakeLock;
private Handler mHandler;
private static final String BASE = "com.hyperion.grabber.service.";
public static final String ACTION_START = BASE + "ACTION_START";
public static final String ACTION_STOP = BASE + "ACTION_STOP";
@@ -43,38 +54,38 @@ public class HyperionScreenService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final int NOTIFICATION_EXIT_INTENT_ID = 2;
private boolean RECONNECT = false;
private boolean hasConnected = false;
private boolean mReconnectEnabled = false;
private boolean mHasConnected = false;
private MediaProjectionManager mMediaProjectionManager;
private HyperionThread mHyperionThread;
private static MediaProjection _mediaProjection;
private static MediaProjection sMediaProjection;
private int mFrameRate;
private int mHorizontalLEDCount;
private int mVerticalLEDCount;
private boolean mSendAverageColor;
private boolean mWledEnabled;
private String mWledIp;
private HyperionScreenEncoder mHyperionEncoder;
private NotificationManager mNotificationManager;
private String mStartError = null;
HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
private final HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
@Override
public void onConnected() {
Log.d(TAG, "CONNECTED TO HYPERION INSTANCE");
hasConnected = true;
if (DEBUG) Log.d(TAG, "Connected to Hyperion server");
mHasConnected = true;
notifyActivity();
}
@Override
public void onConnectionError(int errorID, String error) {
Log.e(TAG, "COULD NOT CONNECT TO HYPERION INSTANCE");
if (error != null) Log.e(TAG, error);
if (!hasConnected) {
Log.e(TAG, "Connection error: " + (error != null ? error : "unknown"));
if (!mHasConnected) {
mStartError = getResources().getString(R.string.error_server_unreachable);
haltStartup();
}
if (RECONNECT && hasConnected) {
Log.e(TAG, "AUTOMATIC RECONNECT ENABLED. CONNECTING ...");
} else if (!RECONNECT && hasConnected) {
} else if (mReconnectEnabled) {
Log.i(TAG, "Attempting automatic reconnect...");
} else {
mStartError = getResources().getString(R.string.error_connection_lost);
stopSelf();
}
@@ -82,8 +93,7 @@ public class HyperionScreenService extends Service {
@Override
public void onReceiveStatus(boolean isCapturing) {
if (DEBUG) Log.v(TAG, "Received grabber status, notifying activity. Status: " +
String.valueOf(isCapturing));
if (DEBUG) Log.v(TAG, "Received status: capturing=" + isCapturing);
notifyActivity();
}
};
@@ -126,6 +136,14 @@ public class HyperionScreenService extends Service {
@Override
public void onCreate() {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mHandler = new Handler(Looper.getMainLooper());
// Try shell bypass on startup for TCL devices
if (TclBypass.isTclDevice() || TclBypass.isRestrictedManufacturer()) {
Log.i(TAG, "Detected restricted manufacturer, attempting shell bypass");
TclBypass.tryShellBypass(this);
}
super.onCreate();
}
@@ -139,9 +157,12 @@ public class HyperionScreenService extends Service {
mHorizontalLEDCount = prefs.getInt(R.string.pref_key_x_led);
mVerticalLEDCount = prefs.getInt(R.string.pref_key_y_led);
mSendAverageColor = prefs.getBoolean(R.string.pref_key_use_avg_color);
RECONNECT = prefs.getBoolean(R.string.pref_key_reconnect);
mReconnectEnabled = prefs.getBoolean(R.string.pref_key_reconnect);
mWledEnabled = prefs.getBoolean(R.string.pref_key_wled_enabled);
mWledIp = prefs.getString(R.string.pref_key_wled_ip, null);
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, "")) {
mStartError = getResources().getString(R.string.error_empty_host);
return false;
@@ -150,12 +171,20 @@ public class HyperionScreenService extends Service {
mStartError = getResources().getString(R.string.error_empty_port);
return false;
}
} else {
if (mWledIp == null || Objects.equals(mWledIp, "0.0.0.0") || Objects.equals(mWledIp, "")) {
mStartError = "WLED IP should not be empty";
return false;
}
}
if (mHorizontalLEDCount <= 0 || mVerticalLEDCount <= 0) {
mStartError = getResources().getString(R.string.error_invalid_led_counts);
return false;
}
mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mHyperionThread = new HyperionThread(mReceiver, host, port, Integer.parseInt(priority), RECONNECT, delay);
int priorityValue = Integer.parseInt(priority);
mHyperionThread = new HyperionThread(mReceiver, host, port, priorityValue, mReconnectEnabled, delay, mWledEnabled, mWledIp);
mHyperionThread.start();
mStartError = null;
return true;
@@ -177,15 +206,20 @@ public class HyperionScreenService extends Service {
if (mHyperionThread == null) {
boolean isPrepared = prepared();
if (isPrepared) {
// For Android 12+, we must start foreground with mediaProjection type BEFORE getting MediaProjection
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
boolean foregroundStarted = tryStartForeground();
if (!foregroundStarted && mTclBlocked) {
acquireWakeLock();
}
try {
startScreenRecord(intent);
} catch (SecurityException e) {
Log.e(TAG, "Failed to start screen recording: " + e.getMessage());
mStartError = getResources().getString(R.string.error_media_projection_denied);
haltStartup();
break;
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
@@ -234,6 +268,7 @@ public class HyperionScreenService extends Service {
if (DEBUG) Log.v(TAG, "Wake receiver not registered");
}
releaseWakeLock();
stopScreenRecord();
stopForeground(true);
notifyActivity();
@@ -241,13 +276,105 @@ public class HyperionScreenService extends Service {
super.onDestroy();
}
private void haltStartup() {
private boolean tryStartForeground() {
mForegroundFailed = false;
mTclBlocked = false;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
}
return true;
} catch (Exception e) {
Log.e(TAG, "Foreground start failed: " + e.getMessage());
mForegroundFailed = true;
String msg = e.getMessage();
if (msg != null && (msg.contains("TclAppBoot") || msg.contains("forbid"))) {
mTclBlocked = true;
}
}
if (mForegroundFailed) {
try {
Thread.sleep(100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
}
mForegroundFailed = false;
mTclBlocked = false;
return true;
} catch (Exception e) {
Log.e(TAG, "Foreground retry failed: " + e.getMessage());
mTclBlocked = true;
}
}
notifyTclBlocked();
return false;
}
private void acquireWakeLock() {
if (mWakeLock == null) {
try {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm != null) {
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"HyperionGrabber::ScreenCapture");
mWakeLock.acquire(60 * 60 * 1000L);
}
} catch (Exception e) {
Log.e(TAG, "Failed to acquire wake lock", e);
}
}
}
private void releaseWakeLock() {
if (mWakeLock != null && mWakeLock.isHeld()) {
try {
mWakeLock.release();
Log.i(TAG, "Wake lock released");
} catch (Exception e) {
Log.e(TAG, "Failed to release wake lock", e);
}
mWakeLock = null;
}
}
private void notifyTclBlocked() {
Intent intent = new Intent(BROADCAST_FILTER);
intent.putExtra(BROADCAST_TAG, false);
intent.putExtra(BROADCAST_TCL_BLOCKED, true);
intent.putExtra(BROADCAST_ERROR, "Foreground service blocked by device manufacturer");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
private void haltStartup() {
// Try to start foreground to show error, but don't fail if blocked
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
}
} catch (Exception e) {
Log.w(TAG, "Could not start foreground during halt: " + e.getMessage());
}
notifyActivity();
if (mHyperionThread != null) {
mHyperionThread.interrupt();
mHyperionThread = null;
}
stopSelf();
}
@@ -267,45 +394,55 @@ public class HyperionScreenService extends Service {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void startScreenRecord(final Intent intent) {
if (DEBUG) Log.v(TAG, "Start screen recorder");
if (DEBUG) Log.v(TAG, "Starting screen recorder");
final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
// get MediaProjection
final MediaProjection projection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
if (projection != null && window != null) {
_mediaProjection = projection;
sMediaProjection = projection;
final DisplayMetrics metrics = new DisplayMetrics();
window.getDefaultDisplay().getRealMetrics(metrics);
final int density = metrics.densityDpi;
HyperionGrabberOptions options = new HyperionGrabberOptions(mHorizontalLEDCount,
mVerticalLEDCount, mFrameRate, mSendAverageColor);
if (DEBUG) Log.v(TAG, "Starting the recorder");
mHyperionEncoder = new HyperionScreenEncoder(mHyperionThread.getReceiver(),
projection, metrics.widthPixels, metrics.heightPixels,
density, options);
HyperionGrabberOptions options = new HyperionGrabberOptions(
mHorizontalLEDCount, mVerticalLEDCount, mFrameRate, mSendAverageColor);
if (DEBUG) Log.v(TAG, "Creating encoder: " + metrics.widthPixels + "x" + metrics.heightPixels);
mHyperionEncoder = new HyperionScreenEncoder(
mHyperionThread.getReceiver(),
projection,
metrics.widthPixels,
metrics.heightPixels,
metrics.densityDpi,
options);
mHyperionEncoder.sendStatus();
}
}
private void stopScreenRecord() {
if (DEBUG) Log.v(TAG, "Stop screen recorder");
RECONNECT = false;
if (DEBUG) Log.v(TAG, "Stopping screen recorder");
mReconnectEnabled = false;
mNotificationManager.cancel(NOTIFICATION_ID);
if (mHyperionEncoder != null) {
if (DEBUG) Log.v(TAG, "Stopping the current encoder");
if (DEBUG) Log.v(TAG, "Stopping encoder");
mHyperionEncoder.stopRecording();
mHyperionEncoder = null;
}
releaseResource();
if (mHyperionThread != null) {
mHyperionThread.interrupt();
mHyperionThread = null;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void releaseResource() {
if (_mediaProjection != null) {
_mediaProjection.stop();
_mediaProjection = null;
private void releaseResource() {
if (sMediaProjection != null) {
sMediaProjection.stop();
sMediaProjection = null;
}
}
@@ -314,7 +451,7 @@ public class HyperionScreenService extends Service {
}
boolean isCommunicating() {
return isCapturing() && hasConnected;
return isCapturing() && mHasConnected;
}
private void notifyActivity() {
@@ -322,11 +459,8 @@ public class HyperionScreenService extends Service {
intent.putExtra(BROADCAST_TAG, isCommunicating());
intent.putExtra(BROADCAST_ERROR, mStartError);
if (DEBUG) {
Log.v(TAG, "Sending status broadcast - communicating: " +
String.valueOf(isCommunicating()));
if (mStartError != null) {
Log.v(TAG, "Startup error: " + mStartError);
}
Log.v(TAG, "Broadcasting status: communicating=" + isCommunicating() +
(mStartError != null ? ", error=" + mStartError : ""));
}
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
@@ -0,0 +1,173 @@
package com.hyperion.grabber.common.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
public class TclBypass {
private static final String TAG = "TclBypass";
public static boolean isTclDevice() {
String manufacturer = Build.MANUFACTURER.toLowerCase();
String brand = Build.BRAND.toLowerCase();
String device = Build.DEVICE.toLowerCase();
String model = Build.MODEL.toLowerCase();
return manufacturer.contains("tcl") ||
brand.contains("tcl") ||
device.startsWith("g10") ||
model.contains("tcl") ||
model.contains("smart tv");
}
public static boolean isRestrictedManufacturer() {
String manufacturer = Build.MANUFACTURER.toLowerCase();
return manufacturer.contains("tcl") ||
manufacturer.contains("xiaomi") ||
manufacturer.contains("huawei") ||
manufacturer.contains("oppo") ||
manufacturer.contains("vivo") ||
manufacturer.contains("realme") ||
manufacturer.contains("samsung");
}
public static boolean openTclAutoStartSettings(Context context) {
Intent[] intents = {
// TCL specific intents
new Intent().setComponent(new ComponentName("com.tcl.guard",
"com.tcl.guard.activity.AutostartActivity")),
new Intent().setComponent(new ComponentName("com.tcl.guard",
"com.tcl.guard.activity.AppAutoStartManagerActivity")),
new Intent().setComponent(new ComponentName("com.android.settings",
"com.tcl.settings.TclAutoStartSettingsActivity")),
new Intent().setComponent(new ComponentName("com.tcl.tvweishi",
"com.tcl.tvweishi.settings.AutoBootManageActivity")),
// TCL TV Settings
new Intent().setComponent(new ComponentName("com.android.tv.settings",
"com.android.tv.settings.MainSettings")),
new Intent().setComponent(new ComponentName("com.android.tv.settings",
"com.android.tv.settings.device.apps.AppsActivity")),
// Generic auto-start intents
new Intent("android.settings.APPLICATION_DEVELOPMENT_SETTINGS"),
new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:" + context.getPackageName())),
};
for (Intent intent : intents) {
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (isIntentAvailable(context, intent)) {
context.startActivity(intent);
Log.d(TAG, "Opened: " + intent.getComponent());
return true;
}
} catch (Exception e) {
Log.d(TAG, "Failed to open: " + intent, e);
}
}
return false;
}
public static boolean openSpecialAppAccess(Context context) {
Intent[] intents = {
// Special app access
new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
.setData(Uri.parse("package:" + context.getPackageName())),
new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION")
.setData(Uri.parse("package:" + context.getPackageName())),
// TV Settings apps section
new Intent().setComponent(new ComponentName("com.android.tv.settings",
"com.android.tv.settings.device.apps.AppManagementActivity"))
.putExtra("packageName", context.getPackageName()),
};
for (Intent intent : intents) {
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (isIntentAvailable(context, intent)) {
context.startActivity(intent);
return true;
}
} catch (Exception e) {
Log.d(TAG, "Failed: " + intent, e);
}
}
return false;
}
public static void tryShellBypass(Context context) {
new Thread(() -> {
String pkg = context.getPackageName();
String[] commands = {
"appops set " + pkg + " PROJECT_MEDIA allow",
"appops set " + pkg + " android:project_media allow",
"appops set " + pkg + " SYSTEM_ALERT_WINDOW allow",
"settings put global auto_start_" + pkg + " 1",
"settings put secure auto_start_" + pkg + " 1",
"am broadcast -a com.tcl.action.ALLOW_AUTO_START -e package " + pkg,
"am broadcast -a com.tcl.appboot.action.SET_ALLOW -e package " + pkg,
"settings put global tcl_app_boot_" + pkg + " allow",
"settings put secure tcl_app_boot_" + pkg + " allow",
"cmd deviceidle whitelist +" + pkg,
"dumpsys deviceidle whitelist +" + pkg,
"appops set " + pkg + " RUN_IN_BACKGROUND allow",
"appops set " + pkg + " RUN_ANY_IN_BACKGROUND allow",
"appops set " + pkg + " START_FOREGROUND allow",
"appops set " + pkg + " INSTANT_APP_START_FOREGROUND allow",
};
for (String cmd : commands) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});
process.waitFor();
int exit = process.exitValue();
if (exit == 0) {
Log.d(TAG, "Success: " + cmd);
}
} catch (Exception e) {
}
}
}).start();
}
public static void showTclHelpDialog(Activity activity, Runnable onRetry) {
String pkg = activity.getPackageName();
String message = "Your TV is blocking the screen recording service.\n\n" +
"USE ADB TO FIX (from computer):\n\n" +
"adb shell appops set " + pkg + " PROJECT_MEDIA allow\n\n" +
"adb shell appops set " + pkg + " START_FOREGROUND allow\n\n" +
"Or reinstall with permissions:\n" +
"adb install -g -r hyperion.apk";
new AlertDialog.Builder(activity)
.setTitle("TCL Blocked")
.setMessage(message)
.setPositiveButton("Retry", (d, w) -> {
tryShellBypass(activity);
if (onRetry != null) {
activity.getWindow().getDecorView().postDelayed(() -> onRetry.run(), 1000);
}
})
.setNegativeButton("Close", null)
.setCancelable(true)
.show();
}
private static boolean isIntentAvailable(Context context, Intent intent) {
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list != null && !list.isEmpty();
}
}
@@ -1,14 +0,0 @@
package com.hyperion.grabber.common.network;
import java.io.IOException;
public interface HyperionClient {
boolean isConnected();
void disconnect() throws IOException;
void clear(int priority) throws IOException;
void clearAll() throws IOException;
void setColor(int color, int priority) throws IOException;
void setColor(int color, int priority, int duration_ms) throws IOException;
void setImage(byte[] data, int width, int height, int priority) throws IOException;
void setImage(byte[] data, int width, int height, int priority, int duration_ms) throws IOException;
}
@@ -0,0 +1,28 @@
package com.hyperion.grabber.common.network
import java.io.IOException
interface HyperionClient {
fun isConnected(): Boolean
@Throws(IOException::class)
fun disconnect()
@Throws(IOException::class)
fun clear(priority: Int)
@Throws(IOException::class)
fun clearAll()
@Throws(IOException::class)
fun setColor(color: Int, priority: Int)
@Throws(IOException::class)
fun setColor(color: Int, priority: Int, duration_ms: Int)
@Throws(IOException::class)
fun setImage(data: ByteArray, width: Int, height: Int, priority: Int)
@Throws(IOException::class)
fun setImage(data: ByteArray, width: Int, height: Int, priority: Int, duration_ms: Int)
}
@@ -1,137 +0,0 @@
package com.hyperion.grabber.common.network;
import com.google.flatbuffers.FlatBufferBuilder;
import hyperionnet.Clear;
import hyperionnet.Color;
import hyperionnet.Command;
import hyperionnet.Image;
import hyperionnet.ImageType;
import hyperionnet.RawImage;
import hyperionnet.Register;
import hyperionnet.Reply;
import hyperionnet.Request;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
public class HyperionFlatBuffers implements HyperionClient {
private final int TIMEOUT = 1000;
private final Socket mSocket;
private final int mPriority;
private final FlatBufferBuilder mBuilder;
public HyperionFlatBuffers(String address, int port, int priority) throws IOException {
mSocket = new Socket();
mSocket.connect(new InetSocketAddress(address, port), TIMEOUT);
mPriority = priority;
mBuilder = new FlatBufferBuilder(1024);
register();
}
private void register() throws IOException {
mBuilder.clear();
int originOffset = mBuilder.createString("HyperionAndroidGrabber");
int registerOffset = Register.createRegister(mBuilder, originOffset, mPriority);
int requestOffset = Request.createRequest(mBuilder, Command.Register, registerOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
@Override
public boolean isConnected() {
return mSocket != null && mSocket.isConnected();
}
@Override
public void disconnect() throws IOException {
if (isConnected()) {
mSocket.close();
}
}
@Override
public void clear(int priority) throws IOException {
mBuilder.clear();
int clearOffset = Clear.createClear(mBuilder, priority);
int requestOffset = Request.createRequest(mBuilder, Command.Clear, clearOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
@Override
public void clearAll() throws IOException {
clear(-1);
}
@Override
public void setColor(int color, int priority) throws IOException {
setColor(color, priority, -1);
}
@Override
public void setColor(int color, int priority, int duration_ms) throws IOException {
mBuilder.clear();
int colorOffset = Color.createColor(mBuilder, color, duration_ms);
int requestOffset = Request.createRequest(mBuilder, Command.Color, colorOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
@Override
public void setImage(byte[] data, int width, int height, int priority) throws IOException {
setImage(data, width, height, priority, -1);
}
@Override
public void setImage(byte[] data, int width, int height, int priority, int duration_ms) throws IOException {
mBuilder.clear();
int dataOffset = RawImage.createDataVector(mBuilder, data);
int rawImageOffset = RawImage.createRawImage(mBuilder, dataOffset, width, height);
int imageOffset = Image.createImage(mBuilder, ImageType.RawImage, rawImageOffset, duration_ms);
int requestOffset = Request.createRequest(mBuilder, Command.Image, imageOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
private void sendRequest(ByteBuffer bb) throws IOException {
if (isConnected()) {
int size = bb.remaining();
byte[] header = new byte[4];
header[0] = (byte)((size >> 24) & 0xFF);
header[1] = (byte)((size >> 16) & 0xFF);
header[2] = (byte)((size >> 8) & 0xFF);
header[3] = (byte)((size ) & 0xFF);
OutputStream output = mSocket.getOutputStream();
output.write(header);
byte[] data = new byte[bb.remaining()];
bb.get(data);
output.write(data);
output.flush();
receiveReply();
}
}
private void receiveReply() throws IOException {
// We don't really need to parse the reply for now, but we should consume it
// to keep the socket clean.
if (mSocket.getInputStream().available() >= 4) {
byte[] header = new byte[4];
int read = mSocket.getInputStream().read(header, 0, 4);
if (read == 4) {
int size = ((header[0] & 0xFF) << 24) | ((header[1] & 0xFF) << 16) | ((header[2] & 0xFF) << 8) | (header[3] & 0xFF);
if (size > 0) {
byte[] data = new byte[size];
mSocket.getInputStream().read(data, 0, size);
// Reply reply = Reply.getRootAsReply(ByteBuffer.wrap(data));
}
}
}
}
}
@@ -0,0 +1,145 @@
package com.hyperion.grabber.common.network
import com.google.flatbuffers.FlatBufferBuilder
import hyperionnet.*
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import java.nio.ByteBuffer
class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : HyperionClient {
private val TIMEOUT = 1000
private val mSocket: Socket = Socket()
private val mPriority: Int
private val mBuilder: FlatBufferBuilder
init {
mSocket.tcpNoDelay = true // Disable Nagle's algorithm for low latency
mSocket.sendBufferSize = 8192 // Smaller buffer for faster sends
mSocket.receiveBufferSize = 4096
mSocket.connect(InetSocketAddress(address, port), TIMEOUT)
mSocket.soTimeout = 10 // Very short timeout for non-blocking behavior
mPriority = priority
mBuilder = FlatBufferBuilder(1024)
register()
}
@Throws(IOException::class)
private fun register() {
mBuilder.clear()
val originOffset = mBuilder.createString("HyperionAndroidGrabber")
val registerOffset = Register.createRegister(mBuilder, originOffset, mPriority)
val requestOffset = Request.createRequest(mBuilder, Command.Register, registerOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
override fun isConnected(): Boolean {
return mSocket.isConnected
}
@Throws(IOException::class)
override fun disconnect() {
if (isConnected()) {
mSocket.close()
}
}
@Throws(IOException::class)
override fun clear(priority: Int) {
mBuilder.clear()
val clearOffset = Clear.createClear(mBuilder, priority)
val requestOffset = Request.createRequest(mBuilder, Command.Clear, clearOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
@Throws(IOException::class)
override fun clearAll() {
clear(-1)
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int) {
setColor(color, priority, -1)
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int, duration_ms: Int) {
mBuilder.clear()
val colorOffset = Color.createColor(mBuilder, color, duration_ms)
val requestOffset = Request.createRequest(mBuilder, Command.Color, colorOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int) {
setImage(data, width, height, priority, -1)
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int, duration_ms: Int) {
mBuilder.clear()
val dataOffset = RawImage.createDataVector(mBuilder, data)
val rawImageOffset = RawImage.createRawImage(mBuilder, dataOffset, width, height)
val imageOffset = Image.createImage(mBuilder, ImageType.RawImage, rawImageOffset, duration_ms)
val requestOffset = Request.createRequest(mBuilder, Command.Image, imageOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
@Throws(IOException::class)
private fun sendRequest(bb: ByteBuffer) {
if (isConnected()) {
val size = bb.remaining()
val header = ByteArray(4)
header[0] = ((size shr 24) and 0xFF).toByte()
header[1] = ((size shr 16) and 0xFF).toByte()
header[2] = ((size shr 8) and 0xFF).toByte()
header[3] = (size and 0xFF).toByte()
val output = mSocket.getOutputStream()
output.write(header)
val data = ByteArray(bb.remaining())
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
}
}
fun cleanReplies() {
receiveReply()
}
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)
val read = mSocket.getInputStream().read(header, 0, 4)
if (read == 4) {
val size = (header[0].toInt() and 0xFF shl 24) or
(header[1].toInt() and 0xFF shl 16) or
(header[2].toInt() and 0xFF shl 8) or
(header[3].toInt() and 0xFF)
if (size > 0 && mSocket.getInputStream().available() >= size) {
val data = ByteArray(size)
mSocket.getInputStream().read(data, 0, size)
} else {
break // Not enough data yet, will consume later
}
} else {
break
}
}
} catch (e: IOException) {
// Ignore - non-blocking read
}
}
}
@@ -1,124 +0,0 @@
package com.hyperion.grabber.common.network;
import com.hyperion.grabber.common.HyperionScreenService;
import java.io.IOException;
public class HyperionThread extends Thread {
private String HOST;
private int PORT;
private int PRIORITY;
private final int FRAME_DURATION = -1;
private boolean RECONNECT = false;
private boolean HAS_CONNECTED = false;
private int RECONNECT_DELAY;
private HyperionClient mHyperion;
HyperionScreenService.HyperionThreadBroadcaster mSender;
HyperionThreadListener mReceiver = new HyperionThreadListener() {
@Override
public void sendFrame(byte[] data, int width, int height) {
if (mHyperion != null && mHyperion.isConnected()) {
try {
mHyperion.setImage(data, width, height, PRIORITY, FRAME_DURATION);
} catch (IOException e) {
mSender.onConnectionError(e.hashCode(), e.getMessage());
e.printStackTrace();
if (RECONNECT && HAS_CONNECTED) {
reconnectDelay(RECONNECT_DELAY);
try {
mHyperion = createClient();
} catch (IOException i) {
i.printStackTrace();
}
}
}
}
}
@Override
public void clear() {
if (mHyperion != null && mHyperion.isConnected()) {
try {
mHyperion.clear(PRIORITY);
} catch (IOException e) {
mSender.onConnectionError(e.hashCode(), e.getMessage());
e.printStackTrace();
}
}
}
@Override
public void disconnect() {
if (mHyperion != null) {
try {
mHyperion.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void sendStatus(boolean isGrabbing) {
if (mSender != null) {
mSender.onReceiveStatus(isGrabbing);
}
}
};
public HyperionThread(HyperionScreenService.HyperionThreadBroadcaster listener, final String host,
final int port, final int priority, final boolean reconnect, final int delay){
HOST = host;
PORT = port;
PRIORITY = priority;
RECONNECT = reconnect;
RECONNECT_DELAY = delay * 1000;
mSender = listener;
}
public HyperionThreadListener getReceiver() {return mReceiver;}
private HyperionClient createClient() throws IOException {
return new HyperionFlatBuffers(HOST, PORT, PRIORITY);
}
@Override
public void run(){
do {
try {
mHyperion = createClient();
} catch (IOException e) {
mSender.onConnectionError(e.hashCode(), e.getMessage());
e.printStackTrace();
if (RECONNECT && HAS_CONNECTED) {
reconnectDelay(RECONNECT_DELAY);
}
} finally {
if (mHyperion != null && mSender != null && mHyperion.isConnected()) {
HAS_CONNECTED = true;
mSender.onConnected();
break;
}
}
} while (RECONNECT && HAS_CONNECTED);
}
public void reconnectDelay(long t) {
try {
Thread.sleep(t);
} catch (InterruptedException e) {
RECONNECT = false;
HAS_CONNECTED = false;
Thread.currentThread().interrupt();
}
}
public interface HyperionThreadListener {
void sendFrame(byte[] data, int width, int height);
void clear();
void disconnect();
void sendStatus(boolean isGrabbing);
}
}
@@ -0,0 +1,182 @@
package com.hyperion.grabber.common.network
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
class HyperionThread(
private val callback: HyperionThreadBroadcaster,
private val host: String?,
private val port: Int,
private val priority: Int,
reconnect: Boolean,
delaySeconds: Int,
private val wledEnabled: Boolean,
private val wledIp: String?
) : Thread(TAG) {
private val reconnectDelayMs = (delaySeconds * 1000).toLong()
private val reconnectEnabled = AtomicBoolean(reconnect)
private val connected = AtomicBoolean(false)
private val clientRef = AtomicReference<HyperionClient>()
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
@Volatile
private var pendingTask: Future<*>? = null
@Volatile
private var pendingFrame: FrameData? = null
val receiver: HyperionThreadListener = object : HyperionThreadListener {
override fun sendFrame(data: ByteArray, width: Int, height: Int) {
val client = clientRef.get()
if (client == null || !client.isConnected()) return
pendingFrame = FrameData(data, width, height)
val pending = pendingTask
if (pending != null && !pending.isDone) {
pending.cancel(false)
}
pendingTask = executor.submit { sendPendingFrame() }
}
private fun sendPendingFrame() {
val frame = pendingFrame
val client = clientRef.get()
if (frame == null || client == null || !client.isConnected()) return
try {
client.setImage(frame.data, frame.width, frame.height, priority, FRAME_DURATION)
if (client is HyperionFlatBuffers) {
client.cleanReplies()
}
} catch (e: IOException) {
handleError(e)
}
}
override fun clear() {
val client = clientRef.get()
if (client != null && client.isConnected()) {
try {
client.clear(priority)
} catch (e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
}
}
}
override fun disconnect() {
val pending = pendingTask
if (pending != null) {
pending.cancel(true)
pendingTask = null
}
pendingFrame = null
if (!executor.isShutdown) {
executor.shutdownNow()
try {
executor.awaitTermination(SHUTDOWN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
} catch (e: InterruptedException) {
currentThread().interrupt()
}
}
val client = clientRef.getAndSet(null)
if (client != null) {
try {
client.disconnect()
} catch (ignored: IOException) {
}
}
connected.set(false)
}
override fun sendStatus(isGrabbing: Boolean) {
callback.onReceiveStatus(isGrabbing)
}
}
override fun run() {
connect()
}
private fun createClient(): HyperionClient {
return if (wledEnabled && wledIp != null) {
WledDdpClient(InetAddress.getByName(wledIp), 4048)
} else {
HyperionFlatBuffers(host, port, priority)
}
}
private fun connect() {
do {
try {
val client = createClient()
if (client.isConnected()) {
clientRef.set(client)
connected.set(true)
callback.onConnected()
return
}
} catch (e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
if (reconnectEnabled.get() && connected.get()) {
sleepSafe(reconnectDelayMs)
}
}
} while (reconnectEnabled.get() && connected.get())
}
private fun handleError(e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
if (reconnectEnabled.get() && connected.get()) {
sleepSafe(reconnectDelayMs)
try {
val newClient = createClient()
if (newClient.isConnected()) {
clientRef.set(newClient)
}
} catch (ignored: IOException) {
}
}
}
private fun sleepSafe(ms: Long) {
try {
sleep(ms)
} catch (e: InterruptedException) {
reconnectEnabled.set(false)
connected.set(false)
currentThread().interrupt()
}
}
private class FrameData(val data: ByteArray, val width: Int, val height: Int)
interface HyperionThreadListener {
fun sendFrame(data: ByteArray, width: Int, height: Int)
fun clear()
fun disconnect()
fun sendStatus(isGrabbing: Boolean)
}
companion object {
private const val TAG = "HyperionThread"
private const val FRAME_DURATION = -1
private const val SHUTDOWN_TIMEOUT_MS = 100
}
}
@@ -1,171 +0,0 @@
package com.hyperion.grabber.common.network;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import android.util.Log;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/** Scans the local network for running Hyperion servers
* Created by nino on 27-5-18.
*/
public class NetworkScanner {
public static final int PORT = 19400;
/** The amount of milliseconds we try to connect to a given ip before giving up */
private static final int ATTEMPT_TIMEOUT_MS = 50;
private final String[] ipsToTry;
private int lastTriedIndex = -1;
public NetworkScanner() {
ipsToTry = getIPsToTry();
}
/** Scan the next ip address in the list of addresses to try
*
* @return the hostname (or an ip represented as String) when a Hyperion server was found
*/
@Nullable
@WorkerThread
public String tryNext(){
if (!hasNextAttempt()){
throw new IllegalStateException("No more ip addresses to try");
}
Socket socket = new Socket();
String ip = ipsToTry[++lastTriedIndex];
try {
socket.connect(new InetSocketAddress(ip, PORT), ATTEMPT_TIMEOUT_MS);
if (socket.isConnected()){
socket.close();
return ip;
}
} catch(Exception e) {
return null;
}
return null;
}
/** An indication of how many of the total ip's have been tried
*
* @return progress in in the range [0.0 .. 1.0]
*/
public float getProgress() {
if (ipsToTry.length == 0){
return 1f;
}
return lastTriedIndex / (float)ipsToTry.length;
}
/** True if not all ip's have been tried yet
*
*/
public boolean hasNextAttempt(){
return ipsToTry.length > 0 && lastTriedIndex + 1 < ipsToTry.length;
}
/**
* Get IP addresses for non-localhost interfaces
* @param useIPv4 true=return ipv4, false=return ipv6
* @return a list of found addresses (may be empty)
*
* https://stackoverflow.com/a/13007325
*/
@NonNull
private static List<String> getIPAddresses(boolean useIPv4) {
List<String> foundAddresses = new ArrayList<>();
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4)
foundAddresses.add(sAddr);
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
String v6Addr = delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
foundAddresses.add(v6Addr);
}
}
}
}
}
} catch (Exception e) {
// for now eat exceptions
Log.e("HYPERION SCANNER", "Could not get ip address", e);
}
return foundAddresses;
}
private String[] getIPsToTry(){
try {
List<String> localIpV4Addresses = getIPAddresses(true);
String[] allIpsToTry = new String[localIpV4Addresses.size() * 254];
for (int localIpIdx = 0; localIpIdx < localIpV4Addresses.size(); localIpIdx++) {
String localIpV4Address = localIpV4Addresses.get(localIpIdx);
String[] ipsToTry = new String[254];
String[] ipParts = localIpV4Address.split("\\.");
String ipPrefix = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".";
for (int i = 1; i< 255 ; i++){
ipsToTry[i-1] = ipPrefix + i;
}
int localNumberInSubnet = Integer.parseInt(ipParts[3]);
// sort in such a way that ips close to the local ip will be tried first
Arrays.sort(ipsToTry, (lhs, rhs) -> {
int lhsNumberInSubnet = Integer.parseInt(lhs.split("\\.")[3]);
int rhsNumberInSubnet = Integer.parseInt(rhs.split("\\.")[3]);
int lhsDistance = Math.abs(lhsNumberInSubnet - localNumberInSubnet);
int rhsDistance = Math.abs(rhsNumberInSubnet - localNumberInSubnet);
return lhsDistance - rhsDistance;
});
for (int i = 0; i < ipsToTry.length; i++) {
// interleave with previously found ip addresses
int allIndex = (localIpV4Addresses.size() * i) + localIpIdx;
allIpsToTry[allIndex] = ipsToTry[i];
}
}
return allIpsToTry;
} catch (Exception e){
// for now eat exceptions
Log.e("HYPERION SCANNER", "Error while building list of subnet ip's", e);
return new String[]{};
}
}
}
@@ -0,0 +1,136 @@
package com.hyperion.grabber.common.network
import android.util.Log
import androidx.annotation.WorkerThread
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.NetworkInterface
import java.net.Socket
import java.util.Collections
import kotlin.math.abs
/** Scans the local network for running Hyperion servers */
class NetworkScanner {
private val ipsToTry: Array<String>
private var lastTriedIndex = -1
init {
ipsToTry = getIPsToTry()
}
/** Scan the next ip address in the list of addresses to try
* @return the hostname (or an ip represented as String) when a Hyperion server was found
*/
@WorkerThread
fun tryNext(): String? {
check(hasNextAttempt()) { "No more ip addresses to try" }
val socket = Socket()
val ip = ipsToTry[++lastTriedIndex]
try {
socket.connect(InetSocketAddress(ip, PORT), ATTEMPT_TIMEOUT_MS)
if (socket.isConnected) {
socket.close()
return ip
}
} catch (e: Exception) {
return null
}
return null
}
/** An indication of how many of the total ip's have been tried
* @return progress in in the range [0.0 .. 1.0]
*/
val progress: Float
get() {
if (ipsToTry.isEmpty()) {
return 1f
}
return lastTriedIndex / ipsToTry.size.toFloat()
}
/** True if not all ip's have been tried yet */
fun hasNextAttempt(): Boolean {
return ipsToTry.isNotEmpty() && lastTriedIndex + 1 < ipsToTry.size
}
private fun getIPsToTry(): Array<String> {
try {
val localIpV4Addresses = getIPAddresses(true)
val allIpsToTry = arrayOfNulls<String>(localIpV4Addresses.size * 254)
for (localIpIdx in localIpV4Addresses.indices) {
val localIpV4Address = localIpV4Addresses[localIpIdx]
val ipsToTry = arrayOfNulls<String>(254)
val ipParts = localIpV4Address.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val ipPrefix = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + "."
for (i in 1..254) {
ipsToTry[i - 1] = ipPrefix + i
}
val localNumberInSubnet = ipParts[3].toInt()
// sort in such a way that ips close to the local ip will be tried first
ipsToTry.sortWith { lhs, rhs ->
val lhsNumberInSubnet = lhs!!.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[3].toInt()
val rhsNumberInSubnet = rhs!!.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[3].toInt()
val lhsDistance = abs(lhsNumberInSubnet - localNumberInSubnet)
val rhsDistance = abs(rhsNumberInSubnet - localNumberInSubnet)
lhsDistance - rhsDistance
}
for (i in ipsToTry.indices) {
// interleave with previously found ip addresses
val allIndex = localIpV4Addresses.size * i + localIpIdx
allIpsToTry[allIndex] = ipsToTry[i]
}
}
@Suppress("UNCHECKED_CAST")
return allIpsToTry as Array<String>
} catch (e: Exception) {
Log.e("HYPERION SCANNER", "Error while building list of subnet ip's", e)
return arrayOf()
}
}
companion object {
const val PORT = 19400
private const val ATTEMPT_TIMEOUT_MS = 50
/**
* Get IP addresses for non-localhost interfaces
* @param useIPv4 true=return ipv4, false=return ipv6
* @return a list of found addresses (may be empty)
*/
private fun getIPAddresses(useIPv4: Boolean): List<String> {
val foundAddresses: MutableList<String> = ArrayList()
try {
val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
val addrs = Collections.list(intf.inetAddresses)
for (addr in addrs) {
if (!addr.isLoopbackAddress) {
val sAddr = addr.hostAddress ?: continue
val isIPv4 = sAddr.indexOf(':') < 0
if (useIPv4) {
if (isIPv4) foundAddresses.add(sAddr)
} else {
if (!isIPv4) {
val delim = sAddr.indexOf('%') // drop ip6 zone suffix
val v6Addr = if (delim < 0) sAddr.uppercase() else sAddr.substring(0, delim).uppercase()
foundAddresses.add(v6Addr)
}
}
}
}
}
} catch (e: Exception) {
Log.e("HYPERION SCANNER", "Could not get ip address", e)
}
return foundAddresses
}
}
}
@@ -0,0 +1,100 @@
package com.hyperion.grabber.common.network
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import kotlin.math.min
class WledDdpClient(
private val address: InetAddress,
private val port: Int = 4048
) : HyperionClient {
private var socket: DatagramSocket? = null
private var sequenceNumber = 1
override fun isConnected(): Boolean {
return socket?.isClosed == false
}
@Throws(IOException::class)
override fun disconnect() {
socket?.close()
socket = null
}
@Throws(IOException::class)
override fun clear(priority: Int) {
// DDP does not have a native 'clear' notion in this context, send black.
}
@Throws(IOException::class)
override fun clearAll() {
// Send black.
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int) {
// Placeholder
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int, duration_ms: Int) {
// Placeholder
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int) {
setImage(data, width, height, priority, -1)
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int, duration_ms: Int) {
if (socket == null || socket?.isClosed == true) {
socket = DatagramSocket()
}
// Each DDP packet can hold up to 1440 bytes of pixel data
val maxDataLen = 1440
var offset = 0
val totalLength = data.size
while (offset < totalLength) {
val chunkLen = min(maxDataLen, totalLength - offset)
val isFinalPacket = (offset + chunkLen) == totalLength
// Flags: 1 = ver1. 0x40 = PUSH. PUSH is only set on the final packet.
val flags = if (isFinalPacket) 0x41.toByte() else 0x01.toByte()
val packet = ByteArray(10 + chunkLen)
// DDP Header
packet[0] = flags // Flags
packet[1] = sequenceNumber.toByte() // Sequence
packet[2] = 1.toByte() // Data type: 1 = RGB, 0 = undefined
packet[3] = 1.toByte() // Destination: 1 = default
// Data offset (32-bit big-endian)
packet[4] = (offset ushr 24).toByte()
packet[5] = (offset ushr 16).toByte()
packet[6] = (offset ushr 8).toByte()
packet[7] = offset.toByte()
// Data length (16-bit big-endian)
packet[8] = (chunkLen ushr 8).toByte()
packet[9] = chunkLen.toByte()
// Copy data chunk
System.arraycopy(data, offset, packet, 10, chunkLen)
val datagram = DatagramPacket(packet, packet.size, address, port)
socket?.send(datagram)
offset += chunkLen
}
sequenceNumber = (sequenceNumber + 1) and 0x0F
if (sequenceNumber == 0) sequenceNumber = 1
}
}
@@ -0,0 +1,150 @@
package com.hyperion.grabber.common.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PermissionHelper {
private static final String TAG = "PermissionHelper";
public static boolean canDrawOverlays(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return Settings.canDrawOverlays(context);
}
return true;
}
public static void requestOverlayPermission(Activity activity, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(activity)) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName()));
activity.startActivityForResult(intent, requestCode);
} catch (Exception e) {
Log.e(TAG, "Cannot request overlay permission", e);
openAppSettings(activity);
}
}
}
public static boolean isIgnoringBatteryOptimizations(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
return pm != null && pm.isIgnoringBatteryOptimizations(context.getPackageName());
}
return true;
}
public static void requestIgnoreBatteryOptimizations(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
activity.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Cannot request battery optimization exemption", e);
}
}
}
public static boolean hasProjectMediaPermission(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow("android:project_media",
android.os.Process.myUid(), context.getPackageName());
return mode == AppOpsManager.MODE_ALLOWED;
} catch (Exception e) {
Log.w(TAG, "Cannot check PROJECT_MEDIA permission", e);
}
}
return true;
}
public static void openAppSettings(Context context) {
try {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Cannot open app settings", e);
Toast.makeText(context, "Please open Settings > Apps > Hyperion Grabber manually", Toast.LENGTH_LONG).show();
}
}
public static void tryGrantProjectMediaViaShell(Context context) {
new Thread(() -> {
try {
String pkg = context.getPackageName();
String[] commands = {
"appops set " + pkg + " PROJECT_MEDIA allow",
"appops set " + pkg + " android:project_media allow",
"appops set " + pkg + " SYSTEM_ALERT_WINDOW allow",
"pm grant " + pkg + " android.permission.SYSTEM_ALERT_WINDOW"
};
for (String cmd : commands) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});
process.waitFor();
Log.d(TAG, "Executed: " + cmd + " (exit: " + process.exitValue() + ")");
} catch (Exception e) {
Log.w(TAG, "Command failed: " + cmd);
}
}
} catch (Exception e) {
Log.e(TAG, "Shell commands failed", e);
}
}).start();
}
public static void showFullPermissionDialog(Activity activity, Runnable onRetry) {
String deviceInfo = "Device: " + Build.MANUFACTURER + " " + Build.MODEL;
String message = "Screen recording permission could not be obtained.\n\n" +
"Your TV may be blocking the permission dialog.\n\n" +
"SOLUTIONS:\n\n" +
"1. OVERLAY PERMISSION:\n" +
" Settings > Apps > Special access > Display over other apps\n\n" +
"2. APP PERMISSIONS:\n" +
" Settings > Apps > Hyperion Grabber > Permissions\n\n" +
"3. AUTO-START (TCL/Smart TVs):\n" +
" Settings > Privacy > Special app access > Auto-start\n" +
" OR Settings > Apps > App management\n\n" +
"4. BATTERY OPTIMIZATION:\n" +
" Settings > Apps > Special access > Battery optimization\n\n" +
"5. ADB COMMAND (requires computer):\n" +
" adb shell appops set " + activity.getPackageName() + " PROJECT_MEDIA allow\n\n" +
deviceInfo;
new AlertDialog.Builder(activity)
.setTitle("Permission Required")
.setMessage(message)
.setPositiveButton("Open App Settings", (d, w) -> openAppSettings(activity))
.setNeutralButton("Try Overlay", (d, w) -> {
requestOverlayPermission(activity, 999);
})
.setNegativeButton("Retry", (d, w) -> {
tryGrantProjectMediaViaShell(activity);
if (onRetry != null) {
activity.getWindow().getDecorView().postDelayed(() -> {
onRetry.run();
}, 1000);
}
})
.setCancelable(true)
.show();
}
}
@@ -0,0 +1,148 @@
package com.hyperion.grabber.common.util
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import org.json.JSONArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
data class GithubRelease(
val tagName: String,
val name: String,
val body: String,
val downloadUrl: String,
val publishedAt: String
)
class UpdateChecker(private val context: Context) {
private val TAG = "UpdateChecker"
private val GITHUB_API_URL = "https://api.github.com/repos/haumlab/hyperion-android-reborn/releases"
private val GITHUB_RELEASES_URL = "https://github.com/haumlab/hyperion-android-reborn/releases"
fun checkForUpdates(): GithubRelease? {
try {
val currentVersion = getCurrentVersion()
val latestRelease = fetchLatestRelease() ?: return null
Log.d(TAG, "Current version: $currentVersion, Latest version: ${latestRelease.tagName}")
if (isNewerVersion(latestRelease.tagName, currentVersion)) {
return latestRelease
}
} catch (e: Exception) {
Log.e(TAG, "Error checking for updates", e)
}
return null
}
private fun getCurrentVersion(): String {
return try {
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0))
} else {
@Suppress("DEPRECATION")
context.packageManager.getPackageInfo(context.packageName, 0)
}
packageInfo.versionName ?: "0.0"
} catch (e: Exception) {
Log.e(TAG, "Error getting current version", e)
"0.0"
}
}
private fun fetchLatestRelease(): GithubRelease? {
var connection: HttpURLConnection? = null
try {
val url = URL(GITHUB_API_URL)
connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
connection.connectTimeout = 10000
connection.readTimeout = 10000
val responseCode = connection.responseCode
if (responseCode != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "GitHub API returned code: $responseCode")
return null
}
val reader = BufferedReader(InputStreamReader(connection.inputStream))
val response = reader.readText()
reader.close()
return parseReleases(response)
} catch (e: Exception) {
Log.e(TAG, "Error fetching releases", e)
return null
} finally {
connection?.disconnect()
}
}
private fun parseReleases(json: String): GithubRelease? {
try {
val releases = JSONArray(json)
// Find the first non-prerelease, non-draft release
for (i in 0 until releases.length()) {
val release = releases.getJSONObject(i)
val isDraft = release.optBoolean("draft", false)
val isPrerelease = release.optBoolean("prerelease", false)
if (!isDraft && !isPrerelease) {
val tagName = release.getString("tag_name")
val name = release.optString("name", tagName)
val body = release.optString("body", "")
val publishedAt = release.optString("published_at", "")
// Find APK asset
val assets = release.optJSONArray("assets")
var downloadUrl = ""
if (assets != null) {
for (j in 0 until assets.length()) {
val asset = assets.getJSONObject(j)
val assetName = asset.getString("name")
if (assetName.endsWith(".apk")) {
downloadUrl = asset.getString("browser_download_url")
break
}
}
}
if (downloadUrl.isEmpty()) {
Log.w(TAG, "No APK found for release $tagName")
continue
}
return GithubRelease(tagName, name, body, downloadUrl, publishedAt)
}
}
} catch (e: Exception) {
Log.e(TAG, "Error parsing releases", e)
}
return null
}
private fun isNewerVersion(newVersion: String, currentVersion: String): Boolean {
try {
val newParts = newVersion.removePrefix("v").split(".")
val currentParts = currentVersion.removePrefix("v").split(".")
for (i in 0 until maxOf(newParts.size, currentParts.size)) {
val newPart = newParts.getOrNull(i)?.toIntOrNull() ?: 0
val currentPart = currentParts.getOrNull(i)?.toIntOrNull() ?: 0
if (newPart > currentPart) return true
if (newPart < currentPart) return false
}
} catch (e: Exception) {
Log.e(TAG, "Error comparing versions", e)
}
return false
}
}
@@ -0,0 +1,157 @@
package com.hyperion.grabber.common.util
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.core.content.FileProvider
import java.io.File
class UpdateManager(private val context: Context) {
private val TAG = "UpdateManager"
private var downloadId: Long = -1
private var downloadReceiver: BroadcastReceiver? = null
private val handler = Handler(Looper.getMainLooper())
fun downloadAndInstall(downloadUrl: String, versionName: String, onComplete: (Boolean) -> Unit) {
try {
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val fileName = "hyperion-grabber-${versionName.replace("v", "")}.apk"
val destinationFile = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName
)
if (destinationFile.exists()) {
destinationFile.delete()
}
val uri = Uri.parse(downloadUrl)
val request = DownloadManager.Request(uri).apply {
setTitle("Hyperion Grabber Update")
setDescription("Downloading $versionName")
setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
setMimeType("application/vnd.android.package-archive")
setAllowedOverMetered(true)
setAllowedOverRoaming(true)
}
downloadId = downloadManager.enqueue(request)
Log.d(TAG, "Download started: $downloadId from $downloadUrl")
showToast("Downloading update...")
downloadReceiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) ?: -1
if (id == downloadId) {
Log.d(TAG, "Download complete: $id")
unregisterReceiver()
val query = DownloadManager.Query().setFilterById(downloadId)
val cursor = downloadManager.query(query)
if (cursor.moveToFirst()) {
val statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
val status = cursor.getInt(statusIndex)
if (status == DownloadManager.STATUS_SUCCESSFUL) {
showToast("Download complete, installing...")
installApk(fileName)
onComplete(true)
} else {
Log.e(TAG, "Download failed with status: $status")
showToast("Download failed")
onComplete(false)
}
}
cursor.close()
}
}
}
val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(downloadReceiver, filter, Context.RECEIVER_EXPORTED)
} else {
context.registerReceiver(downloadReceiver, filter)
}
} catch (e: Exception) {
Log.e(TAG, "Download error", e)
showToast("Download failed: ${e.message}")
onComplete(false)
}
}
private fun installApk(fileName: String) {
try {
val file = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName
)
if (!file.exists()) {
Log.e(TAG, "APK file not found: ${file.absolutePath}")
showToast("APK file not found")
return
}
val uri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
file
)
} else {
Uri.fromFile(file)
}
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
}
context.startActivity(intent)
Log.d(TAG, "Install intent launched for: $uri")
} catch (e: Exception) {
Log.e(TAG, "Install error", e)
showToast("Install failed: ${e.message}")
}
}
private fun unregisterReceiver() {
try {
downloadReceiver?.let { context.unregisterReceiver(it) }
downloadReceiver = null
} catch (e: Exception) {
Log.w(TAG, "Receiver already unregistered")
}
}
private fun showToast(message: String) {
handler.post { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }
}
fun cancelDownload() {
if (downloadId != -1L) {
try {
val dm = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
dm.remove(downloadId)
unregisterReceiver()
} catch (e: Exception) {
Log.e(TAG, "Cancel error", e)
}
}
}
}
@@ -65,4 +65,8 @@
<string name="notification_description">حاليا الاستيلاء على محتوى الشاشة</string>
<string name="pref_title_use_avg_color">إرسال متوسط لون الشاشة</string>
<string name="pref_summary_use_avg_color">يرسل متوسط لون شاشة الجهاز الخاص بك بدلا من صورة منه</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -65,4 +65,8 @@
<string name="notification_description">Momentálně se grabuje obsah obrazovky</string>
<string name="pref_title_use_avg_color">Odeslat průměrnou barvu obrazovky</string>
<string name="pref_summary_use_avg_color">Odesílá průměrnou barvu obrazovky vašeho zařízení namísto přesného obrazu</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -65,4 +65,8 @@
<string name="notification_description">Bildschirminhalt wird übertragen</string>
<string name="pref_title_use_avg_color">Durchschnittliche Bildschirmfarbe senden</string>
<string name="pref_summary_use_avg_color">Es wird die durchschnittliche Farbe jedes Bildes berechnet und deine LEDs leuchten alle nach dieser berechneten Farbe.</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -36,4 +36,8 @@
<string name="error_empty_host">La configuración del host no debe estar vacía</string>
<string name="error_empty_port">El puerto no debe estar vacío</string>
<string name="toast_must_give_permission">Permiso debe concederse a la pantalla de registro de datos</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -65,4 +65,8 @@
<string name="notification_description">Actuellement en train de capturer le contenu de l\'écran</string>
<string name="pref_title_use_avg_color">Envoyer la couleur dominante de l\'écran</string>
<string name="pref_summary_use_avg_color">Envoie la couleur dominante de l\'écran de votre appareil plutôt qu\'une image de celui-ci</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -65,4 +65,8 @@
<string name="notification_description">Acquisizione schermo in corso</string>
<string name="pref_title_use_avg_color">Invia il colore medio dello schermo</string>
<string name="pref_summary_use_avg_color">Invia il colore medio dello schermo del tuo dispositivo piuttosto che un\'immagine di esso</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -65,4 +65,8 @@
<string name="notification_description">Scherminhoud wordt doorgestuurd</string>
<string name="pref_title_use_avg_color">Stuur Gemiddelde Schermkleur</string>
<string name="pref_summary_use_avg_color">Stuurt de gemiddelde kleur van het scherm in plaats van een beeld van het</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -65,4 +65,8 @@
<string name="notification_description">Fanger innholdet på skjermen</string>
<string name="pref_title_use_avg_color">Send gjennomsnittlig skjermfarge</string>
<string name="pref_summary_use_avg_color">Sender gjennomsnittsfargen i enhetens skjerm i stedet for et bilde av det</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -31,4 +31,8 @@
<string name="error_connection_lost">Соединение с вашим сервером hyperion было потеряно. Грабер останавливаться</string>
<string name="toast_must_give_permission">Разрешение должно быть предоставлено для записи экрана данных.</string>
<string name="message_service_started">Нажмите «Назад», чтобы закрыть приложение. Содержимое вашего экрана будет по-прежнему отправляться в Hyperion</string>
<string name="pref_title_wled_enabled">Habilitar WLED DDP</string>
<string name="pref_summary_wled_enabled">Enviar datos de píxeles directamente a una instancia WLED usando DDP</string>
<string name="pref_title_wled_ip">Dirección IP de WLED</string>
<string name="pref_summary_wled_ip">La dirección IP de tu instancia WLED</string>
</resources>
@@ -4,6 +4,11 @@
<string name="pref_key_port" translatable="false">pref_key_port</string>
<integer name="pref_default_port" translatable="false">19400</integer>
<string name="pref_key_wled_enabled" translatable="false">pref_key_wled_enabled</string>
<bool name="pref_default_wled_enabled" translatable="false">false</bool>
<string name="pref_key_wled_ip" translatable="false">pref_key_wled_ip</string>
<string name="pref_key_y_led" translatable="false">pref_key_y_led</string>
<integer name="pref_default_y_led" translatable="false">34</integer>
+7
View File
@@ -33,6 +33,11 @@
<string name="pref_summary_host">Host your hyperion instance is running on</string>
<string name="pref_title_port">Hyperion FlatBuffers Port</string>
<string name="pref_summary_port">The FlatBuffers port of your hyperion instance (usually 19400)</string>
<string name="pref_title_wled_enabled">Enable WLED DDP</string>
<string name="pref_summary_wled_enabled">Send pixel data directly to a WLED instance using DDP</string>
<string name="pref_title_wled_ip">WLED IP Address</string>
<string name="pref_summary_wled_ip">The IP address of your WLED instance</string>
<string name="pref_title_y_led">Vertical LED Count</string>
<string name="pref_summary_y_led">The vertical count of LEDs on your hardware</string>
<string name="pref_title_x_led">Horizontal LED Count</string>
@@ -58,6 +63,8 @@
<string name="error_invalid_led_counts">Horizontal &amp; vertical LED counts must be set and greater than 0</string>
<string name="error_server_unreachable">Could not connect to the hyperion server. Check your settings and make sure hyperion is running</string>
<string name="error_connection_lost">The connection to your hyperion server has been lost, now stopping the grabber</string>
<string name="error_foreground_blocked">This device blocks screen capture services. Please check your device settings and allow Hyperion Grabber to run in the foreground, or grant it auto-start permission</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="message_service_started">Press Back to close the app. Your screen content will continue to be sent to Hyperion</string>
<string name="error_no_host_name_extra">That\'s weird, expected a hostname here</string>
+16
View File
@@ -57,6 +57,22 @@
android:summary="@string/pref_summary_reconnect_delay"
android:title="@string/pref_title_reconnect_delay" />
<CheckBoxPreference
android:defaultValue="@bool/pref_default_wled_enabled"
android:key="@string/pref_key_wled_enabled"
android:summary="@string/pref_summary_wled_enabled"
android:title="@string/pref_title_wled_enabled" />
<EditTextPreference
android:dependency="@string/pref_key_wled_enabled"
android:key="@string/pref_key_wled_ip"
android:maxLines="1"
android:inputType="textUri"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="@string/pref_summary_wled_ip"
android:title="@string/pref_title_wled_ip" />
</PreferenceCategory>
<PreferenceCategory
Executable
+78
View File
@@ -0,0 +1,78 @@
#!/bin/bash
FILES=$(find . -name "strings.xml" | grep -v "values/strings.xml")
for FILE in $FILES; do
# Check if we already added it
if grep -q "pref_title_wled_enabled" "$FILE"; then
continue
fi
# Determine locale
LOCALE=$(basename $(dirname "$FILE"))
# Default to english for undefined translations
ENABLED="Enable WLED DDP"
ENABLED_SUM="Send pixel data directly to a WLED instance using DDP"
IP="WLED IP Address"
IP_SUM="The IP address of your WLED instance"
case "$LOCALE" in
*es*)
ENABLED="Habilitar WLED DDP"
ENABLED_SUM="Enviar datos de píxeles directamente a una instancia WLED usando DDP"
IP="Dirección IP de WLED"
IP_SUM="La dirección IP de tu instancia WLED"
;;
*de*)
ENABLED="WLED DDP aktivieren"
ENABLED_SUM="Pixeldaten direkt über DDP an eine WLED-Instanz senden"
IP="WLED-IP-Adresse"
IP_SUM="Die IP-Adresse deiner WLED-Instanz"
;;
*fr*)
ENABLED="Activer WLED DDP"
ENABLED_SUM="Envoyer des données de pixels directement à une instance WLED via DDP"
IP="Adresse IP WLED"
IP_SUM="L'adresse IP de votre instance WLED"
;;
*it*)
ENABLED="Abilita WLED DDP"
ENABLED_SUM="Invia i dati dei pixel direttamente a un'istanza WLED tramite DDP"
IP="Indirizzo IP WLED"
IP_SUM="L'indirizzo IP della tua istanza WLED"
;;
*ru*)
ENABLED="Включить WLED DDP"
ENABLED_SUM="Отправка пиксельных данных напрямую на экземпляр WLED через DDP"
IP="IP-адрес WLED"
IP_SUM="IP-адрес вашего экземпляра WLED"
;;
*nl*)
ENABLED="WLED DDP inschakelen"
ENABLED_SUM="Stuur pixeldata rechtstreeks naar een WLED instantie via DDP"
IP="WLED IP-adres"
IP_SUM="Het IP-adres van je WLED instantie"
;;
*cs*)
ENABLED="Povolit WLED DDP"
ENABLED_SUM="Odeslat data pixelů přímo do instance WLED přes DDP"
IP="IP adresa WLED"
IP_SUM="IP adresa vaší instance WLED"
;;
*no*)
ENABLED="Aktiver WLED DDP"
ENABLED_SUM="Send pikseldata direkte til en WLED-instans ved bruk av DDP"
IP="WLED IP-adresse"
IP_SUM="IP-adressen til WLED-instansen din"
;;
esac
# Sed to insert before </resources>
# GNU sed vs BSD sed on mac:
sed -i '' -e '$ d' "$FILE"
echo ' <string name="pref_title_wled_enabled">'"$ENABLED"'</string>' >> "$FILE"
echo ' <string name="pref_summary_wled_enabled">'"$ENABLED_SUM"'</string>' >> "$FILE"
echo ' <string name="pref_title_wled_ip">'"$IP"'</string>' >> "$FILE"
echo ' <string name="pref_summary_wled_ip">'"$IP_SUM"'</string>' >> "$FILE"
echo '</resources>' >> "$FILE"
done